blob: 8a1d567877586b94fe7160df28442560f2ada1d1 [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"
Bob Wilson15acadd2009-11-26 00:32:21 +000016#include "llvm/CodeGen/Passes.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000017#include "llvm/ADT/DenseSet.h"
18#include "llvm/ADT/OwningPtr.h"
19#include "llvm/ADT/SetVector.h"
20#include "llvm/ADT/SmallSet.h"
21#include "llvm/ADT/Statistic.h"
Bob Wilson15acadd2009-11-26 00:32:21 +000022#include "llvm/CodeGen/MachineFunctionPass.h"
Jakob Stoklund Olesen1e1098c2010-07-10 22:42:59 +000023#include "llvm/CodeGen/MachineInstrBuilder.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000024#include "llvm/CodeGen/MachineModuleInfo.h"
Evan Cheng111e7622009-12-03 08:43:53 +000025#include "llvm/CodeGen/MachineRegisterInfo.h"
26#include "llvm/CodeGen/MachineSSAUpdater.h"
Evan Chengeb25bd22012-05-30 00:42:39 +000027#include "llvm/CodeGen/RegisterScavenging.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000028#include "llvm/IR/Function.h"
Bob Wilson15acadd2009-11-26 00:32:21 +000029#include "llvm/Support/CommandLine.h"
30#include "llvm/Support/Debug.h"
Evan Cheng75eb5352009-12-07 10:15:19 +000031#include "llvm/Support/ErrorHandling.h"
Bob Wilson15acadd2009-11-26 00:32:21 +000032#include "llvm/Support/raw_ostream.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000033#include "llvm/Target/TargetInstrInfo.h"
34#include "llvm/Target/TargetRegisterInfo.h"
Bob Wilson15acadd2009-11-26 00:32:21 +000035using namespace llvm;
36
Evan Cheng75eb5352009-12-07 10:15:19 +000037STATISTIC(NumTails , "Number of tails duplicated");
Bob Wilson15acadd2009-11-26 00:32:21 +000038STATISTIC(NumTailDups , "Number of tail duplicated blocks");
39STATISTIC(NumInstrDups , "Additional instructions due to tail duplication");
40STATISTIC(NumDeadBlocks, "Number of dead blocks removed");
Rafael Espindola0cdca082011-06-08 14:13:31 +000041STATISTIC(NumAddedPHIs , "Number of phis added");
Bob Wilson15acadd2009-11-26 00:32:21 +000042
43// Heuristic for tail duplication.
44static cl::opt<unsigned>
45TailDuplicateSize("tail-dup-size",
46 cl::desc("Maximum instructions to consider tail duplicating"),
47 cl::init(2), cl::Hidden);
48
Evan Cheng75eb5352009-12-07 10:15:19 +000049static cl::opt<bool>
50TailDupVerify("tail-dup-verify",
51 cl::desc("Verify sanity of PHI instructions during taildup"),
52 cl::init(false), cl::Hidden);
53
54static cl::opt<unsigned>
55TailDupLimit("tail-dup-limit", cl::init(~0U), cl::Hidden);
56
Evan Cheng11572ba2009-12-04 19:09:10 +000057typedef std::vector<std::pair<MachineBasicBlock*,unsigned> > AvailableValsTy;
Evan Cheng111e7622009-12-03 08:43:53 +000058
Bob Wilson15acadd2009-11-26 00:32:21 +000059namespace {
Bob Wilson2d521e52009-11-26 21:38:41 +000060 /// TailDuplicatePass - Perform tail duplication.
61 class TailDuplicatePass : public MachineFunctionPass {
Bob Wilson15acadd2009-11-26 00:32:21 +000062 const TargetInstrInfo *TII;
Evan Chengeb25bd22012-05-30 00:42:39 +000063 const TargetRegisterInfo *TRI;
Bob Wilson15acadd2009-11-26 00:32:21 +000064 MachineModuleInfo *MMI;
Evan Cheng111e7622009-12-03 08:43:53 +000065 MachineRegisterInfo *MRI;
Benjamin Kramerd14e4e12012-06-06 13:53:41 +000066 OwningPtr<RegScavenger> RS;
Andrew Trickd2a7bed2012-02-08 21:22:30 +000067 bool PreRegAlloc;
Evan Cheng111e7622009-12-03 08:43:53 +000068
69 // SSAUpdateVRs - A list of virtual registers for which to update SSA form.
70 SmallVector<unsigned, 16> SSAUpdateVRs;
71
72 // SSAUpdateVals - For each virtual register in SSAUpdateVals keep a list of
73 // source virtual registers.
74 DenseMap<unsigned, AvailableValsTy> SSAUpdateVals;
Bob Wilson15acadd2009-11-26 00:32:21 +000075
76 public:
77 static char ID;
Andrew Trickd2a7bed2012-02-08 21:22:30 +000078 explicit TailDuplicatePass() :
79 MachineFunctionPass(ID), PreRegAlloc(false) {}
Bob Wilson15acadd2009-11-26 00:32:21 +000080
81 virtual bool runOnMachineFunction(MachineFunction &MF);
Bob Wilson15acadd2009-11-26 00:32:21 +000082
83 private:
Evan Cheng11572ba2009-12-04 19:09:10 +000084 void AddSSAUpdateEntry(unsigned OrigReg, unsigned NewReg,
85 MachineBasicBlock *BB);
Evan Cheng79fc6f42009-12-04 09:42:45 +000086 void ProcessPHI(MachineInstr *MI, MachineBasicBlock *TailBB,
87 MachineBasicBlock *PredBB,
Evan Cheng75eb5352009-12-07 10:15:19 +000088 DenseMap<unsigned, unsigned> &LocalVRMap,
Craig Toppera0ec3f92013-07-14 04:42:23 +000089 SmallVectorImpl<std::pair<unsigned,unsigned> > &Copies,
Rafael Espindola689d7d52011-06-09 23:22:56 +000090 const DenseSet<unsigned> &UsedByPhi,
91 bool Remove);
Evan Cheng79fc6f42009-12-04 09:42:45 +000092 void DuplicateInstruction(MachineInstr *MI,
93 MachineBasicBlock *TailBB,
94 MachineBasicBlock *PredBB,
95 MachineFunction &MF,
Rafael Espindola0f28c3f2011-06-09 22:53:47 +000096 DenseMap<unsigned, unsigned> &LocalVRMap,
97 const DenseSet<unsigned> &UsedByPhi);
Evan Cheng75eb5352009-12-07 10:15:19 +000098 void UpdateSuccessorsPHIs(MachineBasicBlock *FromBB, bool isDead,
Craig Toppera0ec3f92013-07-14 04:42:23 +000099 SmallVectorImpl<MachineBasicBlock *> &TDBBs,
Evan Cheng75eb5352009-12-07 10:15:19 +0000100 SmallSetVector<MachineBasicBlock*, 8> &Succs);
Bob Wilson15acadd2009-11-26 00:32:21 +0000101 bool TailDuplicateBlocks(MachineFunction &MF);
Rafael Espindola54c25622011-06-09 19:54:42 +0000102 bool shouldTailDuplicate(const MachineFunction &MF,
Rafael Espindola9dbbd872011-06-23 03:41:29 +0000103 bool IsSimple, MachineBasicBlock &TailBB);
Rafael Espindola275c1f92011-06-20 04:16:35 +0000104 bool isSimpleBB(MachineBasicBlock *TailBB);
Rafael Espindola40179bf2011-06-24 15:50:56 +0000105 bool canCompletelyDuplicateBB(MachineBasicBlock &BB);
Rafael Espindolad7f35fa2011-06-24 15:47:41 +0000106 bool duplicateSimpleBB(MachineBasicBlock *TailBB,
Craig Toppera0ec3f92013-07-14 04:42:23 +0000107 SmallVectorImpl<MachineBasicBlock *> &TDBBs,
Rafael Espindola275c1f92011-06-20 04:16:35 +0000108 const DenseSet<unsigned> &RegsUsedByPhi,
Craig Toppera0ec3f92013-07-14 04:42:23 +0000109 SmallVectorImpl<MachineInstr *> &Copies);
Rafael Espindola6a9d2b12011-07-04 01:21:42 +0000110 bool TailDuplicate(MachineBasicBlock *TailBB,
111 bool IsSimple,
112 MachineFunction &MF,
Craig Toppera0ec3f92013-07-14 04:42:23 +0000113 SmallVectorImpl<MachineBasicBlock *> &TDBBs,
114 SmallVectorImpl<MachineInstr *> &Copies);
Rafael Espindola6a9d2b12011-07-04 01:21:42 +0000115 bool TailDuplicateAndUpdate(MachineBasicBlock *MBB,
116 bool IsSimple,
117 MachineFunction &MF);
118
Bob Wilson15acadd2009-11-26 00:32:21 +0000119 void RemoveDeadBlock(MachineBasicBlock *MBB);
120 };
121
Bob Wilson2d521e52009-11-26 21:38:41 +0000122 char TailDuplicatePass::ID = 0;
Bob Wilson15acadd2009-11-26 00:32:21 +0000123}
124
Andrew Trick1dd8c852012-02-08 21:23:13 +0000125char &llvm::TailDuplicateID = TailDuplicatePass::ID;
126
127INITIALIZE_PASS(TailDuplicatePass, "tailduplication", "Tail Duplication",
128 false, false)
Bob Wilson15acadd2009-11-26 00:32:21 +0000129
Bob Wilson2d521e52009-11-26 21:38:41 +0000130bool TailDuplicatePass::runOnMachineFunction(MachineFunction &MF) {
Bob Wilson15acadd2009-11-26 00:32:21 +0000131 TII = MF.getTarget().getInstrInfo();
Evan Chengeb25bd22012-05-30 00:42:39 +0000132 TRI = MF.getTarget().getRegisterInfo();
Evan Cheng111e7622009-12-03 08:43:53 +0000133 MRI = &MF.getRegInfo();
Bob Wilson15acadd2009-11-26 00:32:21 +0000134 MMI = getAnalysisIfAvailable<MachineModuleInfo>();
Andrew Trickd2a7bed2012-02-08 21:22:30 +0000135 PreRegAlloc = MRI->isSSA();
Benjamin Kramerd14e4e12012-06-06 13:53:41 +0000136 RS.reset();
Evan Chengeb25bd22012-05-30 00:42:39 +0000137 if (MRI->tracksLiveness() && TRI->trackLivenessAfterRegAlloc(MF))
Benjamin Kramerd14e4e12012-06-06 13:53:41 +0000138 RS.reset(new RegScavenger());
Bob Wilson15acadd2009-11-26 00:32:21 +0000139
140 bool MadeChange = false;
Jakob Stoklund Olesen057d5392010-01-15 19:59:57 +0000141 while (TailDuplicateBlocks(MF))
142 MadeChange = true;
Bob Wilson15acadd2009-11-26 00:32:21 +0000143
144 return MadeChange;
145}
146
Evan Cheng75eb5352009-12-07 10:15:19 +0000147static void VerifyPHIs(MachineFunction &MF, bool CheckExtra) {
148 for (MachineFunction::iterator I = ++MF.begin(), E = MF.end(); I != E; ++I) {
149 MachineBasicBlock *MBB = I;
150 SmallSetVector<MachineBasicBlock*, 8> Preds(MBB->pred_begin(),
151 MBB->pred_end());
152 MachineBasicBlock::iterator MI = MBB->begin();
153 while (MI != MBB->end()) {
Chris Lattner518bb532010-02-09 19:54:29 +0000154 if (!MI->isPHI())
Evan Cheng75eb5352009-12-07 10:15:19 +0000155 break;
156 for (SmallSetVector<MachineBasicBlock *, 8>::iterator PI = Preds.begin(),
157 PE = Preds.end(); PI != PE; ++PI) {
158 MachineBasicBlock *PredBB = *PI;
159 bool Found = false;
160 for (unsigned i = 1, e = MI->getNumOperands(); i != e; i += 2) {
161 MachineBasicBlock *PHIBB = MI->getOperand(i+1).getMBB();
162 if (PHIBB == PredBB) {
163 Found = true;
164 break;
165 }
166 }
167 if (!Found) {
David Greene00dec1b2010-01-05 01:25:15 +0000168 dbgs() << "Malformed PHI in BB#" << MBB->getNumber() << ": " << *MI;
169 dbgs() << " missing input from predecessor BB#"
Evan Cheng75eb5352009-12-07 10:15:19 +0000170 << PredBB->getNumber() << '\n';
171 llvm_unreachable(0);
172 }
173 }
174
175 for (unsigned i = 1, e = MI->getNumOperands(); i != e; i += 2) {
176 MachineBasicBlock *PHIBB = MI->getOperand(i+1).getMBB();
177 if (CheckExtra && !Preds.count(PHIBB)) {
David Greene00dec1b2010-01-05 01:25:15 +0000178 dbgs() << "Warning: malformed PHI in BB#" << MBB->getNumber()
Evan Cheng75eb5352009-12-07 10:15:19 +0000179 << ": " << *MI;
David Greene00dec1b2010-01-05 01:25:15 +0000180 dbgs() << " extra input from predecessor BB#"
Evan Cheng75eb5352009-12-07 10:15:19 +0000181 << PHIBB->getNumber() << '\n';
Rafael Espindolad3f4eea2011-06-09 23:55:56 +0000182 llvm_unreachable(0);
Evan Cheng75eb5352009-12-07 10:15:19 +0000183 }
184 if (PHIBB->getNumber() < 0) {
David Greene00dec1b2010-01-05 01:25:15 +0000185 dbgs() << "Malformed PHI in BB#" << MBB->getNumber() << ": " << *MI;
186 dbgs() << " non-existing BB#" << PHIBB->getNumber() << '\n';
Evan Cheng75eb5352009-12-07 10:15:19 +0000187 llvm_unreachable(0);
188 }
189 }
190 ++MI;
191 }
192 }
193}
194
Rafael Espindola6a9d2b12011-07-04 01:21:42 +0000195/// TailDuplicateAndUpdate - Tail duplicate the block and cleanup.
196bool
197TailDuplicatePass::TailDuplicateAndUpdate(MachineBasicBlock *MBB,
198 bool IsSimple,
199 MachineFunction &MF) {
200 // Save the successors list.
201 SmallSetVector<MachineBasicBlock*, 8> Succs(MBB->succ_begin(),
202 MBB->succ_end());
203
204 SmallVector<MachineBasicBlock*, 8> TDBBs;
205 SmallVector<MachineInstr*, 16> Copies;
206 if (!TailDuplicate(MBB, IsSimple, MF, TDBBs, Copies))
207 return false;
208
209 ++NumTails;
210
211 SmallVector<MachineInstr*, 8> NewPHIs;
212 MachineSSAUpdater SSAUpdate(MF, &NewPHIs);
213
214 // TailBB's immediate successors are now successors of those predecessors
215 // which duplicated TailBB. Add the predecessors as sources to the PHI
216 // instructions.
217 bool isDead = MBB->pred_empty() && !MBB->hasAddressTaken();
218 if (PreRegAlloc)
219 UpdateSuccessorsPHIs(MBB, isDead, TDBBs, Succs);
220
221 // If it is dead, remove it.
222 if (isDead) {
223 NumInstrDups -= MBB->size();
224 RemoveDeadBlock(MBB);
225 ++NumDeadBlocks;
226 }
227
228 // Update SSA form.
229 if (!SSAUpdateVRs.empty()) {
230 for (unsigned i = 0, e = SSAUpdateVRs.size(); i != e; ++i) {
231 unsigned VReg = SSAUpdateVRs[i];
232 SSAUpdate.Initialize(VReg);
233
234 // If the original definition is still around, add it as an available
235 // value.
236 MachineInstr *DefMI = MRI->getVRegDef(VReg);
237 MachineBasicBlock *DefBB = 0;
238 if (DefMI) {
239 DefBB = DefMI->getParent();
240 SSAUpdate.AddAvailableValue(DefBB, VReg);
241 }
242
243 // Add the new vregs as available values.
244 DenseMap<unsigned, AvailableValsTy>::iterator LI =
245 SSAUpdateVals.find(VReg);
246 for (unsigned j = 0, ee = LI->second.size(); j != ee; ++j) {
247 MachineBasicBlock *SrcBB = LI->second[j].first;
248 unsigned SrcReg = LI->second[j].second;
249 SSAUpdate.AddAvailableValue(SrcBB, SrcReg);
250 }
251
252 // Rewrite uses that are outside of the original def's block.
253 MachineRegisterInfo::use_iterator UI = MRI->use_begin(VReg);
254 while (UI != MRI->use_end()) {
255 MachineOperand &UseMO = UI.getOperand();
256 MachineInstr *UseMI = &*UI;
257 ++UI;
258 if (UseMI->isDebugValue()) {
259 // SSAUpdate can replace the use with an undef. That creates
260 // a debug instruction that is a kill.
261 // FIXME: Should it SSAUpdate job to delete debug instructions
262 // instead of replacing the use with undef?
263 UseMI->eraseFromParent();
264 continue;
265 }
266 if (UseMI->getParent() == DefBB && !UseMI->isPHI())
267 continue;
268 SSAUpdate.RewriteUse(UseMO);
269 }
270 }
271
272 SSAUpdateVRs.clear();
273 SSAUpdateVals.clear();
274 }
275
276 // Eliminate some of the copies inserted by tail duplication to maintain
277 // SSA form.
278 for (unsigned i = 0, e = Copies.size(); i != e; ++i) {
279 MachineInstr *Copy = Copies[i];
280 if (!Copy->isCopy())
281 continue;
282 unsigned Dst = Copy->getOperand(0).getReg();
283 unsigned Src = Copy->getOperand(1).getReg();
Jakob Stoklund Olesen0fda5452012-05-20 18:42:51 +0000284 if (MRI->hasOneNonDBGUse(Src) &&
285 MRI->constrainRegClass(Src, MRI->getRegClass(Dst))) {
Rafael Espindola6a9d2b12011-07-04 01:21:42 +0000286 // Copy is the only use. Do trivial copy propagation here.
287 MRI->replaceRegWith(Dst, Src);
288 Copy->eraseFromParent();
289 }
290 }
291
292 if (NewPHIs.size())
293 NumAddedPHIs += NewPHIs.size();
294
295 return true;
296}
297
Bob Wilson15acadd2009-11-26 00:32:21 +0000298/// TailDuplicateBlocks - Look for small blocks that are unconditionally
299/// branched to and do not fall through. Tail-duplicate their instructions
300/// into their predecessors to eliminate (dynamic) branches.
Bob Wilson2d521e52009-11-26 21:38:41 +0000301bool TailDuplicatePass::TailDuplicateBlocks(MachineFunction &MF) {
Bob Wilson15acadd2009-11-26 00:32:21 +0000302 bool MadeChange = false;
303
Evan Cheng75eb5352009-12-07 10:15:19 +0000304 if (PreRegAlloc && TailDupVerify) {
David Greene00dec1b2010-01-05 01:25:15 +0000305 DEBUG(dbgs() << "\n*** Before tail-duplicating\n");
Evan Cheng75eb5352009-12-07 10:15:19 +0000306 VerifyPHIs(MF, true);
307 }
308
Bob Wilson15acadd2009-11-26 00:32:21 +0000309 for (MachineFunction::iterator I = ++MF.begin(), E = MF.end(); I != E; ) {
310 MachineBasicBlock *MBB = I++;
311
Evan Cheng75eb5352009-12-07 10:15:19 +0000312 if (NumTails == TailDupLimit)
313 break;
314
Rafael Espindola6a9d2b12011-07-04 01:21:42 +0000315 bool IsSimple = isSimpleBB(MBB);
Bob Wilson15acadd2009-11-26 00:32:21 +0000316
Rafael Espindola6a9d2b12011-07-04 01:21:42 +0000317 if (!shouldTailDuplicate(MF, IsSimple, *MBB))
Rafael Espindolac0af3522011-07-04 00:13:36 +0000318 continue;
Evan Cheng75eb5352009-12-07 10:15:19 +0000319
Rafael Espindola6a9d2b12011-07-04 01:21:42 +0000320 MadeChange |= TailDuplicateAndUpdate(MBB, IsSimple, MF);
Bob Wilson15acadd2009-11-26 00:32:21 +0000321 }
Rafael Espindolac0af3522011-07-04 00:13:36 +0000322
Rafael Espindola6a9d2b12011-07-04 01:21:42 +0000323 if (PreRegAlloc && TailDupVerify)
324 VerifyPHIs(MF, false);
Evan Cheng111e7622009-12-03 08:43:53 +0000325
Bob Wilson15acadd2009-11-26 00:32:21 +0000326 return MadeChange;
327}
328
Evan Cheng111e7622009-12-03 08:43:53 +0000329static bool isDefLiveOut(unsigned Reg, MachineBasicBlock *BB,
330 const MachineRegisterInfo *MRI) {
331 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(Reg),
332 UE = MRI->use_end(); UI != UE; ++UI) {
333 MachineInstr *UseMI = &*UI;
Rafael Espindoladb3983b2011-06-17 13:59:43 +0000334 if (UseMI->isDebugValue())
335 continue;
Evan Cheng111e7622009-12-03 08:43:53 +0000336 if (UseMI->getParent() != BB)
337 return true;
338 }
339 return false;
340}
341
342static unsigned getPHISrcRegOpIdx(MachineInstr *MI, MachineBasicBlock *SrcBB) {
343 for (unsigned i = 1, e = MI->getNumOperands(); i != e; i += 2)
344 if (MI->getOperand(i+1).getMBB() == SrcBB)
345 return i;
346 return 0;
347}
348
Rafael Espindola0f28c3f2011-06-09 22:53:47 +0000349
350// Remember which registers are used by phis in this block. This is
351// used to determine which registers are liveout while modifying the
352// block (which is why we need to copy the information).
353static void getRegsUsedByPHIs(const MachineBasicBlock &BB,
Rafael Espindola33b46582011-06-10 21:01:53 +0000354 DenseSet<unsigned> *UsedByPhi) {
Rafael Espindola0f28c3f2011-06-09 22:53:47 +0000355 for(MachineBasicBlock::const_iterator I = BB.begin(), E = BB.end();
356 I != E; ++I) {
357 const MachineInstr &MI = *I;
358 if (!MI.isPHI())
359 break;
360 for (unsigned i = 1, e = MI.getNumOperands(); i != e; i += 2) {
361 unsigned SrcReg = MI.getOperand(i).getReg();
362 UsedByPhi->insert(SrcReg);
363 }
364 }
365}
366
Evan Cheng111e7622009-12-03 08:43:53 +0000367/// AddSSAUpdateEntry - Add a definition and source virtual registers pair for
368/// SSA update.
Evan Cheng11572ba2009-12-04 19:09:10 +0000369void TailDuplicatePass::AddSSAUpdateEntry(unsigned OrigReg, unsigned NewReg,
370 MachineBasicBlock *BB) {
371 DenseMap<unsigned, AvailableValsTy>::iterator LI= SSAUpdateVals.find(OrigReg);
Evan Cheng111e7622009-12-03 08:43:53 +0000372 if (LI != SSAUpdateVals.end())
Evan Cheng11572ba2009-12-04 19:09:10 +0000373 LI->second.push_back(std::make_pair(BB, NewReg));
Evan Cheng111e7622009-12-03 08:43:53 +0000374 else {
375 AvailableValsTy Vals;
Evan Cheng11572ba2009-12-04 19:09:10 +0000376 Vals.push_back(std::make_pair(BB, NewReg));
Evan Cheng111e7622009-12-03 08:43:53 +0000377 SSAUpdateVals.insert(std::make_pair(OrigReg, Vals));
378 SSAUpdateVRs.push_back(OrigReg);
379 }
380}
381
Evan Cheng75eb5352009-12-07 10:15:19 +0000382/// ProcessPHI - Process PHI node in TailBB by turning it into a copy in PredBB.
383/// Remember the source register that's contributed by PredBB and update SSA
384/// update map.
Tobias Grosser83d63f82013-07-14 06:12:01 +0000385void TailDuplicatePass::ProcessPHI(
386 MachineInstr *MI, MachineBasicBlock *TailBB, MachineBasicBlock *PredBB,
387 DenseMap<unsigned, unsigned> &LocalVRMap,
388 SmallVectorImpl<std::pair<unsigned, unsigned> > &Copies,
389 const DenseSet<unsigned> &RegsUsedByPhi, bool Remove) {
Evan Cheng79fc6f42009-12-04 09:42:45 +0000390 unsigned DefReg = MI->getOperand(0).getReg();
391 unsigned SrcOpIdx = getPHISrcRegOpIdx(MI, PredBB);
392 assert(SrcOpIdx && "Unable to find matching PHI source?");
393 unsigned SrcReg = MI->getOperand(SrcOpIdx).getReg();
Evan Cheng75eb5352009-12-07 10:15:19 +0000394 const TargetRegisterClass *RC = MRI->getRegClass(DefReg);
Evan Cheng79fc6f42009-12-04 09:42:45 +0000395 LocalVRMap.insert(std::make_pair(DefReg, SrcReg));
Evan Cheng75eb5352009-12-07 10:15:19 +0000396
397 // Insert a copy from source to the end of the block. The def register is the
398 // available value liveout of the block.
399 unsigned NewDef = MRI->createVirtualRegister(RC);
400 Copies.push_back(std::make_pair(NewDef, SrcReg));
Rafael Espindola0f28c3f2011-06-09 22:53:47 +0000401 if (isDefLiveOut(DefReg, TailBB, MRI) || RegsUsedByPhi.count(DefReg))
Evan Cheng75eb5352009-12-07 10:15:19 +0000402 AddSSAUpdateEntry(DefReg, NewDef, PredBB);
Evan Cheng79fc6f42009-12-04 09:42:45 +0000403
Rafael Espindola689d7d52011-06-09 23:22:56 +0000404 if (!Remove)
405 return;
406
Evan Cheng79fc6f42009-12-04 09:42:45 +0000407 // Remove PredBB from the PHI node.
408 MI->RemoveOperand(SrcOpIdx+1);
409 MI->RemoveOperand(SrcOpIdx);
410 if (MI->getNumOperands() == 1)
411 MI->eraseFromParent();
412}
413
414/// DuplicateInstruction - Duplicate a TailBB instruction to PredBB and update
415/// the source operands due to earlier PHI translation.
416void TailDuplicatePass::DuplicateInstruction(MachineInstr *MI,
417 MachineBasicBlock *TailBB,
418 MachineBasicBlock *PredBB,
419 MachineFunction &MF,
Rafael Espindola0f28c3f2011-06-09 22:53:47 +0000420 DenseMap<unsigned, unsigned> &LocalVRMap,
421 const DenseSet<unsigned> &UsedByPhi) {
Jakob Stoklund Olesen30ac0462010-01-06 23:47:07 +0000422 MachineInstr *NewMI = TII->duplicate(MI, MF);
Evan Cheng79fc6f42009-12-04 09:42:45 +0000423 for (unsigned i = 0, e = NewMI->getNumOperands(); i != e; ++i) {
424 MachineOperand &MO = NewMI->getOperand(i);
425 if (!MO.isReg())
426 continue;
427 unsigned Reg = MO.getReg();
Jakob Stoklund Olesenc9df0252011-01-10 02:58:51 +0000428 if (!TargetRegisterInfo::isVirtualRegister(Reg))
Evan Cheng79fc6f42009-12-04 09:42:45 +0000429 continue;
430 if (MO.isDef()) {
431 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
432 unsigned NewReg = MRI->createVirtualRegister(RC);
433 MO.setReg(NewReg);
434 LocalVRMap.insert(std::make_pair(Reg, NewReg));
Rafael Espindola0f28c3f2011-06-09 22:53:47 +0000435 if (isDefLiveOut(Reg, TailBB, MRI) || UsedByPhi.count(Reg))
Evan Cheng11572ba2009-12-04 19:09:10 +0000436 AddSSAUpdateEntry(Reg, NewReg, PredBB);
Evan Cheng79fc6f42009-12-04 09:42:45 +0000437 } else {
438 DenseMap<unsigned, unsigned>::iterator VI = LocalVRMap.find(Reg);
Jakob Stoklund Olesen0fda5452012-05-20 18:42:51 +0000439 if (VI != LocalVRMap.end()) {
Evan Cheng79fc6f42009-12-04 09:42:45 +0000440 MO.setReg(VI->second);
Jakob Stoklund Olesen0fda5452012-05-20 18:42:51 +0000441 MRI->constrainRegClass(VI->second, MRI->getRegClass(Reg));
442 }
Evan Cheng79fc6f42009-12-04 09:42:45 +0000443 }
444 }
Evan Chengdf7e8bd2012-02-20 07:51:58 +0000445 PredBB->insert(PredBB->instr_end(), NewMI);
Evan Cheng79fc6f42009-12-04 09:42:45 +0000446}
447
448/// UpdateSuccessorsPHIs - After FromBB is tail duplicated into its predecessor
449/// blocks, the successors have gained new predecessors. Update the PHI
450/// instructions in them accordingly.
Evan Cheng75eb5352009-12-07 10:15:19 +0000451void
452TailDuplicatePass::UpdateSuccessorsPHIs(MachineBasicBlock *FromBB, bool isDead,
Craig Toppera0ec3f92013-07-14 04:42:23 +0000453 SmallVectorImpl<MachineBasicBlock *> &TDBBs,
Evan Cheng79fc6f42009-12-04 09:42:45 +0000454 SmallSetVector<MachineBasicBlock*,8> &Succs) {
455 for (SmallSetVector<MachineBasicBlock*, 8>::iterator SI = Succs.begin(),
456 SE = Succs.end(); SI != SE; ++SI) {
457 MachineBasicBlock *SuccBB = *SI;
458 for (MachineBasicBlock::iterator II = SuccBB->begin(), EE = SuccBB->end();
459 II != EE; ++II) {
Chris Lattner518bb532010-02-09 19:54:29 +0000460 if (!II->isPHI())
Evan Cheng79fc6f42009-12-04 09:42:45 +0000461 break;
Jakob Stoklund Olesen7b79b982012-12-20 18:08:06 +0000462 MachineInstrBuilder MIB(*FromBB->getParent(), II);
Evan Cheng75eb5352009-12-07 10:15:19 +0000463 unsigned Idx = 0;
Evan Cheng79fc6f42009-12-04 09:42:45 +0000464 for (unsigned i = 1, e = II->getNumOperands(); i != e; i += 2) {
Evan Cheng75eb5352009-12-07 10:15:19 +0000465 MachineOperand &MO = II->getOperand(i+1);
466 if (MO.getMBB() == FromBB) {
467 Idx = i;
Evan Cheng79fc6f42009-12-04 09:42:45 +0000468 break;
Evan Cheng75eb5352009-12-07 10:15:19 +0000469 }
470 }
471
472 assert(Idx != 0);
473 MachineOperand &MO0 = II->getOperand(Idx);
474 unsigned Reg = MO0.getReg();
475 if (isDead) {
476 // Folded into the previous BB.
477 // There could be duplicate phi source entries. FIXME: Should sdisel
478 // or earlier pass fixed this?
479 for (unsigned i = II->getNumOperands()-2; i != Idx; i -= 2) {
480 MachineOperand &MO = II->getOperand(i+1);
481 if (MO.getMBB() == FromBB) {
482 II->RemoveOperand(i+1);
483 II->RemoveOperand(i);
484 }
485 }
Jakob Stoklund Olesen09eeac92010-02-11 00:34:33 +0000486 } else
487 Idx = 0;
488
489 // If Idx is set, the operands at Idx and Idx+1 must be removed.
490 // We reuse the location to avoid expensive RemoveOperand calls.
491
Evan Cheng75eb5352009-12-07 10:15:19 +0000492 DenseMap<unsigned,AvailableValsTy>::iterator LI=SSAUpdateVals.find(Reg);
493 if (LI != SSAUpdateVals.end()) {
494 // This register is defined in the tail block.
Evan Cheng79fc6f42009-12-04 09:42:45 +0000495 for (unsigned j = 0, ee = LI->second.size(); j != ee; ++j) {
Evan Cheng11572ba2009-12-04 19:09:10 +0000496 MachineBasicBlock *SrcBB = LI->second[j].first;
Rafael Espindolad3f4eea2011-06-09 23:55:56 +0000497 // If we didn't duplicate a bb into a particular predecessor, we
498 // might still have added an entry to SSAUpdateVals to correcly
499 // recompute SSA. If that case, avoid adding a dummy extra argument
500 // this PHI.
501 if (!SrcBB->isSuccessor(SuccBB))
502 continue;
503
Evan Cheng11572ba2009-12-04 19:09:10 +0000504 unsigned SrcReg = LI->second[j].second;
Jakob Stoklund Olesen09eeac92010-02-11 00:34:33 +0000505 if (Idx != 0) {
506 II->getOperand(Idx).setReg(SrcReg);
507 II->getOperand(Idx+1).setMBB(SrcBB);
508 Idx = 0;
509 } else {
Jakob Stoklund Olesen7b79b982012-12-20 18:08:06 +0000510 MIB.addReg(SrcReg).addMBB(SrcBB);
Jakob Stoklund Olesen09eeac92010-02-11 00:34:33 +0000511 }
Evan Cheng79fc6f42009-12-04 09:42:45 +0000512 }
Evan Cheng75eb5352009-12-07 10:15:19 +0000513 } else {
514 // Live in tail block, must also be live in predecessors.
515 for (unsigned j = 0, ee = TDBBs.size(); j != ee; ++j) {
516 MachineBasicBlock *SrcBB = TDBBs[j];
Jakob Stoklund Olesen09eeac92010-02-11 00:34:33 +0000517 if (Idx != 0) {
518 II->getOperand(Idx).setReg(Reg);
519 II->getOperand(Idx+1).setMBB(SrcBB);
520 Idx = 0;
521 } else {
Jakob Stoklund Olesen7b79b982012-12-20 18:08:06 +0000522 MIB.addReg(Reg).addMBB(SrcBB);
Jakob Stoklund Olesen09eeac92010-02-11 00:34:33 +0000523 }
Evan Cheng75eb5352009-12-07 10:15:19 +0000524 }
Evan Cheng79fc6f42009-12-04 09:42:45 +0000525 }
Jakob Stoklund Olesen09eeac92010-02-11 00:34:33 +0000526 if (Idx != 0) {
527 II->RemoveOperand(Idx+1);
528 II->RemoveOperand(Idx);
529 }
Evan Cheng79fc6f42009-12-04 09:42:45 +0000530 }
531 }
532}
533
Rafael Espindola54c25622011-06-09 19:54:42 +0000534/// shouldTailDuplicate - Determine if it is profitable to duplicate this block.
Evan Cheng75eb5352009-12-07 10:15:19 +0000535bool
Rafael Espindola54c25622011-06-09 19:54:42 +0000536TailDuplicatePass::shouldTailDuplicate(const MachineFunction &MF,
Rafael Espindola9dbbd872011-06-23 03:41:29 +0000537 bool IsSimple,
Rafael Espindola54c25622011-06-09 19:54:42 +0000538 MachineBasicBlock &TailBB) {
539 // Only duplicate blocks that end with unconditional branches.
540 if (TailBB.canFallThrough())
541 return false;
542
Rafael Espindolaec324e52011-06-17 05:54:50 +0000543 // Don't try to tail-duplicate single-block loops.
544 if (TailBB.isSuccessor(&TailBB))
545 return false;
546
Rafael Espindola54c25622011-06-09 19:54:42 +0000547 // Set the limit on the cost to duplicate. When optimizing for size,
Bob Wilson15acadd2009-11-26 00:32:21 +0000548 // duplicate only one, because one branch instruction can be eliminated to
549 // compensate for the duplication.
550 unsigned MaxDuplicateCount;
Jakob Stoklund Olesen83520622011-01-30 20:38:12 +0000551 if (TailDuplicateSize.getNumOccurrences() == 0 &&
Bill Wendling831737d2012-12-30 10:32:01 +0000552 MF.getFunction()->getAttributes().
553 hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize))
Bob Wilson38582252009-11-30 18:56:45 +0000554 MaxDuplicateCount = 1;
Bob Wilson15acadd2009-11-26 00:32:21 +0000555 else
556 MaxDuplicateCount = TailDuplicateSize;
557
Rafael Espindolaec324e52011-06-17 05:54:50 +0000558 // If the target has hardware branch prediction that can handle indirect
559 // branches, duplicating them can often make them predictable when there
560 // are common paths through the code. The limit needs to be high enough
561 // to allow undoing the effects of tail merging and other optimizations
562 // that rearrange the predecessors of the indirect branch.
Bob Wilsoncb44b282010-01-16 00:42:25 +0000563
Rafael Espindola6a9d2b12011-07-04 01:21:42 +0000564 bool HasIndirectbr = false;
565 if (!TailBB.empty())
Evan Cheng5a96b3d2011-12-07 07:15:52 +0000566 HasIndirectbr = TailBB.back().isIndirectBranch();
Rafael Espindola6a9d2b12011-07-04 01:21:42 +0000567
568 if (HasIndirectbr && PreRegAlloc)
569 MaxDuplicateCount = 20;
Bob Wilsonbfdcf3b2010-01-15 06:29:17 +0000570
Bob Wilson15acadd2009-11-26 00:32:21 +0000571 // Check the instructions in the block to determine whether tail-duplication
572 // is invalid or unlikely to be profitable.
Bob Wilsonf1e01dc2009-12-02 17:15:24 +0000573 unsigned InstrCount = 0;
Evan Cheng7c2a4a32011-12-06 22:12:01 +0000574 for (MachineBasicBlock::iterator I = TailBB.begin(); I != TailBB.end(); ++I) {
Bob Wilson15acadd2009-11-26 00:32:21 +0000575 // Non-duplicable things shouldn't be tail-duplicated.
Evan Cheng5a96b3d2011-12-07 07:15:52 +0000576 if (I->isNotDuplicable())
Rafael Espindolaec324e52011-06-17 05:54:50 +0000577 return false;
578
Evan Cheng79fc6f42009-12-04 09:42:45 +0000579 // Do not duplicate 'return' instructions if this is a pre-regalloc run.
580 // A return may expand into a lot more instructions (e.g. reload of callee
581 // saved registers) after PEI.
Evan Cheng5a96b3d2011-12-07 07:15:52 +0000582 if (PreRegAlloc && I->isReturn())
Rafael Espindolaec324e52011-06-17 05:54:50 +0000583 return false;
584
585 // Avoid duplicating calls before register allocation. Calls presents a
586 // barrier to register allocation so duplicating them may end up increasing
587 // spills.
Evan Cheng5a96b3d2011-12-07 07:15:52 +0000588 if (PreRegAlloc && I->isCall())
Rafael Espindolaec324e52011-06-17 05:54:50 +0000589 return false;
590
Devang Patelcbe1e312010-03-16 21:02:07 +0000591 if (!I->isPHI() && !I->isDebugValue())
Bob Wilsonf1e01dc2009-12-02 17:15:24 +0000592 InstrCount += 1;
Rafael Espindolaec324e52011-06-17 05:54:50 +0000593
594 if (InstrCount > MaxDuplicateCount)
595 return false;
Bob Wilson15acadd2009-11-26 00:32:21 +0000596 }
Bob Wilson15acadd2009-11-26 00:32:21 +0000597
Rafael Espindola6a9d2b12011-07-04 01:21:42 +0000598 if (HasIndirectbr && PreRegAlloc)
Rafael Espindola9dbbd872011-06-23 03:41:29 +0000599 return true;
600
601 if (IsSimple)
Rafael Espindolad7f35fa2011-06-24 15:47:41 +0000602 return true;
Rafael Espindola9dbbd872011-06-23 03:41:29 +0000603
604 if (!PreRegAlloc)
605 return true;
606
Rafael Espindola40179bf2011-06-24 15:50:56 +0000607 return canCompletelyDuplicateBB(TailBB);
Rafael Espindola54c25622011-06-09 19:54:42 +0000608}
609
Rafael Espindola275c1f92011-06-20 04:16:35 +0000610/// isSimpleBB - True if this BB has only one unconditional jump.
611bool
612TailDuplicatePass::isSimpleBB(MachineBasicBlock *TailBB) {
613 if (TailBB->succ_size() != 1)
614 return false;
Rafael Espindola9dbbd872011-06-23 03:41:29 +0000615 if (TailBB->pred_empty())
616 return false;
Rafael Espindolad6379a92011-06-22 22:31:57 +0000617 MachineBasicBlock::iterator I = TailBB->begin();
Rafael Espindola275c1f92011-06-20 04:16:35 +0000618 MachineBasicBlock::iterator E = TailBB->end();
Rafael Espindolad6379a92011-06-22 22:31:57 +0000619 while (I != E && I->isDebugValue())
Rafael Espindola275c1f92011-06-20 04:16:35 +0000620 ++I;
621 if (I == E)
622 return true;
Evan Cheng5a96b3d2011-12-07 07:15:52 +0000623 return I->isUnconditionalBranch();
Rafael Espindola275c1f92011-06-20 04:16:35 +0000624}
625
626static bool
627bothUsedInPHI(const MachineBasicBlock &A,
628 SmallPtrSet<MachineBasicBlock*, 8> SuccsB) {
629 for (MachineBasicBlock::const_succ_iterator SI = A.succ_begin(),
630 SE = A.succ_end(); SI != SE; ++SI) {
631 MachineBasicBlock *BB = *SI;
632 if (SuccsB.count(BB) && !BB->empty() && BB->begin()->isPHI())
633 return true;
634 }
635
636 return false;
637}
638
639bool
Rafael Espindola40179bf2011-06-24 15:50:56 +0000640TailDuplicatePass::canCompletelyDuplicateBB(MachineBasicBlock &BB) {
Rafael Espindola275c1f92011-06-20 04:16:35 +0000641 SmallPtrSet<MachineBasicBlock*, 8> Succs(BB.succ_begin(), BB.succ_end());
642
643 for (MachineBasicBlock::pred_iterator PI = BB.pred_begin(),
644 PE = BB.pred_end(); PI != PE; ++PI) {
645 MachineBasicBlock *PredBB = *PI;
Rafael Espindola9dbbd872011-06-23 03:41:29 +0000646
Rafael Espindola40179bf2011-06-24 15:50:56 +0000647 if (PredBB->succ_size() > 1)
648 return false;
Rafael Espindola9dbbd872011-06-23 03:41:29 +0000649
Rafael Espindola275c1f92011-06-20 04:16:35 +0000650 MachineBasicBlock *PredTBB = NULL, *PredFBB = NULL;
651 SmallVector<MachineOperand, 4> PredCond;
652 if (TII->AnalyzeBranch(*PredBB, PredTBB, PredFBB, PredCond, true))
653 return false;
Rafael Espindola9dbbd872011-06-23 03:41:29 +0000654
Rafael Espindola40179bf2011-06-24 15:50:56 +0000655 if (!PredCond.empty())
Rafael Espindola9dbbd872011-06-23 03:41:29 +0000656 return false;
Rafael Espindola275c1f92011-06-20 04:16:35 +0000657 }
658 return true;
659}
660
Rafael Espindolad7f35fa2011-06-24 15:47:41 +0000661bool
Rafael Espindola275c1f92011-06-20 04:16:35 +0000662TailDuplicatePass::duplicateSimpleBB(MachineBasicBlock *TailBB,
Craig Toppera0ec3f92013-07-14 04:42:23 +0000663 SmallVectorImpl<MachineBasicBlock *> &TDBBs,
664 const DenseSet<unsigned> &UsedByPhi,
665 SmallVectorImpl<MachineInstr *> &Copies) {
Rafael Espindolad7f35fa2011-06-24 15:47:41 +0000666 SmallPtrSet<MachineBasicBlock*, 8> Succs(TailBB->succ_begin(),
667 TailBB->succ_end());
Rafael Espindola275c1f92011-06-20 04:16:35 +0000668 SmallVector<MachineBasicBlock*, 8> Preds(TailBB->pred_begin(),
669 TailBB->pred_end());
Rafael Espindolad7f35fa2011-06-24 15:47:41 +0000670 bool Changed = false;
Rafael Espindola275c1f92011-06-20 04:16:35 +0000671 for (SmallSetVector<MachineBasicBlock *, 8>::iterator PI = Preds.begin(),
672 PE = Preds.end(); PI != PE; ++PI) {
673 MachineBasicBlock *PredBB = *PI;
674
Rafael Espindolad7f35fa2011-06-24 15:47:41 +0000675 if (PredBB->getLandingPadSuccessor())
676 continue;
677
678 if (bothUsedInPHI(*PredBB, Succs))
679 continue;
680
Rafael Espindola275c1f92011-06-20 04:16:35 +0000681 MachineBasicBlock *PredTBB = NULL, *PredFBB = NULL;
682 SmallVector<MachineOperand, 4> PredCond;
Rafael Espindolad7f35fa2011-06-24 15:47:41 +0000683 if (TII->AnalyzeBranch(*PredBB, PredTBB, PredFBB, PredCond, true))
684 continue;
Rafael Espindola275c1f92011-06-20 04:16:35 +0000685
Rafael Espindolad7f35fa2011-06-24 15:47:41 +0000686 Changed = true;
Rafael Espindola275c1f92011-06-20 04:16:35 +0000687 DEBUG(dbgs() << "\nTail-duplicating into PredBB: " << *PredBB
688 << "From simple Succ: " << *TailBB);
689
690 MachineBasicBlock *NewTarget = *TailBB->succ_begin();
Francois Pichet289a2792011-06-20 05:19:37 +0000691 MachineBasicBlock *NextBB = llvm::next(MachineFunction::iterator(PredBB));
Rafael Espindola275c1f92011-06-20 04:16:35 +0000692
Rafael Espindola275c1f92011-06-20 04:16:35 +0000693 // Make PredFBB explicit.
694 if (PredCond.empty())
695 PredFBB = PredTBB;
696
697 // Make fall through explicit.
698 if (!PredTBB)
699 PredTBB = NextBB;
700 if (!PredFBB)
701 PredFBB = NextBB;
702
703 // Redirect
704 if (PredFBB == TailBB)
705 PredFBB = NewTarget;
706 if (PredTBB == TailBB)
707 PredTBB = NewTarget;
708
709 // Make the branch unconditional if possible
Rafael Espindola689c2472011-06-20 14:11:42 +0000710 if (PredTBB == PredFBB) {
711 PredCond.clear();
Rafael Espindola275c1f92011-06-20 04:16:35 +0000712 PredFBB = NULL;
Rafael Espindola689c2472011-06-20 14:11:42 +0000713 }
Rafael Espindola275c1f92011-06-20 04:16:35 +0000714
715 // Avoid adding fall through branches.
716 if (PredFBB == NextBB)
717 PredFBB = NULL;
718 if (PredTBB == NextBB && PredFBB == NULL)
719 PredTBB = NULL;
720
721 TII->RemoveBranch(*PredBB);
722
723 if (PredTBB)
724 TII->InsertBranch(*PredBB, PredTBB, PredFBB, PredCond, DebugLoc());
725
726 PredBB->removeSuccessor(TailBB);
Rafael Espindola689c2472011-06-20 14:11:42 +0000727 unsigned NumSuccessors = PredBB->succ_size();
728 assert(NumSuccessors <= 1);
729 if (NumSuccessors == 0 || *PredBB->succ_begin() != NewTarget)
730 PredBB->addSuccessor(NewTarget);
Rafael Espindola275c1f92011-06-20 04:16:35 +0000731
732 TDBBs.push_back(PredBB);
Rafael Espindola275c1f92011-06-20 04:16:35 +0000733 }
Rafael Espindolad7f35fa2011-06-24 15:47:41 +0000734 return Changed;
Rafael Espindola275c1f92011-06-20 04:16:35 +0000735}
736
Rafael Espindola54c25622011-06-09 19:54:42 +0000737/// TailDuplicate - If it is profitable, duplicate TailBB's contents in each
738/// of its predecessors.
739bool
Rafael Espindola6a9d2b12011-07-04 01:21:42 +0000740TailDuplicatePass::TailDuplicate(MachineBasicBlock *TailBB,
741 bool IsSimple,
742 MachineFunction &MF,
Craig Toppera0ec3f92013-07-14 04:42:23 +0000743 SmallVectorImpl<MachineBasicBlock *> &TDBBs,
744 SmallVectorImpl<MachineInstr *> &Copies) {
David Greene00dec1b2010-01-05 01:25:15 +0000745 DEBUG(dbgs() << "\n*** Tail-duplicating BB#" << TailBB->getNumber() << '\n');
Evan Cheng75eb5352009-12-07 10:15:19 +0000746
Rafael Espindola275c1f92011-06-20 04:16:35 +0000747 DenseSet<unsigned> UsedByPhi;
748 getRegsUsedByPHIs(*TailBB, &UsedByPhi);
749
Rafael Espindolad7f35fa2011-06-24 15:47:41 +0000750 if (IsSimple)
751 return duplicateSimpleBB(TailBB, TDBBs, UsedByPhi, Copies);
Rafael Espindola275c1f92011-06-20 04:16:35 +0000752
Bob Wilson15acadd2009-11-26 00:32:21 +0000753 // Iterate through all the unique predecessors and tail-duplicate this
754 // block into them, if possible. Copying the list ahead of time also
755 // avoids trouble with the predecessor list reallocating.
756 bool Changed = false;
Evan Cheng79fc6f42009-12-04 09:42:45 +0000757 SmallSetVector<MachineBasicBlock*, 8> Preds(TailBB->pred_begin(),
758 TailBB->pred_end());
Bob Wilson15acadd2009-11-26 00:32:21 +0000759 for (SmallSetVector<MachineBasicBlock *, 8>::iterator PI = Preds.begin(),
760 PE = Preds.end(); PI != PE; ++PI) {
761 MachineBasicBlock *PredBB = *PI;
762
763 assert(TailBB != PredBB &&
764 "Single-block loop should have been rejected earlier!");
Rafael Espindola9a9a3a52011-06-10 20:08:23 +0000765 // EH edges are ignored by AnalyzeBranch.
766 if (PredBB->succ_size() > 1)
767 continue;
Bob Wilson15acadd2009-11-26 00:32:21 +0000768
769 MachineBasicBlock *PredTBB, *PredFBB;
770 SmallVector<MachineOperand, 4> PredCond;
771 if (TII->AnalyzeBranch(*PredBB, PredTBB, PredFBB, PredCond, true))
772 continue;
773 if (!PredCond.empty())
774 continue;
Bob Wilson15acadd2009-11-26 00:32:21 +0000775 // Don't duplicate into a fall-through predecessor (at least for now).
776 if (PredBB->isLayoutSuccessor(TailBB) && PredBB->canFallThrough())
777 continue;
778
David Greene00dec1b2010-01-05 01:25:15 +0000779 DEBUG(dbgs() << "\nTail-duplicating into PredBB: " << *PredBB
Bob Wilson15acadd2009-11-26 00:32:21 +0000780 << "From Succ: " << *TailBB);
781
Evan Cheng75eb5352009-12-07 10:15:19 +0000782 TDBBs.push_back(PredBB);
783
Bob Wilson15acadd2009-11-26 00:32:21 +0000784 // Remove PredBB's unconditional branch.
785 TII->RemoveBranch(*PredBB);
Evan Cheng111e7622009-12-03 08:43:53 +0000786
Evan Chengeb25bd22012-05-30 00:42:39 +0000787 if (RS && !TailBB->livein_empty()) {
788 // Update PredBB livein.
789 RS->enterBasicBlock(PredBB);
790 if (!PredBB->empty())
791 RS->forward(prior(PredBB->end()));
792 BitVector RegsLiveAtExit(TRI->getNumRegs());
793 RS->getRegsUsed(RegsLiveAtExit, false);
794 for (MachineBasicBlock::livein_iterator I = TailBB->livein_begin(),
795 E = TailBB->livein_end(); I != E; ++I) {
796 if (!RegsLiveAtExit[*I])
797 // If a register is previously livein to the tail but it's not live
798 // at the end of predecessor BB, then it should be added to its
799 // livein list.
800 PredBB->addLiveIn(*I);
801 }
802 }
803
Bob Wilson15acadd2009-11-26 00:32:21 +0000804 // Clone the contents of TailBB into PredBB.
Evan Cheng111e7622009-12-03 08:43:53 +0000805 DenseMap<unsigned, unsigned> LocalVRMap;
Evan Cheng3466f132009-12-15 01:44:10 +0000806 SmallVector<std::pair<unsigned,unsigned>, 4> CopyInfos;
Evan Chengdf7e8bd2012-02-20 07:51:58 +0000807 // Use instr_iterator here to properly handle bundles, e.g.
808 // ARM Thumb2 IT block.
809 MachineBasicBlock::instr_iterator I = TailBB->instr_begin();
810 while (I != TailBB->instr_end()) {
Evan Cheng79fc6f42009-12-04 09:42:45 +0000811 MachineInstr *MI = &*I;
812 ++I;
Chris Lattner518bb532010-02-09 19:54:29 +0000813 if (MI->isPHI()) {
Evan Cheng111e7622009-12-03 08:43:53 +0000814 // Replace the uses of the def of the PHI with the register coming
815 // from PredBB.
Rafael Espindola689d7d52011-06-09 23:22:56 +0000816 ProcessPHI(MI, TailBB, PredBB, LocalVRMap, CopyInfos, UsedByPhi, true);
Evan Cheng79fc6f42009-12-04 09:42:45 +0000817 } else {
818 // Replace def of virtual registers with new registers, and update
819 // uses with PHI source register or the new registers.
Rafael Espindola0f28c3f2011-06-09 22:53:47 +0000820 DuplicateInstruction(MI, TailBB, PredBB, MF, LocalVRMap, UsedByPhi);
Evan Cheng111e7622009-12-03 08:43:53 +0000821 }
Bob Wilson15acadd2009-11-26 00:32:21 +0000822 }
Evan Cheng75eb5352009-12-07 10:15:19 +0000823 MachineBasicBlock::iterator Loc = PredBB->getFirstTerminator();
Evan Cheng3466f132009-12-15 01:44:10 +0000824 for (unsigned i = 0, e = CopyInfos.size(); i != e; ++i) {
Jakob Stoklund Olesen1e1098c2010-07-10 22:42:59 +0000825 Copies.push_back(BuildMI(*PredBB, Loc, DebugLoc(),
826 TII->get(TargetOpcode::COPY),
827 CopyInfos[i].first).addReg(CopyInfos[i].second));
Evan Cheng75eb5352009-12-07 10:15:19 +0000828 }
Rafael Espindolaec324e52011-06-17 05:54:50 +0000829
830 // Simplify
831 TII->AnalyzeBranch(*PredBB, PredTBB, PredFBB, PredCond, true);
832
Bob Wilson15acadd2009-11-26 00:32:21 +0000833 NumInstrDups += TailBB->size() - 1; // subtract one for removed branch
834
835 // Update the CFG.
836 PredBB->removeSuccessor(PredBB->succ_begin());
837 assert(PredBB->succ_empty() &&
838 "TailDuplicate called on block with multiple successors!");
839 for (MachineBasicBlock::succ_iterator I = TailBB->succ_begin(),
Evan Cheng79fc6f42009-12-04 09:42:45 +0000840 E = TailBB->succ_end(); I != E; ++I)
841 PredBB->addSuccessor(*I);
Bob Wilson15acadd2009-11-26 00:32:21 +0000842
843 Changed = true;
844 ++NumTailDups;
845 }
846
847 // If TailBB was duplicated into all its predecessors except for the prior
848 // block, which falls through unconditionally, move the contents of this
849 // block into the prior block.
Evan Cheng79fc6f42009-12-04 09:42:45 +0000850 MachineBasicBlock *PrevBB = prior(MachineFunction::iterator(TailBB));
Bob Wilson15acadd2009-11-26 00:32:21 +0000851 MachineBasicBlock *PriorTBB = 0, *PriorFBB = 0;
852 SmallVector<MachineOperand, 4> PriorCond;
Bob Wilson15acadd2009-11-26 00:32:21 +0000853 // This has to check PrevBB->succ_size() because EH edges are ignored by
854 // AnalyzeBranch.
Andrew Trickd2a7bed2012-02-08 21:22:30 +0000855 if (PrevBB->succ_size() == 1 &&
Rafael Espindolaa899b222011-06-09 21:43:25 +0000856 !TII->AnalyzeBranch(*PrevBB, PriorTBB, PriorFBB, PriorCond, true) &&
857 PriorCond.empty() && !PriorTBB && TailBB->pred_size() == 1 &&
Bob Wilson15acadd2009-11-26 00:32:21 +0000858 !TailBB->hasAddressTaken()) {
David Greene00dec1b2010-01-05 01:25:15 +0000859 DEBUG(dbgs() << "\nMerging into block: " << *PrevBB
Bob Wilson15acadd2009-11-26 00:32:21 +0000860 << "From MBB: " << *TailBB);
Evan Cheng79fc6f42009-12-04 09:42:45 +0000861 if (PreRegAlloc) {
862 DenseMap<unsigned, unsigned> LocalVRMap;
Evan Cheng3466f132009-12-15 01:44:10 +0000863 SmallVector<std::pair<unsigned,unsigned>, 4> CopyInfos;
Evan Cheng79fc6f42009-12-04 09:42:45 +0000864 MachineBasicBlock::iterator I = TailBB->begin();
865 // Process PHI instructions first.
Chris Lattner518bb532010-02-09 19:54:29 +0000866 while (I != TailBB->end() && I->isPHI()) {
Evan Cheng79fc6f42009-12-04 09:42:45 +0000867 // Replace the uses of the def of the PHI with the register coming
868 // from PredBB.
869 MachineInstr *MI = &*I++;
Rafael Espindola689d7d52011-06-09 23:22:56 +0000870 ProcessPHI(MI, TailBB, PrevBB, LocalVRMap, CopyInfos, UsedByPhi, true);
Evan Cheng79fc6f42009-12-04 09:42:45 +0000871 if (MI->getParent())
872 MI->eraseFromParent();
873 }
874
875 // Now copy the non-PHI instructions.
876 while (I != TailBB->end()) {
877 // Replace def of virtual registers with new registers, and update
878 // uses with PHI source register or the new registers.
879 MachineInstr *MI = &*I++;
Evan Chengdf7e8bd2012-02-20 07:51:58 +0000880 assert(!MI->isBundle() && "Not expecting bundles before regalloc!");
Rafael Espindola0f28c3f2011-06-09 22:53:47 +0000881 DuplicateInstruction(MI, TailBB, PrevBB, MF, LocalVRMap, UsedByPhi);
Evan Cheng79fc6f42009-12-04 09:42:45 +0000882 MI->eraseFromParent();
883 }
Evan Cheng75eb5352009-12-07 10:15:19 +0000884 MachineBasicBlock::iterator Loc = PrevBB->getFirstTerminator();
Evan Cheng3466f132009-12-15 01:44:10 +0000885 for (unsigned i = 0, e = CopyInfos.size(); i != e; ++i) {
Jakob Stoklund Olesen1e1098c2010-07-10 22:42:59 +0000886 Copies.push_back(BuildMI(*PrevBB, Loc, DebugLoc(),
887 TII->get(TargetOpcode::COPY),
888 CopyInfos[i].first)
889 .addReg(CopyInfos[i].second));
Evan Cheng75eb5352009-12-07 10:15:19 +0000890 }
Evan Cheng79fc6f42009-12-04 09:42:45 +0000891 } else {
892 // No PHIs to worry about, just splice the instructions over.
893 PrevBB->splice(PrevBB->end(), TailBB, TailBB->begin(), TailBB->end());
894 }
895 PrevBB->removeSuccessor(PrevBB->succ_begin());
896 assert(PrevBB->succ_empty());
897 PrevBB->transferSuccessors(TailBB);
Evan Cheng75eb5352009-12-07 10:15:19 +0000898 TDBBs.push_back(PrevBB);
Bob Wilson15acadd2009-11-26 00:32:21 +0000899 Changed = true;
900 }
901
Rafael Espindola689d7d52011-06-09 23:22:56 +0000902 // If this is after register allocation, there are no phis to fix.
903 if (!PreRegAlloc)
904 return Changed;
905
906 // If we made no changes so far, we are safe.
907 if (!Changed)
908 return Changed;
909
910
911 // Handle the nasty case in that we duplicated a block that is part of a loop
912 // into some but not all of its predecessors. For example:
Rafael Espindola4d7b4572011-06-09 23:51:45 +0000913 // 1 -> 2 <-> 3 |
914 // \ |
915 // \---> rest |
Rafael Espindola689d7d52011-06-09 23:22:56 +0000916 // if we duplicate 2 into 1 but not into 3, we end up with
Rafael Espindola4d7b4572011-06-09 23:51:45 +0000917 // 12 -> 3 <-> 2 -> rest |
918 // \ / |
919 // \----->-----/ |
Rafael Espindola689d7d52011-06-09 23:22:56 +0000920 // If there was a "var = phi(1, 3)" in 2, it has to be ultimately replaced
921 // with a phi in 3 (which now dominates 2).
922 // What we do here is introduce a copy in 3 of the register defined by the
923 // phi, just like when we are duplicating 2 into 3, but we don't copy any
924 // real instructions or remove the 3 -> 2 edge from the phi in 2.
925 for (SmallSetVector<MachineBasicBlock *, 8>::iterator PI = Preds.begin(),
926 PE = Preds.end(); PI != PE; ++PI) {
927 MachineBasicBlock *PredBB = *PI;
928 if (std::find(TDBBs.begin(), TDBBs.end(), PredBB) != TDBBs.end())
929 continue;
930
931 // EH edges
932 if (PredBB->succ_size() != 1)
933 continue;
934
935 DenseMap<unsigned, unsigned> LocalVRMap;
936 SmallVector<std::pair<unsigned,unsigned>, 4> CopyInfos;
937 MachineBasicBlock::iterator I = TailBB->begin();
938 // Process PHI instructions first.
939 while (I != TailBB->end() && I->isPHI()) {
940 // Replace the uses of the def of the PHI with the register coming
941 // from PredBB.
942 MachineInstr *MI = &*I++;
943 ProcessPHI(MI, TailBB, PredBB, LocalVRMap, CopyInfos, UsedByPhi, false);
944 }
945 MachineBasicBlock::iterator Loc = PredBB->getFirstTerminator();
946 for (unsigned i = 0, e = CopyInfos.size(); i != e; ++i) {
947 Copies.push_back(BuildMI(*PredBB, Loc, DebugLoc(),
948 TII->get(TargetOpcode::COPY),
949 CopyInfos[i].first).addReg(CopyInfos[i].second));
950 }
951 }
952
Bob Wilson15acadd2009-11-26 00:32:21 +0000953 return Changed;
954}
955
956/// RemoveDeadBlock - Remove the specified dead machine basic block from the
957/// function, updating the CFG.
Bob Wilson2d521e52009-11-26 21:38:41 +0000958void TailDuplicatePass::RemoveDeadBlock(MachineBasicBlock *MBB) {
Bob Wilson15acadd2009-11-26 00:32:21 +0000959 assert(MBB->pred_empty() && "MBB must be dead!");
David Greene00dec1b2010-01-05 01:25:15 +0000960 DEBUG(dbgs() << "\nRemoving MBB: " << *MBB);
Bob Wilson15acadd2009-11-26 00:32:21 +0000961
962 // Remove all successors.
963 while (!MBB->succ_empty())
964 MBB->removeSuccessor(MBB->succ_end()-1);
965
Bob Wilson15acadd2009-11-26 00:32:21 +0000966 // Remove the block.
967 MBB->eraseFromParent();
968}