blob: 04b39922627e034c03bdde038601312c932fcd1b [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
Bob Wilson15acadd2009-11-26 00:32:21 +000015#include "llvm/CodeGen/Passes.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000016#include "llvm/ADT/DenseSet.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000017#include "llvm/ADT/SetVector.h"
18#include "llvm/ADT/SmallSet.h"
19#include "llvm/ADT/Statistic.h"
Stephen Hines36b56882014-04-23 16:57:46 -070020#include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
Bob Wilson15acadd2009-11-26 00:32:21 +000021#include "llvm/CodeGen/MachineFunctionPass.h"
Jakob Stoklund Olesen1e1098c2010-07-10 22:42:59 +000022#include "llvm/CodeGen/MachineInstrBuilder.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000023#include "llvm/CodeGen/MachineModuleInfo.h"
Evan Cheng111e7622009-12-03 08:43:53 +000024#include "llvm/CodeGen/MachineRegisterInfo.h"
25#include "llvm/CodeGen/MachineSSAUpdater.h"
Evan Chengeb25bd22012-05-30 00:42:39 +000026#include "llvm/CodeGen/RegisterScavenging.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000027#include "llvm/IR/Function.h"
Bob Wilson15acadd2009-11-26 00:32:21 +000028#include "llvm/Support/CommandLine.h"
29#include "llvm/Support/Debug.h"
Evan Cheng75eb5352009-12-07 10:15:19 +000030#include "llvm/Support/ErrorHandling.h"
Bob Wilson15acadd2009-11-26 00:32:21 +000031#include "llvm/Support/raw_ostream.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000032#include "llvm/Target/TargetInstrInfo.h"
33#include "llvm/Target/TargetRegisterInfo.h"
Stephen Hines37ed9c12014-12-01 14:51:49 -080034#include "llvm/Target/TargetSubtargetInfo.h"
Bob Wilson15acadd2009-11-26 00:32:21 +000035using namespace llvm;
36
Stephen Hinesdce4a402014-05-29 02:49:00 -070037#define DEBUG_TYPE "tailduplication"
38
Evan Cheng75eb5352009-12-07 10:15:19 +000039STATISTIC(NumTails , "Number of tails duplicated");
Bob Wilson15acadd2009-11-26 00:32:21 +000040STATISTIC(NumTailDups , "Number of tail duplicated blocks");
41STATISTIC(NumInstrDups , "Additional instructions due to tail duplication");
42STATISTIC(NumDeadBlocks, "Number of dead blocks removed");
Rafael Espindola0cdca082011-06-08 14:13:31 +000043STATISTIC(NumAddedPHIs , "Number of phis added");
Bob Wilson15acadd2009-11-26 00:32:21 +000044
45// Heuristic for tail duplication.
46static cl::opt<unsigned>
47TailDuplicateSize("tail-dup-size",
48 cl::desc("Maximum instructions to consider tail duplicating"),
49 cl::init(2), cl::Hidden);
50
Evan Cheng75eb5352009-12-07 10:15:19 +000051static cl::opt<bool>
52TailDupVerify("tail-dup-verify",
53 cl::desc("Verify sanity of PHI instructions during taildup"),
54 cl::init(false), cl::Hidden);
55
56static cl::opt<unsigned>
57TailDupLimit("tail-dup-limit", cl::init(~0U), cl::Hidden);
58
Evan Cheng11572ba2009-12-04 19:09:10 +000059typedef std::vector<std::pair<MachineBasicBlock*,unsigned> > AvailableValsTy;
Evan Cheng111e7622009-12-03 08:43:53 +000060
Bob Wilson15acadd2009-11-26 00:32:21 +000061namespace {
Bob Wilson2d521e52009-11-26 21:38:41 +000062 /// TailDuplicatePass - Perform tail duplication.
63 class TailDuplicatePass : public MachineFunctionPass {
Bob Wilson15acadd2009-11-26 00:32:21 +000064 const TargetInstrInfo *TII;
Evan Chengeb25bd22012-05-30 00:42:39 +000065 const TargetRegisterInfo *TRI;
Stephen Hines36b56882014-04-23 16:57:46 -070066 const MachineBranchProbabilityInfo *MBPI;
Bob Wilson15acadd2009-11-26 00:32:21 +000067 MachineModuleInfo *MMI;
Evan Cheng111e7622009-12-03 08:43:53 +000068 MachineRegisterInfo *MRI;
Stephen Hines36b56882014-04-23 16:57:46 -070069 std::unique_ptr<RegScavenger> RS;
Andrew Trickd2a7bed2012-02-08 21:22:30 +000070 bool PreRegAlloc;
Evan Cheng111e7622009-12-03 08:43:53 +000071
72 // SSAUpdateVRs - A list of virtual registers for which to update SSA form.
73 SmallVector<unsigned, 16> SSAUpdateVRs;
74
75 // SSAUpdateVals - For each virtual register in SSAUpdateVals keep a list of
76 // source virtual registers.
77 DenseMap<unsigned, AvailableValsTy> SSAUpdateVals;
Bob Wilson15acadd2009-11-26 00:32:21 +000078
79 public:
80 static char ID;
Andrew Trickd2a7bed2012-02-08 21:22:30 +000081 explicit TailDuplicatePass() :
82 MachineFunctionPass(ID), PreRegAlloc(false) {}
Bob Wilson15acadd2009-11-26 00:32:21 +000083
Stephen Hines36b56882014-04-23 16:57:46 -070084 bool runOnMachineFunction(MachineFunction &MF) override;
85
86 void getAnalysisUsage(AnalysisUsage &AU) const override;
Bob Wilson15acadd2009-11-26 00:32:21 +000087
88 private:
Evan Cheng11572ba2009-12-04 19:09:10 +000089 void AddSSAUpdateEntry(unsigned OrigReg, unsigned NewReg,
90 MachineBasicBlock *BB);
Evan Cheng79fc6f42009-12-04 09:42:45 +000091 void ProcessPHI(MachineInstr *MI, MachineBasicBlock *TailBB,
92 MachineBasicBlock *PredBB,
Evan Cheng75eb5352009-12-07 10:15:19 +000093 DenseMap<unsigned, unsigned> &LocalVRMap,
Craig Toppera0ec3f92013-07-14 04:42:23 +000094 SmallVectorImpl<std::pair<unsigned,unsigned> > &Copies,
Rafael Espindola689d7d52011-06-09 23:22:56 +000095 const DenseSet<unsigned> &UsedByPhi,
96 bool Remove);
Evan Cheng79fc6f42009-12-04 09:42:45 +000097 void DuplicateInstruction(MachineInstr *MI,
98 MachineBasicBlock *TailBB,
99 MachineBasicBlock *PredBB,
100 MachineFunction &MF,
Rafael Espindola0f28c3f2011-06-09 22:53:47 +0000101 DenseMap<unsigned, unsigned> &LocalVRMap,
102 const DenseSet<unsigned> &UsedByPhi);
Evan Cheng75eb5352009-12-07 10:15:19 +0000103 void UpdateSuccessorsPHIs(MachineBasicBlock *FromBB, bool isDead,
Craig Toppera0ec3f92013-07-14 04:42:23 +0000104 SmallVectorImpl<MachineBasicBlock *> &TDBBs,
Evan Cheng75eb5352009-12-07 10:15:19 +0000105 SmallSetVector<MachineBasicBlock*, 8> &Succs);
Bob Wilson15acadd2009-11-26 00:32:21 +0000106 bool TailDuplicateBlocks(MachineFunction &MF);
Rafael Espindola54c25622011-06-09 19:54:42 +0000107 bool shouldTailDuplicate(const MachineFunction &MF,
Rafael Espindola9dbbd872011-06-23 03:41:29 +0000108 bool IsSimple, MachineBasicBlock &TailBB);
Rafael Espindola275c1f92011-06-20 04:16:35 +0000109 bool isSimpleBB(MachineBasicBlock *TailBB);
Rafael Espindola40179bf2011-06-24 15:50:56 +0000110 bool canCompletelyDuplicateBB(MachineBasicBlock &BB);
Rafael Espindolad7f35fa2011-06-24 15:47:41 +0000111 bool duplicateSimpleBB(MachineBasicBlock *TailBB,
Craig Toppera0ec3f92013-07-14 04:42:23 +0000112 SmallVectorImpl<MachineBasicBlock *> &TDBBs,
Rafael Espindola275c1f92011-06-20 04:16:35 +0000113 const DenseSet<unsigned> &RegsUsedByPhi,
Craig Toppera0ec3f92013-07-14 04:42:23 +0000114 SmallVectorImpl<MachineInstr *> &Copies);
Rafael Espindola6a9d2b12011-07-04 01:21:42 +0000115 bool TailDuplicate(MachineBasicBlock *TailBB,
116 bool IsSimple,
117 MachineFunction &MF,
Craig Toppera0ec3f92013-07-14 04:42:23 +0000118 SmallVectorImpl<MachineBasicBlock *> &TDBBs,
119 SmallVectorImpl<MachineInstr *> &Copies);
Rafael Espindola6a9d2b12011-07-04 01:21:42 +0000120 bool TailDuplicateAndUpdate(MachineBasicBlock *MBB,
121 bool IsSimple,
122 MachineFunction &MF);
123
Bob Wilson15acadd2009-11-26 00:32:21 +0000124 void RemoveDeadBlock(MachineBasicBlock *MBB);
125 };
126
Bob Wilson2d521e52009-11-26 21:38:41 +0000127 char TailDuplicatePass::ID = 0;
Bob Wilson15acadd2009-11-26 00:32:21 +0000128}
129
Andrew Trick1dd8c852012-02-08 21:23:13 +0000130char &llvm::TailDuplicateID = TailDuplicatePass::ID;
131
132INITIALIZE_PASS(TailDuplicatePass, "tailduplication", "Tail Duplication",
133 false, false)
Bob Wilson15acadd2009-11-26 00:32:21 +0000134
Bob Wilson2d521e52009-11-26 21:38:41 +0000135bool TailDuplicatePass::runOnMachineFunction(MachineFunction &MF) {
Stephen Hines36b56882014-04-23 16:57:46 -0700136 if (skipOptnoneFunction(*MF.getFunction()))
137 return false;
138
Stephen Hines37ed9c12014-12-01 14:51:49 -0800139 TII = MF.getSubtarget().getInstrInfo();
140 TRI = MF.getSubtarget().getRegisterInfo();
Evan Cheng111e7622009-12-03 08:43:53 +0000141 MRI = &MF.getRegInfo();
Bob Wilson15acadd2009-11-26 00:32:21 +0000142 MMI = getAnalysisIfAvailable<MachineModuleInfo>();
Stephen Hines36b56882014-04-23 16:57:46 -0700143 MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
144
Andrew Trickd2a7bed2012-02-08 21:22:30 +0000145 PreRegAlloc = MRI->isSSA();
Benjamin Kramerd14e4e12012-06-06 13:53:41 +0000146 RS.reset();
Evan Chengeb25bd22012-05-30 00:42:39 +0000147 if (MRI->tracksLiveness() && TRI->trackLivenessAfterRegAlloc(MF))
Benjamin Kramerd14e4e12012-06-06 13:53:41 +0000148 RS.reset(new RegScavenger());
Bob Wilson15acadd2009-11-26 00:32:21 +0000149
150 bool MadeChange = false;
Jakob Stoklund Olesen057d5392010-01-15 19:59:57 +0000151 while (TailDuplicateBlocks(MF))
152 MadeChange = true;
Bob Wilson15acadd2009-11-26 00:32:21 +0000153
154 return MadeChange;
155}
156
Stephen Hines36b56882014-04-23 16:57:46 -0700157void TailDuplicatePass::getAnalysisUsage(AnalysisUsage &AU) const {
158 AU.addRequired<MachineBranchProbabilityInfo>();
159 MachineFunctionPass::getAnalysisUsage(AU);
160}
161
Evan Cheng75eb5352009-12-07 10:15:19 +0000162static void VerifyPHIs(MachineFunction &MF, bool CheckExtra) {
163 for (MachineFunction::iterator I = ++MF.begin(), E = MF.end(); I != E; ++I) {
164 MachineBasicBlock *MBB = I;
165 SmallSetVector<MachineBasicBlock*, 8> Preds(MBB->pred_begin(),
166 MBB->pred_end());
167 MachineBasicBlock::iterator MI = MBB->begin();
168 while (MI != MBB->end()) {
Chris Lattner518bb532010-02-09 19:54:29 +0000169 if (!MI->isPHI())
Evan Cheng75eb5352009-12-07 10:15:19 +0000170 break;
171 for (SmallSetVector<MachineBasicBlock *, 8>::iterator PI = Preds.begin(),
172 PE = Preds.end(); PI != PE; ++PI) {
173 MachineBasicBlock *PredBB = *PI;
174 bool Found = false;
175 for (unsigned i = 1, e = MI->getNumOperands(); i != e; i += 2) {
176 MachineBasicBlock *PHIBB = MI->getOperand(i+1).getMBB();
177 if (PHIBB == PredBB) {
178 Found = true;
179 break;
180 }
181 }
182 if (!Found) {
David Greene00dec1b2010-01-05 01:25:15 +0000183 dbgs() << "Malformed PHI in BB#" << MBB->getNumber() << ": " << *MI;
184 dbgs() << " missing input from predecessor BB#"
Evan Cheng75eb5352009-12-07 10:15:19 +0000185 << PredBB->getNumber() << '\n';
Stephen Hinesdce4a402014-05-29 02:49:00 -0700186 llvm_unreachable(nullptr);
Evan Cheng75eb5352009-12-07 10:15:19 +0000187 }
188 }
189
190 for (unsigned i = 1, e = MI->getNumOperands(); i != e; i += 2) {
191 MachineBasicBlock *PHIBB = MI->getOperand(i+1).getMBB();
192 if (CheckExtra && !Preds.count(PHIBB)) {
David Greene00dec1b2010-01-05 01:25:15 +0000193 dbgs() << "Warning: malformed PHI in BB#" << MBB->getNumber()
Evan Cheng75eb5352009-12-07 10:15:19 +0000194 << ": " << *MI;
David Greene00dec1b2010-01-05 01:25:15 +0000195 dbgs() << " extra input from predecessor BB#"
Evan Cheng75eb5352009-12-07 10:15:19 +0000196 << PHIBB->getNumber() << '\n';
Stephen Hinesdce4a402014-05-29 02:49:00 -0700197 llvm_unreachable(nullptr);
Evan Cheng75eb5352009-12-07 10:15:19 +0000198 }
199 if (PHIBB->getNumber() < 0) {
David Greene00dec1b2010-01-05 01:25:15 +0000200 dbgs() << "Malformed PHI in BB#" << MBB->getNumber() << ": " << *MI;
201 dbgs() << " non-existing BB#" << PHIBB->getNumber() << '\n';
Stephen Hinesdce4a402014-05-29 02:49:00 -0700202 llvm_unreachable(nullptr);
Evan Cheng75eb5352009-12-07 10:15:19 +0000203 }
204 }
205 ++MI;
206 }
207 }
208}
209
Rafael Espindola6a9d2b12011-07-04 01:21:42 +0000210/// TailDuplicateAndUpdate - Tail duplicate the block and cleanup.
211bool
212TailDuplicatePass::TailDuplicateAndUpdate(MachineBasicBlock *MBB,
213 bool IsSimple,
214 MachineFunction &MF) {
215 // Save the successors list.
216 SmallSetVector<MachineBasicBlock*, 8> Succs(MBB->succ_begin(),
217 MBB->succ_end());
218
219 SmallVector<MachineBasicBlock*, 8> TDBBs;
220 SmallVector<MachineInstr*, 16> Copies;
221 if (!TailDuplicate(MBB, IsSimple, MF, TDBBs, Copies))
222 return false;
223
224 ++NumTails;
225
226 SmallVector<MachineInstr*, 8> NewPHIs;
227 MachineSSAUpdater SSAUpdate(MF, &NewPHIs);
228
229 // TailBB's immediate successors are now successors of those predecessors
230 // which duplicated TailBB. Add the predecessors as sources to the PHI
231 // instructions.
232 bool isDead = MBB->pred_empty() && !MBB->hasAddressTaken();
233 if (PreRegAlloc)
234 UpdateSuccessorsPHIs(MBB, isDead, TDBBs, Succs);
235
236 // If it is dead, remove it.
237 if (isDead) {
238 NumInstrDups -= MBB->size();
239 RemoveDeadBlock(MBB);
240 ++NumDeadBlocks;
241 }
242
243 // Update SSA form.
244 if (!SSAUpdateVRs.empty()) {
245 for (unsigned i = 0, e = SSAUpdateVRs.size(); i != e; ++i) {
246 unsigned VReg = SSAUpdateVRs[i];
247 SSAUpdate.Initialize(VReg);
248
249 // If the original definition is still around, add it as an available
250 // value.
251 MachineInstr *DefMI = MRI->getVRegDef(VReg);
Stephen Hinesdce4a402014-05-29 02:49:00 -0700252 MachineBasicBlock *DefBB = nullptr;
Rafael Espindola6a9d2b12011-07-04 01:21:42 +0000253 if (DefMI) {
254 DefBB = DefMI->getParent();
255 SSAUpdate.AddAvailableValue(DefBB, VReg);
256 }
257
258 // Add the new vregs as available values.
259 DenseMap<unsigned, AvailableValsTy>::iterator LI =
260 SSAUpdateVals.find(VReg);
261 for (unsigned j = 0, ee = LI->second.size(); j != ee; ++j) {
262 MachineBasicBlock *SrcBB = LI->second[j].first;
263 unsigned SrcReg = LI->second[j].second;
264 SSAUpdate.AddAvailableValue(SrcBB, SrcReg);
265 }
266
267 // Rewrite uses that are outside of the original def's block.
268 MachineRegisterInfo::use_iterator UI = MRI->use_begin(VReg);
269 while (UI != MRI->use_end()) {
Stephen Hines36b56882014-04-23 16:57:46 -0700270 MachineOperand &UseMO = *UI;
271 MachineInstr *UseMI = UseMO.getParent();
Rafael Espindola6a9d2b12011-07-04 01:21:42 +0000272 ++UI;
273 if (UseMI->isDebugValue()) {
274 // SSAUpdate can replace the use with an undef. That creates
275 // a debug instruction that is a kill.
276 // FIXME: Should it SSAUpdate job to delete debug instructions
277 // instead of replacing the use with undef?
278 UseMI->eraseFromParent();
279 continue;
280 }
281 if (UseMI->getParent() == DefBB && !UseMI->isPHI())
282 continue;
283 SSAUpdate.RewriteUse(UseMO);
284 }
285 }
286
287 SSAUpdateVRs.clear();
288 SSAUpdateVals.clear();
289 }
290
291 // Eliminate some of the copies inserted by tail duplication to maintain
292 // SSA form.
293 for (unsigned i = 0, e = Copies.size(); i != e; ++i) {
294 MachineInstr *Copy = Copies[i];
295 if (!Copy->isCopy())
296 continue;
297 unsigned Dst = Copy->getOperand(0).getReg();
298 unsigned Src = Copy->getOperand(1).getReg();
Jakob Stoklund Olesen0fda5452012-05-20 18:42:51 +0000299 if (MRI->hasOneNonDBGUse(Src) &&
300 MRI->constrainRegClass(Src, MRI->getRegClass(Dst))) {
Rafael Espindola6a9d2b12011-07-04 01:21:42 +0000301 // Copy is the only use. Do trivial copy propagation here.
302 MRI->replaceRegWith(Dst, Src);
303 Copy->eraseFromParent();
304 }
305 }
306
307 if (NewPHIs.size())
308 NumAddedPHIs += NewPHIs.size();
309
310 return true;
311}
312
Bob Wilson15acadd2009-11-26 00:32:21 +0000313/// TailDuplicateBlocks - Look for small blocks that are unconditionally
314/// branched to and do not fall through. Tail-duplicate their instructions
315/// into their predecessors to eliminate (dynamic) branches.
Bob Wilson2d521e52009-11-26 21:38:41 +0000316bool TailDuplicatePass::TailDuplicateBlocks(MachineFunction &MF) {
Bob Wilson15acadd2009-11-26 00:32:21 +0000317 bool MadeChange = false;
318
Evan Cheng75eb5352009-12-07 10:15:19 +0000319 if (PreRegAlloc && TailDupVerify) {
David Greene00dec1b2010-01-05 01:25:15 +0000320 DEBUG(dbgs() << "\n*** Before tail-duplicating\n");
Evan Cheng75eb5352009-12-07 10:15:19 +0000321 VerifyPHIs(MF, true);
322 }
323
Bob Wilson15acadd2009-11-26 00:32:21 +0000324 for (MachineFunction::iterator I = ++MF.begin(), E = MF.end(); I != E; ) {
325 MachineBasicBlock *MBB = I++;
326
Evan Cheng75eb5352009-12-07 10:15:19 +0000327 if (NumTails == TailDupLimit)
328 break;
329
Rafael Espindola6a9d2b12011-07-04 01:21:42 +0000330 bool IsSimple = isSimpleBB(MBB);
Bob Wilson15acadd2009-11-26 00:32:21 +0000331
Rafael Espindola6a9d2b12011-07-04 01:21:42 +0000332 if (!shouldTailDuplicate(MF, IsSimple, *MBB))
Rafael Espindolac0af3522011-07-04 00:13:36 +0000333 continue;
Evan Cheng75eb5352009-12-07 10:15:19 +0000334
Rafael Espindola6a9d2b12011-07-04 01:21:42 +0000335 MadeChange |= TailDuplicateAndUpdate(MBB, IsSimple, MF);
Bob Wilson15acadd2009-11-26 00:32:21 +0000336 }
Rafael Espindolac0af3522011-07-04 00:13:36 +0000337
Rafael Espindola6a9d2b12011-07-04 01:21:42 +0000338 if (PreRegAlloc && TailDupVerify)
339 VerifyPHIs(MF, false);
Evan Cheng111e7622009-12-03 08:43:53 +0000340
Bob Wilson15acadd2009-11-26 00:32:21 +0000341 return MadeChange;
342}
343
Evan Cheng111e7622009-12-03 08:43:53 +0000344static bool isDefLiveOut(unsigned Reg, MachineBasicBlock *BB,
345 const MachineRegisterInfo *MRI) {
Stephen Hines36b56882014-04-23 16:57:46 -0700346 for (MachineInstr &UseMI : MRI->use_instructions(Reg)) {
347 if (UseMI.isDebugValue())
Rafael Espindoladb3983b2011-06-17 13:59:43 +0000348 continue;
Stephen Hines36b56882014-04-23 16:57:46 -0700349 if (UseMI.getParent() != BB)
Evan Cheng111e7622009-12-03 08:43:53 +0000350 return true;
351 }
352 return false;
353}
354
355static unsigned getPHISrcRegOpIdx(MachineInstr *MI, MachineBasicBlock *SrcBB) {
356 for (unsigned i = 1, e = MI->getNumOperands(); i != e; i += 2)
357 if (MI->getOperand(i+1).getMBB() == SrcBB)
358 return i;
359 return 0;
360}
361
Rafael Espindola0f28c3f2011-06-09 22:53:47 +0000362
363// Remember which registers are used by phis in this block. This is
364// used to determine which registers are liveout while modifying the
365// block (which is why we need to copy the information).
366static void getRegsUsedByPHIs(const MachineBasicBlock &BB,
Rafael Espindola33b46582011-06-10 21:01:53 +0000367 DenseSet<unsigned> *UsedByPhi) {
Stephen Hinesdce4a402014-05-29 02:49:00 -0700368 for (const auto &MI : BB) {
Rafael Espindola0f28c3f2011-06-09 22:53:47 +0000369 if (!MI.isPHI())
370 break;
371 for (unsigned i = 1, e = MI.getNumOperands(); i != e; i += 2) {
372 unsigned SrcReg = MI.getOperand(i).getReg();
373 UsedByPhi->insert(SrcReg);
374 }
375 }
376}
377
Evan Cheng111e7622009-12-03 08:43:53 +0000378/// AddSSAUpdateEntry - Add a definition and source virtual registers pair for
379/// SSA update.
Evan Cheng11572ba2009-12-04 19:09:10 +0000380void TailDuplicatePass::AddSSAUpdateEntry(unsigned OrigReg, unsigned NewReg,
381 MachineBasicBlock *BB) {
382 DenseMap<unsigned, AvailableValsTy>::iterator LI= SSAUpdateVals.find(OrigReg);
Evan Cheng111e7622009-12-03 08:43:53 +0000383 if (LI != SSAUpdateVals.end())
Evan Cheng11572ba2009-12-04 19:09:10 +0000384 LI->second.push_back(std::make_pair(BB, NewReg));
Evan Cheng111e7622009-12-03 08:43:53 +0000385 else {
386 AvailableValsTy Vals;
Evan Cheng11572ba2009-12-04 19:09:10 +0000387 Vals.push_back(std::make_pair(BB, NewReg));
Evan Cheng111e7622009-12-03 08:43:53 +0000388 SSAUpdateVals.insert(std::make_pair(OrigReg, Vals));
389 SSAUpdateVRs.push_back(OrigReg);
390 }
391}
392
Evan Cheng75eb5352009-12-07 10:15:19 +0000393/// ProcessPHI - Process PHI node in TailBB by turning it into a copy in PredBB.
394/// Remember the source register that's contributed by PredBB and update SSA
395/// update map.
Tobias Grosser83d63f82013-07-14 06:12:01 +0000396void TailDuplicatePass::ProcessPHI(
397 MachineInstr *MI, MachineBasicBlock *TailBB, MachineBasicBlock *PredBB,
398 DenseMap<unsigned, unsigned> &LocalVRMap,
399 SmallVectorImpl<std::pair<unsigned, unsigned> > &Copies,
400 const DenseSet<unsigned> &RegsUsedByPhi, bool Remove) {
Evan Cheng79fc6f42009-12-04 09:42:45 +0000401 unsigned DefReg = MI->getOperand(0).getReg();
402 unsigned SrcOpIdx = getPHISrcRegOpIdx(MI, PredBB);
403 assert(SrcOpIdx && "Unable to find matching PHI source?");
404 unsigned SrcReg = MI->getOperand(SrcOpIdx).getReg();
Evan Cheng75eb5352009-12-07 10:15:19 +0000405 const TargetRegisterClass *RC = MRI->getRegClass(DefReg);
Evan Cheng79fc6f42009-12-04 09:42:45 +0000406 LocalVRMap.insert(std::make_pair(DefReg, SrcReg));
Evan Cheng75eb5352009-12-07 10:15:19 +0000407
408 // Insert a copy from source to the end of the block. The def register is the
409 // available value liveout of the block.
410 unsigned NewDef = MRI->createVirtualRegister(RC);
411 Copies.push_back(std::make_pair(NewDef, SrcReg));
Rafael Espindola0f28c3f2011-06-09 22:53:47 +0000412 if (isDefLiveOut(DefReg, TailBB, MRI) || RegsUsedByPhi.count(DefReg))
Evan Cheng75eb5352009-12-07 10:15:19 +0000413 AddSSAUpdateEntry(DefReg, NewDef, PredBB);
Evan Cheng79fc6f42009-12-04 09:42:45 +0000414
Rafael Espindola689d7d52011-06-09 23:22:56 +0000415 if (!Remove)
416 return;
417
Evan Cheng79fc6f42009-12-04 09:42:45 +0000418 // Remove PredBB from the PHI node.
419 MI->RemoveOperand(SrcOpIdx+1);
420 MI->RemoveOperand(SrcOpIdx);
421 if (MI->getNumOperands() == 1)
422 MI->eraseFromParent();
423}
424
425/// DuplicateInstruction - Duplicate a TailBB instruction to PredBB and update
426/// the source operands due to earlier PHI translation.
427void TailDuplicatePass::DuplicateInstruction(MachineInstr *MI,
428 MachineBasicBlock *TailBB,
429 MachineBasicBlock *PredBB,
430 MachineFunction &MF,
Rafael Espindola0f28c3f2011-06-09 22:53:47 +0000431 DenseMap<unsigned, unsigned> &LocalVRMap,
432 const DenseSet<unsigned> &UsedByPhi) {
Jakob Stoklund Olesen30ac0462010-01-06 23:47:07 +0000433 MachineInstr *NewMI = TII->duplicate(MI, MF);
Evan Cheng79fc6f42009-12-04 09:42:45 +0000434 for (unsigned i = 0, e = NewMI->getNumOperands(); i != e; ++i) {
435 MachineOperand &MO = NewMI->getOperand(i);
436 if (!MO.isReg())
437 continue;
438 unsigned Reg = MO.getReg();
Jakob Stoklund Olesenc9df0252011-01-10 02:58:51 +0000439 if (!TargetRegisterInfo::isVirtualRegister(Reg))
Evan Cheng79fc6f42009-12-04 09:42:45 +0000440 continue;
441 if (MO.isDef()) {
442 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
443 unsigned NewReg = MRI->createVirtualRegister(RC);
444 MO.setReg(NewReg);
445 LocalVRMap.insert(std::make_pair(Reg, NewReg));
Rafael Espindola0f28c3f2011-06-09 22:53:47 +0000446 if (isDefLiveOut(Reg, TailBB, MRI) || UsedByPhi.count(Reg))
Evan Cheng11572ba2009-12-04 19:09:10 +0000447 AddSSAUpdateEntry(Reg, NewReg, PredBB);
Evan Cheng79fc6f42009-12-04 09:42:45 +0000448 } else {
449 DenseMap<unsigned, unsigned>::iterator VI = LocalVRMap.find(Reg);
Jakob Stoklund Olesen0fda5452012-05-20 18:42:51 +0000450 if (VI != LocalVRMap.end()) {
Evan Cheng79fc6f42009-12-04 09:42:45 +0000451 MO.setReg(VI->second);
Jakob Stoklund Olesen0fda5452012-05-20 18:42:51 +0000452 MRI->constrainRegClass(VI->second, MRI->getRegClass(Reg));
453 }
Evan Cheng79fc6f42009-12-04 09:42:45 +0000454 }
455 }
Evan Chengdf7e8bd2012-02-20 07:51:58 +0000456 PredBB->insert(PredBB->instr_end(), NewMI);
Evan Cheng79fc6f42009-12-04 09:42:45 +0000457}
458
459/// UpdateSuccessorsPHIs - After FromBB is tail duplicated into its predecessor
460/// blocks, the successors have gained new predecessors. Update the PHI
461/// instructions in them accordingly.
Evan Cheng75eb5352009-12-07 10:15:19 +0000462void
463TailDuplicatePass::UpdateSuccessorsPHIs(MachineBasicBlock *FromBB, bool isDead,
Craig Toppera0ec3f92013-07-14 04:42:23 +0000464 SmallVectorImpl<MachineBasicBlock *> &TDBBs,
Evan Cheng79fc6f42009-12-04 09:42:45 +0000465 SmallSetVector<MachineBasicBlock*,8> &Succs) {
466 for (SmallSetVector<MachineBasicBlock*, 8>::iterator SI = Succs.begin(),
467 SE = Succs.end(); SI != SE; ++SI) {
468 MachineBasicBlock *SuccBB = *SI;
469 for (MachineBasicBlock::iterator II = SuccBB->begin(), EE = SuccBB->end();
470 II != EE; ++II) {
Chris Lattner518bb532010-02-09 19:54:29 +0000471 if (!II->isPHI())
Evan Cheng79fc6f42009-12-04 09:42:45 +0000472 break;
Jakob Stoklund Olesen7b79b982012-12-20 18:08:06 +0000473 MachineInstrBuilder MIB(*FromBB->getParent(), II);
Evan Cheng75eb5352009-12-07 10:15:19 +0000474 unsigned Idx = 0;
Evan Cheng79fc6f42009-12-04 09:42:45 +0000475 for (unsigned i = 1, e = II->getNumOperands(); i != e; i += 2) {
Evan Cheng75eb5352009-12-07 10:15:19 +0000476 MachineOperand &MO = II->getOperand(i+1);
477 if (MO.getMBB() == FromBB) {
478 Idx = i;
Evan Cheng79fc6f42009-12-04 09:42:45 +0000479 break;
Evan Cheng75eb5352009-12-07 10:15:19 +0000480 }
481 }
482
483 assert(Idx != 0);
484 MachineOperand &MO0 = II->getOperand(Idx);
485 unsigned Reg = MO0.getReg();
486 if (isDead) {
487 // Folded into the previous BB.
488 // There could be duplicate phi source entries. FIXME: Should sdisel
489 // or earlier pass fixed this?
490 for (unsigned i = II->getNumOperands()-2; i != Idx; i -= 2) {
491 MachineOperand &MO = II->getOperand(i+1);
492 if (MO.getMBB() == FromBB) {
493 II->RemoveOperand(i+1);
494 II->RemoveOperand(i);
495 }
496 }
Jakob Stoklund Olesen09eeac92010-02-11 00:34:33 +0000497 } else
498 Idx = 0;
499
500 // If Idx is set, the operands at Idx and Idx+1 must be removed.
501 // We reuse the location to avoid expensive RemoveOperand calls.
502
Evan Cheng75eb5352009-12-07 10:15:19 +0000503 DenseMap<unsigned,AvailableValsTy>::iterator LI=SSAUpdateVals.find(Reg);
504 if (LI != SSAUpdateVals.end()) {
505 // This register is defined in the tail block.
Evan Cheng79fc6f42009-12-04 09:42:45 +0000506 for (unsigned j = 0, ee = LI->second.size(); j != ee; ++j) {
Evan Cheng11572ba2009-12-04 19:09:10 +0000507 MachineBasicBlock *SrcBB = LI->second[j].first;
Rafael Espindolad3f4eea2011-06-09 23:55:56 +0000508 // If we didn't duplicate a bb into a particular predecessor, we
509 // might still have added an entry to SSAUpdateVals to correcly
510 // recompute SSA. If that case, avoid adding a dummy extra argument
511 // this PHI.
512 if (!SrcBB->isSuccessor(SuccBB))
513 continue;
514
Evan Cheng11572ba2009-12-04 19:09:10 +0000515 unsigned SrcReg = LI->second[j].second;
Jakob Stoklund Olesen09eeac92010-02-11 00:34:33 +0000516 if (Idx != 0) {
517 II->getOperand(Idx).setReg(SrcReg);
518 II->getOperand(Idx+1).setMBB(SrcBB);
519 Idx = 0;
520 } else {
Jakob Stoklund Olesen7b79b982012-12-20 18:08:06 +0000521 MIB.addReg(SrcReg).addMBB(SrcBB);
Jakob Stoklund Olesen09eeac92010-02-11 00:34:33 +0000522 }
Evan Cheng79fc6f42009-12-04 09:42:45 +0000523 }
Evan Cheng75eb5352009-12-07 10:15:19 +0000524 } else {
525 // Live in tail block, must also be live in predecessors.
526 for (unsigned j = 0, ee = TDBBs.size(); j != ee; ++j) {
527 MachineBasicBlock *SrcBB = TDBBs[j];
Jakob Stoklund Olesen09eeac92010-02-11 00:34:33 +0000528 if (Idx != 0) {
529 II->getOperand(Idx).setReg(Reg);
530 II->getOperand(Idx+1).setMBB(SrcBB);
531 Idx = 0;
532 } else {
Jakob Stoklund Olesen7b79b982012-12-20 18:08:06 +0000533 MIB.addReg(Reg).addMBB(SrcBB);
Jakob Stoklund Olesen09eeac92010-02-11 00:34:33 +0000534 }
Evan Cheng75eb5352009-12-07 10:15:19 +0000535 }
Evan Cheng79fc6f42009-12-04 09:42:45 +0000536 }
Jakob Stoklund Olesen09eeac92010-02-11 00:34:33 +0000537 if (Idx != 0) {
538 II->RemoveOperand(Idx+1);
539 II->RemoveOperand(Idx);
540 }
Evan Cheng79fc6f42009-12-04 09:42:45 +0000541 }
542 }
543}
544
Rafael Espindola54c25622011-06-09 19:54:42 +0000545/// shouldTailDuplicate - Determine if it is profitable to duplicate this block.
Evan Cheng75eb5352009-12-07 10:15:19 +0000546bool
Rafael Espindola54c25622011-06-09 19:54:42 +0000547TailDuplicatePass::shouldTailDuplicate(const MachineFunction &MF,
Rafael Espindola9dbbd872011-06-23 03:41:29 +0000548 bool IsSimple,
Rafael Espindola54c25622011-06-09 19:54:42 +0000549 MachineBasicBlock &TailBB) {
550 // Only duplicate blocks that end with unconditional branches.
551 if (TailBB.canFallThrough())
552 return false;
553
Rafael Espindolaec324e52011-06-17 05:54:50 +0000554 // Don't try to tail-duplicate single-block loops.
555 if (TailBB.isSuccessor(&TailBB))
556 return false;
557
Rafael Espindola54c25622011-06-09 19:54:42 +0000558 // Set the limit on the cost to duplicate. When optimizing for size,
Bob Wilson15acadd2009-11-26 00:32:21 +0000559 // duplicate only one, because one branch instruction can be eliminated to
560 // compensate for the duplication.
561 unsigned MaxDuplicateCount;
Jakob Stoklund Olesen83520622011-01-30 20:38:12 +0000562 if (TailDuplicateSize.getNumOccurrences() == 0 &&
Stephen Hinesebe69fe2015-03-23 12:10:34 -0700563 MF.getFunction()->hasFnAttribute(Attribute::OptimizeForSize))
Bob Wilson38582252009-11-30 18:56:45 +0000564 MaxDuplicateCount = 1;
Bob Wilson15acadd2009-11-26 00:32:21 +0000565 else
566 MaxDuplicateCount = TailDuplicateSize;
567
Rafael Espindolaec324e52011-06-17 05:54:50 +0000568 // If the target has hardware branch prediction that can handle indirect
569 // branches, duplicating them can often make them predictable when there
570 // are common paths through the code. The limit needs to be high enough
571 // to allow undoing the effects of tail merging and other optimizations
572 // that rearrange the predecessors of the indirect branch.
Bob Wilsoncb44b282010-01-16 00:42:25 +0000573
Rafael Espindola6a9d2b12011-07-04 01:21:42 +0000574 bool HasIndirectbr = false;
575 if (!TailBB.empty())
Evan Cheng5a96b3d2011-12-07 07:15:52 +0000576 HasIndirectbr = TailBB.back().isIndirectBranch();
Rafael Espindola6a9d2b12011-07-04 01:21:42 +0000577
578 if (HasIndirectbr && PreRegAlloc)
579 MaxDuplicateCount = 20;
Bob Wilsonbfdcf3b2010-01-15 06:29:17 +0000580
Bob Wilson15acadd2009-11-26 00:32:21 +0000581 // Check the instructions in the block to determine whether tail-duplication
582 // is invalid or unlikely to be profitable.
Bob Wilsonf1e01dc2009-12-02 17:15:24 +0000583 unsigned InstrCount = 0;
Evan Cheng7c2a4a32011-12-06 22:12:01 +0000584 for (MachineBasicBlock::iterator I = TailBB.begin(); I != TailBB.end(); ++I) {
Bob Wilson15acadd2009-11-26 00:32:21 +0000585 // Non-duplicable things shouldn't be tail-duplicated.
Evan Cheng5a96b3d2011-12-07 07:15:52 +0000586 if (I->isNotDuplicable())
Rafael Espindolaec324e52011-06-17 05:54:50 +0000587 return false;
588
Evan Cheng79fc6f42009-12-04 09:42:45 +0000589 // Do not duplicate 'return' instructions if this is a pre-regalloc run.
590 // A return may expand into a lot more instructions (e.g. reload of callee
591 // saved registers) after PEI.
Evan Cheng5a96b3d2011-12-07 07:15:52 +0000592 if (PreRegAlloc && I->isReturn())
Rafael Espindolaec324e52011-06-17 05:54:50 +0000593 return false;
594
595 // Avoid duplicating calls before register allocation. Calls presents a
596 // barrier to register allocation so duplicating them may end up increasing
597 // spills.
Evan Cheng5a96b3d2011-12-07 07:15:52 +0000598 if (PreRegAlloc && I->isCall())
Rafael Espindolaec324e52011-06-17 05:54:50 +0000599 return false;
600
Devang Patelcbe1e312010-03-16 21:02:07 +0000601 if (!I->isPHI() && !I->isDebugValue())
Bob Wilsonf1e01dc2009-12-02 17:15:24 +0000602 InstrCount += 1;
Rafael Espindolaec324e52011-06-17 05:54:50 +0000603
604 if (InstrCount > MaxDuplicateCount)
605 return false;
Bob Wilson15acadd2009-11-26 00:32:21 +0000606 }
Bob Wilson15acadd2009-11-26 00:32:21 +0000607
Rafael Espindola6a9d2b12011-07-04 01:21:42 +0000608 if (HasIndirectbr && PreRegAlloc)
Rafael Espindola9dbbd872011-06-23 03:41:29 +0000609 return true;
610
611 if (IsSimple)
Rafael Espindolad7f35fa2011-06-24 15:47:41 +0000612 return true;
Rafael Espindola9dbbd872011-06-23 03:41:29 +0000613
614 if (!PreRegAlloc)
615 return true;
616
Rafael Espindola40179bf2011-06-24 15:50:56 +0000617 return canCompletelyDuplicateBB(TailBB);
Rafael Espindola54c25622011-06-09 19:54:42 +0000618}
619
Rafael Espindola275c1f92011-06-20 04:16:35 +0000620/// isSimpleBB - True if this BB has only one unconditional jump.
621bool
622TailDuplicatePass::isSimpleBB(MachineBasicBlock *TailBB) {
623 if (TailBB->succ_size() != 1)
624 return false;
Rafael Espindola9dbbd872011-06-23 03:41:29 +0000625 if (TailBB->pred_empty())
626 return false;
Rafael Espindolad6379a92011-06-22 22:31:57 +0000627 MachineBasicBlock::iterator I = TailBB->begin();
Rafael Espindola275c1f92011-06-20 04:16:35 +0000628 MachineBasicBlock::iterator E = TailBB->end();
Rafael Espindolad6379a92011-06-22 22:31:57 +0000629 while (I != E && I->isDebugValue())
Rafael Espindola275c1f92011-06-20 04:16:35 +0000630 ++I;
631 if (I == E)
632 return true;
Evan Cheng5a96b3d2011-12-07 07:15:52 +0000633 return I->isUnconditionalBranch();
Rafael Espindola275c1f92011-06-20 04:16:35 +0000634}
635
636static bool
637bothUsedInPHI(const MachineBasicBlock &A,
638 SmallPtrSet<MachineBasicBlock*, 8> SuccsB) {
639 for (MachineBasicBlock::const_succ_iterator SI = A.succ_begin(),
640 SE = A.succ_end(); SI != SE; ++SI) {
641 MachineBasicBlock *BB = *SI;
642 if (SuccsB.count(BB) && !BB->empty() && BB->begin()->isPHI())
643 return true;
644 }
645
646 return false;
647}
648
649bool
Rafael Espindola40179bf2011-06-24 15:50:56 +0000650TailDuplicatePass::canCompletelyDuplicateBB(MachineBasicBlock &BB) {
Rafael Espindola275c1f92011-06-20 04:16:35 +0000651 for (MachineBasicBlock::pred_iterator PI = BB.pred_begin(),
652 PE = BB.pred_end(); PI != PE; ++PI) {
653 MachineBasicBlock *PredBB = *PI;
Rafael Espindola9dbbd872011-06-23 03:41:29 +0000654
Rafael Espindola40179bf2011-06-24 15:50:56 +0000655 if (PredBB->succ_size() > 1)
656 return false;
Rafael Espindola9dbbd872011-06-23 03:41:29 +0000657
Stephen Hinesdce4a402014-05-29 02:49:00 -0700658 MachineBasicBlock *PredTBB = nullptr, *PredFBB = nullptr;
Rafael Espindola275c1f92011-06-20 04:16:35 +0000659 SmallVector<MachineOperand, 4> PredCond;
660 if (TII->AnalyzeBranch(*PredBB, PredTBB, PredFBB, PredCond, true))
661 return false;
Rafael Espindola9dbbd872011-06-23 03:41:29 +0000662
Rafael Espindola40179bf2011-06-24 15:50:56 +0000663 if (!PredCond.empty())
Rafael Espindola9dbbd872011-06-23 03:41:29 +0000664 return false;
Rafael Espindola275c1f92011-06-20 04:16:35 +0000665 }
666 return true;
667}
668
Rafael Espindolad7f35fa2011-06-24 15:47:41 +0000669bool
Rafael Espindola275c1f92011-06-20 04:16:35 +0000670TailDuplicatePass::duplicateSimpleBB(MachineBasicBlock *TailBB,
Craig Toppera0ec3f92013-07-14 04:42:23 +0000671 SmallVectorImpl<MachineBasicBlock *> &TDBBs,
672 const DenseSet<unsigned> &UsedByPhi,
673 SmallVectorImpl<MachineInstr *> &Copies) {
Rafael Espindolad7f35fa2011-06-24 15:47:41 +0000674 SmallPtrSet<MachineBasicBlock*, 8> Succs(TailBB->succ_begin(),
675 TailBB->succ_end());
Rafael Espindola275c1f92011-06-20 04:16:35 +0000676 SmallVector<MachineBasicBlock*, 8> Preds(TailBB->pred_begin(),
677 TailBB->pred_end());
Rafael Espindolad7f35fa2011-06-24 15:47:41 +0000678 bool Changed = false;
Rafael Espindola275c1f92011-06-20 04:16:35 +0000679 for (SmallSetVector<MachineBasicBlock *, 8>::iterator PI = Preds.begin(),
680 PE = Preds.end(); PI != PE; ++PI) {
681 MachineBasicBlock *PredBB = *PI;
682
Rafael Espindolad7f35fa2011-06-24 15:47:41 +0000683 if (PredBB->getLandingPadSuccessor())
684 continue;
685
686 if (bothUsedInPHI(*PredBB, Succs))
687 continue;
688
Stephen Hinesdce4a402014-05-29 02:49:00 -0700689 MachineBasicBlock *PredTBB = nullptr, *PredFBB = nullptr;
Rafael Espindola275c1f92011-06-20 04:16:35 +0000690 SmallVector<MachineOperand, 4> PredCond;
Rafael Espindolad7f35fa2011-06-24 15:47:41 +0000691 if (TII->AnalyzeBranch(*PredBB, PredTBB, PredFBB, PredCond, true))
692 continue;
Rafael Espindola275c1f92011-06-20 04:16:35 +0000693
Rafael Espindolad7f35fa2011-06-24 15:47:41 +0000694 Changed = true;
Rafael Espindola275c1f92011-06-20 04:16:35 +0000695 DEBUG(dbgs() << "\nTail-duplicating into PredBB: " << *PredBB
696 << "From simple Succ: " << *TailBB);
697
698 MachineBasicBlock *NewTarget = *TailBB->succ_begin();
Stephen Hines36b56882014-04-23 16:57:46 -0700699 MachineBasicBlock *NextBB = std::next(MachineFunction::iterator(PredBB));
Rafael Espindola275c1f92011-06-20 04:16:35 +0000700
Rafael Espindola275c1f92011-06-20 04:16:35 +0000701 // Make PredFBB explicit.
702 if (PredCond.empty())
703 PredFBB = PredTBB;
704
705 // Make fall through explicit.
706 if (!PredTBB)
707 PredTBB = NextBB;
708 if (!PredFBB)
709 PredFBB = NextBB;
710
711 // Redirect
712 if (PredFBB == TailBB)
713 PredFBB = NewTarget;
714 if (PredTBB == TailBB)
715 PredTBB = NewTarget;
716
717 // Make the branch unconditional if possible
Rafael Espindola689c2472011-06-20 14:11:42 +0000718 if (PredTBB == PredFBB) {
719 PredCond.clear();
Stephen Hinesdce4a402014-05-29 02:49:00 -0700720 PredFBB = nullptr;
Rafael Espindola689c2472011-06-20 14:11:42 +0000721 }
Rafael Espindola275c1f92011-06-20 04:16:35 +0000722
723 // Avoid adding fall through branches.
724 if (PredFBB == NextBB)
Stephen Hinesdce4a402014-05-29 02:49:00 -0700725 PredFBB = nullptr;
726 if (PredTBB == NextBB && PredFBB == nullptr)
727 PredTBB = nullptr;
Rafael Espindola275c1f92011-06-20 04:16:35 +0000728
729 TII->RemoveBranch(*PredBB);
730
731 if (PredTBB)
732 TII->InsertBranch(*PredBB, PredTBB, PredFBB, PredCond, DebugLoc());
733
Stephen Hines36b56882014-04-23 16:57:46 -0700734 uint32_t Weight = MBPI->getEdgeWeight(PredBB, TailBB);
Rafael Espindola275c1f92011-06-20 04:16:35 +0000735 PredBB->removeSuccessor(TailBB);
Rafael Espindola689c2472011-06-20 14:11:42 +0000736 unsigned NumSuccessors = PredBB->succ_size();
737 assert(NumSuccessors <= 1);
738 if (NumSuccessors == 0 || *PredBB->succ_begin() != NewTarget)
Stephen Hines36b56882014-04-23 16:57:46 -0700739 PredBB->addSuccessor(NewTarget, Weight);
Rafael Espindola275c1f92011-06-20 04:16:35 +0000740
741 TDBBs.push_back(PredBB);
Rafael Espindola275c1f92011-06-20 04:16:35 +0000742 }
Rafael Espindolad7f35fa2011-06-24 15:47:41 +0000743 return Changed;
Rafael Espindola275c1f92011-06-20 04:16:35 +0000744}
745
Rafael Espindola54c25622011-06-09 19:54:42 +0000746/// TailDuplicate - If it is profitable, duplicate TailBB's contents in each
747/// of its predecessors.
748bool
Rafael Espindola6a9d2b12011-07-04 01:21:42 +0000749TailDuplicatePass::TailDuplicate(MachineBasicBlock *TailBB,
750 bool IsSimple,
751 MachineFunction &MF,
Craig Toppera0ec3f92013-07-14 04:42:23 +0000752 SmallVectorImpl<MachineBasicBlock *> &TDBBs,
753 SmallVectorImpl<MachineInstr *> &Copies) {
David Greene00dec1b2010-01-05 01:25:15 +0000754 DEBUG(dbgs() << "\n*** Tail-duplicating BB#" << TailBB->getNumber() << '\n');
Evan Cheng75eb5352009-12-07 10:15:19 +0000755
Rafael Espindola275c1f92011-06-20 04:16:35 +0000756 DenseSet<unsigned> UsedByPhi;
757 getRegsUsedByPHIs(*TailBB, &UsedByPhi);
758
Rafael Espindolad7f35fa2011-06-24 15:47:41 +0000759 if (IsSimple)
760 return duplicateSimpleBB(TailBB, TDBBs, UsedByPhi, Copies);
Rafael Espindola275c1f92011-06-20 04:16:35 +0000761
Bob Wilson15acadd2009-11-26 00:32:21 +0000762 // Iterate through all the unique predecessors and tail-duplicate this
763 // block into them, if possible. Copying the list ahead of time also
764 // avoids trouble with the predecessor list reallocating.
765 bool Changed = false;
Evan Cheng79fc6f42009-12-04 09:42:45 +0000766 SmallSetVector<MachineBasicBlock*, 8> Preds(TailBB->pred_begin(),
767 TailBB->pred_end());
Bob Wilson15acadd2009-11-26 00:32:21 +0000768 for (SmallSetVector<MachineBasicBlock *, 8>::iterator PI = Preds.begin(),
769 PE = Preds.end(); PI != PE; ++PI) {
770 MachineBasicBlock *PredBB = *PI;
771
772 assert(TailBB != PredBB &&
773 "Single-block loop should have been rejected earlier!");
Rafael Espindola9a9a3a52011-06-10 20:08:23 +0000774 // EH edges are ignored by AnalyzeBranch.
775 if (PredBB->succ_size() > 1)
776 continue;
Bob Wilson15acadd2009-11-26 00:32:21 +0000777
778 MachineBasicBlock *PredTBB, *PredFBB;
779 SmallVector<MachineOperand, 4> PredCond;
780 if (TII->AnalyzeBranch(*PredBB, PredTBB, PredFBB, PredCond, true))
781 continue;
782 if (!PredCond.empty())
783 continue;
Bob Wilson15acadd2009-11-26 00:32:21 +0000784 // Don't duplicate into a fall-through predecessor (at least for now).
785 if (PredBB->isLayoutSuccessor(TailBB) && PredBB->canFallThrough())
786 continue;
787
David Greene00dec1b2010-01-05 01:25:15 +0000788 DEBUG(dbgs() << "\nTail-duplicating into PredBB: " << *PredBB
Bob Wilson15acadd2009-11-26 00:32:21 +0000789 << "From Succ: " << *TailBB);
790
Evan Cheng75eb5352009-12-07 10:15:19 +0000791 TDBBs.push_back(PredBB);
792
Bob Wilson15acadd2009-11-26 00:32:21 +0000793 // Remove PredBB's unconditional branch.
794 TII->RemoveBranch(*PredBB);
Evan Cheng111e7622009-12-03 08:43:53 +0000795
Evan Chengeb25bd22012-05-30 00:42:39 +0000796 if (RS && !TailBB->livein_empty()) {
797 // Update PredBB livein.
798 RS->enterBasicBlock(PredBB);
799 if (!PredBB->empty())
Stephen Hines36b56882014-04-23 16:57:46 -0700800 RS->forward(std::prev(PredBB->end()));
Evan Chengeb25bd22012-05-30 00:42:39 +0000801 for (MachineBasicBlock::livein_iterator I = TailBB->livein_begin(),
802 E = TailBB->livein_end(); I != E; ++I) {
Stephen Hines37ed9c12014-12-01 14:51:49 -0800803 if (!RS->isRegUsed(*I, false))
Evan Chengeb25bd22012-05-30 00:42:39 +0000804 // 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 Wilson15acadd2009-11-26 00:32:21 +0000811 // Clone the contents of TailBB into PredBB.
Evan Cheng111e7622009-12-03 08:43:53 +0000812 DenseMap<unsigned, unsigned> LocalVRMap;
Evan Cheng3466f132009-12-15 01:44:10 +0000813 SmallVector<std::pair<unsigned,unsigned>, 4> CopyInfos;
Evan Chengdf7e8bd2012-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 Cheng79fc6f42009-12-04 09:42:45 +0000818 MachineInstr *MI = &*I;
819 ++I;
Chris Lattner518bb532010-02-09 19:54:29 +0000820 if (MI->isPHI()) {
Evan Cheng111e7622009-12-03 08:43:53 +0000821 // Replace the uses of the def of the PHI with the register coming
822 // from PredBB.
Rafael Espindola689d7d52011-06-09 23:22:56 +0000823 ProcessPHI(MI, TailBB, PredBB, LocalVRMap, CopyInfos, UsedByPhi, true);
Evan Cheng79fc6f42009-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 Espindola0f28c3f2011-06-09 22:53:47 +0000827 DuplicateInstruction(MI, TailBB, PredBB, MF, LocalVRMap, UsedByPhi);
Evan Cheng111e7622009-12-03 08:43:53 +0000828 }
Bob Wilson15acadd2009-11-26 00:32:21 +0000829 }
Evan Cheng75eb5352009-12-07 10:15:19 +0000830 MachineBasicBlock::iterator Loc = PredBB->getFirstTerminator();
Evan Cheng3466f132009-12-15 01:44:10 +0000831 for (unsigned i = 0, e = CopyInfos.size(); i != e; ++i) {
Jakob Stoklund Olesen1e1098c2010-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 Cheng75eb5352009-12-07 10:15:19 +0000835 }
Rafael Espindolaec324e52011-06-17 05:54:50 +0000836
837 // Simplify
838 TII->AnalyzeBranch(*PredBB, PredTBB, PredFBB, PredCond, true);
839
Bob Wilson15acadd2009-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 Cheng79fc6f42009-12-04 09:42:45 +0000847 E = TailBB->succ_end(); I != E; ++I)
Stephen Hines36b56882014-04-23 16:57:46 -0700848 PredBB->addSuccessor(*I, MBPI->getEdgeWeight(TailBB, I));
Bob Wilson15acadd2009-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.
Stephen Hines36b56882014-04-23 16:57:46 -0700857 MachineBasicBlock *PrevBB = std::prev(MachineFunction::iterator(TailBB));
Stephen Hinesdce4a402014-05-29 02:49:00 -0700858 MachineBasicBlock *PriorTBB = nullptr, *PriorFBB = nullptr;
Bob Wilson15acadd2009-11-26 00:32:21 +0000859 SmallVector<MachineOperand, 4> PriorCond;
Bob Wilson15acadd2009-11-26 00:32:21 +0000860 // This has to check PrevBB->succ_size() because EH edges are ignored by
861 // AnalyzeBranch.
Andrew Trickd2a7bed2012-02-08 21:22:30 +0000862 if (PrevBB->succ_size() == 1 &&
Rafael Espindolaa899b222011-06-09 21:43:25 +0000863 !TII->AnalyzeBranch(*PrevBB, PriorTBB, PriorFBB, PriorCond, true) &&
864 PriorCond.empty() && !PriorTBB && TailBB->pred_size() == 1 &&
Bob Wilson15acadd2009-11-26 00:32:21 +0000865 !TailBB->hasAddressTaken()) {
David Greene00dec1b2010-01-05 01:25:15 +0000866 DEBUG(dbgs() << "\nMerging into block: " << *PrevBB
Bob Wilson15acadd2009-11-26 00:32:21 +0000867 << "From MBB: " << *TailBB);
Evan Cheng79fc6f42009-12-04 09:42:45 +0000868 if (PreRegAlloc) {
869 DenseMap<unsigned, unsigned> LocalVRMap;
Evan Cheng3466f132009-12-15 01:44:10 +0000870 SmallVector<std::pair<unsigned,unsigned>, 4> CopyInfos;
Evan Cheng79fc6f42009-12-04 09:42:45 +0000871 MachineBasicBlock::iterator I = TailBB->begin();
872 // Process PHI instructions first.
Chris Lattner518bb532010-02-09 19:54:29 +0000873 while (I != TailBB->end() && I->isPHI()) {
Evan Cheng79fc6f42009-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 Espindola689d7d52011-06-09 23:22:56 +0000877 ProcessPHI(MI, TailBB, PrevBB, LocalVRMap, CopyInfos, UsedByPhi, true);
Evan Cheng79fc6f42009-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 Chengdf7e8bd2012-02-20 07:51:58 +0000887 assert(!MI->isBundle() && "Not expecting bundles before regalloc!");
Rafael Espindola0f28c3f2011-06-09 22:53:47 +0000888 DuplicateInstruction(MI, TailBB, PrevBB, MF, LocalVRMap, UsedByPhi);
Evan Cheng79fc6f42009-12-04 09:42:45 +0000889 MI->eraseFromParent();
890 }
Evan Cheng75eb5352009-12-07 10:15:19 +0000891 MachineBasicBlock::iterator Loc = PrevBB->getFirstTerminator();
Evan Cheng3466f132009-12-15 01:44:10 +0000892 for (unsigned i = 0, e = CopyInfos.size(); i != e; ++i) {
Jakob Stoklund Olesen1e1098c2010-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 Cheng75eb5352009-12-07 10:15:19 +0000897 }
Evan Cheng79fc6f42009-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 Cheng75eb5352009-12-07 10:15:19 +0000905 TDBBs.push_back(PrevBB);
Bob Wilson15acadd2009-11-26 00:32:21 +0000906 Changed = true;
907 }
908
Rafael Espindola689d7d52011-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 Espindola4d7b4572011-06-09 23:51:45 +0000920 // 1 -> 2 <-> 3 |
921 // \ |
922 // \---> rest |
Rafael Espindola689d7d52011-06-09 23:22:56 +0000923 // if we duplicate 2 into 1 but not into 3, we end up with
Rafael Espindola4d7b4572011-06-09 23:51:45 +0000924 // 12 -> 3 <-> 2 -> rest |
925 // \ / |
926 // \----->-----/ |
Rafael Espindola689d7d52011-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 Wilson15acadd2009-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 Wilson2d521e52009-11-26 21:38:41 +0000965void TailDuplicatePass::RemoveDeadBlock(MachineBasicBlock *MBB) {
Bob Wilson15acadd2009-11-26 00:32:21 +0000966 assert(MBB->pred_empty() && "MBB must be dead!");
David Greene00dec1b2010-01-05 01:25:15 +0000967 DEBUG(dbgs() << "\nRemoving MBB: " << *MBB);
Bob Wilson15acadd2009-11-26 00:32:21 +0000968
969 // Remove all successors.
970 while (!MBB->succ_empty())
971 MBB->removeSuccessor(MBB->succ_end()-1);
972
Bob Wilson15acadd2009-11-26 00:32:21 +0000973 // Remove the block.
974 MBB->eraseFromParent();
975}