blob: c2c7a1a3d927f69d38aa5080df5ad89247d2c1c6 [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
Bob Wilson2d4ff122009-11-26 00:32:21 +000015#include "llvm/CodeGen/Passes.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000016#include "llvm/ADT/DenseSet.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000017#include "llvm/ADT/SetVector.h"
18#include "llvm/ADT/SmallSet.h"
19#include "llvm/ADT/Statistic.h"
Akira Hatanakaa07ffb52014-02-12 18:09:18 +000020#include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
Bob Wilson2d4ff122009-11-26 00:32:21 +000021#include "llvm/CodeGen/MachineFunctionPass.h"
Jakob Stoklund Olesen0c76d6e2010-07-10 22:42:59 +000022#include "llvm/CodeGen/MachineInstrBuilder.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000023#include "llvm/CodeGen/MachineModuleInfo.h"
Evan Cheng1bbe6be2009-12-03 08:43:53 +000024#include "llvm/CodeGen/MachineRegisterInfo.h"
25#include "llvm/CodeGen/MachineSSAUpdater.h"
Evan Chengbc2453d2012-05-30 00:42:39 +000026#include "llvm/CodeGen/RegisterScavenging.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000027#include "llvm/IR/Function.h"
Bob Wilson2d4ff122009-11-26 00:32:21 +000028#include "llvm/Support/CommandLine.h"
29#include "llvm/Support/Debug.h"
Evan Chengcc770622009-12-07 10:15:19 +000030#include "llvm/Support/ErrorHandling.h"
Bob Wilson2d4ff122009-11-26 00:32:21 +000031#include "llvm/Support/raw_ostream.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000032#include "llvm/Target/TargetInstrInfo.h"
33#include "llvm/Target/TargetRegisterInfo.h"
Eric Christopherd9134482014-08-04 21:25:23 +000034#include "llvm/Target/TargetSubtargetInfo.h"
Bob Wilson2d4ff122009-11-26 00:32:21 +000035using namespace llvm;
36
Chandler Carruth1b9dde02014-04-22 02:02:50 +000037#define DEBUG_TYPE "tailduplication"
38
Evan Chengcc770622009-12-07 10:15:19 +000039STATISTIC(NumTails , "Number of tails duplicated");
Bob Wilson2d4ff122009-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 Espindoladfbf6de2011-06-08 14:13:31 +000043STATISTIC(NumAddedPHIs , "Number of phis added");
Bob Wilson2d4ff122009-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 Chengcc770622009-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 Cheng9e672552009-12-04 19:09:10 +000059typedef std::vector<std::pair<MachineBasicBlock*,unsigned> > AvailableValsTy;
Evan Cheng1bbe6be2009-12-03 08:43:53 +000060
Bob Wilson2d4ff122009-11-26 00:32:21 +000061namespace {
Sanjay Patelcc655432015-08-10 21:28:16 +000062 /// Perform tail duplication.
Bob Wilson9594db52009-11-26 21:38:41 +000063 class TailDuplicatePass : public MachineFunctionPass {
Bob Wilson2d4ff122009-11-26 00:32:21 +000064 const TargetInstrInfo *TII;
Evan Chengbc2453d2012-05-30 00:42:39 +000065 const TargetRegisterInfo *TRI;
Akira Hatanakaa07ffb52014-02-12 18:09:18 +000066 const MachineBranchProbabilityInfo *MBPI;
Bob Wilson2d4ff122009-11-26 00:32:21 +000067 MachineModuleInfo *MMI;
Evan Cheng1bbe6be2009-12-03 08:43:53 +000068 MachineRegisterInfo *MRI;
Ahmed Charles56440fd2014-03-06 05:51:42 +000069 std::unique_ptr<RegScavenger> RS;
Andrew Trickc0449172012-02-08 21:22:30 +000070 bool PreRegAlloc;
Evan Cheng1bbe6be2009-12-03 08:43:53 +000071
Sanjay Patelcc655432015-08-10 21:28:16 +000072 // A list of virtual registers for which to update SSA form.
Evan Cheng1bbe6be2009-12-03 08:43:53 +000073 SmallVector<unsigned, 16> SSAUpdateVRs;
74
Sanjay Patelcc655432015-08-10 21:28:16 +000075 // For each virtual register in SSAUpdateVals keep a list of source virtual
76 // registers.
Evan Cheng1bbe6be2009-12-03 08:43:53 +000077 DenseMap<unsigned, AvailableValsTy> SSAUpdateVals;
Bob Wilson2d4ff122009-11-26 00:32:21 +000078
79 public:
80 static char ID;
Andrew Trickc0449172012-02-08 21:22:30 +000081 explicit TailDuplicatePass() :
82 MachineFunctionPass(ID), PreRegAlloc(false) {}
Bob Wilson2d4ff122009-11-26 00:32:21 +000083
Craig Topper4584cd52014-03-07 09:26:03 +000084 bool runOnMachineFunction(MachineFunction &MF) override;
Bob Wilson2d4ff122009-11-26 00:32:21 +000085
Craig Topper4584cd52014-03-07 09:26:03 +000086 void getAnalysisUsage(AnalysisUsage &AU) const override;
Akira Hatanakaa07ffb52014-02-12 18:09:18 +000087
Bob Wilson2d4ff122009-11-26 00:32:21 +000088 private:
Evan Cheng9e672552009-12-04 19:09:10 +000089 void AddSSAUpdateEntry(unsigned OrigReg, unsigned NewReg,
90 MachineBasicBlock *BB);
Evan Cheng6154dbd2009-12-04 09:42:45 +000091 void ProcessPHI(MachineInstr *MI, MachineBasicBlock *TailBB,
92 MachineBasicBlock *PredBB,
Evan Chengcc770622009-12-07 10:15:19 +000093 DenseMap<unsigned, unsigned> &LocalVRMap,
Craig Topperb94011f2013-07-14 04:42:23 +000094 SmallVectorImpl<std::pair<unsigned,unsigned> > &Copies,
Rafael Espindolac735f132011-06-09 23:22:56 +000095 const DenseSet<unsigned> &UsedByPhi,
96 bool Remove);
Evan Cheng6154dbd2009-12-04 09:42:45 +000097 void DuplicateInstruction(MachineInstr *MI,
98 MachineBasicBlock *TailBB,
99 MachineBasicBlock *PredBB,
100 MachineFunction &MF,
Rafael Espindola81512fc2011-06-09 22:53:47 +0000101 DenseMap<unsigned, unsigned> &LocalVRMap,
102 const DenseSet<unsigned> &UsedByPhi);
Evan Chengcc770622009-12-07 10:15:19 +0000103 void UpdateSuccessorsPHIs(MachineBasicBlock *FromBB, bool isDead,
Craig Topperb94011f2013-07-14 04:42:23 +0000104 SmallVectorImpl<MachineBasicBlock *> &TDBBs,
Evan Chengcc770622009-12-07 10:15:19 +0000105 SmallSetVector<MachineBasicBlock*, 8> &Succs);
Bob Wilson2d4ff122009-11-26 00:32:21 +0000106 bool TailDuplicateBlocks(MachineFunction &MF);
Rafael Espindola73f93932011-06-09 19:54:42 +0000107 bool shouldTailDuplicate(const MachineFunction &MF,
Rafael Espindolae25a8712011-06-23 03:41:29 +0000108 bool IsSimple, MachineBasicBlock &TailBB);
Rafael Espindolaef636bf2011-06-20 04:16:35 +0000109 bool isSimpleBB(MachineBasicBlock *TailBB);
Rafael Espindola5135ae22011-06-24 15:50:56 +0000110 bool canCompletelyDuplicateBB(MachineBasicBlock &BB);
Rafael Espindolacb0213b2011-06-24 15:47:41 +0000111 bool duplicateSimpleBB(MachineBasicBlock *TailBB,
Craig Topperb94011f2013-07-14 04:42:23 +0000112 SmallVectorImpl<MachineBasicBlock *> &TDBBs,
Rafael Espindolaef636bf2011-06-20 04:16:35 +0000113 const DenseSet<unsigned> &RegsUsedByPhi,
Craig Topperb94011f2013-07-14 04:42:23 +0000114 SmallVectorImpl<MachineInstr *> &Copies);
Rafael Espindolaf9f012e2011-07-04 01:21:42 +0000115 bool TailDuplicate(MachineBasicBlock *TailBB,
116 bool IsSimple,
117 MachineFunction &MF,
Craig Topperb94011f2013-07-14 04:42:23 +0000118 SmallVectorImpl<MachineBasicBlock *> &TDBBs,
119 SmallVectorImpl<MachineInstr *> &Copies);
Rafael Espindolaf9f012e2011-07-04 01:21:42 +0000120 bool TailDuplicateAndUpdate(MachineBasicBlock *MBB,
121 bool IsSimple,
122 MachineFunction &MF);
123
Bob Wilson2d4ff122009-11-26 00:32:21 +0000124 void RemoveDeadBlock(MachineBasicBlock *MBB);
125 };
126
Bob Wilson9594db52009-11-26 21:38:41 +0000127 char TailDuplicatePass::ID = 0;
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000128}
Bob Wilson2d4ff122009-11-26 00:32:21 +0000129
Andrew Trick1fa5bcb2012-02-08 21:23:13 +0000130char &llvm::TailDuplicateID = TailDuplicatePass::ID;
131
132INITIALIZE_PASS(TailDuplicatePass, "tailduplication", "Tail Duplication",
133 false, false)
Bob Wilson2d4ff122009-11-26 00:32:21 +0000134
Bob Wilson9594db52009-11-26 21:38:41 +0000135bool TailDuplicatePass::runOnMachineFunction(MachineFunction &MF) {
Paul Robinson7c99ec52014-03-31 17:43:35 +0000136 if (skipOptnoneFunction(*MF.getFunction()))
137 return false;
138
Eric Christopherfc6de422014-08-05 02:39:49 +0000139 TII = MF.getSubtarget().getInstrInfo();
140 TRI = MF.getSubtarget().getRegisterInfo();
Evan Cheng1bbe6be2009-12-03 08:43:53 +0000141 MRI = &MF.getRegInfo();
Bob Wilson2d4ff122009-11-26 00:32:21 +0000142 MMI = getAnalysisIfAvailable<MachineModuleInfo>();
Akira Hatanakaa07ffb52014-02-12 18:09:18 +0000143 MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
144
Andrew Trickc0449172012-02-08 21:22:30 +0000145 PreRegAlloc = MRI->isSSA();
Benjamin Kramer3de5d402012-06-06 13:53:41 +0000146 RS.reset();
Evan Chengbc2453d2012-05-30 00:42:39 +0000147 if (MRI->tracksLiveness() && TRI->trackLivenessAfterRegAlloc(MF))
Benjamin Kramer3de5d402012-06-06 13:53:41 +0000148 RS.reset(new RegScavenger());
Bob Wilson2d4ff122009-11-26 00:32:21 +0000149
150 bool MadeChange = false;
Jakob Stoklund Olesen73ef9552010-01-15 19:59:57 +0000151 while (TailDuplicateBlocks(MF))
152 MadeChange = true;
Bob Wilson2d4ff122009-11-26 00:32:21 +0000153
154 return MadeChange;
155}
156
Akira Hatanakaa07ffb52014-02-12 18:09:18 +0000157void TailDuplicatePass::getAnalysisUsage(AnalysisUsage &AU) const {
158 AU.addRequired<MachineBranchProbabilityInfo>();
159 MachineFunctionPass::getAnalysisUsage(AU);
160}
161
Evan Chengcc770622009-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) {
Duncan P. N. Exon Smithf1ff53e2015-10-09 22:56:24 +0000164 MachineBasicBlock *MBB = &*I;
Evan Chengcc770622009-12-07 10:15:19 +0000165 SmallSetVector<MachineBasicBlock*, 8> Preds(MBB->pred_begin(),
166 MBB->pred_end());
167 MachineBasicBlock::iterator MI = MBB->begin();
168 while (MI != MBB->end()) {
Chris Lattnerb06015a2010-02-09 19:54:29 +0000169 if (!MI->isPHI())
Evan Chengcc770622009-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 Greene85afc852010-01-05 01:25:15 +0000183 dbgs() << "Malformed PHI in BB#" << MBB->getNumber() << ": " << *MI;
184 dbgs() << " missing input from predecessor BB#"
Evan Chengcc770622009-12-07 10:15:19 +0000185 << PredBB->getNumber() << '\n';
Craig Topperc0196b12014-04-14 00:51:57 +0000186 llvm_unreachable(nullptr);
Evan Chengcc770622009-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 Greene85afc852010-01-05 01:25:15 +0000193 dbgs() << "Warning: malformed PHI in BB#" << MBB->getNumber()
Evan Chengcc770622009-12-07 10:15:19 +0000194 << ": " << *MI;
David Greene85afc852010-01-05 01:25:15 +0000195 dbgs() << " extra input from predecessor BB#"
Evan Chengcc770622009-12-07 10:15:19 +0000196 << PHIBB->getNumber() << '\n';
Craig Topperc0196b12014-04-14 00:51:57 +0000197 llvm_unreachable(nullptr);
Evan Chengcc770622009-12-07 10:15:19 +0000198 }
199 if (PHIBB->getNumber() < 0) {
David Greene85afc852010-01-05 01:25:15 +0000200 dbgs() << "Malformed PHI in BB#" << MBB->getNumber() << ": " << *MI;
201 dbgs() << " non-existing BB#" << PHIBB->getNumber() << '\n';
Craig Topperc0196b12014-04-14 00:51:57 +0000202 llvm_unreachable(nullptr);
Evan Chengcc770622009-12-07 10:15:19 +0000203 }
204 }
205 ++MI;
206 }
207 }
208}
209
Sanjay Patelcc655432015-08-10 21:28:16 +0000210/// Tail duplicate the block and cleanup.
Rafael Espindolaf9f012e2011-07-04 01:21:42 +0000211bool
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);
Craig Topperc0196b12014-04-14 00:51:57 +0000252 MachineBasicBlock *DefBB = nullptr;
Rafael Espindolaf9f012e2011-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()) {
Owen Anderson16c6bf42014-03-13 23:12:04 +0000270 MachineOperand &UseMO = *UI;
271 MachineInstr *UseMI = UseMO.getParent();
Rafael Espindolaf9f012e2011-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 Olesen00f07de2012-05-20 18:42:51 +0000299 if (MRI->hasOneNonDBGUse(Src) &&
300 MRI->constrainRegClass(Src, MRI->getRegClass(Dst))) {
Rafael Espindolaf9f012e2011-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
Sanjay Patelcc655432015-08-10 21:28:16 +0000313/// Look for small blocks that are unconditionally branched to and do not fall
314/// through. Tail-duplicate their instructions into their predecessors to
315/// eliminate (dynamic) branches.
Bob Wilson9594db52009-11-26 21:38:41 +0000316bool TailDuplicatePass::TailDuplicateBlocks(MachineFunction &MF) {
Bob Wilson2d4ff122009-11-26 00:32:21 +0000317 bool MadeChange = false;
318
Evan Chengcc770622009-12-07 10:15:19 +0000319 if (PreRegAlloc && TailDupVerify) {
David Greene85afc852010-01-05 01:25:15 +0000320 DEBUG(dbgs() << "\n*** Before tail-duplicating\n");
Evan Chengcc770622009-12-07 10:15:19 +0000321 VerifyPHIs(MF, true);
322 }
323
Bob Wilson2d4ff122009-11-26 00:32:21 +0000324 for (MachineFunction::iterator I = ++MF.begin(), E = MF.end(); I != E; ) {
Duncan P. N. Exon Smithf1ff53e2015-10-09 22:56:24 +0000325 MachineBasicBlock *MBB = &*I++;
Bob Wilson2d4ff122009-11-26 00:32:21 +0000326
Evan Chengcc770622009-12-07 10:15:19 +0000327 if (NumTails == TailDupLimit)
328 break;
329
Rafael Espindolaf9f012e2011-07-04 01:21:42 +0000330 bool IsSimple = isSimpleBB(MBB);
Bob Wilson2d4ff122009-11-26 00:32:21 +0000331
Rafael Espindolaf9f012e2011-07-04 01:21:42 +0000332 if (!shouldTailDuplicate(MF, IsSimple, *MBB))
Rafael Espindola79dc4e72011-07-04 00:13:36 +0000333 continue;
Evan Chengcc770622009-12-07 10:15:19 +0000334
Rafael Espindolaf9f012e2011-07-04 01:21:42 +0000335 MadeChange |= TailDuplicateAndUpdate(MBB, IsSimple, MF);
Bob Wilson2d4ff122009-11-26 00:32:21 +0000336 }
Rafael Espindola79dc4e72011-07-04 00:13:36 +0000337
Rafael Espindolaf9f012e2011-07-04 01:21:42 +0000338 if (PreRegAlloc && TailDupVerify)
339 VerifyPHIs(MF, false);
Evan Cheng1bbe6be2009-12-03 08:43:53 +0000340
Bob Wilson2d4ff122009-11-26 00:32:21 +0000341 return MadeChange;
342}
343
Evan Cheng1bbe6be2009-12-03 08:43:53 +0000344static bool isDefLiveOut(unsigned Reg, MachineBasicBlock *BB,
345 const MachineRegisterInfo *MRI) {
Owen Andersonb36376e2014-03-17 19:36:09 +0000346 for (MachineInstr &UseMI : MRI->use_instructions(Reg)) {
347 if (UseMI.isDebugValue())
Rafael Espindolae0304d12011-06-17 13:59:43 +0000348 continue;
Owen Andersonb36376e2014-03-17 19:36:09 +0000349 if (UseMI.getParent() != BB)
Evan Cheng1bbe6be2009-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 Espindola81512fc2011-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 Espindola0f62e4c2011-06-10 21:01:53 +0000367 DenseSet<unsigned> *UsedByPhi) {
Alexey Samsonovf74bde62014-04-30 22:17:38 +0000368 for (const auto &MI : BB) {
Rafael Espindola81512fc2011-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
Sanjay Patelcc655432015-08-10 21:28:16 +0000378/// Add a definition and source virtual registers pair for SSA update.
Evan Cheng9e672552009-12-04 19:09:10 +0000379void TailDuplicatePass::AddSSAUpdateEntry(unsigned OrigReg, unsigned NewReg,
380 MachineBasicBlock *BB) {
381 DenseMap<unsigned, AvailableValsTy>::iterator LI= SSAUpdateVals.find(OrigReg);
Evan Cheng1bbe6be2009-12-03 08:43:53 +0000382 if (LI != SSAUpdateVals.end())
Evan Cheng9e672552009-12-04 19:09:10 +0000383 LI->second.push_back(std::make_pair(BB, NewReg));
Evan Cheng1bbe6be2009-12-03 08:43:53 +0000384 else {
385 AvailableValsTy Vals;
Evan Cheng9e672552009-12-04 19:09:10 +0000386 Vals.push_back(std::make_pair(BB, NewReg));
Evan Cheng1bbe6be2009-12-03 08:43:53 +0000387 SSAUpdateVals.insert(std::make_pair(OrigReg, Vals));
388 SSAUpdateVRs.push_back(OrigReg);
389 }
390}
391
Sanjay Patelcc655432015-08-10 21:28:16 +0000392/// Process PHI node in TailBB by turning it into a copy in PredBB. Remember the
393/// source register that's contributed by PredBB and update SSA update map.
Tobias Grosser84f34be2013-07-14 06:12:01 +0000394void TailDuplicatePass::ProcessPHI(
395 MachineInstr *MI, MachineBasicBlock *TailBB, MachineBasicBlock *PredBB,
396 DenseMap<unsigned, unsigned> &LocalVRMap,
397 SmallVectorImpl<std::pair<unsigned, unsigned> > &Copies,
398 const DenseSet<unsigned> &RegsUsedByPhi, bool Remove) {
Evan Cheng6154dbd2009-12-04 09:42:45 +0000399 unsigned DefReg = MI->getOperand(0).getReg();
400 unsigned SrcOpIdx = getPHISrcRegOpIdx(MI, PredBB);
401 assert(SrcOpIdx && "Unable to find matching PHI source?");
402 unsigned SrcReg = MI->getOperand(SrcOpIdx).getReg();
Evan Chengcc770622009-12-07 10:15:19 +0000403 const TargetRegisterClass *RC = MRI->getRegClass(DefReg);
Evan Cheng6154dbd2009-12-04 09:42:45 +0000404 LocalVRMap.insert(std::make_pair(DefReg, SrcReg));
Evan Chengcc770622009-12-07 10:15:19 +0000405
406 // Insert a copy from source to the end of the block. The def register is the
407 // available value liveout of the block.
408 unsigned NewDef = MRI->createVirtualRegister(RC);
409 Copies.push_back(std::make_pair(NewDef, SrcReg));
Rafael Espindola81512fc2011-06-09 22:53:47 +0000410 if (isDefLiveOut(DefReg, TailBB, MRI) || RegsUsedByPhi.count(DefReg))
Evan Chengcc770622009-12-07 10:15:19 +0000411 AddSSAUpdateEntry(DefReg, NewDef, PredBB);
Evan Cheng6154dbd2009-12-04 09:42:45 +0000412
Rafael Espindolac735f132011-06-09 23:22:56 +0000413 if (!Remove)
414 return;
415
Evan Cheng6154dbd2009-12-04 09:42:45 +0000416 // Remove PredBB from the PHI node.
417 MI->RemoveOperand(SrcOpIdx+1);
418 MI->RemoveOperand(SrcOpIdx);
419 if (MI->getNumOperands() == 1)
420 MI->eraseFromParent();
421}
422
Sanjay Patelcc655432015-08-10 21:28:16 +0000423/// Duplicate a TailBB instruction to PredBB and update
Evan Cheng6154dbd2009-12-04 09:42:45 +0000424/// the source operands due to earlier PHI translation.
425void TailDuplicatePass::DuplicateInstruction(MachineInstr *MI,
426 MachineBasicBlock *TailBB,
427 MachineBasicBlock *PredBB,
428 MachineFunction &MF,
Rafael Espindola81512fc2011-06-09 22:53:47 +0000429 DenseMap<unsigned, unsigned> &LocalVRMap,
430 const DenseSet<unsigned> &UsedByPhi) {
Jakob Stoklund Olesen29a64c92010-01-06 23:47:07 +0000431 MachineInstr *NewMI = TII->duplicate(MI, MF);
Dan Gohmand1c5a3a2016-02-20 21:28:18 +0000432 if (PreRegAlloc) {
433 for (unsigned i = 0, e = NewMI->getNumOperands(); i != e; ++i) {
434 MachineOperand &MO = NewMI->getOperand(i);
435 if (!MO.isReg())
436 continue;
437 unsigned Reg = MO.getReg();
438 if (!TargetRegisterInfo::isVirtualRegister(Reg))
439 continue;
440 if (MO.isDef()) {
441 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
442 unsigned NewReg = MRI->createVirtualRegister(RC);
443 MO.setReg(NewReg);
444 LocalVRMap.insert(std::make_pair(Reg, NewReg));
445 if (isDefLiveOut(Reg, TailBB, MRI) || UsedByPhi.count(Reg))
446 AddSSAUpdateEntry(Reg, NewReg, PredBB);
447 } else {
448 DenseMap<unsigned, unsigned>::iterator VI = LocalVRMap.find(Reg);
449 if (VI != LocalVRMap.end()) {
450 MO.setReg(VI->second);
451 // Clear any kill flags from this operand. The new register could have
452 // uses after this one, so kills are not valid here.
453 MO.setIsKill(false);
454 MRI->constrainRegClass(VI->second, MRI->getRegClass(Reg));
455 }
Jakob Stoklund Olesen00f07de2012-05-20 18:42:51 +0000456 }
Evan Cheng6154dbd2009-12-04 09:42:45 +0000457 }
458 }
Evan Chengd0c02962012-02-20 07:51:58 +0000459 PredBB->insert(PredBB->instr_end(), NewMI);
Evan Cheng6154dbd2009-12-04 09:42:45 +0000460}
461
Sanjay Patelcc655432015-08-10 21:28:16 +0000462/// After FromBB is tail duplicated into its predecessor blocks, the successors
463/// have gained new predecessors. Update the PHI instructions in them
464/// accordingly.
Evan Chengcc770622009-12-07 10:15:19 +0000465void
466TailDuplicatePass::UpdateSuccessorsPHIs(MachineBasicBlock *FromBB, bool isDead,
Craig Topperb94011f2013-07-14 04:42:23 +0000467 SmallVectorImpl<MachineBasicBlock *> &TDBBs,
Evan Cheng6154dbd2009-12-04 09:42:45 +0000468 SmallSetVector<MachineBasicBlock*,8> &Succs) {
469 for (SmallSetVector<MachineBasicBlock*, 8>::iterator SI = Succs.begin(),
470 SE = Succs.end(); SI != SE; ++SI) {
471 MachineBasicBlock *SuccBB = *SI;
472 for (MachineBasicBlock::iterator II = SuccBB->begin(), EE = SuccBB->end();
473 II != EE; ++II) {
Chris Lattnerb06015a2010-02-09 19:54:29 +0000474 if (!II->isPHI())
Evan Cheng6154dbd2009-12-04 09:42:45 +0000475 break;
Jakob Stoklund Olesenf623e982012-12-20 18:08:06 +0000476 MachineInstrBuilder MIB(*FromBB->getParent(), II);
Evan Chengcc770622009-12-07 10:15:19 +0000477 unsigned Idx = 0;
Evan Cheng6154dbd2009-12-04 09:42:45 +0000478 for (unsigned i = 1, e = II->getNumOperands(); i != e; i += 2) {
Evan Chengcc770622009-12-07 10:15:19 +0000479 MachineOperand &MO = II->getOperand(i+1);
480 if (MO.getMBB() == FromBB) {
481 Idx = i;
Evan Cheng6154dbd2009-12-04 09:42:45 +0000482 break;
Evan Chengcc770622009-12-07 10:15:19 +0000483 }
484 }
485
486 assert(Idx != 0);
487 MachineOperand &MO0 = II->getOperand(Idx);
488 unsigned Reg = MO0.getReg();
489 if (isDead) {
490 // Folded into the previous BB.
491 // There could be duplicate phi source entries. FIXME: Should sdisel
492 // or earlier pass fixed this?
493 for (unsigned i = II->getNumOperands()-2; i != Idx; i -= 2) {
494 MachineOperand &MO = II->getOperand(i+1);
495 if (MO.getMBB() == FromBB) {
496 II->RemoveOperand(i+1);
497 II->RemoveOperand(i);
498 }
499 }
Jakob Stoklund Olesen75521ca2010-02-11 00:34:33 +0000500 } else
501 Idx = 0;
502
503 // If Idx is set, the operands at Idx and Idx+1 must be removed.
504 // We reuse the location to avoid expensive RemoveOperand calls.
505
Evan Chengcc770622009-12-07 10:15:19 +0000506 DenseMap<unsigned,AvailableValsTy>::iterator LI=SSAUpdateVals.find(Reg);
507 if (LI != SSAUpdateVals.end()) {
508 // This register is defined in the tail block.
Evan Cheng6154dbd2009-12-04 09:42:45 +0000509 for (unsigned j = 0, ee = LI->second.size(); j != ee; ++j) {
Evan Cheng9e672552009-12-04 19:09:10 +0000510 MachineBasicBlock *SrcBB = LI->second[j].first;
Rafael Espindola9e97a892011-06-09 23:55:56 +0000511 // If we didn't duplicate a bb into a particular predecessor, we
512 // might still have added an entry to SSAUpdateVals to correcly
513 // recompute SSA. If that case, avoid adding a dummy extra argument
514 // this PHI.
515 if (!SrcBB->isSuccessor(SuccBB))
516 continue;
517
Evan Cheng9e672552009-12-04 19:09:10 +0000518 unsigned SrcReg = LI->second[j].second;
Jakob Stoklund Olesen75521ca2010-02-11 00:34:33 +0000519 if (Idx != 0) {
520 II->getOperand(Idx).setReg(SrcReg);
521 II->getOperand(Idx+1).setMBB(SrcBB);
522 Idx = 0;
523 } else {
Jakob Stoklund Olesenf623e982012-12-20 18:08:06 +0000524 MIB.addReg(SrcReg).addMBB(SrcBB);
Jakob Stoklund Olesen75521ca2010-02-11 00:34:33 +0000525 }
Evan Cheng6154dbd2009-12-04 09:42:45 +0000526 }
Evan Chengcc770622009-12-07 10:15:19 +0000527 } else {
528 // Live in tail block, must also be live in predecessors.
529 for (unsigned j = 0, ee = TDBBs.size(); j != ee; ++j) {
530 MachineBasicBlock *SrcBB = TDBBs[j];
Jakob Stoklund Olesen75521ca2010-02-11 00:34:33 +0000531 if (Idx != 0) {
532 II->getOperand(Idx).setReg(Reg);
533 II->getOperand(Idx+1).setMBB(SrcBB);
534 Idx = 0;
535 } else {
Jakob Stoklund Olesenf623e982012-12-20 18:08:06 +0000536 MIB.addReg(Reg).addMBB(SrcBB);
Jakob Stoklund Olesen75521ca2010-02-11 00:34:33 +0000537 }
Evan Chengcc770622009-12-07 10:15:19 +0000538 }
Evan Cheng6154dbd2009-12-04 09:42:45 +0000539 }
Jakob Stoklund Olesen75521ca2010-02-11 00:34:33 +0000540 if (Idx != 0) {
541 II->RemoveOperand(Idx+1);
542 II->RemoveOperand(Idx);
543 }
Evan Cheng6154dbd2009-12-04 09:42:45 +0000544 }
545 }
546}
547
Sanjay Patelcc655432015-08-10 21:28:16 +0000548/// Determine if it is profitable to duplicate this block.
Evan Chengcc770622009-12-07 10:15:19 +0000549bool
Rafael Espindola73f93932011-06-09 19:54:42 +0000550TailDuplicatePass::shouldTailDuplicate(const MachineFunction &MF,
Rafael Espindolae25a8712011-06-23 03:41:29 +0000551 bool IsSimple,
Rafael Espindola73f93932011-06-09 19:54:42 +0000552 MachineBasicBlock &TailBB) {
553 // Only duplicate blocks that end with unconditional branches.
554 if (TailBB.canFallThrough())
555 return false;
556
Rafael Espindola79a4b7e2011-06-17 05:54:50 +0000557 // Don't try to tail-duplicate single-block loops.
558 if (TailBB.isSuccessor(&TailBB))
559 return false;
560
Rafael Espindola73f93932011-06-09 19:54:42 +0000561 // Set the limit on the cost to duplicate. When optimizing for size,
Bob Wilson2d4ff122009-11-26 00:32:21 +0000562 // duplicate only one, because one branch instruction can be eliminated to
563 // compensate for the duplication.
564 unsigned MaxDuplicateCount;
Jakob Stoklund Olesen9af7afc2011-01-30 20:38:12 +0000565 if (TailDuplicateSize.getNumOccurrences() == 0 &&
Sanjay Patel924879a2015-08-04 15:49:57 +0000566 // FIXME: Use Function::optForSize().
Duncan P. N. Exon Smith70eb9c52015-02-14 01:44:41 +0000567 MF.getFunction()->hasFnAttribute(Attribute::OptimizeForSize))
Bob Wilson598f8ff2009-11-30 18:56:45 +0000568 MaxDuplicateCount = 1;
Bob Wilson2d4ff122009-11-26 00:32:21 +0000569 else
570 MaxDuplicateCount = TailDuplicateSize;
571
Rafael Espindola79a4b7e2011-06-17 05:54:50 +0000572 // If the target has hardware branch prediction that can handle indirect
573 // branches, duplicating them can often make them predictable when there
574 // are common paths through the code. The limit needs to be high enough
575 // to allow undoing the effects of tail merging and other optimizations
576 // that rearrange the predecessors of the indirect branch.
Bob Wilson97598f02010-01-16 00:42:25 +0000577
Rafael Espindolaf9f012e2011-07-04 01:21:42 +0000578 bool HasIndirectbr = false;
579 if (!TailBB.empty())
Evan Cheng7f8e5632011-12-07 07:15:52 +0000580 HasIndirectbr = TailBB.back().isIndirectBranch();
Rafael Espindolaf9f012e2011-07-04 01:21:42 +0000581
582 if (HasIndirectbr && PreRegAlloc)
583 MaxDuplicateCount = 20;
Bob Wilson1a234c02010-01-15 06:29:17 +0000584
Bob Wilson2d4ff122009-11-26 00:32:21 +0000585 // Check the instructions in the block to determine whether tail-duplication
586 // is invalid or unlikely to be profitable.
Bob Wilsonfffbc0c2009-12-02 17:15:24 +0000587 unsigned InstrCount = 0;
Sanjay Patel9f11c142015-08-10 23:29:41 +0000588 for (MachineInstr &MI : TailBB) {
Bob Wilson2d4ff122009-11-26 00:32:21 +0000589 // Non-duplicable things shouldn't be tail-duplicated.
Sanjay Patel9f11c142015-08-10 23:29:41 +0000590 if (MI.isNotDuplicable())
Rafael Espindola79a4b7e2011-06-17 05:54:50 +0000591 return false;
592
Evan Cheng6154dbd2009-12-04 09:42:45 +0000593 // Do not duplicate 'return' instructions if this is a pre-regalloc run.
594 // A return may expand into a lot more instructions (e.g. reload of callee
595 // saved registers) after PEI.
Sanjay Patel9f11c142015-08-10 23:29:41 +0000596 if (PreRegAlloc && MI.isReturn())
Rafael Espindola79a4b7e2011-06-17 05:54:50 +0000597 return false;
598
599 // Avoid duplicating calls before register allocation. Calls presents a
600 // barrier to register allocation so duplicating them may end up increasing
601 // spills.
Sanjay Patel9f11c142015-08-10 23:29:41 +0000602 if (PreRegAlloc && MI.isCall())
Rafael Espindola79a4b7e2011-06-17 05:54:50 +0000603 return false;
604
Sanjay Patel9f11c142015-08-10 23:29:41 +0000605 if (!MI.isPHI() && !MI.isDebugValue())
Bob Wilsonfffbc0c2009-12-02 17:15:24 +0000606 InstrCount += 1;
Rafael Espindola79a4b7e2011-06-17 05:54:50 +0000607
608 if (InstrCount > MaxDuplicateCount)
609 return false;
Bob Wilson2d4ff122009-11-26 00:32:21 +0000610 }
Bob Wilson2d4ff122009-11-26 00:32:21 +0000611
Krzysztof Parzyszekfdb7b692015-10-21 02:40:06 +0000612 // Check if any of the successors of TailBB has a PHI node in which the
613 // value corresponding to TailBB uses a subregister.
614 // If a phi node uses a register paired with a subregister, the actual
615 // "value type" of the phi may differ from the type of the register without
616 // any subregisters. Due to a bug, tail duplication may add a new operand
617 // without a necessary subregister, producing an invalid code. This is
618 // demonstrated by test/CodeGen/Hexagon/tail-dup-subreg-abort.ll.
619 // Disable tail duplication for this case for now, until the problem is
620 // fixed.
621 for (auto SB : TailBB.successors()) {
622 for (auto &I : *SB) {
623 if (!I.isPHI())
624 break;
625 unsigned Idx = getPHISrcRegOpIdx(&I, &TailBB);
626 assert(Idx != 0);
627 MachineOperand &PU = I.getOperand(Idx);
628 if (PU.getSubReg() != 0)
629 return false;
630 }
631 }
632
Rafael Espindolaf9f012e2011-07-04 01:21:42 +0000633 if (HasIndirectbr && PreRegAlloc)
Rafael Espindolae25a8712011-06-23 03:41:29 +0000634 return true;
635
636 if (IsSimple)
Rafael Espindolacb0213b2011-06-24 15:47:41 +0000637 return true;
Rafael Espindolae25a8712011-06-23 03:41:29 +0000638
639 if (!PreRegAlloc)
640 return true;
641
Rafael Espindola5135ae22011-06-24 15:50:56 +0000642 return canCompletelyDuplicateBB(TailBB);
Rafael Espindola73f93932011-06-09 19:54:42 +0000643}
644
Sanjay Patelcc655432015-08-10 21:28:16 +0000645/// True if this BB has only one unconditional jump.
Rafael Espindolaef636bf2011-06-20 04:16:35 +0000646bool
647TailDuplicatePass::isSimpleBB(MachineBasicBlock *TailBB) {
648 if (TailBB->succ_size() != 1)
649 return false;
Rafael Espindolae25a8712011-06-23 03:41:29 +0000650 if (TailBB->pred_empty())
651 return false;
Benjamin Kramer6b568962015-06-23 14:47:29 +0000652 MachineBasicBlock::iterator I = TailBB->getFirstNonDebugInstr();
653 if (I == TailBB->end())
Rafael Espindolaef636bf2011-06-20 04:16:35 +0000654 return true;
Evan Cheng7f8e5632011-12-07 07:15:52 +0000655 return I->isUnconditionalBranch();
Rafael Espindolaef636bf2011-06-20 04:16:35 +0000656}
657
658static bool
659bothUsedInPHI(const MachineBasicBlock &A,
660 SmallPtrSet<MachineBasicBlock*, 8> SuccsB) {
Sanjay Patelf609c112015-08-11 00:26:05 +0000661 for (MachineBasicBlock *BB : A.successors())
Rafael Espindolaef636bf2011-06-20 04:16:35 +0000662 if (SuccsB.count(BB) && !BB->empty() && BB->begin()->isPHI())
663 return true;
Rafael Espindolaef636bf2011-06-20 04:16:35 +0000664
665 return false;
666}
667
668bool
Rafael Espindola5135ae22011-06-24 15:50:56 +0000669TailDuplicatePass::canCompletelyDuplicateBB(MachineBasicBlock &BB) {
Sanjay Patelf609c112015-08-11 00:26:05 +0000670 for (MachineBasicBlock *PredBB : BB.predecessors()) {
Rafael Espindola5135ae22011-06-24 15:50:56 +0000671 if (PredBB->succ_size() > 1)
672 return false;
Rafael Espindolae25a8712011-06-23 03:41:29 +0000673
Craig Topperc0196b12014-04-14 00:51:57 +0000674 MachineBasicBlock *PredTBB = nullptr, *PredFBB = nullptr;
Rafael Espindolaef636bf2011-06-20 04:16:35 +0000675 SmallVector<MachineOperand, 4> PredCond;
676 if (TII->AnalyzeBranch(*PredBB, PredTBB, PredFBB, PredCond, true))
677 return false;
Rafael Espindolae25a8712011-06-23 03:41:29 +0000678
Rafael Espindola5135ae22011-06-24 15:50:56 +0000679 if (!PredCond.empty())
Rafael Espindolae25a8712011-06-23 03:41:29 +0000680 return false;
Rafael Espindolaef636bf2011-06-20 04:16:35 +0000681 }
682 return true;
683}
684
Rafael Espindolacb0213b2011-06-24 15:47:41 +0000685bool
Rafael Espindolaef636bf2011-06-20 04:16:35 +0000686TailDuplicatePass::duplicateSimpleBB(MachineBasicBlock *TailBB,
Craig Topperb94011f2013-07-14 04:42:23 +0000687 SmallVectorImpl<MachineBasicBlock *> &TDBBs,
688 const DenseSet<unsigned> &UsedByPhi,
689 SmallVectorImpl<MachineInstr *> &Copies) {
Rafael Espindolacb0213b2011-06-24 15:47:41 +0000690 SmallPtrSet<MachineBasicBlock*, 8> Succs(TailBB->succ_begin(),
691 TailBB->succ_end());
Rafael Espindolaef636bf2011-06-20 04:16:35 +0000692 SmallVector<MachineBasicBlock*, 8> Preds(TailBB->pred_begin(),
693 TailBB->pred_end());
Rafael Espindolacb0213b2011-06-24 15:47:41 +0000694 bool Changed = false;
Rafael Espindolaef636bf2011-06-20 04:16:35 +0000695 for (SmallSetVector<MachineBasicBlock *, 8>::iterator PI = Preds.begin(),
696 PE = Preds.end(); PI != PE; ++PI) {
697 MachineBasicBlock *PredBB = *PI;
698
Reid Klecknered170792015-09-17 17:19:40 +0000699 if (PredBB->hasEHPadSuccessor())
Rafael Espindolacb0213b2011-06-24 15:47:41 +0000700 continue;
701
702 if (bothUsedInPHI(*PredBB, Succs))
703 continue;
704
Craig Topperc0196b12014-04-14 00:51:57 +0000705 MachineBasicBlock *PredTBB = nullptr, *PredFBB = nullptr;
Rafael Espindolaef636bf2011-06-20 04:16:35 +0000706 SmallVector<MachineOperand, 4> PredCond;
Rafael Espindolacb0213b2011-06-24 15:47:41 +0000707 if (TII->AnalyzeBranch(*PredBB, PredTBB, PredFBB, PredCond, true))
708 continue;
Rafael Espindolaef636bf2011-06-20 04:16:35 +0000709
Rafael Espindolacb0213b2011-06-24 15:47:41 +0000710 Changed = true;
Rafael Espindolaef636bf2011-06-20 04:16:35 +0000711 DEBUG(dbgs() << "\nTail-duplicating into PredBB: " << *PredBB
712 << "From simple Succ: " << *TailBB);
713
714 MachineBasicBlock *NewTarget = *TailBB->succ_begin();
Duncan P. N. Exon Smithf1ff53e2015-10-09 22:56:24 +0000715 MachineBasicBlock *NextBB = &*std::next(PredBB->getIterator());
Rafael Espindolaef636bf2011-06-20 04:16:35 +0000716
Rafael Espindolaef636bf2011-06-20 04:16:35 +0000717 // Make PredFBB explicit.
718 if (PredCond.empty())
719 PredFBB = PredTBB;
720
721 // Make fall through explicit.
722 if (!PredTBB)
723 PredTBB = NextBB;
724 if (!PredFBB)
725 PredFBB = NextBB;
726
727 // Redirect
728 if (PredFBB == TailBB)
729 PredFBB = NewTarget;
730 if (PredTBB == TailBB)
731 PredTBB = NewTarget;
732
733 // Make the branch unconditional if possible
Rafael Espindola336e1022011-06-20 14:11:42 +0000734 if (PredTBB == PredFBB) {
735 PredCond.clear();
Craig Topperc0196b12014-04-14 00:51:57 +0000736 PredFBB = nullptr;
Rafael Espindola336e1022011-06-20 14:11:42 +0000737 }
Rafael Espindolaef636bf2011-06-20 04:16:35 +0000738
739 // Avoid adding fall through branches.
740 if (PredFBB == NextBB)
Craig Topperc0196b12014-04-14 00:51:57 +0000741 PredFBB = nullptr;
742 if (PredTBB == NextBB && PredFBB == nullptr)
743 PredTBB = nullptr;
Rafael Espindolaef636bf2011-06-20 04:16:35 +0000744
745 TII->RemoveBranch(*PredBB);
746
747 if (PredTBB)
748 TII->InsertBranch(*PredBB, PredTBB, PredFBB, PredCond, DebugLoc());
749
Cong Hou3ba9cf62015-12-15 10:10:40 +0000750 if (!PredBB->isSuccessor(NewTarget))
751 PredBB->replaceSuccessor(TailBB, NewTarget);
752 else {
Cong Hou08ec3d92015-12-16 06:03:30 +0000753 PredBB->removeSuccessor(TailBB, true);
Cong Hou3ba9cf62015-12-15 10:10:40 +0000754 assert(PredBB->succ_size() <= 1);
755 }
Rafael Espindolaef636bf2011-06-20 04:16:35 +0000756
757 TDBBs.push_back(PredBB);
Rafael Espindolaef636bf2011-06-20 04:16:35 +0000758 }
Rafael Espindolacb0213b2011-06-24 15:47:41 +0000759 return Changed;
Rafael Espindolaef636bf2011-06-20 04:16:35 +0000760}
761
Sanjay Patelcc655432015-08-10 21:28:16 +0000762/// If it is profitable, duplicate TailBB's contents in each
Rafael Espindola73f93932011-06-09 19:54:42 +0000763/// of its predecessors.
764bool
Rafael Espindolaf9f012e2011-07-04 01:21:42 +0000765TailDuplicatePass::TailDuplicate(MachineBasicBlock *TailBB,
766 bool IsSimple,
767 MachineFunction &MF,
Craig Topperb94011f2013-07-14 04:42:23 +0000768 SmallVectorImpl<MachineBasicBlock *> &TDBBs,
769 SmallVectorImpl<MachineInstr *> &Copies) {
David Greene85afc852010-01-05 01:25:15 +0000770 DEBUG(dbgs() << "\n*** Tail-duplicating BB#" << TailBB->getNumber() << '\n');
Evan Chengcc770622009-12-07 10:15:19 +0000771
Rafael Espindolaef636bf2011-06-20 04:16:35 +0000772 DenseSet<unsigned> UsedByPhi;
773 getRegsUsedByPHIs(*TailBB, &UsedByPhi);
774
Rafael Espindolacb0213b2011-06-24 15:47:41 +0000775 if (IsSimple)
776 return duplicateSimpleBB(TailBB, TDBBs, UsedByPhi, Copies);
Rafael Espindolaef636bf2011-06-20 04:16:35 +0000777
Bob Wilson2d4ff122009-11-26 00:32:21 +0000778 // Iterate through all the unique predecessors and tail-duplicate this
779 // block into them, if possible. Copying the list ahead of time also
780 // avoids trouble with the predecessor list reallocating.
781 bool Changed = false;
Evan Cheng6154dbd2009-12-04 09:42:45 +0000782 SmallSetVector<MachineBasicBlock*, 8> Preds(TailBB->pred_begin(),
783 TailBB->pred_end());
Bob Wilson2d4ff122009-11-26 00:32:21 +0000784 for (SmallSetVector<MachineBasicBlock *, 8>::iterator PI = Preds.begin(),
785 PE = Preds.end(); PI != PE; ++PI) {
786 MachineBasicBlock *PredBB = *PI;
787
788 assert(TailBB != PredBB &&
789 "Single-block loop should have been rejected earlier!");
Rafael Espindola1ffadd72011-06-10 20:08:23 +0000790 // EH edges are ignored by AnalyzeBranch.
791 if (PredBB->succ_size() > 1)
792 continue;
Bob Wilson2d4ff122009-11-26 00:32:21 +0000793
794 MachineBasicBlock *PredTBB, *PredFBB;
795 SmallVector<MachineOperand, 4> PredCond;
796 if (TII->AnalyzeBranch(*PredBB, PredTBB, PredFBB, PredCond, true))
797 continue;
798 if (!PredCond.empty())
799 continue;
Bob Wilson2d4ff122009-11-26 00:32:21 +0000800 // Don't duplicate into a fall-through predecessor (at least for now).
801 if (PredBB->isLayoutSuccessor(TailBB) && PredBB->canFallThrough())
802 continue;
803
David Greene85afc852010-01-05 01:25:15 +0000804 DEBUG(dbgs() << "\nTail-duplicating into PredBB: " << *PredBB
Bob Wilson2d4ff122009-11-26 00:32:21 +0000805 << "From Succ: " << *TailBB);
806
Evan Chengcc770622009-12-07 10:15:19 +0000807 TDBBs.push_back(PredBB);
808
Bob Wilson2d4ff122009-11-26 00:32:21 +0000809 // Remove PredBB's unconditional branch.
810 TII->RemoveBranch(*PredBB);
Evan Cheng1bbe6be2009-12-03 08:43:53 +0000811
Evan Chengbc2453d2012-05-30 00:42:39 +0000812 if (RS && !TailBB->livein_empty()) {
813 // Update PredBB livein.
814 RS->enterBasicBlock(PredBB);
815 if (!PredBB->empty())
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000816 RS->forward(std::prev(PredBB->end()));
Matthias Braund9da1622015-09-09 18:08:03 +0000817 for (const auto &LI : TailBB->liveins()) {
818 if (!RS->isRegUsed(LI.PhysReg, false))
Evan Chengbc2453d2012-05-30 00:42:39 +0000819 // If a register is previously livein to the tail but it's not live
820 // at the end of predecessor BB, then it should be added to its
821 // livein list.
Matthias Braunb2b7ef12015-08-24 22:59:52 +0000822 PredBB->addLiveIn(LI);
Evan Chengbc2453d2012-05-30 00:42:39 +0000823 }
824 }
825
Bob Wilson2d4ff122009-11-26 00:32:21 +0000826 // Clone the contents of TailBB into PredBB.
Evan Cheng1bbe6be2009-12-03 08:43:53 +0000827 DenseMap<unsigned, unsigned> LocalVRMap;
Evan Cheng45430bb2009-12-15 01:44:10 +0000828 SmallVector<std::pair<unsigned,unsigned>, 4> CopyInfos;
Evan Chengd0c02962012-02-20 07:51:58 +0000829 // Use instr_iterator here to properly handle bundles, e.g.
830 // ARM Thumb2 IT block.
831 MachineBasicBlock::instr_iterator I = TailBB->instr_begin();
832 while (I != TailBB->instr_end()) {
Evan Cheng6154dbd2009-12-04 09:42:45 +0000833 MachineInstr *MI = &*I;
834 ++I;
Chris Lattnerb06015a2010-02-09 19:54:29 +0000835 if (MI->isPHI()) {
Evan Cheng1bbe6be2009-12-03 08:43:53 +0000836 // Replace the uses of the def of the PHI with the register coming
837 // from PredBB.
Rafael Espindolac735f132011-06-09 23:22:56 +0000838 ProcessPHI(MI, TailBB, PredBB, LocalVRMap, CopyInfos, UsedByPhi, true);
Evan Cheng6154dbd2009-12-04 09:42:45 +0000839 } else {
840 // Replace def of virtual registers with new registers, and update
841 // uses with PHI source register or the new registers.
Rafael Espindola81512fc2011-06-09 22:53:47 +0000842 DuplicateInstruction(MI, TailBB, PredBB, MF, LocalVRMap, UsedByPhi);
Evan Cheng1bbe6be2009-12-03 08:43:53 +0000843 }
Bob Wilson2d4ff122009-11-26 00:32:21 +0000844 }
Evan Chengcc770622009-12-07 10:15:19 +0000845 MachineBasicBlock::iterator Loc = PredBB->getFirstTerminator();
Evan Cheng45430bb2009-12-15 01:44:10 +0000846 for (unsigned i = 0, e = CopyInfos.size(); i != e; ++i) {
Jakob Stoklund Olesen0c76d6e2010-07-10 22:42:59 +0000847 Copies.push_back(BuildMI(*PredBB, Loc, DebugLoc(),
848 TII->get(TargetOpcode::COPY),
849 CopyInfos[i].first).addReg(CopyInfos[i].second));
Evan Chengcc770622009-12-07 10:15:19 +0000850 }
Rafael Espindola79a4b7e2011-06-17 05:54:50 +0000851
852 // Simplify
853 TII->AnalyzeBranch(*PredBB, PredTBB, PredFBB, PredCond, true);
854
Bob Wilson2d4ff122009-11-26 00:32:21 +0000855 NumInstrDups += TailBB->size() - 1; // subtract one for removed branch
856
857 // Update the CFG.
858 PredBB->removeSuccessor(PredBB->succ_begin());
859 assert(PredBB->succ_empty() &&
860 "TailDuplicate called on block with multiple successors!");
861 for (MachineBasicBlock::succ_iterator I = TailBB->succ_begin(),
Evan Cheng6154dbd2009-12-04 09:42:45 +0000862 E = TailBB->succ_end(); I != E; ++I)
Cong Houd97c1002015-12-01 05:29:22 +0000863 PredBB->addSuccessor(*I, MBPI->getEdgeProbability(TailBB, I));
Bob Wilson2d4ff122009-11-26 00:32:21 +0000864
865 Changed = true;
866 ++NumTailDups;
867 }
868
869 // If TailBB was duplicated into all its predecessors except for the prior
870 // block, which falls through unconditionally, move the contents of this
871 // block into the prior block.
Duncan P. N. Exon Smithf1ff53e2015-10-09 22:56:24 +0000872 MachineBasicBlock *PrevBB = &*std::prev(TailBB->getIterator());
Craig Topperc0196b12014-04-14 00:51:57 +0000873 MachineBasicBlock *PriorTBB = nullptr, *PriorFBB = nullptr;
Bob Wilson2d4ff122009-11-26 00:32:21 +0000874 SmallVector<MachineOperand, 4> PriorCond;
Bob Wilson2d4ff122009-11-26 00:32:21 +0000875 // This has to check PrevBB->succ_size() because EH edges are ignored by
876 // AnalyzeBranch.
Andrew Trickc0449172012-02-08 21:22:30 +0000877 if (PrevBB->succ_size() == 1 &&
Rafael Espindolac90a32a2011-06-09 21:43:25 +0000878 !TII->AnalyzeBranch(*PrevBB, PriorTBB, PriorFBB, PriorCond, true) &&
879 PriorCond.empty() && !PriorTBB && TailBB->pred_size() == 1 &&
Bob Wilson2d4ff122009-11-26 00:32:21 +0000880 !TailBB->hasAddressTaken()) {
David Greene85afc852010-01-05 01:25:15 +0000881 DEBUG(dbgs() << "\nMerging into block: " << *PrevBB
Bob Wilson2d4ff122009-11-26 00:32:21 +0000882 << "From MBB: " << *TailBB);
Evan Cheng6154dbd2009-12-04 09:42:45 +0000883 if (PreRegAlloc) {
884 DenseMap<unsigned, unsigned> LocalVRMap;
Evan Cheng45430bb2009-12-15 01:44:10 +0000885 SmallVector<std::pair<unsigned,unsigned>, 4> CopyInfos;
Evan Cheng6154dbd2009-12-04 09:42:45 +0000886 MachineBasicBlock::iterator I = TailBB->begin();
887 // Process PHI instructions first.
Chris Lattnerb06015a2010-02-09 19:54:29 +0000888 while (I != TailBB->end() && I->isPHI()) {
Evan Cheng6154dbd2009-12-04 09:42:45 +0000889 // Replace the uses of the def of the PHI with the register coming
890 // from PredBB.
891 MachineInstr *MI = &*I++;
Rafael Espindolac735f132011-06-09 23:22:56 +0000892 ProcessPHI(MI, TailBB, PrevBB, LocalVRMap, CopyInfos, UsedByPhi, true);
Evan Cheng6154dbd2009-12-04 09:42:45 +0000893 if (MI->getParent())
894 MI->eraseFromParent();
895 }
896
897 // Now copy the non-PHI instructions.
898 while (I != TailBB->end()) {
899 // Replace def of virtual registers with new registers, and update
900 // uses with PHI source register or the new registers.
901 MachineInstr *MI = &*I++;
Evan Chengd0c02962012-02-20 07:51:58 +0000902 assert(!MI->isBundle() && "Not expecting bundles before regalloc!");
Rafael Espindola81512fc2011-06-09 22:53:47 +0000903 DuplicateInstruction(MI, TailBB, PrevBB, MF, LocalVRMap, UsedByPhi);
Evan Cheng6154dbd2009-12-04 09:42:45 +0000904 MI->eraseFromParent();
905 }
Evan Chengcc770622009-12-07 10:15:19 +0000906 MachineBasicBlock::iterator Loc = PrevBB->getFirstTerminator();
Evan Cheng45430bb2009-12-15 01:44:10 +0000907 for (unsigned i = 0, e = CopyInfos.size(); i != e; ++i) {
Jakob Stoklund Olesen0c76d6e2010-07-10 22:42:59 +0000908 Copies.push_back(BuildMI(*PrevBB, Loc, DebugLoc(),
909 TII->get(TargetOpcode::COPY),
910 CopyInfos[i].first)
911 .addReg(CopyInfos[i].second));
Evan Chengcc770622009-12-07 10:15:19 +0000912 }
Evan Cheng6154dbd2009-12-04 09:42:45 +0000913 } else {
914 // No PHIs to worry about, just splice the instructions over.
915 PrevBB->splice(PrevBB->end(), TailBB, TailBB->begin(), TailBB->end());
916 }
917 PrevBB->removeSuccessor(PrevBB->succ_begin());
918 assert(PrevBB->succ_empty());
919 PrevBB->transferSuccessors(TailBB);
Evan Chengcc770622009-12-07 10:15:19 +0000920 TDBBs.push_back(PrevBB);
Bob Wilson2d4ff122009-11-26 00:32:21 +0000921 Changed = true;
922 }
923
Rafael Espindolac735f132011-06-09 23:22:56 +0000924 // If this is after register allocation, there are no phis to fix.
925 if (!PreRegAlloc)
926 return Changed;
927
928 // If we made no changes so far, we are safe.
929 if (!Changed)
930 return Changed;
931
932
933 // Handle the nasty case in that we duplicated a block that is part of a loop
934 // into some but not all of its predecessors. For example:
Rafael Espindolac9e93a42011-06-09 23:51:45 +0000935 // 1 -> 2 <-> 3 |
936 // \ |
937 // \---> rest |
Rafael Espindolac735f132011-06-09 23:22:56 +0000938 // if we duplicate 2 into 1 but not into 3, we end up with
Rafael Espindolac9e93a42011-06-09 23:51:45 +0000939 // 12 -> 3 <-> 2 -> rest |
940 // \ / |
941 // \----->-----/ |
Rafael Espindolac735f132011-06-09 23:22:56 +0000942 // If there was a "var = phi(1, 3)" in 2, it has to be ultimately replaced
943 // with a phi in 3 (which now dominates 2).
944 // What we do here is introduce a copy in 3 of the register defined by the
945 // phi, just like when we are duplicating 2 into 3, but we don't copy any
946 // real instructions or remove the 3 -> 2 edge from the phi in 2.
947 for (SmallSetVector<MachineBasicBlock *, 8>::iterator PI = Preds.begin(),
948 PE = Preds.end(); PI != PE; ++PI) {
949 MachineBasicBlock *PredBB = *PI;
950 if (std::find(TDBBs.begin(), TDBBs.end(), PredBB) != TDBBs.end())
951 continue;
952
953 // EH edges
954 if (PredBB->succ_size() != 1)
955 continue;
956
957 DenseMap<unsigned, unsigned> LocalVRMap;
958 SmallVector<std::pair<unsigned,unsigned>, 4> CopyInfos;
959 MachineBasicBlock::iterator I = TailBB->begin();
960 // Process PHI instructions first.
961 while (I != TailBB->end() && I->isPHI()) {
962 // Replace the uses of the def of the PHI with the register coming
963 // from PredBB.
964 MachineInstr *MI = &*I++;
965 ProcessPHI(MI, TailBB, PredBB, LocalVRMap, CopyInfos, UsedByPhi, false);
966 }
967 MachineBasicBlock::iterator Loc = PredBB->getFirstTerminator();
968 for (unsigned i = 0, e = CopyInfos.size(); i != e; ++i) {
969 Copies.push_back(BuildMI(*PredBB, Loc, DebugLoc(),
970 TII->get(TargetOpcode::COPY),
971 CopyInfos[i].first).addReg(CopyInfos[i].second));
972 }
973 }
974
Bob Wilson2d4ff122009-11-26 00:32:21 +0000975 return Changed;
976}
977
Sanjay Patelcc655432015-08-10 21:28:16 +0000978/// Remove the specified dead machine basic block from the function, updating
979/// the CFG.
Bob Wilson9594db52009-11-26 21:38:41 +0000980void TailDuplicatePass::RemoveDeadBlock(MachineBasicBlock *MBB) {
Bob Wilson2d4ff122009-11-26 00:32:21 +0000981 assert(MBB->pred_empty() && "MBB must be dead!");
David Greene85afc852010-01-05 01:25:15 +0000982 DEBUG(dbgs() << "\nRemoving MBB: " << *MBB);
Bob Wilson2d4ff122009-11-26 00:32:21 +0000983
984 // Remove all successors.
985 while (!MBB->succ_empty())
986 MBB->removeSuccessor(MBB->succ_end()-1);
987
Bob Wilson2d4ff122009-11-26 00:32:21 +0000988 // Remove the block.
989 MBB->eraseFromParent();
990}