blob: d077b091937dc1eb0b35edcb1db30f4888d9d45b [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"
Evan Chengeb25bd22012-05-30 00:42:39 +000023#include "llvm/CodeGen/RegisterScavenging.h"
Bob Wilson15acadd2009-11-26 00:32:21 +000024#include "llvm/Target/TargetInstrInfo.h"
Evan Chengeb25bd22012-05-30 00:42:39 +000025#include "llvm/Target/TargetRegisterInfo.h"
Bob Wilson15acadd2009-11-26 00:32:21 +000026#include "llvm/Support/CommandLine.h"
27#include "llvm/Support/Debug.h"
Evan Cheng75eb5352009-12-07 10:15:19 +000028#include "llvm/Support/ErrorHandling.h"
Bob Wilson15acadd2009-11-26 00:32:21 +000029#include "llvm/Support/raw_ostream.h"
Jakob Stoklund Olesenc66d3602011-08-09 23:49:21 +000030#include "llvm/ADT/DenseSet.h"
Bob Wilson15acadd2009-11-26 00:32:21 +000031#include "llvm/ADT/SmallSet.h"
32#include "llvm/ADT/SetVector.h"
33#include "llvm/ADT/Statistic.h"
34using namespace llvm;
35
Evan Cheng75eb5352009-12-07 10:15:19 +000036STATISTIC(NumTails , "Number of tails duplicated");
Bob Wilson15acadd2009-11-26 00:32:21 +000037STATISTIC(NumTailDups , "Number of tail duplicated blocks");
38STATISTIC(NumInstrDups , "Additional instructions due to tail duplication");
39STATISTIC(NumDeadBlocks, "Number of dead blocks removed");
Rafael Espindola0cdca082011-06-08 14:13:31 +000040STATISTIC(NumAddedPHIs , "Number of phis added");
Bob Wilson15acadd2009-11-26 00:32:21 +000041
42// Heuristic for tail duplication.
43static cl::opt<unsigned>
44TailDuplicateSize("tail-dup-size",
45 cl::desc("Maximum instructions to consider tail duplicating"),
46 cl::init(2), cl::Hidden);
47
Evan Cheng75eb5352009-12-07 10:15:19 +000048static cl::opt<bool>
49TailDupVerify("tail-dup-verify",
50 cl::desc("Verify sanity of PHI instructions during taildup"),
51 cl::init(false), cl::Hidden);
52
53static cl::opt<unsigned>
54TailDupLimit("tail-dup-limit", cl::init(~0U), cl::Hidden);
55
Evan Cheng11572ba2009-12-04 19:09:10 +000056typedef std::vector<std::pair<MachineBasicBlock*,unsigned> > AvailableValsTy;
Evan Cheng111e7622009-12-03 08:43:53 +000057
Bob Wilson15acadd2009-11-26 00:32:21 +000058namespace {
Bob Wilson2d521e52009-11-26 21:38:41 +000059 /// TailDuplicatePass - Perform tail duplication.
60 class TailDuplicatePass : public MachineFunctionPass {
Bob Wilson15acadd2009-11-26 00:32:21 +000061 const TargetInstrInfo *TII;
Evan Chengeb25bd22012-05-30 00:42:39 +000062 const TargetRegisterInfo *TRI;
Bob Wilson15acadd2009-11-26 00:32:21 +000063 MachineModuleInfo *MMI;
Evan Cheng111e7622009-12-03 08:43:53 +000064 MachineRegisterInfo *MRI;
Evan Chengeb25bd22012-05-30 00:42:39 +000065 RegScavenger *RS;
Andrew Trickd2a7bed2012-02-08 21:22:30 +000066 bool PreRegAlloc;
Evan Cheng111e7622009-12-03 08:43:53 +000067
68 // SSAUpdateVRs - A list of virtual registers for which to update SSA form.
69 SmallVector<unsigned, 16> SSAUpdateVRs;
70
71 // SSAUpdateVals - For each virtual register in SSAUpdateVals keep a list of
72 // source virtual registers.
73 DenseMap<unsigned, AvailableValsTy> SSAUpdateVals;
Bob Wilson15acadd2009-11-26 00:32:21 +000074
75 public:
76 static char ID;
Andrew Trickd2a7bed2012-02-08 21:22:30 +000077 explicit TailDuplicatePass() :
78 MachineFunctionPass(ID), PreRegAlloc(false) {}
Bob Wilson15acadd2009-11-26 00:32:21 +000079
80 virtual bool runOnMachineFunction(MachineFunction &MF);
Bob Wilson15acadd2009-11-26 00:32:21 +000081
82 private:
Evan Cheng11572ba2009-12-04 19:09:10 +000083 void AddSSAUpdateEntry(unsigned OrigReg, unsigned NewReg,
84 MachineBasicBlock *BB);
Evan Cheng79fc6f42009-12-04 09:42:45 +000085 void ProcessPHI(MachineInstr *MI, MachineBasicBlock *TailBB,
86 MachineBasicBlock *PredBB,
Evan Cheng75eb5352009-12-07 10:15:19 +000087 DenseMap<unsigned, unsigned> &LocalVRMap,
Rafael Espindola0f28c3f2011-06-09 22:53:47 +000088 SmallVector<std::pair<unsigned,unsigned>, 4> &Copies,
Rafael Espindola689d7d52011-06-09 23:22:56 +000089 const DenseSet<unsigned> &UsedByPhi,
90 bool Remove);
Evan Cheng79fc6f42009-12-04 09:42:45 +000091 void DuplicateInstruction(MachineInstr *MI,
92 MachineBasicBlock *TailBB,
93 MachineBasicBlock *PredBB,
94 MachineFunction &MF,
Rafael Espindola0f28c3f2011-06-09 22:53:47 +000095 DenseMap<unsigned, unsigned> &LocalVRMap,
96 const DenseSet<unsigned> &UsedByPhi);
Evan Cheng75eb5352009-12-07 10:15:19 +000097 void UpdateSuccessorsPHIs(MachineBasicBlock *FromBB, bool isDead,
98 SmallVector<MachineBasicBlock*, 8> &TDBBs,
99 SmallSetVector<MachineBasicBlock*, 8> &Succs);
Bob Wilson15acadd2009-11-26 00:32:21 +0000100 bool TailDuplicateBlocks(MachineFunction &MF);
Rafael Espindola54c25622011-06-09 19:54:42 +0000101 bool shouldTailDuplicate(const MachineFunction &MF,
Rafael Espindola9dbbd872011-06-23 03:41:29 +0000102 bool IsSimple, MachineBasicBlock &TailBB);
Rafael Espindola275c1f92011-06-20 04:16:35 +0000103 bool isSimpleBB(MachineBasicBlock *TailBB);
Rafael Espindola40179bf2011-06-24 15:50:56 +0000104 bool canCompletelyDuplicateBB(MachineBasicBlock &BB);
Rafael Espindolad7f35fa2011-06-24 15:47:41 +0000105 bool duplicateSimpleBB(MachineBasicBlock *TailBB,
Rafael Espindola275c1f92011-06-20 04:16:35 +0000106 SmallVector<MachineBasicBlock*, 8> &TDBBs,
107 const DenseSet<unsigned> &RegsUsedByPhi,
108 SmallVector<MachineInstr*, 16> &Copies);
Rafael Espindola6a9d2b12011-07-04 01:21:42 +0000109 bool TailDuplicate(MachineBasicBlock *TailBB,
110 bool IsSimple,
111 MachineFunction &MF,
Evan Cheng3466f132009-12-15 01:44:10 +0000112 SmallVector<MachineBasicBlock*, 8> &TDBBs,
113 SmallVector<MachineInstr*, 16> &Copies);
Rafael Espindola6a9d2b12011-07-04 01:21:42 +0000114 bool TailDuplicateAndUpdate(MachineBasicBlock *MBB,
115 bool IsSimple,
116 MachineFunction &MF);
117
Bob Wilson15acadd2009-11-26 00:32:21 +0000118 void RemoveDeadBlock(MachineBasicBlock *MBB);
119 };
120
Bob Wilson2d521e52009-11-26 21:38:41 +0000121 char TailDuplicatePass::ID = 0;
Bob Wilson15acadd2009-11-26 00:32:21 +0000122}
123
Andrew Trick1dd8c852012-02-08 21:23:13 +0000124char &llvm::TailDuplicateID = TailDuplicatePass::ID;
125
126INITIALIZE_PASS(TailDuplicatePass, "tailduplication", "Tail Duplication",
127 false, false)
Bob Wilson15acadd2009-11-26 00:32:21 +0000128
Bob Wilson2d521e52009-11-26 21:38:41 +0000129bool TailDuplicatePass::runOnMachineFunction(MachineFunction &MF) {
Bob Wilson15acadd2009-11-26 00:32:21 +0000130 TII = MF.getTarget().getInstrInfo();
Evan Chengeb25bd22012-05-30 00:42:39 +0000131 TRI = MF.getTarget().getRegisterInfo();
Evan Cheng111e7622009-12-03 08:43:53 +0000132 MRI = &MF.getRegInfo();
Bob Wilson15acadd2009-11-26 00:32:21 +0000133 MMI = getAnalysisIfAvailable<MachineModuleInfo>();
Andrew Trickd2a7bed2012-02-08 21:22:30 +0000134 PreRegAlloc = MRI->isSSA();
Evan Chengeb25bd22012-05-30 00:42:39 +0000135 RS = NULL;
136 if (MRI->tracksLiveness() && TRI->trackLivenessAfterRegAlloc(MF))
137 RS = new RegScavenger();
Bob Wilson15acadd2009-11-26 00:32:21 +0000138
139 bool MadeChange = false;
Jakob Stoklund Olesen057d5392010-01-15 19:59:57 +0000140 while (TailDuplicateBlocks(MF))
141 MadeChange = true;
Bob Wilson15acadd2009-11-26 00:32:21 +0000142
143 return MadeChange;
144}
145
Evan Cheng75eb5352009-12-07 10:15:19 +0000146static void VerifyPHIs(MachineFunction &MF, bool CheckExtra) {
147 for (MachineFunction::iterator I = ++MF.begin(), E = MF.end(); I != E; ++I) {
148 MachineBasicBlock *MBB = I;
149 SmallSetVector<MachineBasicBlock*, 8> Preds(MBB->pred_begin(),
150 MBB->pred_end());
151 MachineBasicBlock::iterator MI = MBB->begin();
152 while (MI != MBB->end()) {
Chris Lattner518bb532010-02-09 19:54:29 +0000153 if (!MI->isPHI())
Evan Cheng75eb5352009-12-07 10:15:19 +0000154 break;
155 for (SmallSetVector<MachineBasicBlock *, 8>::iterator PI = Preds.begin(),
156 PE = Preds.end(); PI != PE; ++PI) {
157 MachineBasicBlock *PredBB = *PI;
158 bool Found = false;
159 for (unsigned i = 1, e = MI->getNumOperands(); i != e; i += 2) {
160 MachineBasicBlock *PHIBB = MI->getOperand(i+1).getMBB();
161 if (PHIBB == PredBB) {
162 Found = true;
163 break;
164 }
165 }
166 if (!Found) {
David Greene00dec1b2010-01-05 01:25:15 +0000167 dbgs() << "Malformed PHI in BB#" << MBB->getNumber() << ": " << *MI;
168 dbgs() << " missing input from predecessor BB#"
Evan Cheng75eb5352009-12-07 10:15:19 +0000169 << PredBB->getNumber() << '\n';
170 llvm_unreachable(0);
171 }
172 }
173
174 for (unsigned i = 1, e = MI->getNumOperands(); i != e; i += 2) {
175 MachineBasicBlock *PHIBB = MI->getOperand(i+1).getMBB();
176 if (CheckExtra && !Preds.count(PHIBB)) {
David Greene00dec1b2010-01-05 01:25:15 +0000177 dbgs() << "Warning: malformed PHI in BB#" << MBB->getNumber()
Evan Cheng75eb5352009-12-07 10:15:19 +0000178 << ": " << *MI;
David Greene00dec1b2010-01-05 01:25:15 +0000179 dbgs() << " extra input from predecessor BB#"
Evan Cheng75eb5352009-12-07 10:15:19 +0000180 << PHIBB->getNumber() << '\n';
Rafael Espindolad3f4eea2011-06-09 23:55:56 +0000181 llvm_unreachable(0);
Evan Cheng75eb5352009-12-07 10:15:19 +0000182 }
183 if (PHIBB->getNumber() < 0) {
David Greene00dec1b2010-01-05 01:25:15 +0000184 dbgs() << "Malformed PHI in BB#" << MBB->getNumber() << ": " << *MI;
185 dbgs() << " non-existing BB#" << PHIBB->getNumber() << '\n';
Evan Cheng75eb5352009-12-07 10:15:19 +0000186 llvm_unreachable(0);
187 }
188 }
189 ++MI;
190 }
191 }
192}
193
Rafael Espindola6a9d2b12011-07-04 01:21:42 +0000194/// TailDuplicateAndUpdate - Tail duplicate the block and cleanup.
195bool
196TailDuplicatePass::TailDuplicateAndUpdate(MachineBasicBlock *MBB,
197 bool IsSimple,
198 MachineFunction &MF) {
199 // Save the successors list.
200 SmallSetVector<MachineBasicBlock*, 8> Succs(MBB->succ_begin(),
201 MBB->succ_end());
202
203 SmallVector<MachineBasicBlock*, 8> TDBBs;
204 SmallVector<MachineInstr*, 16> Copies;
205 if (!TailDuplicate(MBB, IsSimple, MF, TDBBs, Copies))
206 return false;
207
208 ++NumTails;
209
210 SmallVector<MachineInstr*, 8> NewPHIs;
211 MachineSSAUpdater SSAUpdate(MF, &NewPHIs);
212
213 // TailBB's immediate successors are now successors of those predecessors
214 // which duplicated TailBB. Add the predecessors as sources to the PHI
215 // instructions.
216 bool isDead = MBB->pred_empty() && !MBB->hasAddressTaken();
217 if (PreRegAlloc)
218 UpdateSuccessorsPHIs(MBB, isDead, TDBBs, Succs);
219
220 // If it is dead, remove it.
221 if (isDead) {
222 NumInstrDups -= MBB->size();
223 RemoveDeadBlock(MBB);
224 ++NumDeadBlocks;
225 }
226
227 // Update SSA form.
228 if (!SSAUpdateVRs.empty()) {
229 for (unsigned i = 0, e = SSAUpdateVRs.size(); i != e; ++i) {
230 unsigned VReg = SSAUpdateVRs[i];
231 SSAUpdate.Initialize(VReg);
232
233 // If the original definition is still around, add it as an available
234 // value.
235 MachineInstr *DefMI = MRI->getVRegDef(VReg);
236 MachineBasicBlock *DefBB = 0;
237 if (DefMI) {
238 DefBB = DefMI->getParent();
239 SSAUpdate.AddAvailableValue(DefBB, VReg);
240 }
241
242 // Add the new vregs as available values.
243 DenseMap<unsigned, AvailableValsTy>::iterator LI =
244 SSAUpdateVals.find(VReg);
245 for (unsigned j = 0, ee = LI->second.size(); j != ee; ++j) {
246 MachineBasicBlock *SrcBB = LI->second[j].first;
247 unsigned SrcReg = LI->second[j].second;
248 SSAUpdate.AddAvailableValue(SrcBB, SrcReg);
249 }
250
251 // Rewrite uses that are outside of the original def's block.
252 MachineRegisterInfo::use_iterator UI = MRI->use_begin(VReg);
253 while (UI != MRI->use_end()) {
254 MachineOperand &UseMO = UI.getOperand();
255 MachineInstr *UseMI = &*UI;
256 ++UI;
257 if (UseMI->isDebugValue()) {
258 // SSAUpdate can replace the use with an undef. That creates
259 // a debug instruction that is a kill.
260 // FIXME: Should it SSAUpdate job to delete debug instructions
261 // instead of replacing the use with undef?
262 UseMI->eraseFromParent();
263 continue;
264 }
265 if (UseMI->getParent() == DefBB && !UseMI->isPHI())
266 continue;
267 SSAUpdate.RewriteUse(UseMO);
268 }
269 }
270
271 SSAUpdateVRs.clear();
272 SSAUpdateVals.clear();
273 }
274
275 // Eliminate some of the copies inserted by tail duplication to maintain
276 // SSA form.
277 for (unsigned i = 0, e = Copies.size(); i != e; ++i) {
278 MachineInstr *Copy = Copies[i];
279 if (!Copy->isCopy())
280 continue;
281 unsigned Dst = Copy->getOperand(0).getReg();
282 unsigned Src = Copy->getOperand(1).getReg();
Jakob Stoklund Olesen0fda5452012-05-20 18:42:51 +0000283 if (MRI->hasOneNonDBGUse(Src) &&
284 MRI->constrainRegClass(Src, MRI->getRegClass(Dst))) {
Rafael Espindola6a9d2b12011-07-04 01:21:42 +0000285 // Copy is the only use. Do trivial copy propagation here.
286 MRI->replaceRegWith(Dst, Src);
287 Copy->eraseFromParent();
288 }
289 }
290
291 if (NewPHIs.size())
292 NumAddedPHIs += NewPHIs.size();
293
294 return true;
295}
296
Bob Wilson15acadd2009-11-26 00:32:21 +0000297/// TailDuplicateBlocks - Look for small blocks that are unconditionally
298/// branched to and do not fall through. Tail-duplicate their instructions
299/// into their predecessors to eliminate (dynamic) branches.
Bob Wilson2d521e52009-11-26 21:38:41 +0000300bool TailDuplicatePass::TailDuplicateBlocks(MachineFunction &MF) {
Bob Wilson15acadd2009-11-26 00:32:21 +0000301 bool MadeChange = false;
302
Evan Cheng75eb5352009-12-07 10:15:19 +0000303 if (PreRegAlloc && TailDupVerify) {
David Greene00dec1b2010-01-05 01:25:15 +0000304 DEBUG(dbgs() << "\n*** Before tail-duplicating\n");
Evan Cheng75eb5352009-12-07 10:15:19 +0000305 VerifyPHIs(MF, true);
306 }
307
Bob Wilson15acadd2009-11-26 00:32:21 +0000308 for (MachineFunction::iterator I = ++MF.begin(), E = MF.end(); I != E; ) {
309 MachineBasicBlock *MBB = I++;
310
Evan Cheng75eb5352009-12-07 10:15:19 +0000311 if (NumTails == TailDupLimit)
312 break;
313
Rafael Espindola6a9d2b12011-07-04 01:21:42 +0000314 bool IsSimple = isSimpleBB(MBB);
Bob Wilson15acadd2009-11-26 00:32:21 +0000315
Rafael Espindola6a9d2b12011-07-04 01:21:42 +0000316 if (!shouldTailDuplicate(MF, IsSimple, *MBB))
Rafael Espindolac0af3522011-07-04 00:13:36 +0000317 continue;
Evan Cheng75eb5352009-12-07 10:15:19 +0000318
Rafael Espindola6a9d2b12011-07-04 01:21:42 +0000319 MadeChange |= TailDuplicateAndUpdate(MBB, IsSimple, MF);
Bob Wilson15acadd2009-11-26 00:32:21 +0000320 }
Rafael Espindolac0af3522011-07-04 00:13:36 +0000321
Rafael Espindola6a9d2b12011-07-04 01:21:42 +0000322 if (PreRegAlloc && TailDupVerify)
323 VerifyPHIs(MF, false);
Evan Cheng111e7622009-12-03 08:43:53 +0000324
Bob Wilson15acadd2009-11-26 00:32:21 +0000325 return MadeChange;
326}
327
Evan Cheng111e7622009-12-03 08:43:53 +0000328static bool isDefLiveOut(unsigned Reg, MachineBasicBlock *BB,
329 const MachineRegisterInfo *MRI) {
330 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(Reg),
331 UE = MRI->use_end(); UI != UE; ++UI) {
332 MachineInstr *UseMI = &*UI;
Rafael Espindoladb3983b2011-06-17 13:59:43 +0000333 if (UseMI->isDebugValue())
334 continue;
Evan Cheng111e7622009-12-03 08:43:53 +0000335 if (UseMI->getParent() != BB)
336 return true;
337 }
338 return false;
339}
340
341static unsigned getPHISrcRegOpIdx(MachineInstr *MI, MachineBasicBlock *SrcBB) {
342 for (unsigned i = 1, e = MI->getNumOperands(); i != e; i += 2)
343 if (MI->getOperand(i+1).getMBB() == SrcBB)
344 return i;
345 return 0;
346}
347
Rafael Espindola0f28c3f2011-06-09 22:53:47 +0000348
349// Remember which registers are used by phis in this block. This is
350// used to determine which registers are liveout while modifying the
351// block (which is why we need to copy the information).
352static void getRegsUsedByPHIs(const MachineBasicBlock &BB,
Rafael Espindola33b46582011-06-10 21:01:53 +0000353 DenseSet<unsigned> *UsedByPhi) {
Rafael Espindola0f28c3f2011-06-09 22:53:47 +0000354 for(MachineBasicBlock::const_iterator I = BB.begin(), E = BB.end();
355 I != E; ++I) {
356 const MachineInstr &MI = *I;
357 if (!MI.isPHI())
358 break;
359 for (unsigned i = 1, e = MI.getNumOperands(); i != e; i += 2) {
360 unsigned SrcReg = MI.getOperand(i).getReg();
361 UsedByPhi->insert(SrcReg);
362 }
363 }
364}
365
Evan Cheng111e7622009-12-03 08:43:53 +0000366/// AddSSAUpdateEntry - Add a definition and source virtual registers pair for
367/// SSA update.
Evan Cheng11572ba2009-12-04 19:09:10 +0000368void TailDuplicatePass::AddSSAUpdateEntry(unsigned OrigReg, unsigned NewReg,
369 MachineBasicBlock *BB) {
370 DenseMap<unsigned, AvailableValsTy>::iterator LI= SSAUpdateVals.find(OrigReg);
Evan Cheng111e7622009-12-03 08:43:53 +0000371 if (LI != SSAUpdateVals.end())
Evan Cheng11572ba2009-12-04 19:09:10 +0000372 LI->second.push_back(std::make_pair(BB, NewReg));
Evan Cheng111e7622009-12-03 08:43:53 +0000373 else {
374 AvailableValsTy Vals;
Evan Cheng11572ba2009-12-04 19:09:10 +0000375 Vals.push_back(std::make_pair(BB, NewReg));
Evan Cheng111e7622009-12-03 08:43:53 +0000376 SSAUpdateVals.insert(std::make_pair(OrigReg, Vals));
377 SSAUpdateVRs.push_back(OrigReg);
378 }
379}
380
Evan Cheng75eb5352009-12-07 10:15:19 +0000381/// ProcessPHI - Process PHI node in TailBB by turning it into a copy in PredBB.
382/// Remember the source register that's contributed by PredBB and update SSA
383/// update map.
Evan Cheng79fc6f42009-12-04 09:42:45 +0000384void TailDuplicatePass::ProcessPHI(MachineInstr *MI,
385 MachineBasicBlock *TailBB,
386 MachineBasicBlock *PredBB,
Evan Cheng75eb5352009-12-07 10:15:19 +0000387 DenseMap<unsigned, unsigned> &LocalVRMap,
Rafael Espindola0f28c3f2011-06-09 22:53:47 +0000388 SmallVector<std::pair<unsigned,unsigned>, 4> &Copies,
Rafael Espindola33b46582011-06-10 21:01:53 +0000389 const DenseSet<unsigned> &RegsUsedByPhi,
Rafael Espindola689d7d52011-06-09 23:22:56 +0000390 bool Remove) {
Evan Cheng79fc6f42009-12-04 09:42:45 +0000391 unsigned DefReg = MI->getOperand(0).getReg();
392 unsigned SrcOpIdx = getPHISrcRegOpIdx(MI, PredBB);
393 assert(SrcOpIdx && "Unable to find matching PHI source?");
394 unsigned SrcReg = MI->getOperand(SrcOpIdx).getReg();
Evan Cheng75eb5352009-12-07 10:15:19 +0000395 const TargetRegisterClass *RC = MRI->getRegClass(DefReg);
Evan Cheng79fc6f42009-12-04 09:42:45 +0000396 LocalVRMap.insert(std::make_pair(DefReg, SrcReg));
Evan Cheng75eb5352009-12-07 10:15:19 +0000397
398 // Insert a copy from source to the end of the block. The def register is the
399 // available value liveout of the block.
400 unsigned NewDef = MRI->createVirtualRegister(RC);
401 Copies.push_back(std::make_pair(NewDef, SrcReg));
Rafael Espindola0f28c3f2011-06-09 22:53:47 +0000402 if (isDefLiveOut(DefReg, TailBB, MRI) || RegsUsedByPhi.count(DefReg))
Evan Cheng75eb5352009-12-07 10:15:19 +0000403 AddSSAUpdateEntry(DefReg, NewDef, PredBB);
Evan Cheng79fc6f42009-12-04 09:42:45 +0000404
Rafael Espindola689d7d52011-06-09 23:22:56 +0000405 if (!Remove)
406 return;
407
Evan Cheng79fc6f42009-12-04 09:42:45 +0000408 // Remove PredBB from the PHI node.
409 MI->RemoveOperand(SrcOpIdx+1);
410 MI->RemoveOperand(SrcOpIdx);
411 if (MI->getNumOperands() == 1)
412 MI->eraseFromParent();
413}
414
415/// DuplicateInstruction - Duplicate a TailBB instruction to PredBB and update
416/// the source operands due to earlier PHI translation.
417void TailDuplicatePass::DuplicateInstruction(MachineInstr *MI,
418 MachineBasicBlock *TailBB,
419 MachineBasicBlock *PredBB,
420 MachineFunction &MF,
Rafael Espindola0f28c3f2011-06-09 22:53:47 +0000421 DenseMap<unsigned, unsigned> &LocalVRMap,
422 const DenseSet<unsigned> &UsedByPhi) {
Jakob Stoklund Olesen30ac0462010-01-06 23:47:07 +0000423 MachineInstr *NewMI = TII->duplicate(MI, MF);
Evan Cheng79fc6f42009-12-04 09:42:45 +0000424 for (unsigned i = 0, e = NewMI->getNumOperands(); i != e; ++i) {
425 MachineOperand &MO = NewMI->getOperand(i);
426 if (!MO.isReg())
427 continue;
428 unsigned Reg = MO.getReg();
Jakob Stoklund Olesenc9df0252011-01-10 02:58:51 +0000429 if (!TargetRegisterInfo::isVirtualRegister(Reg))
Evan Cheng79fc6f42009-12-04 09:42:45 +0000430 continue;
431 if (MO.isDef()) {
432 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
433 unsigned NewReg = MRI->createVirtualRegister(RC);
434 MO.setReg(NewReg);
435 LocalVRMap.insert(std::make_pair(Reg, NewReg));
Rafael Espindola0f28c3f2011-06-09 22:53:47 +0000436 if (isDefLiveOut(Reg, TailBB, MRI) || UsedByPhi.count(Reg))
Evan Cheng11572ba2009-12-04 19:09:10 +0000437 AddSSAUpdateEntry(Reg, NewReg, PredBB);
Evan Cheng79fc6f42009-12-04 09:42:45 +0000438 } else {
439 DenseMap<unsigned, unsigned>::iterator VI = LocalVRMap.find(Reg);
Jakob Stoklund Olesen0fda5452012-05-20 18:42:51 +0000440 if (VI != LocalVRMap.end()) {
Evan Cheng79fc6f42009-12-04 09:42:45 +0000441 MO.setReg(VI->second);
Jakob Stoklund Olesen0fda5452012-05-20 18:42:51 +0000442 MRI->constrainRegClass(VI->second, MRI->getRegClass(Reg));
443 }
Evan Cheng79fc6f42009-12-04 09:42:45 +0000444 }
445 }
Evan Chengdf7e8bd2012-02-20 07:51:58 +0000446 PredBB->insert(PredBB->instr_end(), NewMI);
Evan Cheng79fc6f42009-12-04 09:42:45 +0000447}
448
449/// UpdateSuccessorsPHIs - After FromBB is tail duplicated into its predecessor
450/// blocks, the successors have gained new predecessors. Update the PHI
451/// instructions in them accordingly.
Evan Cheng75eb5352009-12-07 10:15:19 +0000452void
453TailDuplicatePass::UpdateSuccessorsPHIs(MachineBasicBlock *FromBB, bool isDead,
454 SmallVector<MachineBasicBlock*, 8> &TDBBs,
Evan Cheng79fc6f42009-12-04 09:42:45 +0000455 SmallSetVector<MachineBasicBlock*,8> &Succs) {
456 for (SmallSetVector<MachineBasicBlock*, 8>::iterator SI = Succs.begin(),
457 SE = Succs.end(); SI != SE; ++SI) {
458 MachineBasicBlock *SuccBB = *SI;
459 for (MachineBasicBlock::iterator II = SuccBB->begin(), EE = SuccBB->end();
460 II != EE; ++II) {
Chris Lattner518bb532010-02-09 19:54:29 +0000461 if (!II->isPHI())
Evan Cheng79fc6f42009-12-04 09:42:45 +0000462 break;
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 {
510 II->addOperand(MachineOperand::CreateReg(SrcReg, false));
511 II->addOperand(MachineOperand::CreateMBB(SrcBB));
512 }
Evan Cheng79fc6f42009-12-04 09:42:45 +0000513 }
Evan Cheng75eb5352009-12-07 10:15:19 +0000514 } else {
515 // Live in tail block, must also be live in predecessors.
516 for (unsigned j = 0, ee = TDBBs.size(); j != ee; ++j) {
517 MachineBasicBlock *SrcBB = TDBBs[j];
Jakob Stoklund Olesen09eeac92010-02-11 00:34:33 +0000518 if (Idx != 0) {
519 II->getOperand(Idx).setReg(Reg);
520 II->getOperand(Idx+1).setMBB(SrcBB);
521 Idx = 0;
522 } else {
523 II->addOperand(MachineOperand::CreateReg(Reg, false));
524 II->addOperand(MachineOperand::CreateMBB(SrcBB));
525 }
Evan Cheng75eb5352009-12-07 10:15:19 +0000526 }
Evan Cheng79fc6f42009-12-04 09:42:45 +0000527 }
Jakob Stoklund Olesen09eeac92010-02-11 00:34:33 +0000528 if (Idx != 0) {
529 II->RemoveOperand(Idx+1);
530 II->RemoveOperand(Idx);
531 }
Evan Cheng79fc6f42009-12-04 09:42:45 +0000532 }
533 }
534}
535
Rafael Espindola54c25622011-06-09 19:54:42 +0000536/// shouldTailDuplicate - Determine if it is profitable to duplicate this block.
Evan Cheng75eb5352009-12-07 10:15:19 +0000537bool
Rafael Espindola54c25622011-06-09 19:54:42 +0000538TailDuplicatePass::shouldTailDuplicate(const MachineFunction &MF,
Rafael Espindola9dbbd872011-06-23 03:41:29 +0000539 bool IsSimple,
Rafael Espindola54c25622011-06-09 19:54:42 +0000540 MachineBasicBlock &TailBB) {
541 // Only duplicate blocks that end with unconditional branches.
542 if (TailBB.canFallThrough())
543 return false;
544
Rafael Espindolaec324e52011-06-17 05:54:50 +0000545 // Don't try to tail-duplicate single-block loops.
546 if (TailBB.isSuccessor(&TailBB))
547 return false;
548
Rafael Espindola54c25622011-06-09 19:54:42 +0000549 // Set the limit on the cost to duplicate. When optimizing for size,
Bob Wilson15acadd2009-11-26 00:32:21 +0000550 // duplicate only one, because one branch instruction can be eliminated to
551 // compensate for the duplication.
552 unsigned MaxDuplicateCount;
Jakob Stoklund Olesen83520622011-01-30 20:38:12 +0000553 if (TailDuplicateSize.getNumOccurrences() == 0 &&
554 MF.getFunction()->hasFnAttr(Attribute::OptimizeForSize))
Bob Wilson38582252009-11-30 18:56:45 +0000555 MaxDuplicateCount = 1;
Bob Wilson15acadd2009-11-26 00:32:21 +0000556 else
557 MaxDuplicateCount = TailDuplicateSize;
558
Rafael Espindolaec324e52011-06-17 05:54:50 +0000559 // If the target has hardware branch prediction that can handle indirect
560 // branches, duplicating them can often make them predictable when there
561 // are common paths through the code. The limit needs to be high enough
562 // to allow undoing the effects of tail merging and other optimizations
563 // that rearrange the predecessors of the indirect branch.
Bob Wilsoncb44b282010-01-16 00:42:25 +0000564
Rafael Espindola6a9d2b12011-07-04 01:21:42 +0000565 bool HasIndirectbr = false;
566 if (!TailBB.empty())
Evan Cheng5a96b3d2011-12-07 07:15:52 +0000567 HasIndirectbr = TailBB.back().isIndirectBranch();
Rafael Espindola6a9d2b12011-07-04 01:21:42 +0000568
569 if (HasIndirectbr && PreRegAlloc)
570 MaxDuplicateCount = 20;
Bob Wilsonbfdcf3b2010-01-15 06:29:17 +0000571
Bob Wilson15acadd2009-11-26 00:32:21 +0000572 // Check the instructions in the block to determine whether tail-duplication
573 // is invalid or unlikely to be profitable.
Bob Wilsonf1e01dc2009-12-02 17:15:24 +0000574 unsigned InstrCount = 0;
Evan Cheng7c2a4a32011-12-06 22:12:01 +0000575 for (MachineBasicBlock::iterator I = TailBB.begin(); I != TailBB.end(); ++I) {
Bob Wilson15acadd2009-11-26 00:32:21 +0000576 // Non-duplicable things shouldn't be tail-duplicated.
Evan Cheng5a96b3d2011-12-07 07:15:52 +0000577 if (I->isNotDuplicable())
Rafael Espindolaec324e52011-06-17 05:54:50 +0000578 return false;
579
Evan Cheng79fc6f42009-12-04 09:42:45 +0000580 // Do not duplicate 'return' instructions if this is a pre-regalloc run.
581 // A return may expand into a lot more instructions (e.g. reload of callee
582 // saved registers) after PEI.
Evan Cheng5a96b3d2011-12-07 07:15:52 +0000583 if (PreRegAlloc && I->isReturn())
Rafael Espindolaec324e52011-06-17 05:54:50 +0000584 return false;
585
586 // Avoid duplicating calls before register allocation. Calls presents a
587 // barrier to register allocation so duplicating them may end up increasing
588 // spills.
Evan Cheng5a96b3d2011-12-07 07:15:52 +0000589 if (PreRegAlloc && I->isCall())
Rafael Espindolaec324e52011-06-17 05:54:50 +0000590 return false;
591
Devang Patelcbe1e312010-03-16 21:02:07 +0000592 if (!I->isPHI() && !I->isDebugValue())
Bob Wilsonf1e01dc2009-12-02 17:15:24 +0000593 InstrCount += 1;
Rafael Espindolaec324e52011-06-17 05:54:50 +0000594
595 if (InstrCount > MaxDuplicateCount)
596 return false;
Bob Wilson15acadd2009-11-26 00:32:21 +0000597 }
Bob Wilson15acadd2009-11-26 00:32:21 +0000598
Rafael Espindola6a9d2b12011-07-04 01:21:42 +0000599 if (HasIndirectbr && PreRegAlloc)
Rafael Espindola9dbbd872011-06-23 03:41:29 +0000600 return true;
601
602 if (IsSimple)
Rafael Espindolad7f35fa2011-06-24 15:47:41 +0000603 return true;
Rafael Espindola9dbbd872011-06-23 03:41:29 +0000604
605 if (!PreRegAlloc)
606 return true;
607
Rafael Espindola40179bf2011-06-24 15:50:56 +0000608 return canCompletelyDuplicateBB(TailBB);
Rafael Espindola54c25622011-06-09 19:54:42 +0000609}
610
Rafael Espindola275c1f92011-06-20 04:16:35 +0000611/// isSimpleBB - True if this BB has only one unconditional jump.
612bool
613TailDuplicatePass::isSimpleBB(MachineBasicBlock *TailBB) {
614 if (TailBB->succ_size() != 1)
615 return false;
Rafael Espindola9dbbd872011-06-23 03:41:29 +0000616 if (TailBB->pred_empty())
617 return false;
Rafael Espindolad6379a92011-06-22 22:31:57 +0000618 MachineBasicBlock::iterator I = TailBB->begin();
Rafael Espindola275c1f92011-06-20 04:16:35 +0000619 MachineBasicBlock::iterator E = TailBB->end();
Rafael Espindolad6379a92011-06-22 22:31:57 +0000620 while (I != E && I->isDebugValue())
Rafael Espindola275c1f92011-06-20 04:16:35 +0000621 ++I;
622 if (I == E)
623 return true;
Evan Cheng5a96b3d2011-12-07 07:15:52 +0000624 return I->isUnconditionalBranch();
Rafael Espindola275c1f92011-06-20 04:16:35 +0000625}
626
627static bool
628bothUsedInPHI(const MachineBasicBlock &A,
629 SmallPtrSet<MachineBasicBlock*, 8> SuccsB) {
630 for (MachineBasicBlock::const_succ_iterator SI = A.succ_begin(),
631 SE = A.succ_end(); SI != SE; ++SI) {
632 MachineBasicBlock *BB = *SI;
633 if (SuccsB.count(BB) && !BB->empty() && BB->begin()->isPHI())
634 return true;
635 }
636
637 return false;
638}
639
640bool
Rafael Espindola40179bf2011-06-24 15:50:56 +0000641TailDuplicatePass::canCompletelyDuplicateBB(MachineBasicBlock &BB) {
Rafael Espindola275c1f92011-06-20 04:16:35 +0000642 SmallPtrSet<MachineBasicBlock*, 8> Succs(BB.succ_begin(), BB.succ_end());
643
644 for (MachineBasicBlock::pred_iterator PI = BB.pred_begin(),
645 PE = BB.pred_end(); PI != PE; ++PI) {
646 MachineBasicBlock *PredBB = *PI;
Rafael Espindola9dbbd872011-06-23 03:41:29 +0000647
Rafael Espindola40179bf2011-06-24 15:50:56 +0000648 if (PredBB->succ_size() > 1)
649 return false;
Rafael Espindola9dbbd872011-06-23 03:41:29 +0000650
Rafael Espindola275c1f92011-06-20 04:16:35 +0000651 MachineBasicBlock *PredTBB = NULL, *PredFBB = NULL;
652 SmallVector<MachineOperand, 4> PredCond;
653 if (TII->AnalyzeBranch(*PredBB, PredTBB, PredFBB, PredCond, true))
654 return false;
Rafael Espindola9dbbd872011-06-23 03:41:29 +0000655
Rafael Espindola40179bf2011-06-24 15:50:56 +0000656 if (!PredCond.empty())
Rafael Espindola9dbbd872011-06-23 03:41:29 +0000657 return false;
Rafael Espindola275c1f92011-06-20 04:16:35 +0000658 }
659 return true;
660}
661
Rafael Espindolad7f35fa2011-06-24 15:47:41 +0000662bool
Rafael Espindola275c1f92011-06-20 04:16:35 +0000663TailDuplicatePass::duplicateSimpleBB(MachineBasicBlock *TailBB,
664 SmallVector<MachineBasicBlock*, 8> &TDBBs,
665 const DenseSet<unsigned> &UsedByPhi,
666 SmallVector<MachineInstr*, 16> &Copies) {
Rafael Espindolad7f35fa2011-06-24 15:47:41 +0000667 SmallPtrSet<MachineBasicBlock*, 8> Succs(TailBB->succ_begin(),
668 TailBB->succ_end());
Rafael Espindola275c1f92011-06-20 04:16:35 +0000669 SmallVector<MachineBasicBlock*, 8> Preds(TailBB->pred_begin(),
670 TailBB->pred_end());
Rafael Espindolad7f35fa2011-06-24 15:47:41 +0000671 bool Changed = false;
Rafael Espindola275c1f92011-06-20 04:16:35 +0000672 for (SmallSetVector<MachineBasicBlock *, 8>::iterator PI = Preds.begin(),
673 PE = Preds.end(); PI != PE; ++PI) {
674 MachineBasicBlock *PredBB = *PI;
675
Rafael Espindolad7f35fa2011-06-24 15:47:41 +0000676 if (PredBB->getLandingPadSuccessor())
677 continue;
678
679 if (bothUsedInPHI(*PredBB, Succs))
680 continue;
681
Rafael Espindola275c1f92011-06-20 04:16:35 +0000682 MachineBasicBlock *PredTBB = NULL, *PredFBB = NULL;
683 SmallVector<MachineOperand, 4> PredCond;
Rafael Espindolad7f35fa2011-06-24 15:47:41 +0000684 if (TII->AnalyzeBranch(*PredBB, PredTBB, PredFBB, PredCond, true))
685 continue;
Rafael Espindola275c1f92011-06-20 04:16:35 +0000686
Rafael Espindolad7f35fa2011-06-24 15:47:41 +0000687 Changed = true;
Rafael Espindola275c1f92011-06-20 04:16:35 +0000688 DEBUG(dbgs() << "\nTail-duplicating into PredBB: " << *PredBB
689 << "From simple Succ: " << *TailBB);
690
691 MachineBasicBlock *NewTarget = *TailBB->succ_begin();
Francois Pichet289a2792011-06-20 05:19:37 +0000692 MachineBasicBlock *NextBB = llvm::next(MachineFunction::iterator(PredBB));
Rafael Espindola275c1f92011-06-20 04:16:35 +0000693
Rafael Espindola275c1f92011-06-20 04:16:35 +0000694 // Make PredFBB explicit.
695 if (PredCond.empty())
696 PredFBB = PredTBB;
697
698 // Make fall through explicit.
699 if (!PredTBB)
700 PredTBB = NextBB;
701 if (!PredFBB)
702 PredFBB = NextBB;
703
704 // Redirect
705 if (PredFBB == TailBB)
706 PredFBB = NewTarget;
707 if (PredTBB == TailBB)
708 PredTBB = NewTarget;
709
710 // Make the branch unconditional if possible
Rafael Espindola689c2472011-06-20 14:11:42 +0000711 if (PredTBB == PredFBB) {
712 PredCond.clear();
Rafael Espindola275c1f92011-06-20 04:16:35 +0000713 PredFBB = NULL;
Rafael Espindola689c2472011-06-20 14:11:42 +0000714 }
Rafael Espindola275c1f92011-06-20 04:16:35 +0000715
716 // Avoid adding fall through branches.
717 if (PredFBB == NextBB)
718 PredFBB = NULL;
719 if (PredTBB == NextBB && PredFBB == NULL)
720 PredTBB = NULL;
721
722 TII->RemoveBranch(*PredBB);
723
724 if (PredTBB)
725 TII->InsertBranch(*PredBB, PredTBB, PredFBB, PredCond, DebugLoc());
726
727 PredBB->removeSuccessor(TailBB);
Rafael Espindola689c2472011-06-20 14:11:42 +0000728 unsigned NumSuccessors = PredBB->succ_size();
729 assert(NumSuccessors <= 1);
730 if (NumSuccessors == 0 || *PredBB->succ_begin() != NewTarget)
731 PredBB->addSuccessor(NewTarget);
Rafael Espindola275c1f92011-06-20 04:16:35 +0000732
733 TDBBs.push_back(PredBB);
Rafael Espindola275c1f92011-06-20 04:16:35 +0000734 }
Rafael Espindolad7f35fa2011-06-24 15:47:41 +0000735 return Changed;
Rafael Espindola275c1f92011-06-20 04:16:35 +0000736}
737
Rafael Espindola54c25622011-06-09 19:54:42 +0000738/// TailDuplicate - If it is profitable, duplicate TailBB's contents in each
739/// of its predecessors.
740bool
Rafael Espindola6a9d2b12011-07-04 01:21:42 +0000741TailDuplicatePass::TailDuplicate(MachineBasicBlock *TailBB,
742 bool IsSimple,
743 MachineFunction &MF,
Rafael Espindola54c25622011-06-09 19:54:42 +0000744 SmallVector<MachineBasicBlock*, 8> &TDBBs,
745 SmallVector<MachineInstr*, 16> &Copies) {
David Greene00dec1b2010-01-05 01:25:15 +0000746 DEBUG(dbgs() << "\n*** Tail-duplicating BB#" << TailBB->getNumber() << '\n');
Evan Cheng75eb5352009-12-07 10:15:19 +0000747
Rafael Espindola275c1f92011-06-20 04:16:35 +0000748 DenseSet<unsigned> UsedByPhi;
749 getRegsUsedByPHIs(*TailBB, &UsedByPhi);
750
Rafael Espindolad7f35fa2011-06-24 15:47:41 +0000751 if (IsSimple)
752 return duplicateSimpleBB(TailBB, TDBBs, UsedByPhi, Copies);
Rafael Espindola275c1f92011-06-20 04:16:35 +0000753
Bob Wilson15acadd2009-11-26 00:32:21 +0000754 // Iterate through all the unique predecessors and tail-duplicate this
755 // block into them, if possible. Copying the list ahead of time also
756 // avoids trouble with the predecessor list reallocating.
757 bool Changed = false;
Evan Cheng79fc6f42009-12-04 09:42:45 +0000758 SmallSetVector<MachineBasicBlock*, 8> Preds(TailBB->pred_begin(),
759 TailBB->pred_end());
Bob Wilson15acadd2009-11-26 00:32:21 +0000760 for (SmallSetVector<MachineBasicBlock *, 8>::iterator PI = Preds.begin(),
761 PE = Preds.end(); PI != PE; ++PI) {
762 MachineBasicBlock *PredBB = *PI;
763
764 assert(TailBB != PredBB &&
765 "Single-block loop should have been rejected earlier!");
Rafael Espindola9a9a3a52011-06-10 20:08:23 +0000766 // EH edges are ignored by AnalyzeBranch.
767 if (PredBB->succ_size() > 1)
768 continue;
Bob Wilson15acadd2009-11-26 00:32:21 +0000769
770 MachineBasicBlock *PredTBB, *PredFBB;
771 SmallVector<MachineOperand, 4> PredCond;
772 if (TII->AnalyzeBranch(*PredBB, PredTBB, PredFBB, PredCond, true))
773 continue;
774 if (!PredCond.empty())
775 continue;
Bob Wilson15acadd2009-11-26 00:32:21 +0000776 // Don't duplicate into a fall-through predecessor (at least for now).
777 if (PredBB->isLayoutSuccessor(TailBB) && PredBB->canFallThrough())
778 continue;
779
David Greene00dec1b2010-01-05 01:25:15 +0000780 DEBUG(dbgs() << "\nTail-duplicating into PredBB: " << *PredBB
Bob Wilson15acadd2009-11-26 00:32:21 +0000781 << "From Succ: " << *TailBB);
782
Evan Cheng75eb5352009-12-07 10:15:19 +0000783 TDBBs.push_back(PredBB);
784
Bob Wilson15acadd2009-11-26 00:32:21 +0000785 // Remove PredBB's unconditional branch.
786 TII->RemoveBranch(*PredBB);
Evan Cheng111e7622009-12-03 08:43:53 +0000787
Evan Chengeb25bd22012-05-30 00:42:39 +0000788 if (RS && !TailBB->livein_empty()) {
789 // Update PredBB livein.
790 RS->enterBasicBlock(PredBB);
791 if (!PredBB->empty())
792 RS->forward(prior(PredBB->end()));
793 BitVector RegsLiveAtExit(TRI->getNumRegs());
794 RS->getRegsUsed(RegsLiveAtExit, false);
795 for (MachineBasicBlock::livein_iterator I = TailBB->livein_begin(),
796 E = TailBB->livein_end(); I != E; ++I) {
797 if (!RegsLiveAtExit[*I])
798 // If a register is previously livein to the tail but it's not live
799 // at the end of predecessor BB, then it should be added to its
800 // livein list.
801 PredBB->addLiveIn(*I);
802 }
803 }
804
Bob Wilson15acadd2009-11-26 00:32:21 +0000805 // Clone the contents of TailBB into PredBB.
Evan Cheng111e7622009-12-03 08:43:53 +0000806 DenseMap<unsigned, unsigned> LocalVRMap;
Evan Cheng3466f132009-12-15 01:44:10 +0000807 SmallVector<std::pair<unsigned,unsigned>, 4> CopyInfos;
Evan Chengdf7e8bd2012-02-20 07:51:58 +0000808 // Use instr_iterator here to properly handle bundles, e.g.
809 // ARM Thumb2 IT block.
810 MachineBasicBlock::instr_iterator I = TailBB->instr_begin();
811 while (I != TailBB->instr_end()) {
Evan Cheng79fc6f42009-12-04 09:42:45 +0000812 MachineInstr *MI = &*I;
813 ++I;
Chris Lattner518bb532010-02-09 19:54:29 +0000814 if (MI->isPHI()) {
Evan Cheng111e7622009-12-03 08:43:53 +0000815 // Replace the uses of the def of the PHI with the register coming
816 // from PredBB.
Rafael Espindola689d7d52011-06-09 23:22:56 +0000817 ProcessPHI(MI, TailBB, PredBB, LocalVRMap, CopyInfos, UsedByPhi, true);
Evan Cheng79fc6f42009-12-04 09:42:45 +0000818 } else {
819 // Replace def of virtual registers with new registers, and update
820 // uses with PHI source register or the new registers.
Rafael Espindola0f28c3f2011-06-09 22:53:47 +0000821 DuplicateInstruction(MI, TailBB, PredBB, MF, LocalVRMap, UsedByPhi);
Evan Cheng111e7622009-12-03 08:43:53 +0000822 }
Bob Wilson15acadd2009-11-26 00:32:21 +0000823 }
Evan Cheng75eb5352009-12-07 10:15:19 +0000824 MachineBasicBlock::iterator Loc = PredBB->getFirstTerminator();
Evan Cheng3466f132009-12-15 01:44:10 +0000825 for (unsigned i = 0, e = CopyInfos.size(); i != e; ++i) {
Jakob Stoklund Olesen1e1098c2010-07-10 22:42:59 +0000826 Copies.push_back(BuildMI(*PredBB, Loc, DebugLoc(),
827 TII->get(TargetOpcode::COPY),
828 CopyInfos[i].first).addReg(CopyInfos[i].second));
Evan Cheng75eb5352009-12-07 10:15:19 +0000829 }
Rafael Espindolaec324e52011-06-17 05:54:50 +0000830
831 // Simplify
832 TII->AnalyzeBranch(*PredBB, PredTBB, PredFBB, PredCond, true);
833
Bob Wilson15acadd2009-11-26 00:32:21 +0000834 NumInstrDups += TailBB->size() - 1; // subtract one for removed branch
835
836 // Update the CFG.
837 PredBB->removeSuccessor(PredBB->succ_begin());
838 assert(PredBB->succ_empty() &&
839 "TailDuplicate called on block with multiple successors!");
840 for (MachineBasicBlock::succ_iterator I = TailBB->succ_begin(),
Evan Cheng79fc6f42009-12-04 09:42:45 +0000841 E = TailBB->succ_end(); I != E; ++I)
842 PredBB->addSuccessor(*I);
Bob Wilson15acadd2009-11-26 00:32:21 +0000843
844 Changed = true;
845 ++NumTailDups;
846 }
847
848 // If TailBB was duplicated into all its predecessors except for the prior
849 // block, which falls through unconditionally, move the contents of this
850 // block into the prior block.
Evan Cheng79fc6f42009-12-04 09:42:45 +0000851 MachineBasicBlock *PrevBB = prior(MachineFunction::iterator(TailBB));
Bob Wilson15acadd2009-11-26 00:32:21 +0000852 MachineBasicBlock *PriorTBB = 0, *PriorFBB = 0;
853 SmallVector<MachineOperand, 4> PriorCond;
Bob Wilson15acadd2009-11-26 00:32:21 +0000854 // This has to check PrevBB->succ_size() because EH edges are ignored by
855 // AnalyzeBranch.
Andrew Trickd2a7bed2012-02-08 21:22:30 +0000856 if (PrevBB->succ_size() == 1 &&
Rafael Espindolaa899b222011-06-09 21:43:25 +0000857 !TII->AnalyzeBranch(*PrevBB, PriorTBB, PriorFBB, PriorCond, true) &&
858 PriorCond.empty() && !PriorTBB && TailBB->pred_size() == 1 &&
Bob Wilson15acadd2009-11-26 00:32:21 +0000859 !TailBB->hasAddressTaken()) {
David Greene00dec1b2010-01-05 01:25:15 +0000860 DEBUG(dbgs() << "\nMerging into block: " << *PrevBB
Bob Wilson15acadd2009-11-26 00:32:21 +0000861 << "From MBB: " << *TailBB);
Evan Cheng79fc6f42009-12-04 09:42:45 +0000862 if (PreRegAlloc) {
863 DenseMap<unsigned, unsigned> LocalVRMap;
Evan Cheng3466f132009-12-15 01:44:10 +0000864 SmallVector<std::pair<unsigned,unsigned>, 4> CopyInfos;
Evan Cheng79fc6f42009-12-04 09:42:45 +0000865 MachineBasicBlock::iterator I = TailBB->begin();
866 // Process PHI instructions first.
Chris Lattner518bb532010-02-09 19:54:29 +0000867 while (I != TailBB->end() && I->isPHI()) {
Evan Cheng79fc6f42009-12-04 09:42:45 +0000868 // Replace the uses of the def of the PHI with the register coming
869 // from PredBB.
870 MachineInstr *MI = &*I++;
Rafael Espindola689d7d52011-06-09 23:22:56 +0000871 ProcessPHI(MI, TailBB, PrevBB, LocalVRMap, CopyInfos, UsedByPhi, true);
Evan Cheng79fc6f42009-12-04 09:42:45 +0000872 if (MI->getParent())
873 MI->eraseFromParent();
874 }
875
876 // Now copy the non-PHI instructions.
877 while (I != TailBB->end()) {
878 // Replace def of virtual registers with new registers, and update
879 // uses with PHI source register or the new registers.
880 MachineInstr *MI = &*I++;
Evan Chengdf7e8bd2012-02-20 07:51:58 +0000881 assert(!MI->isBundle() && "Not expecting bundles before regalloc!");
Rafael Espindola0f28c3f2011-06-09 22:53:47 +0000882 DuplicateInstruction(MI, TailBB, PrevBB, MF, LocalVRMap, UsedByPhi);
Evan Cheng79fc6f42009-12-04 09:42:45 +0000883 MI->eraseFromParent();
884 }
Evan Cheng75eb5352009-12-07 10:15:19 +0000885 MachineBasicBlock::iterator Loc = PrevBB->getFirstTerminator();
Evan Cheng3466f132009-12-15 01:44:10 +0000886 for (unsigned i = 0, e = CopyInfos.size(); i != e; ++i) {
Jakob Stoklund Olesen1e1098c2010-07-10 22:42:59 +0000887 Copies.push_back(BuildMI(*PrevBB, Loc, DebugLoc(),
888 TII->get(TargetOpcode::COPY),
889 CopyInfos[i].first)
890 .addReg(CopyInfos[i].second));
Evan Cheng75eb5352009-12-07 10:15:19 +0000891 }
Evan Cheng79fc6f42009-12-04 09:42:45 +0000892 } else {
893 // No PHIs to worry about, just splice the instructions over.
894 PrevBB->splice(PrevBB->end(), TailBB, TailBB->begin(), TailBB->end());
895 }
896 PrevBB->removeSuccessor(PrevBB->succ_begin());
897 assert(PrevBB->succ_empty());
898 PrevBB->transferSuccessors(TailBB);
Evan Cheng75eb5352009-12-07 10:15:19 +0000899 TDBBs.push_back(PrevBB);
Bob Wilson15acadd2009-11-26 00:32:21 +0000900 Changed = true;
901 }
902
Rafael Espindola689d7d52011-06-09 23:22:56 +0000903 // If this is after register allocation, there are no phis to fix.
904 if (!PreRegAlloc)
905 return Changed;
906
907 // If we made no changes so far, we are safe.
908 if (!Changed)
909 return Changed;
910
911
912 // Handle the nasty case in that we duplicated a block that is part of a loop
913 // into some but not all of its predecessors. For example:
Rafael Espindola4d7b4572011-06-09 23:51:45 +0000914 // 1 -> 2 <-> 3 |
915 // \ |
916 // \---> rest |
Rafael Espindola689d7d52011-06-09 23:22:56 +0000917 // if we duplicate 2 into 1 but not into 3, we end up with
Rafael Espindola4d7b4572011-06-09 23:51:45 +0000918 // 12 -> 3 <-> 2 -> rest |
919 // \ / |
920 // \----->-----/ |
Rafael Espindola689d7d52011-06-09 23:22:56 +0000921 // If there was a "var = phi(1, 3)" in 2, it has to be ultimately replaced
922 // with a phi in 3 (which now dominates 2).
923 // What we do here is introduce a copy in 3 of the register defined by the
924 // phi, just like when we are duplicating 2 into 3, but we don't copy any
925 // real instructions or remove the 3 -> 2 edge from the phi in 2.
926 for (SmallSetVector<MachineBasicBlock *, 8>::iterator PI = Preds.begin(),
927 PE = Preds.end(); PI != PE; ++PI) {
928 MachineBasicBlock *PredBB = *PI;
929 if (std::find(TDBBs.begin(), TDBBs.end(), PredBB) != TDBBs.end())
930 continue;
931
932 // EH edges
933 if (PredBB->succ_size() != 1)
934 continue;
935
936 DenseMap<unsigned, unsigned> LocalVRMap;
937 SmallVector<std::pair<unsigned,unsigned>, 4> CopyInfos;
938 MachineBasicBlock::iterator I = TailBB->begin();
939 // Process PHI instructions first.
940 while (I != TailBB->end() && I->isPHI()) {
941 // Replace the uses of the def of the PHI with the register coming
942 // from PredBB.
943 MachineInstr *MI = &*I++;
944 ProcessPHI(MI, TailBB, PredBB, LocalVRMap, CopyInfos, UsedByPhi, false);
945 }
946 MachineBasicBlock::iterator Loc = PredBB->getFirstTerminator();
947 for (unsigned i = 0, e = CopyInfos.size(); i != e; ++i) {
948 Copies.push_back(BuildMI(*PredBB, Loc, DebugLoc(),
949 TII->get(TargetOpcode::COPY),
950 CopyInfos[i].first).addReg(CopyInfos[i].second));
951 }
952 }
953
Bob Wilson15acadd2009-11-26 00:32:21 +0000954 return Changed;
955}
956
957/// RemoveDeadBlock - Remove the specified dead machine basic block from the
958/// function, updating the CFG.
Bob Wilson2d521e52009-11-26 21:38:41 +0000959void TailDuplicatePass::RemoveDeadBlock(MachineBasicBlock *MBB) {
Bob Wilson15acadd2009-11-26 00:32:21 +0000960 assert(MBB->pred_empty() && "MBB must be dead!");
David Greene00dec1b2010-01-05 01:25:15 +0000961 DEBUG(dbgs() << "\nRemoving MBB: " << *MBB);
Bob Wilson15acadd2009-11-26 00:32:21 +0000962
963 // Remove all successors.
964 while (!MBB->succ_empty())
965 MBB->removeSuccessor(MBB->succ_end()-1);
966
Bob Wilson15acadd2009-11-26 00:32:21 +0000967 // Remove the block.
968 MBB->eraseFromParent();
969}