blob: 40ce2b6cbba9907dbfc89972553836d303362454 [file] [log] [blame]
Bob Wilson2d4ff122009-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 Wilson2d4ff122009-11-26 00:32:21 +000016#include "llvm/CodeGen/Passes.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000017#include "llvm/ADT/DenseSet.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000018#include "llvm/ADT/SetVector.h"
19#include "llvm/ADT/SmallSet.h"
20#include "llvm/ADT/Statistic.h"
Akira Hatanakaa07ffb52014-02-12 18:09:18 +000021#include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
Bob Wilson2d4ff122009-11-26 00:32:21 +000022#include "llvm/CodeGen/MachineFunctionPass.h"
Jakob Stoklund Olesen0c76d6e2010-07-10 22:42:59 +000023#include "llvm/CodeGen/MachineInstrBuilder.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000024#include "llvm/CodeGen/MachineModuleInfo.h"
Evan Cheng1bbe6be2009-12-03 08:43:53 +000025#include "llvm/CodeGen/MachineRegisterInfo.h"
26#include "llvm/CodeGen/MachineSSAUpdater.h"
Evan Chengbc2453d2012-05-30 00:42:39 +000027#include "llvm/CodeGen/RegisterScavenging.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000028#include "llvm/IR/Function.h"
Bob Wilson2d4ff122009-11-26 00:32:21 +000029#include "llvm/Support/CommandLine.h"
30#include "llvm/Support/Debug.h"
Evan Chengcc770622009-12-07 10:15:19 +000031#include "llvm/Support/ErrorHandling.h"
Bob Wilson2d4ff122009-11-26 00:32:21 +000032#include "llvm/Support/raw_ostream.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000033#include "llvm/Target/TargetInstrInfo.h"
34#include "llvm/Target/TargetRegisterInfo.h"
Bob Wilson2d4ff122009-11-26 00:32:21 +000035using namespace llvm;
36
Evan Chengcc770622009-12-07 10:15:19 +000037STATISTIC(NumTails , "Number of tails duplicated");
Bob Wilson2d4ff122009-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 Espindoladfbf6de2011-06-08 14:13:31 +000041STATISTIC(NumAddedPHIs , "Number of phis added");
Bob Wilson2d4ff122009-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 Chengcc770622009-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 Cheng9e672552009-12-04 19:09:10 +000057typedef std::vector<std::pair<MachineBasicBlock*,unsigned> > AvailableValsTy;
Evan Cheng1bbe6be2009-12-03 08:43:53 +000058
Bob Wilson2d4ff122009-11-26 00:32:21 +000059namespace {
Bob Wilson9594db52009-11-26 21:38:41 +000060 /// TailDuplicatePass - Perform tail duplication.
61 class TailDuplicatePass : public MachineFunctionPass {
Bob Wilson2d4ff122009-11-26 00:32:21 +000062 const TargetInstrInfo *TII;
Evan Chengbc2453d2012-05-30 00:42:39 +000063 const TargetRegisterInfo *TRI;
Akira Hatanakaa07ffb52014-02-12 18:09:18 +000064 const MachineBranchProbabilityInfo *MBPI;
Bob Wilson2d4ff122009-11-26 00:32:21 +000065 MachineModuleInfo *MMI;
Evan Cheng1bbe6be2009-12-03 08:43:53 +000066 MachineRegisterInfo *MRI;
Ahmed Charles56440fd2014-03-06 05:51:42 +000067 std::unique_ptr<RegScavenger> RS;
Andrew Trickc0449172012-02-08 21:22:30 +000068 bool PreRegAlloc;
Evan Cheng1bbe6be2009-12-03 08:43:53 +000069
70 // SSAUpdateVRs - A list of virtual registers for which to update SSA form.
71 SmallVector<unsigned, 16> SSAUpdateVRs;
72
73 // SSAUpdateVals - For each virtual register in SSAUpdateVals keep a list of
74 // source virtual registers.
75 DenseMap<unsigned, AvailableValsTy> SSAUpdateVals;
Bob Wilson2d4ff122009-11-26 00:32:21 +000076
77 public:
78 static char ID;
Andrew Trickc0449172012-02-08 21:22:30 +000079 explicit TailDuplicatePass() :
80 MachineFunctionPass(ID), PreRegAlloc(false) {}
Bob Wilson2d4ff122009-11-26 00:32:21 +000081
Craig Topper4584cd52014-03-07 09:26:03 +000082 bool runOnMachineFunction(MachineFunction &MF) override;
Bob Wilson2d4ff122009-11-26 00:32:21 +000083
Craig Topper4584cd52014-03-07 09:26:03 +000084 void getAnalysisUsage(AnalysisUsage &AU) const override;
Akira Hatanakaa07ffb52014-02-12 18:09:18 +000085
Bob Wilson2d4ff122009-11-26 00:32:21 +000086 private:
Evan Cheng9e672552009-12-04 19:09:10 +000087 void AddSSAUpdateEntry(unsigned OrigReg, unsigned NewReg,
88 MachineBasicBlock *BB);
Evan Cheng6154dbd2009-12-04 09:42:45 +000089 void ProcessPHI(MachineInstr *MI, MachineBasicBlock *TailBB,
90 MachineBasicBlock *PredBB,
Evan Chengcc770622009-12-07 10:15:19 +000091 DenseMap<unsigned, unsigned> &LocalVRMap,
Craig Topperb94011f2013-07-14 04:42:23 +000092 SmallVectorImpl<std::pair<unsigned,unsigned> > &Copies,
Rafael Espindolac735f132011-06-09 23:22:56 +000093 const DenseSet<unsigned> &UsedByPhi,
94 bool Remove);
Evan Cheng6154dbd2009-12-04 09:42:45 +000095 void DuplicateInstruction(MachineInstr *MI,
96 MachineBasicBlock *TailBB,
97 MachineBasicBlock *PredBB,
98 MachineFunction &MF,
Rafael Espindola81512fc2011-06-09 22:53:47 +000099 DenseMap<unsigned, unsigned> &LocalVRMap,
100 const DenseSet<unsigned> &UsedByPhi);
Evan Chengcc770622009-12-07 10:15:19 +0000101 void UpdateSuccessorsPHIs(MachineBasicBlock *FromBB, bool isDead,
Craig Topperb94011f2013-07-14 04:42:23 +0000102 SmallVectorImpl<MachineBasicBlock *> &TDBBs,
Evan Chengcc770622009-12-07 10:15:19 +0000103 SmallSetVector<MachineBasicBlock*, 8> &Succs);
Bob Wilson2d4ff122009-11-26 00:32:21 +0000104 bool TailDuplicateBlocks(MachineFunction &MF);
Rafael Espindola73f93932011-06-09 19:54:42 +0000105 bool shouldTailDuplicate(const MachineFunction &MF,
Rafael Espindolae25a8712011-06-23 03:41:29 +0000106 bool IsSimple, MachineBasicBlock &TailBB);
Rafael Espindolaef636bf2011-06-20 04:16:35 +0000107 bool isSimpleBB(MachineBasicBlock *TailBB);
Rafael Espindola5135ae22011-06-24 15:50:56 +0000108 bool canCompletelyDuplicateBB(MachineBasicBlock &BB);
Rafael Espindolacb0213b2011-06-24 15:47:41 +0000109 bool duplicateSimpleBB(MachineBasicBlock *TailBB,
Craig Topperb94011f2013-07-14 04:42:23 +0000110 SmallVectorImpl<MachineBasicBlock *> &TDBBs,
Rafael Espindolaef636bf2011-06-20 04:16:35 +0000111 const DenseSet<unsigned> &RegsUsedByPhi,
Craig Topperb94011f2013-07-14 04:42:23 +0000112 SmallVectorImpl<MachineInstr *> &Copies);
Rafael Espindolaf9f012e2011-07-04 01:21:42 +0000113 bool TailDuplicate(MachineBasicBlock *TailBB,
114 bool IsSimple,
115 MachineFunction &MF,
Craig Topperb94011f2013-07-14 04:42:23 +0000116 SmallVectorImpl<MachineBasicBlock *> &TDBBs,
117 SmallVectorImpl<MachineInstr *> &Copies);
Rafael Espindolaf9f012e2011-07-04 01:21:42 +0000118 bool TailDuplicateAndUpdate(MachineBasicBlock *MBB,
119 bool IsSimple,
120 MachineFunction &MF);
121
Bob Wilson2d4ff122009-11-26 00:32:21 +0000122 void RemoveDeadBlock(MachineBasicBlock *MBB);
123 };
124
Bob Wilson9594db52009-11-26 21:38:41 +0000125 char TailDuplicatePass::ID = 0;
Bob Wilson2d4ff122009-11-26 00:32:21 +0000126}
127
Andrew Trick1fa5bcb2012-02-08 21:23:13 +0000128char &llvm::TailDuplicateID = TailDuplicatePass::ID;
129
130INITIALIZE_PASS(TailDuplicatePass, "tailduplication", "Tail Duplication",
131 false, false)
Bob Wilson2d4ff122009-11-26 00:32:21 +0000132
Bob Wilson9594db52009-11-26 21:38:41 +0000133bool TailDuplicatePass::runOnMachineFunction(MachineFunction &MF) {
Bob Wilson2d4ff122009-11-26 00:32:21 +0000134 TII = MF.getTarget().getInstrInfo();
Evan Chengbc2453d2012-05-30 00:42:39 +0000135 TRI = MF.getTarget().getRegisterInfo();
Evan Cheng1bbe6be2009-12-03 08:43:53 +0000136 MRI = &MF.getRegInfo();
Bob Wilson2d4ff122009-11-26 00:32:21 +0000137 MMI = getAnalysisIfAvailable<MachineModuleInfo>();
Akira Hatanakaa07ffb52014-02-12 18:09:18 +0000138 MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
139
Andrew Trickc0449172012-02-08 21:22:30 +0000140 PreRegAlloc = MRI->isSSA();
Benjamin Kramer3de5d402012-06-06 13:53:41 +0000141 RS.reset();
Evan Chengbc2453d2012-05-30 00:42:39 +0000142 if (MRI->tracksLiveness() && TRI->trackLivenessAfterRegAlloc(MF))
Benjamin Kramer3de5d402012-06-06 13:53:41 +0000143 RS.reset(new RegScavenger());
Bob Wilson2d4ff122009-11-26 00:32:21 +0000144
145 bool MadeChange = false;
Jakob Stoklund Olesen73ef9552010-01-15 19:59:57 +0000146 while (TailDuplicateBlocks(MF))
147 MadeChange = true;
Bob Wilson2d4ff122009-11-26 00:32:21 +0000148
149 return MadeChange;
150}
151
Akira Hatanakaa07ffb52014-02-12 18:09:18 +0000152void TailDuplicatePass::getAnalysisUsage(AnalysisUsage &AU) const {
153 AU.addRequired<MachineBranchProbabilityInfo>();
154 MachineFunctionPass::getAnalysisUsage(AU);
155}
156
Evan Chengcc770622009-12-07 10:15:19 +0000157static void VerifyPHIs(MachineFunction &MF, bool CheckExtra) {
158 for (MachineFunction::iterator I = ++MF.begin(), E = MF.end(); I != E; ++I) {
159 MachineBasicBlock *MBB = I;
160 SmallSetVector<MachineBasicBlock*, 8> Preds(MBB->pred_begin(),
161 MBB->pred_end());
162 MachineBasicBlock::iterator MI = MBB->begin();
163 while (MI != MBB->end()) {
Chris Lattnerb06015a2010-02-09 19:54:29 +0000164 if (!MI->isPHI())
Evan Chengcc770622009-12-07 10:15:19 +0000165 break;
166 for (SmallSetVector<MachineBasicBlock *, 8>::iterator PI = Preds.begin(),
167 PE = Preds.end(); PI != PE; ++PI) {
168 MachineBasicBlock *PredBB = *PI;
169 bool Found = false;
170 for (unsigned i = 1, e = MI->getNumOperands(); i != e; i += 2) {
171 MachineBasicBlock *PHIBB = MI->getOperand(i+1).getMBB();
172 if (PHIBB == PredBB) {
173 Found = true;
174 break;
175 }
176 }
177 if (!Found) {
David Greene85afc852010-01-05 01:25:15 +0000178 dbgs() << "Malformed PHI in BB#" << MBB->getNumber() << ": " << *MI;
179 dbgs() << " missing input from predecessor BB#"
Evan Chengcc770622009-12-07 10:15:19 +0000180 << PredBB->getNumber() << '\n';
181 llvm_unreachable(0);
182 }
183 }
184
185 for (unsigned i = 1, e = MI->getNumOperands(); i != e; i += 2) {
186 MachineBasicBlock *PHIBB = MI->getOperand(i+1).getMBB();
187 if (CheckExtra && !Preds.count(PHIBB)) {
David Greene85afc852010-01-05 01:25:15 +0000188 dbgs() << "Warning: malformed PHI in BB#" << MBB->getNumber()
Evan Chengcc770622009-12-07 10:15:19 +0000189 << ": " << *MI;
David Greene85afc852010-01-05 01:25:15 +0000190 dbgs() << " extra input from predecessor BB#"
Evan Chengcc770622009-12-07 10:15:19 +0000191 << PHIBB->getNumber() << '\n';
Rafael Espindola9e97a892011-06-09 23:55:56 +0000192 llvm_unreachable(0);
Evan Chengcc770622009-12-07 10:15:19 +0000193 }
194 if (PHIBB->getNumber() < 0) {
David Greene85afc852010-01-05 01:25:15 +0000195 dbgs() << "Malformed PHI in BB#" << MBB->getNumber() << ": " << *MI;
196 dbgs() << " non-existing BB#" << PHIBB->getNumber() << '\n';
Evan Chengcc770622009-12-07 10:15:19 +0000197 llvm_unreachable(0);
198 }
199 }
200 ++MI;
201 }
202 }
203}
204
Rafael Espindolaf9f012e2011-07-04 01:21:42 +0000205/// TailDuplicateAndUpdate - Tail duplicate the block and cleanup.
206bool
207TailDuplicatePass::TailDuplicateAndUpdate(MachineBasicBlock *MBB,
208 bool IsSimple,
209 MachineFunction &MF) {
210 // Save the successors list.
211 SmallSetVector<MachineBasicBlock*, 8> Succs(MBB->succ_begin(),
212 MBB->succ_end());
213
214 SmallVector<MachineBasicBlock*, 8> TDBBs;
215 SmallVector<MachineInstr*, 16> Copies;
216 if (!TailDuplicate(MBB, IsSimple, MF, TDBBs, Copies))
217 return false;
218
219 ++NumTails;
220
221 SmallVector<MachineInstr*, 8> NewPHIs;
222 MachineSSAUpdater SSAUpdate(MF, &NewPHIs);
223
224 // TailBB's immediate successors are now successors of those predecessors
225 // which duplicated TailBB. Add the predecessors as sources to the PHI
226 // instructions.
227 bool isDead = MBB->pred_empty() && !MBB->hasAddressTaken();
228 if (PreRegAlloc)
229 UpdateSuccessorsPHIs(MBB, isDead, TDBBs, Succs);
230
231 // If it is dead, remove it.
232 if (isDead) {
233 NumInstrDups -= MBB->size();
234 RemoveDeadBlock(MBB);
235 ++NumDeadBlocks;
236 }
237
238 // Update SSA form.
239 if (!SSAUpdateVRs.empty()) {
240 for (unsigned i = 0, e = SSAUpdateVRs.size(); i != e; ++i) {
241 unsigned VReg = SSAUpdateVRs[i];
242 SSAUpdate.Initialize(VReg);
243
244 // If the original definition is still around, add it as an available
245 // value.
246 MachineInstr *DefMI = MRI->getVRegDef(VReg);
247 MachineBasicBlock *DefBB = 0;
248 if (DefMI) {
249 DefBB = DefMI->getParent();
250 SSAUpdate.AddAvailableValue(DefBB, VReg);
251 }
252
253 // Add the new vregs as available values.
254 DenseMap<unsigned, AvailableValsTy>::iterator LI =
255 SSAUpdateVals.find(VReg);
256 for (unsigned j = 0, ee = LI->second.size(); j != ee; ++j) {
257 MachineBasicBlock *SrcBB = LI->second[j].first;
258 unsigned SrcReg = LI->second[j].second;
259 SSAUpdate.AddAvailableValue(SrcBB, SrcReg);
260 }
261
262 // Rewrite uses that are outside of the original def's block.
263 MachineRegisterInfo::use_iterator UI = MRI->use_begin(VReg);
264 while (UI != MRI->use_end()) {
Owen Anderson16c6bf42014-03-13 23:12:04 +0000265 MachineOperand &UseMO = *UI;
266 MachineInstr *UseMI = UseMO.getParent();
Rafael Espindolaf9f012e2011-07-04 01:21:42 +0000267 ++UI;
268 if (UseMI->isDebugValue()) {
269 // SSAUpdate can replace the use with an undef. That creates
270 // a debug instruction that is a kill.
271 // FIXME: Should it SSAUpdate job to delete debug instructions
272 // instead of replacing the use with undef?
273 UseMI->eraseFromParent();
274 continue;
275 }
276 if (UseMI->getParent() == DefBB && !UseMI->isPHI())
277 continue;
278 SSAUpdate.RewriteUse(UseMO);
279 }
280 }
281
282 SSAUpdateVRs.clear();
283 SSAUpdateVals.clear();
284 }
285
286 // Eliminate some of the copies inserted by tail duplication to maintain
287 // SSA form.
288 for (unsigned i = 0, e = Copies.size(); i != e; ++i) {
289 MachineInstr *Copy = Copies[i];
290 if (!Copy->isCopy())
291 continue;
292 unsigned Dst = Copy->getOperand(0).getReg();
293 unsigned Src = Copy->getOperand(1).getReg();
Jakob Stoklund Olesen00f07de2012-05-20 18:42:51 +0000294 if (MRI->hasOneNonDBGUse(Src) &&
295 MRI->constrainRegClass(Src, MRI->getRegClass(Dst))) {
Rafael Espindolaf9f012e2011-07-04 01:21:42 +0000296 // Copy is the only use. Do trivial copy propagation here.
297 MRI->replaceRegWith(Dst, Src);
298 Copy->eraseFromParent();
299 }
300 }
301
302 if (NewPHIs.size())
303 NumAddedPHIs += NewPHIs.size();
304
305 return true;
306}
307
Bob Wilson2d4ff122009-11-26 00:32:21 +0000308/// TailDuplicateBlocks - Look for small blocks that are unconditionally
309/// branched to and do not fall through. Tail-duplicate their instructions
310/// into their predecessors to eliminate (dynamic) branches.
Bob Wilson9594db52009-11-26 21:38:41 +0000311bool TailDuplicatePass::TailDuplicateBlocks(MachineFunction &MF) {
Bob Wilson2d4ff122009-11-26 00:32:21 +0000312 bool MadeChange = false;
313
Evan Chengcc770622009-12-07 10:15:19 +0000314 if (PreRegAlloc && TailDupVerify) {
David Greene85afc852010-01-05 01:25:15 +0000315 DEBUG(dbgs() << "\n*** Before tail-duplicating\n");
Evan Chengcc770622009-12-07 10:15:19 +0000316 VerifyPHIs(MF, true);
317 }
318
Bob Wilson2d4ff122009-11-26 00:32:21 +0000319 for (MachineFunction::iterator I = ++MF.begin(), E = MF.end(); I != E; ) {
320 MachineBasicBlock *MBB = I++;
321
Evan Chengcc770622009-12-07 10:15:19 +0000322 if (NumTails == TailDupLimit)
323 break;
324
Rafael Espindolaf9f012e2011-07-04 01:21:42 +0000325 bool IsSimple = isSimpleBB(MBB);
Bob Wilson2d4ff122009-11-26 00:32:21 +0000326
Rafael Espindolaf9f012e2011-07-04 01:21:42 +0000327 if (!shouldTailDuplicate(MF, IsSimple, *MBB))
Rafael Espindola79dc4e72011-07-04 00:13:36 +0000328 continue;
Evan Chengcc770622009-12-07 10:15:19 +0000329
Rafael Espindolaf9f012e2011-07-04 01:21:42 +0000330 MadeChange |= TailDuplicateAndUpdate(MBB, IsSimple, MF);
Bob Wilson2d4ff122009-11-26 00:32:21 +0000331 }
Rafael Espindola79dc4e72011-07-04 00:13:36 +0000332
Rafael Espindolaf9f012e2011-07-04 01:21:42 +0000333 if (PreRegAlloc && TailDupVerify)
334 VerifyPHIs(MF, false);
Evan Cheng1bbe6be2009-12-03 08:43:53 +0000335
Bob Wilson2d4ff122009-11-26 00:32:21 +0000336 return MadeChange;
337}
338
Evan Cheng1bbe6be2009-12-03 08:43:53 +0000339static bool isDefLiveOut(unsigned Reg, MachineBasicBlock *BB,
340 const MachineRegisterInfo *MRI) {
Owen Andersonb36376e2014-03-17 19:36:09 +0000341 for (MachineInstr &UseMI : MRI->use_instructions(Reg)) {
342 if (UseMI.isDebugValue())
Rafael Espindolae0304d12011-06-17 13:59:43 +0000343 continue;
Owen Andersonb36376e2014-03-17 19:36:09 +0000344 if (UseMI.getParent() != BB)
Evan Cheng1bbe6be2009-12-03 08:43:53 +0000345 return true;
346 }
347 return false;
348}
349
350static unsigned getPHISrcRegOpIdx(MachineInstr *MI, MachineBasicBlock *SrcBB) {
351 for (unsigned i = 1, e = MI->getNumOperands(); i != e; i += 2)
352 if (MI->getOperand(i+1).getMBB() == SrcBB)
353 return i;
354 return 0;
355}
356
Rafael Espindola81512fc2011-06-09 22:53:47 +0000357
358// Remember which registers are used by phis in this block. This is
359// used to determine which registers are liveout while modifying the
360// block (which is why we need to copy the information).
361static void getRegsUsedByPHIs(const MachineBasicBlock &BB,
Rafael Espindola0f62e4c2011-06-10 21:01:53 +0000362 DenseSet<unsigned> *UsedByPhi) {
Rafael Espindola81512fc2011-06-09 22:53:47 +0000363 for(MachineBasicBlock::const_iterator I = BB.begin(), E = BB.end();
364 I != E; ++I) {
365 const MachineInstr &MI = *I;
366 if (!MI.isPHI())
367 break;
368 for (unsigned i = 1, e = MI.getNumOperands(); i != e; i += 2) {
369 unsigned SrcReg = MI.getOperand(i).getReg();
370 UsedByPhi->insert(SrcReg);
371 }
372 }
373}
374
Evan Cheng1bbe6be2009-12-03 08:43:53 +0000375/// AddSSAUpdateEntry - Add a definition and source virtual registers pair for
376/// SSA update.
Evan Cheng9e672552009-12-04 19:09:10 +0000377void TailDuplicatePass::AddSSAUpdateEntry(unsigned OrigReg, unsigned NewReg,
378 MachineBasicBlock *BB) {
379 DenseMap<unsigned, AvailableValsTy>::iterator LI= SSAUpdateVals.find(OrigReg);
Evan Cheng1bbe6be2009-12-03 08:43:53 +0000380 if (LI != SSAUpdateVals.end())
Evan Cheng9e672552009-12-04 19:09:10 +0000381 LI->second.push_back(std::make_pair(BB, NewReg));
Evan Cheng1bbe6be2009-12-03 08:43:53 +0000382 else {
383 AvailableValsTy Vals;
Evan Cheng9e672552009-12-04 19:09:10 +0000384 Vals.push_back(std::make_pair(BB, NewReg));
Evan Cheng1bbe6be2009-12-03 08:43:53 +0000385 SSAUpdateVals.insert(std::make_pair(OrigReg, Vals));
386 SSAUpdateVRs.push_back(OrigReg);
387 }
388}
389
Evan Chengcc770622009-12-07 10:15:19 +0000390/// ProcessPHI - Process PHI node in TailBB by turning it into a copy in PredBB.
391/// Remember the source register that's contributed by PredBB and update SSA
392/// update map.
Tobias Grosser84f34be2013-07-14 06:12:01 +0000393void TailDuplicatePass::ProcessPHI(
394 MachineInstr *MI, MachineBasicBlock *TailBB, MachineBasicBlock *PredBB,
395 DenseMap<unsigned, unsigned> &LocalVRMap,
396 SmallVectorImpl<std::pair<unsigned, unsigned> > &Copies,
397 const DenseSet<unsigned> &RegsUsedByPhi, bool Remove) {
Evan Cheng6154dbd2009-12-04 09:42:45 +0000398 unsigned DefReg = MI->getOperand(0).getReg();
399 unsigned SrcOpIdx = getPHISrcRegOpIdx(MI, PredBB);
400 assert(SrcOpIdx && "Unable to find matching PHI source?");
401 unsigned SrcReg = MI->getOperand(SrcOpIdx).getReg();
Evan Chengcc770622009-12-07 10:15:19 +0000402 const TargetRegisterClass *RC = MRI->getRegClass(DefReg);
Evan Cheng6154dbd2009-12-04 09:42:45 +0000403 LocalVRMap.insert(std::make_pair(DefReg, SrcReg));
Evan Chengcc770622009-12-07 10:15:19 +0000404
405 // Insert a copy from source to the end of the block. The def register is the
406 // available value liveout of the block.
407 unsigned NewDef = MRI->createVirtualRegister(RC);
408 Copies.push_back(std::make_pair(NewDef, SrcReg));
Rafael Espindola81512fc2011-06-09 22:53:47 +0000409 if (isDefLiveOut(DefReg, TailBB, MRI) || RegsUsedByPhi.count(DefReg))
Evan Chengcc770622009-12-07 10:15:19 +0000410 AddSSAUpdateEntry(DefReg, NewDef, PredBB);
Evan Cheng6154dbd2009-12-04 09:42:45 +0000411
Rafael Espindolac735f132011-06-09 23:22:56 +0000412 if (!Remove)
413 return;
414
Evan Cheng6154dbd2009-12-04 09:42:45 +0000415 // Remove PredBB from the PHI node.
416 MI->RemoveOperand(SrcOpIdx+1);
417 MI->RemoveOperand(SrcOpIdx);
418 if (MI->getNumOperands() == 1)
419 MI->eraseFromParent();
420}
421
422/// DuplicateInstruction - Duplicate a TailBB instruction to PredBB and update
423/// the source operands due to earlier PHI translation.
424void TailDuplicatePass::DuplicateInstruction(MachineInstr *MI,
425 MachineBasicBlock *TailBB,
426 MachineBasicBlock *PredBB,
427 MachineFunction &MF,
Rafael Espindola81512fc2011-06-09 22:53:47 +0000428 DenseMap<unsigned, unsigned> &LocalVRMap,
429 const DenseSet<unsigned> &UsedByPhi) {
Jakob Stoklund Olesen29a64c92010-01-06 23:47:07 +0000430 MachineInstr *NewMI = TII->duplicate(MI, MF);
Evan Cheng6154dbd2009-12-04 09:42:45 +0000431 for (unsigned i = 0, e = NewMI->getNumOperands(); i != e; ++i) {
432 MachineOperand &MO = NewMI->getOperand(i);
433 if (!MO.isReg())
434 continue;
435 unsigned Reg = MO.getReg();
Jakob Stoklund Olesen2fb5b312011-01-10 02:58:51 +0000436 if (!TargetRegisterInfo::isVirtualRegister(Reg))
Evan Cheng6154dbd2009-12-04 09:42:45 +0000437 continue;
438 if (MO.isDef()) {
439 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
440 unsigned NewReg = MRI->createVirtualRegister(RC);
441 MO.setReg(NewReg);
442 LocalVRMap.insert(std::make_pair(Reg, NewReg));
Rafael Espindola81512fc2011-06-09 22:53:47 +0000443 if (isDefLiveOut(Reg, TailBB, MRI) || UsedByPhi.count(Reg))
Evan Cheng9e672552009-12-04 19:09:10 +0000444 AddSSAUpdateEntry(Reg, NewReg, PredBB);
Evan Cheng6154dbd2009-12-04 09:42:45 +0000445 } else {
446 DenseMap<unsigned, unsigned>::iterator VI = LocalVRMap.find(Reg);
Jakob Stoklund Olesen00f07de2012-05-20 18:42:51 +0000447 if (VI != LocalVRMap.end()) {
Evan Cheng6154dbd2009-12-04 09:42:45 +0000448 MO.setReg(VI->second);
Jakob Stoklund Olesen00f07de2012-05-20 18:42:51 +0000449 MRI->constrainRegClass(VI->second, MRI->getRegClass(Reg));
450 }
Evan Cheng6154dbd2009-12-04 09:42:45 +0000451 }
452 }
Evan Chengd0c02962012-02-20 07:51:58 +0000453 PredBB->insert(PredBB->instr_end(), NewMI);
Evan Cheng6154dbd2009-12-04 09:42:45 +0000454}
455
456/// UpdateSuccessorsPHIs - After FromBB is tail duplicated into its predecessor
457/// blocks, the successors have gained new predecessors. Update the PHI
458/// instructions in them accordingly.
Evan Chengcc770622009-12-07 10:15:19 +0000459void
460TailDuplicatePass::UpdateSuccessorsPHIs(MachineBasicBlock *FromBB, bool isDead,
Craig Topperb94011f2013-07-14 04:42:23 +0000461 SmallVectorImpl<MachineBasicBlock *> &TDBBs,
Evan Cheng6154dbd2009-12-04 09:42:45 +0000462 SmallSetVector<MachineBasicBlock*,8> &Succs) {
463 for (SmallSetVector<MachineBasicBlock*, 8>::iterator SI = Succs.begin(),
464 SE = Succs.end(); SI != SE; ++SI) {
465 MachineBasicBlock *SuccBB = *SI;
466 for (MachineBasicBlock::iterator II = SuccBB->begin(), EE = SuccBB->end();
467 II != EE; ++II) {
Chris Lattnerb06015a2010-02-09 19:54:29 +0000468 if (!II->isPHI())
Evan Cheng6154dbd2009-12-04 09:42:45 +0000469 break;
Jakob Stoklund Olesenf623e982012-12-20 18:08:06 +0000470 MachineInstrBuilder MIB(*FromBB->getParent(), II);
Evan Chengcc770622009-12-07 10:15:19 +0000471 unsigned Idx = 0;
Evan Cheng6154dbd2009-12-04 09:42:45 +0000472 for (unsigned i = 1, e = II->getNumOperands(); i != e; i += 2) {
Evan Chengcc770622009-12-07 10:15:19 +0000473 MachineOperand &MO = II->getOperand(i+1);
474 if (MO.getMBB() == FromBB) {
475 Idx = i;
Evan Cheng6154dbd2009-12-04 09:42:45 +0000476 break;
Evan Chengcc770622009-12-07 10:15:19 +0000477 }
478 }
479
480 assert(Idx != 0);
481 MachineOperand &MO0 = II->getOperand(Idx);
482 unsigned Reg = MO0.getReg();
483 if (isDead) {
484 // Folded into the previous BB.
485 // There could be duplicate phi source entries. FIXME: Should sdisel
486 // or earlier pass fixed this?
487 for (unsigned i = II->getNumOperands()-2; i != Idx; i -= 2) {
488 MachineOperand &MO = II->getOperand(i+1);
489 if (MO.getMBB() == FromBB) {
490 II->RemoveOperand(i+1);
491 II->RemoveOperand(i);
492 }
493 }
Jakob Stoklund Olesen75521ca2010-02-11 00:34:33 +0000494 } else
495 Idx = 0;
496
497 // If Idx is set, the operands at Idx and Idx+1 must be removed.
498 // We reuse the location to avoid expensive RemoveOperand calls.
499
Evan Chengcc770622009-12-07 10:15:19 +0000500 DenseMap<unsigned,AvailableValsTy>::iterator LI=SSAUpdateVals.find(Reg);
501 if (LI != SSAUpdateVals.end()) {
502 // This register is defined in the tail block.
Evan Cheng6154dbd2009-12-04 09:42:45 +0000503 for (unsigned j = 0, ee = LI->second.size(); j != ee; ++j) {
Evan Cheng9e672552009-12-04 19:09:10 +0000504 MachineBasicBlock *SrcBB = LI->second[j].first;
Rafael Espindola9e97a892011-06-09 23:55:56 +0000505 // If we didn't duplicate a bb into a particular predecessor, we
506 // might still have added an entry to SSAUpdateVals to correcly
507 // recompute SSA. If that case, avoid adding a dummy extra argument
508 // this PHI.
509 if (!SrcBB->isSuccessor(SuccBB))
510 continue;
511
Evan Cheng9e672552009-12-04 19:09:10 +0000512 unsigned SrcReg = LI->second[j].second;
Jakob Stoklund Olesen75521ca2010-02-11 00:34:33 +0000513 if (Idx != 0) {
514 II->getOperand(Idx).setReg(SrcReg);
515 II->getOperand(Idx+1).setMBB(SrcBB);
516 Idx = 0;
517 } else {
Jakob Stoklund Olesenf623e982012-12-20 18:08:06 +0000518 MIB.addReg(SrcReg).addMBB(SrcBB);
Jakob Stoklund Olesen75521ca2010-02-11 00:34:33 +0000519 }
Evan Cheng6154dbd2009-12-04 09:42:45 +0000520 }
Evan Chengcc770622009-12-07 10:15:19 +0000521 } else {
522 // Live in tail block, must also be live in predecessors.
523 for (unsigned j = 0, ee = TDBBs.size(); j != ee; ++j) {
524 MachineBasicBlock *SrcBB = TDBBs[j];
Jakob Stoklund Olesen75521ca2010-02-11 00:34:33 +0000525 if (Idx != 0) {
526 II->getOperand(Idx).setReg(Reg);
527 II->getOperand(Idx+1).setMBB(SrcBB);
528 Idx = 0;
529 } else {
Jakob Stoklund Olesenf623e982012-12-20 18:08:06 +0000530 MIB.addReg(Reg).addMBB(SrcBB);
Jakob Stoklund Olesen75521ca2010-02-11 00:34:33 +0000531 }
Evan Chengcc770622009-12-07 10:15:19 +0000532 }
Evan Cheng6154dbd2009-12-04 09:42:45 +0000533 }
Jakob Stoklund Olesen75521ca2010-02-11 00:34:33 +0000534 if (Idx != 0) {
535 II->RemoveOperand(Idx+1);
536 II->RemoveOperand(Idx);
537 }
Evan Cheng6154dbd2009-12-04 09:42:45 +0000538 }
539 }
540}
541
Rafael Espindola73f93932011-06-09 19:54:42 +0000542/// shouldTailDuplicate - Determine if it is profitable to duplicate this block.
Evan Chengcc770622009-12-07 10:15:19 +0000543bool
Rafael Espindola73f93932011-06-09 19:54:42 +0000544TailDuplicatePass::shouldTailDuplicate(const MachineFunction &MF,
Rafael Espindolae25a8712011-06-23 03:41:29 +0000545 bool IsSimple,
Rafael Espindola73f93932011-06-09 19:54:42 +0000546 MachineBasicBlock &TailBB) {
547 // Only duplicate blocks that end with unconditional branches.
548 if (TailBB.canFallThrough())
549 return false;
550
Rafael Espindola79a4b7e2011-06-17 05:54:50 +0000551 // Don't try to tail-duplicate single-block loops.
552 if (TailBB.isSuccessor(&TailBB))
553 return false;
554
Rafael Espindola73f93932011-06-09 19:54:42 +0000555 // Set the limit on the cost to duplicate. When optimizing for size,
Bob Wilson2d4ff122009-11-26 00:32:21 +0000556 // duplicate only one, because one branch instruction can be eliminated to
557 // compensate for the duplication.
558 unsigned MaxDuplicateCount;
Jakob Stoklund Olesen9af7afc2011-01-30 20:38:12 +0000559 if (TailDuplicateSize.getNumOccurrences() == 0 &&
Bill Wendling698e84f2012-12-30 10:32:01 +0000560 MF.getFunction()->getAttributes().
561 hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize))
Bob Wilson598f8ff2009-11-30 18:56:45 +0000562 MaxDuplicateCount = 1;
Bob Wilson2d4ff122009-11-26 00:32:21 +0000563 else
564 MaxDuplicateCount = TailDuplicateSize;
565
Rafael Espindola79a4b7e2011-06-17 05:54:50 +0000566 // If the target has hardware branch prediction that can handle indirect
567 // branches, duplicating them can often make them predictable when there
568 // are common paths through the code. The limit needs to be high enough
569 // to allow undoing the effects of tail merging and other optimizations
570 // that rearrange the predecessors of the indirect branch.
Bob Wilson97598f02010-01-16 00:42:25 +0000571
Rafael Espindolaf9f012e2011-07-04 01:21:42 +0000572 bool HasIndirectbr = false;
573 if (!TailBB.empty())
Evan Cheng7f8e5632011-12-07 07:15:52 +0000574 HasIndirectbr = TailBB.back().isIndirectBranch();
Rafael Espindolaf9f012e2011-07-04 01:21:42 +0000575
576 if (HasIndirectbr && PreRegAlloc)
577 MaxDuplicateCount = 20;
Bob Wilson1a234c02010-01-15 06:29:17 +0000578
Bob Wilson2d4ff122009-11-26 00:32:21 +0000579 // Check the instructions in the block to determine whether tail-duplication
580 // is invalid or unlikely to be profitable.
Bob Wilsonfffbc0c2009-12-02 17:15:24 +0000581 unsigned InstrCount = 0;
Evan Cheng2a81dd42011-12-06 22:12:01 +0000582 for (MachineBasicBlock::iterator I = TailBB.begin(); I != TailBB.end(); ++I) {
Bob Wilson2d4ff122009-11-26 00:32:21 +0000583 // Non-duplicable things shouldn't be tail-duplicated.
Evan Cheng7f8e5632011-12-07 07:15:52 +0000584 if (I->isNotDuplicable())
Rafael Espindola79a4b7e2011-06-17 05:54:50 +0000585 return false;
586
Evan Cheng6154dbd2009-12-04 09:42:45 +0000587 // Do not duplicate 'return' instructions if this is a pre-regalloc run.
588 // A return may expand into a lot more instructions (e.g. reload of callee
589 // saved registers) after PEI.
Evan Cheng7f8e5632011-12-07 07:15:52 +0000590 if (PreRegAlloc && I->isReturn())
Rafael Espindola79a4b7e2011-06-17 05:54:50 +0000591 return false;
592
593 // Avoid duplicating calls before register allocation. Calls presents a
594 // barrier to register allocation so duplicating them may end up increasing
595 // spills.
Evan Cheng7f8e5632011-12-07 07:15:52 +0000596 if (PreRegAlloc && I->isCall())
Rafael Espindola79a4b7e2011-06-17 05:54:50 +0000597 return false;
598
Devang Patela0bb7152010-03-16 21:02:07 +0000599 if (!I->isPHI() && !I->isDebugValue())
Bob Wilsonfffbc0c2009-12-02 17:15:24 +0000600 InstrCount += 1;
Rafael Espindola79a4b7e2011-06-17 05:54:50 +0000601
602 if (InstrCount > MaxDuplicateCount)
603 return false;
Bob Wilson2d4ff122009-11-26 00:32:21 +0000604 }
Bob Wilson2d4ff122009-11-26 00:32:21 +0000605
Rafael Espindolaf9f012e2011-07-04 01:21:42 +0000606 if (HasIndirectbr && PreRegAlloc)
Rafael Espindolae25a8712011-06-23 03:41:29 +0000607 return true;
608
609 if (IsSimple)
Rafael Espindolacb0213b2011-06-24 15:47:41 +0000610 return true;
Rafael Espindolae25a8712011-06-23 03:41:29 +0000611
612 if (!PreRegAlloc)
613 return true;
614
Rafael Espindola5135ae22011-06-24 15:50:56 +0000615 return canCompletelyDuplicateBB(TailBB);
Rafael Espindola73f93932011-06-09 19:54:42 +0000616}
617
Rafael Espindolaef636bf2011-06-20 04:16:35 +0000618/// isSimpleBB - True if this BB has only one unconditional jump.
619bool
620TailDuplicatePass::isSimpleBB(MachineBasicBlock *TailBB) {
621 if (TailBB->succ_size() != 1)
622 return false;
Rafael Espindolae25a8712011-06-23 03:41:29 +0000623 if (TailBB->pred_empty())
624 return false;
Rafael Espindola2496c1f2011-06-22 22:31:57 +0000625 MachineBasicBlock::iterator I = TailBB->begin();
Rafael Espindolaef636bf2011-06-20 04:16:35 +0000626 MachineBasicBlock::iterator E = TailBB->end();
Rafael Espindola2496c1f2011-06-22 22:31:57 +0000627 while (I != E && I->isDebugValue())
Rafael Espindolaef636bf2011-06-20 04:16:35 +0000628 ++I;
629 if (I == E)
630 return true;
Evan Cheng7f8e5632011-12-07 07:15:52 +0000631 return I->isUnconditionalBranch();
Rafael Espindolaef636bf2011-06-20 04:16:35 +0000632}
633
634static bool
635bothUsedInPHI(const MachineBasicBlock &A,
636 SmallPtrSet<MachineBasicBlock*, 8> SuccsB) {
637 for (MachineBasicBlock::const_succ_iterator SI = A.succ_begin(),
638 SE = A.succ_end(); SI != SE; ++SI) {
639 MachineBasicBlock *BB = *SI;
640 if (SuccsB.count(BB) && !BB->empty() && BB->begin()->isPHI())
641 return true;
642 }
643
644 return false;
645}
646
647bool
Rafael Espindola5135ae22011-06-24 15:50:56 +0000648TailDuplicatePass::canCompletelyDuplicateBB(MachineBasicBlock &BB) {
Rafael Espindolaef636bf2011-06-20 04:16:35 +0000649 for (MachineBasicBlock::pred_iterator PI = BB.pred_begin(),
650 PE = BB.pred_end(); PI != PE; ++PI) {
651 MachineBasicBlock *PredBB = *PI;
Rafael Espindolae25a8712011-06-23 03:41:29 +0000652
Rafael Espindola5135ae22011-06-24 15:50:56 +0000653 if (PredBB->succ_size() > 1)
654 return false;
Rafael Espindolae25a8712011-06-23 03:41:29 +0000655
Rafael Espindolaef636bf2011-06-20 04:16:35 +0000656 MachineBasicBlock *PredTBB = NULL, *PredFBB = NULL;
657 SmallVector<MachineOperand, 4> PredCond;
658 if (TII->AnalyzeBranch(*PredBB, PredTBB, PredFBB, PredCond, true))
659 return false;
Rafael Espindolae25a8712011-06-23 03:41:29 +0000660
Rafael Espindola5135ae22011-06-24 15:50:56 +0000661 if (!PredCond.empty())
Rafael Espindolae25a8712011-06-23 03:41:29 +0000662 return false;
Rafael Espindolaef636bf2011-06-20 04:16:35 +0000663 }
664 return true;
665}
666
Rafael Espindolacb0213b2011-06-24 15:47:41 +0000667bool
Rafael Espindolaef636bf2011-06-20 04:16:35 +0000668TailDuplicatePass::duplicateSimpleBB(MachineBasicBlock *TailBB,
Craig Topperb94011f2013-07-14 04:42:23 +0000669 SmallVectorImpl<MachineBasicBlock *> &TDBBs,
670 const DenseSet<unsigned> &UsedByPhi,
671 SmallVectorImpl<MachineInstr *> &Copies) {
Rafael Espindolacb0213b2011-06-24 15:47:41 +0000672 SmallPtrSet<MachineBasicBlock*, 8> Succs(TailBB->succ_begin(),
673 TailBB->succ_end());
Rafael Espindolaef636bf2011-06-20 04:16:35 +0000674 SmallVector<MachineBasicBlock*, 8> Preds(TailBB->pred_begin(),
675 TailBB->pred_end());
Rafael Espindolacb0213b2011-06-24 15:47:41 +0000676 bool Changed = false;
Rafael Espindolaef636bf2011-06-20 04:16:35 +0000677 for (SmallSetVector<MachineBasicBlock *, 8>::iterator PI = Preds.begin(),
678 PE = Preds.end(); PI != PE; ++PI) {
679 MachineBasicBlock *PredBB = *PI;
680
Rafael Espindolacb0213b2011-06-24 15:47:41 +0000681 if (PredBB->getLandingPadSuccessor())
682 continue;
683
684 if (bothUsedInPHI(*PredBB, Succs))
685 continue;
686
Rafael Espindolaef636bf2011-06-20 04:16:35 +0000687 MachineBasicBlock *PredTBB = NULL, *PredFBB = NULL;
688 SmallVector<MachineOperand, 4> PredCond;
Rafael Espindolacb0213b2011-06-24 15:47:41 +0000689 if (TII->AnalyzeBranch(*PredBB, PredTBB, PredFBB, PredCond, true))
690 continue;
Rafael Espindolaef636bf2011-06-20 04:16:35 +0000691
Rafael Espindolacb0213b2011-06-24 15:47:41 +0000692 Changed = true;
Rafael Espindolaef636bf2011-06-20 04:16:35 +0000693 DEBUG(dbgs() << "\nTail-duplicating into PredBB: " << *PredBB
694 << "From simple Succ: " << *TailBB);
695
696 MachineBasicBlock *NewTarget = *TailBB->succ_begin();
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000697 MachineBasicBlock *NextBB = std::next(MachineFunction::iterator(PredBB));
Rafael Espindolaef636bf2011-06-20 04:16:35 +0000698
Rafael Espindolaef636bf2011-06-20 04:16:35 +0000699 // Make PredFBB explicit.
700 if (PredCond.empty())
701 PredFBB = PredTBB;
702
703 // Make fall through explicit.
704 if (!PredTBB)
705 PredTBB = NextBB;
706 if (!PredFBB)
707 PredFBB = NextBB;
708
709 // Redirect
710 if (PredFBB == TailBB)
711 PredFBB = NewTarget;
712 if (PredTBB == TailBB)
713 PredTBB = NewTarget;
714
715 // Make the branch unconditional if possible
Rafael Espindola336e1022011-06-20 14:11:42 +0000716 if (PredTBB == PredFBB) {
717 PredCond.clear();
Rafael Espindolaef636bf2011-06-20 04:16:35 +0000718 PredFBB = NULL;
Rafael Espindola336e1022011-06-20 14:11:42 +0000719 }
Rafael Espindolaef636bf2011-06-20 04:16:35 +0000720
721 // Avoid adding fall through branches.
722 if (PredFBB == NextBB)
723 PredFBB = NULL;
724 if (PredTBB == NextBB && PredFBB == NULL)
725 PredTBB = NULL;
726
727 TII->RemoveBranch(*PredBB);
728
729 if (PredTBB)
730 TII->InsertBranch(*PredBB, PredTBB, PredFBB, PredCond, DebugLoc());
731
Akira Hatanakaa07ffb52014-02-12 18:09:18 +0000732 uint32_t Weight = MBPI->getEdgeWeight(PredBB, TailBB);
Rafael Espindolaef636bf2011-06-20 04:16:35 +0000733 PredBB->removeSuccessor(TailBB);
Rafael Espindola336e1022011-06-20 14:11:42 +0000734 unsigned NumSuccessors = PredBB->succ_size();
735 assert(NumSuccessors <= 1);
736 if (NumSuccessors == 0 || *PredBB->succ_begin() != NewTarget)
Akira Hatanakaa07ffb52014-02-12 18:09:18 +0000737 PredBB->addSuccessor(NewTarget, Weight);
Rafael Espindolaef636bf2011-06-20 04:16:35 +0000738
739 TDBBs.push_back(PredBB);
Rafael Espindolaef636bf2011-06-20 04:16:35 +0000740 }
Rafael Espindolacb0213b2011-06-24 15:47:41 +0000741 return Changed;
Rafael Espindolaef636bf2011-06-20 04:16:35 +0000742}
743
Rafael Espindola73f93932011-06-09 19:54:42 +0000744/// TailDuplicate - If it is profitable, duplicate TailBB's contents in each
745/// of its predecessors.
746bool
Rafael Espindolaf9f012e2011-07-04 01:21:42 +0000747TailDuplicatePass::TailDuplicate(MachineBasicBlock *TailBB,
748 bool IsSimple,
749 MachineFunction &MF,
Craig Topperb94011f2013-07-14 04:42:23 +0000750 SmallVectorImpl<MachineBasicBlock *> &TDBBs,
751 SmallVectorImpl<MachineInstr *> &Copies) {
David Greene85afc852010-01-05 01:25:15 +0000752 DEBUG(dbgs() << "\n*** Tail-duplicating BB#" << TailBB->getNumber() << '\n');
Evan Chengcc770622009-12-07 10:15:19 +0000753
Rafael Espindolaef636bf2011-06-20 04:16:35 +0000754 DenseSet<unsigned> UsedByPhi;
755 getRegsUsedByPHIs(*TailBB, &UsedByPhi);
756
Rafael Espindolacb0213b2011-06-24 15:47:41 +0000757 if (IsSimple)
758 return duplicateSimpleBB(TailBB, TDBBs, UsedByPhi, Copies);
Rafael Espindolaef636bf2011-06-20 04:16:35 +0000759
Bob Wilson2d4ff122009-11-26 00:32:21 +0000760 // Iterate through all the unique predecessors and tail-duplicate this
761 // block into them, if possible. Copying the list ahead of time also
762 // avoids trouble with the predecessor list reallocating.
763 bool Changed = false;
Evan Cheng6154dbd2009-12-04 09:42:45 +0000764 SmallSetVector<MachineBasicBlock*, 8> Preds(TailBB->pred_begin(),
765 TailBB->pred_end());
Bob Wilson2d4ff122009-11-26 00:32:21 +0000766 for (SmallSetVector<MachineBasicBlock *, 8>::iterator PI = Preds.begin(),
767 PE = Preds.end(); PI != PE; ++PI) {
768 MachineBasicBlock *PredBB = *PI;
769
770 assert(TailBB != PredBB &&
771 "Single-block loop should have been rejected earlier!");
Rafael Espindola1ffadd72011-06-10 20:08:23 +0000772 // EH edges are ignored by AnalyzeBranch.
773 if (PredBB->succ_size() > 1)
774 continue;
Bob Wilson2d4ff122009-11-26 00:32:21 +0000775
776 MachineBasicBlock *PredTBB, *PredFBB;
777 SmallVector<MachineOperand, 4> PredCond;
778 if (TII->AnalyzeBranch(*PredBB, PredTBB, PredFBB, PredCond, true))
779 continue;
780 if (!PredCond.empty())
781 continue;
Bob Wilson2d4ff122009-11-26 00:32:21 +0000782 // Don't duplicate into a fall-through predecessor (at least for now).
783 if (PredBB->isLayoutSuccessor(TailBB) && PredBB->canFallThrough())
784 continue;
785
David Greene85afc852010-01-05 01:25:15 +0000786 DEBUG(dbgs() << "\nTail-duplicating into PredBB: " << *PredBB
Bob Wilson2d4ff122009-11-26 00:32:21 +0000787 << "From Succ: " << *TailBB);
788
Evan Chengcc770622009-12-07 10:15:19 +0000789 TDBBs.push_back(PredBB);
790
Bob Wilson2d4ff122009-11-26 00:32:21 +0000791 // Remove PredBB's unconditional branch.
792 TII->RemoveBranch(*PredBB);
Evan Cheng1bbe6be2009-12-03 08:43:53 +0000793
Evan Chengbc2453d2012-05-30 00:42:39 +0000794 if (RS && !TailBB->livein_empty()) {
795 // Update PredBB livein.
796 RS->enterBasicBlock(PredBB);
797 if (!PredBB->empty())
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000798 RS->forward(std::prev(PredBB->end()));
Evan Chengbc2453d2012-05-30 00:42:39 +0000799 BitVector RegsLiveAtExit(TRI->getNumRegs());
800 RS->getRegsUsed(RegsLiveAtExit, false);
801 for (MachineBasicBlock::livein_iterator I = TailBB->livein_begin(),
802 E = TailBB->livein_end(); I != E; ++I) {
803 if (!RegsLiveAtExit[*I])
804 // If a register is previously livein to the tail but it's not live
805 // at the end of predecessor BB, then it should be added to its
806 // livein list.
807 PredBB->addLiveIn(*I);
808 }
809 }
810
Bob Wilson2d4ff122009-11-26 00:32:21 +0000811 // Clone the contents of TailBB into PredBB.
Evan Cheng1bbe6be2009-12-03 08:43:53 +0000812 DenseMap<unsigned, unsigned> LocalVRMap;
Evan Cheng45430bb2009-12-15 01:44:10 +0000813 SmallVector<std::pair<unsigned,unsigned>, 4> CopyInfos;
Evan Chengd0c02962012-02-20 07:51:58 +0000814 // Use instr_iterator here to properly handle bundles, e.g.
815 // ARM Thumb2 IT block.
816 MachineBasicBlock::instr_iterator I = TailBB->instr_begin();
817 while (I != TailBB->instr_end()) {
Evan Cheng6154dbd2009-12-04 09:42:45 +0000818 MachineInstr *MI = &*I;
819 ++I;
Chris Lattnerb06015a2010-02-09 19:54:29 +0000820 if (MI->isPHI()) {
Evan Cheng1bbe6be2009-12-03 08:43:53 +0000821 // Replace the uses of the def of the PHI with the register coming
822 // from PredBB.
Rafael Espindolac735f132011-06-09 23:22:56 +0000823 ProcessPHI(MI, TailBB, PredBB, LocalVRMap, CopyInfos, UsedByPhi, true);
Evan Cheng6154dbd2009-12-04 09:42:45 +0000824 } else {
825 // Replace def of virtual registers with new registers, and update
826 // uses with PHI source register or the new registers.
Rafael Espindola81512fc2011-06-09 22:53:47 +0000827 DuplicateInstruction(MI, TailBB, PredBB, MF, LocalVRMap, UsedByPhi);
Evan Cheng1bbe6be2009-12-03 08:43:53 +0000828 }
Bob Wilson2d4ff122009-11-26 00:32:21 +0000829 }
Evan Chengcc770622009-12-07 10:15:19 +0000830 MachineBasicBlock::iterator Loc = PredBB->getFirstTerminator();
Evan Cheng45430bb2009-12-15 01:44:10 +0000831 for (unsigned i = 0, e = CopyInfos.size(); i != e; ++i) {
Jakob Stoklund Olesen0c76d6e2010-07-10 22:42:59 +0000832 Copies.push_back(BuildMI(*PredBB, Loc, DebugLoc(),
833 TII->get(TargetOpcode::COPY),
834 CopyInfos[i].first).addReg(CopyInfos[i].second));
Evan Chengcc770622009-12-07 10:15:19 +0000835 }
Rafael Espindola79a4b7e2011-06-17 05:54:50 +0000836
837 // Simplify
838 TII->AnalyzeBranch(*PredBB, PredTBB, PredFBB, PredCond, true);
839
Bob Wilson2d4ff122009-11-26 00:32:21 +0000840 NumInstrDups += TailBB->size() - 1; // subtract one for removed branch
841
842 // Update the CFG.
843 PredBB->removeSuccessor(PredBB->succ_begin());
844 assert(PredBB->succ_empty() &&
845 "TailDuplicate called on block with multiple successors!");
846 for (MachineBasicBlock::succ_iterator I = TailBB->succ_begin(),
Evan Cheng6154dbd2009-12-04 09:42:45 +0000847 E = TailBB->succ_end(); I != E; ++I)
Akira Hatanakaa07ffb52014-02-12 18:09:18 +0000848 PredBB->addSuccessor(*I, MBPI->getEdgeWeight(TailBB, I));
Bob Wilson2d4ff122009-11-26 00:32:21 +0000849
850 Changed = true;
851 ++NumTailDups;
852 }
853
854 // If TailBB was duplicated into all its predecessors except for the prior
855 // block, which falls through unconditionally, move the contents of this
856 // block into the prior block.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000857 MachineBasicBlock *PrevBB = std::prev(MachineFunction::iterator(TailBB));
Bob Wilson2d4ff122009-11-26 00:32:21 +0000858 MachineBasicBlock *PriorTBB = 0, *PriorFBB = 0;
859 SmallVector<MachineOperand, 4> PriorCond;
Bob Wilson2d4ff122009-11-26 00:32:21 +0000860 // This has to check PrevBB->succ_size() because EH edges are ignored by
861 // AnalyzeBranch.
Andrew Trickc0449172012-02-08 21:22:30 +0000862 if (PrevBB->succ_size() == 1 &&
Rafael Espindolac90a32a2011-06-09 21:43:25 +0000863 !TII->AnalyzeBranch(*PrevBB, PriorTBB, PriorFBB, PriorCond, true) &&
864 PriorCond.empty() && !PriorTBB && TailBB->pred_size() == 1 &&
Bob Wilson2d4ff122009-11-26 00:32:21 +0000865 !TailBB->hasAddressTaken()) {
David Greene85afc852010-01-05 01:25:15 +0000866 DEBUG(dbgs() << "\nMerging into block: " << *PrevBB
Bob Wilson2d4ff122009-11-26 00:32:21 +0000867 << "From MBB: " << *TailBB);
Evan Cheng6154dbd2009-12-04 09:42:45 +0000868 if (PreRegAlloc) {
869 DenseMap<unsigned, unsigned> LocalVRMap;
Evan Cheng45430bb2009-12-15 01:44:10 +0000870 SmallVector<std::pair<unsigned,unsigned>, 4> CopyInfos;
Evan Cheng6154dbd2009-12-04 09:42:45 +0000871 MachineBasicBlock::iterator I = TailBB->begin();
872 // Process PHI instructions first.
Chris Lattnerb06015a2010-02-09 19:54:29 +0000873 while (I != TailBB->end() && I->isPHI()) {
Evan Cheng6154dbd2009-12-04 09:42:45 +0000874 // Replace the uses of the def of the PHI with the register coming
875 // from PredBB.
876 MachineInstr *MI = &*I++;
Rafael Espindolac735f132011-06-09 23:22:56 +0000877 ProcessPHI(MI, TailBB, PrevBB, LocalVRMap, CopyInfos, UsedByPhi, true);
Evan Cheng6154dbd2009-12-04 09:42:45 +0000878 if (MI->getParent())
879 MI->eraseFromParent();
880 }
881
882 // Now copy the non-PHI instructions.
883 while (I != TailBB->end()) {
884 // Replace def of virtual registers with new registers, and update
885 // uses with PHI source register or the new registers.
886 MachineInstr *MI = &*I++;
Evan Chengd0c02962012-02-20 07:51:58 +0000887 assert(!MI->isBundle() && "Not expecting bundles before regalloc!");
Rafael Espindola81512fc2011-06-09 22:53:47 +0000888 DuplicateInstruction(MI, TailBB, PrevBB, MF, LocalVRMap, UsedByPhi);
Evan Cheng6154dbd2009-12-04 09:42:45 +0000889 MI->eraseFromParent();
890 }
Evan Chengcc770622009-12-07 10:15:19 +0000891 MachineBasicBlock::iterator Loc = PrevBB->getFirstTerminator();
Evan Cheng45430bb2009-12-15 01:44:10 +0000892 for (unsigned i = 0, e = CopyInfos.size(); i != e; ++i) {
Jakob Stoklund Olesen0c76d6e2010-07-10 22:42:59 +0000893 Copies.push_back(BuildMI(*PrevBB, Loc, DebugLoc(),
894 TII->get(TargetOpcode::COPY),
895 CopyInfos[i].first)
896 .addReg(CopyInfos[i].second));
Evan Chengcc770622009-12-07 10:15:19 +0000897 }
Evan Cheng6154dbd2009-12-04 09:42:45 +0000898 } else {
899 // No PHIs to worry about, just splice the instructions over.
900 PrevBB->splice(PrevBB->end(), TailBB, TailBB->begin(), TailBB->end());
901 }
902 PrevBB->removeSuccessor(PrevBB->succ_begin());
903 assert(PrevBB->succ_empty());
904 PrevBB->transferSuccessors(TailBB);
Evan Chengcc770622009-12-07 10:15:19 +0000905 TDBBs.push_back(PrevBB);
Bob Wilson2d4ff122009-11-26 00:32:21 +0000906 Changed = true;
907 }
908
Rafael Espindolac735f132011-06-09 23:22:56 +0000909 // If this is after register allocation, there are no phis to fix.
910 if (!PreRegAlloc)
911 return Changed;
912
913 // If we made no changes so far, we are safe.
914 if (!Changed)
915 return Changed;
916
917
918 // Handle the nasty case in that we duplicated a block that is part of a loop
919 // into some but not all of its predecessors. For example:
Rafael Espindolac9e93a42011-06-09 23:51:45 +0000920 // 1 -> 2 <-> 3 |
921 // \ |
922 // \---> rest |
Rafael Espindolac735f132011-06-09 23:22:56 +0000923 // if we duplicate 2 into 1 but not into 3, we end up with
Rafael Espindolac9e93a42011-06-09 23:51:45 +0000924 // 12 -> 3 <-> 2 -> rest |
925 // \ / |
926 // \----->-----/ |
Rafael Espindolac735f132011-06-09 23:22:56 +0000927 // If there was a "var = phi(1, 3)" in 2, it has to be ultimately replaced
928 // with a phi in 3 (which now dominates 2).
929 // What we do here is introduce a copy in 3 of the register defined by the
930 // phi, just like when we are duplicating 2 into 3, but we don't copy any
931 // real instructions or remove the 3 -> 2 edge from the phi in 2.
932 for (SmallSetVector<MachineBasicBlock *, 8>::iterator PI = Preds.begin(),
933 PE = Preds.end(); PI != PE; ++PI) {
934 MachineBasicBlock *PredBB = *PI;
935 if (std::find(TDBBs.begin(), TDBBs.end(), PredBB) != TDBBs.end())
936 continue;
937
938 // EH edges
939 if (PredBB->succ_size() != 1)
940 continue;
941
942 DenseMap<unsigned, unsigned> LocalVRMap;
943 SmallVector<std::pair<unsigned,unsigned>, 4> CopyInfos;
944 MachineBasicBlock::iterator I = TailBB->begin();
945 // Process PHI instructions first.
946 while (I != TailBB->end() && I->isPHI()) {
947 // Replace the uses of the def of the PHI with the register coming
948 // from PredBB.
949 MachineInstr *MI = &*I++;
950 ProcessPHI(MI, TailBB, PredBB, LocalVRMap, CopyInfos, UsedByPhi, false);
951 }
952 MachineBasicBlock::iterator Loc = PredBB->getFirstTerminator();
953 for (unsigned i = 0, e = CopyInfos.size(); i != e; ++i) {
954 Copies.push_back(BuildMI(*PredBB, Loc, DebugLoc(),
955 TII->get(TargetOpcode::COPY),
956 CopyInfos[i].first).addReg(CopyInfos[i].second));
957 }
958 }
959
Bob Wilson2d4ff122009-11-26 00:32:21 +0000960 return Changed;
961}
962
963/// RemoveDeadBlock - Remove the specified dead machine basic block from the
964/// function, updating the CFG.
Bob Wilson9594db52009-11-26 21:38:41 +0000965void TailDuplicatePass::RemoveDeadBlock(MachineBasicBlock *MBB) {
Bob Wilson2d4ff122009-11-26 00:32:21 +0000966 assert(MBB->pred_empty() && "MBB must be dead!");
David Greene85afc852010-01-05 01:25:15 +0000967 DEBUG(dbgs() << "\nRemoving MBB: " << *MBB);
Bob Wilson2d4ff122009-11-26 00:32:21 +0000968
969 // Remove all successors.
970 while (!MBB->succ_empty())
971 MBB->removeSuccessor(MBB->succ_end()-1);
972
Bob Wilson2d4ff122009-11-26 00:32:21 +0000973 // Remove the block.
974 MBB->eraseFromParent();
975}