blob: b4ee8777d1fd2ccbc2beea5b2536117bc3ad3ed8 [file] [log] [blame]
Eugene Zelenko6ac7a342017-06-07 23:53:32 +00001//===- TailDuplicator.cpp - Duplicate blocks into predecessors' tails -----===//
Kyle Butt3232dbb2016-04-08 20:35:01 +00002//
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 utility class duplicates basic blocks ending in unconditional branches
11// into the tails of their predecessors.
12//
13//===----------------------------------------------------------------------===//
14
David Blaikie3f833ed2017-11-08 01:01:31 +000015#include "llvm/CodeGen/TailDuplicator.h"
Eugene Zelenko6ac7a342017-06-07 23:53:32 +000016#include "llvm/ADT/DenseMap.h"
Kyle Butt3232dbb2016-04-08 20:35:01 +000017#include "llvm/ADT/DenseSet.h"
David Blaikie3f833ed2017-11-08 01:01:31 +000018#include "llvm/ADT/STLExtras.h"
Kyle Butt3232dbb2016-04-08 20:35:01 +000019#include "llvm/ADT/SetVector.h"
Eugene Zelenko6ac7a342017-06-07 23:53:32 +000020#include "llvm/ADT/SmallPtrSet.h"
21#include "llvm/ADT/SmallVector.h"
Kyle Butt3232dbb2016-04-08 20:35:01 +000022#include "llvm/ADT/Statistic.h"
Eugene Zelenko6ac7a342017-06-07 23:53:32 +000023#include "llvm/CodeGen/MachineBasicBlock.h"
Kyle Butt3232dbb2016-04-08 20:35:01 +000024#include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
Eugene Zelenko6ac7a342017-06-07 23:53:32 +000025#include "llvm/CodeGen/MachineFunction.h"
26#include "llvm/CodeGen/MachineInstr.h"
Kyle Butt3232dbb2016-04-08 20:35:01 +000027#include "llvm/CodeGen/MachineInstrBuilder.h"
Eugene Zelenko6ac7a342017-06-07 23:53:32 +000028#include "llvm/CodeGen/MachineOperand.h"
29#include "llvm/CodeGen/MachineRegisterInfo.h"
30#include "llvm/CodeGen/MachineSSAUpdater.h"
David Blaikie3f833ed2017-11-08 01:01:31 +000031#include "llvm/CodeGen/TargetInstrInfo.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000032#include "llvm/CodeGen/TargetRegisterInfo.h"
33#include "llvm/CodeGen/TargetSubtargetInfo.h"
Eugene Zelenko6ac7a342017-06-07 23:53:32 +000034#include "llvm/IR/DebugLoc.h"
Kyle Butt3232dbb2016-04-08 20:35:01 +000035#include "llvm/IR/Function.h"
36#include "llvm/Support/CommandLine.h"
37#include "llvm/Support/Debug.h"
38#include "llvm/Support/ErrorHandling.h"
39#include "llvm/Support/raw_ostream.h"
Petar Jovanovic540f4cd2018-01-31 15:57:57 +000040#include "llvm/Target/TargetMachine.h"
Eugene Zelenko6ac7a342017-06-07 23:53:32 +000041#include <algorithm>
42#include <cassert>
43#include <iterator>
44#include <utility>
45
Kyle Butt3232dbb2016-04-08 20:35:01 +000046using namespace llvm;
47
48#define DEBUG_TYPE "tailduplication"
49
50STATISTIC(NumTails, "Number of tails duplicated");
51STATISTIC(NumTailDups, "Number of tail duplicated blocks");
Geoff Berryf8c29d62016-06-14 19:40:10 +000052STATISTIC(NumTailDupAdded,
53 "Number of instructions added due to tail duplication");
54STATISTIC(NumTailDupRemoved,
55 "Number of instructions removed due to tail duplication");
Kyle Butt3232dbb2016-04-08 20:35:01 +000056STATISTIC(NumDeadBlocks, "Number of dead blocks removed");
57STATISTIC(NumAddedPHIs, "Number of phis added");
58
59// Heuristic for tail duplication.
60static cl::opt<unsigned> TailDuplicateSize(
61 "tail-dup-size",
62 cl::desc("Maximum instructions to consider tail duplicating"), cl::init(2),
63 cl::Hidden);
64
Eugene Zelenko6ac7a342017-06-07 23:53:32 +000065static cl::opt<unsigned> TailDupIndirectBranchSize(
Kyle Butt61aca6e2016-08-30 18:18:54 +000066 "tail-dup-indirect-size",
67 cl::desc("Maximum instructions to consider tail duplicating blocks that "
68 "end with indirect branches."), cl::init(20),
69 cl::Hidden);
70
Kyle Butt3232dbb2016-04-08 20:35:01 +000071static cl::opt<bool>
72 TailDupVerify("tail-dup-verify",
73 cl::desc("Verify sanity of PHI instructions during taildup"),
74 cl::init(false), cl::Hidden);
75
76static cl::opt<unsigned> TailDupLimit("tail-dup-limit", cl::init(~0U),
77 cl::Hidden);
78
Matthias Braun8426d132017-08-23 03:17:59 +000079void TailDuplicator::initMF(MachineFunction &MFin, bool PreRegAlloc,
Kyle Buttdb3391e2016-08-17 21:07:35 +000080 const MachineBranchProbabilityInfo *MBPIin,
Kyle Butt0846e562016-10-11 20:36:43 +000081 bool LayoutModeIn, unsigned TailDupSizeIn) {
Kyle Butt3ed42732016-08-25 01:37:03 +000082 MF = &MFin;
83 TII = MF->getSubtarget().getInstrInfo();
84 TRI = MF->getSubtarget().getRegisterInfo();
85 MRI = &MF->getRegInfo();
Kyle Buttc7f1eac2016-08-25 01:37:07 +000086 MMI = &MF->getMMI();
Kyle Butt3232dbb2016-04-08 20:35:01 +000087 MBPI = MBPIin;
Kyle Buttdb3391e2016-08-17 21:07:35 +000088 TailDupSize = TailDupSizeIn;
Kyle Butt3232dbb2016-04-08 20:35:01 +000089
90 assert(MBPI != nullptr && "Machine Branch Probability Info required");
91
Kyle Butt0846e562016-10-11 20:36:43 +000092 LayoutMode = LayoutModeIn;
Matthias Braun8426d132017-08-23 03:17:59 +000093 this->PreRegAlloc = PreRegAlloc;
Kyle Butt3232dbb2016-04-08 20:35:01 +000094}
95
96static void VerifyPHIs(MachineFunction &MF, bool CheckExtra) {
97 for (MachineFunction::iterator I = ++MF.begin(), E = MF.end(); I != E; ++I) {
98 MachineBasicBlock *MBB = &*I;
99 SmallSetVector<MachineBasicBlock *, 8> Preds(MBB->pred_begin(),
100 MBB->pred_end());
101 MachineBasicBlock::iterator MI = MBB->begin();
102 while (MI != MBB->end()) {
103 if (!MI->isPHI())
104 break;
Matt Arsenaultb8037a12016-08-16 20:38:05 +0000105 for (MachineBasicBlock *PredBB : Preds) {
Kyle Butt3232dbb2016-04-08 20:35:01 +0000106 bool Found = false;
107 for (unsigned i = 1, e = MI->getNumOperands(); i != e; i += 2) {
108 MachineBasicBlock *PHIBB = MI->getOperand(i + 1).getMBB();
109 if (PHIBB == PredBB) {
110 Found = true;
111 break;
112 }
113 }
114 if (!Found) {
Francis Visoiu Mistrih25528d62017-12-04 17:18:51 +0000115 dbgs() << "Malformed PHI in " << printMBBReference(*MBB) << ": "
116 << *MI;
117 dbgs() << " missing input from predecessor "
118 << printMBBReference(*PredBB) << '\n';
Kyle Butt3232dbb2016-04-08 20:35:01 +0000119 llvm_unreachable(nullptr);
120 }
121 }
122
123 for (unsigned i = 1, e = MI->getNumOperands(); i != e; i += 2) {
124 MachineBasicBlock *PHIBB = MI->getOperand(i + 1).getMBB();
125 if (CheckExtra && !Preds.count(PHIBB)) {
Francis Visoiu Mistrih25528d62017-12-04 17:18:51 +0000126 dbgs() << "Warning: malformed PHI in " << printMBBReference(*MBB)
127 << ": " << *MI;
128 dbgs() << " extra input from predecessor "
129 << printMBBReference(*PHIBB) << '\n';
Kyle Butt3232dbb2016-04-08 20:35:01 +0000130 llvm_unreachable(nullptr);
131 }
132 if (PHIBB->getNumber() < 0) {
Francis Visoiu Mistrih25528d62017-12-04 17:18:51 +0000133 dbgs() << "Malformed PHI in " << printMBBReference(*MBB) << ": "
134 << *MI;
135 dbgs() << " non-existing " << printMBBReference(*PHIBB) << '\n';
Kyle Butt3232dbb2016-04-08 20:35:01 +0000136 llvm_unreachable(nullptr);
137 }
138 }
139 ++MI;
140 }
141 }
142}
143
144/// Tail duplicate the block and cleanup.
Kyle Butt723aa132016-08-26 20:12:40 +0000145/// \p IsSimple - return value of isSimpleBB
146/// \p MBB - block to be duplicated
Kyle Butt0846e562016-10-11 20:36:43 +0000147/// \p ForcedLayoutPred - If non-null, treat this block as the layout
148/// predecessor, instead of using the ordering in MF
Kyle Butt723aa132016-08-26 20:12:40 +0000149/// \p DuplicatedPreds - if non-null, \p DuplicatedPreds will contain a list of
150/// all Preds that received a copy of \p MBB.
Kyle Butt0846e562016-10-11 20:36:43 +0000151/// \p RemovalCallback - if non-null, called just before MBB is deleted.
Kyle Butt723aa132016-08-26 20:12:40 +0000152bool TailDuplicator::tailDuplicateAndUpdate(
153 bool IsSimple, MachineBasicBlock *MBB,
Kyle Butt0846e562016-10-11 20:36:43 +0000154 MachineBasicBlock *ForcedLayoutPred,
155 SmallVectorImpl<MachineBasicBlock*> *DuplicatedPreds,
Eugene Zelenko6ac7a342017-06-07 23:53:32 +0000156 function_ref<void(MachineBasicBlock *)> *RemovalCallback) {
Kyle Butt3232dbb2016-04-08 20:35:01 +0000157 // Save the successors list.
158 SmallSetVector<MachineBasicBlock *, 8> Succs(MBB->succ_begin(),
159 MBB->succ_end());
160
161 SmallVector<MachineBasicBlock *, 8> TDBBs;
162 SmallVector<MachineInstr *, 16> Copies;
Kyle Butt0846e562016-10-11 20:36:43 +0000163 if (!tailDuplicate(IsSimple, MBB, ForcedLayoutPred, TDBBs, Copies))
Kyle Butt3232dbb2016-04-08 20:35:01 +0000164 return false;
165
166 ++NumTails;
167
168 SmallVector<MachineInstr *, 8> NewPHIs;
Kyle Butt3ed42732016-08-25 01:37:03 +0000169 MachineSSAUpdater SSAUpdate(*MF, &NewPHIs);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000170
171 // TailBB's immediate successors are now successors of those predecessors
172 // which duplicated TailBB. Add the predecessors as sources to the PHI
173 // instructions.
174 bool isDead = MBB->pred_empty() && !MBB->hasAddressTaken();
175 if (PreRegAlloc)
176 updateSuccessorsPHIs(MBB, isDead, TDBBs, Succs);
177
178 // If it is dead, remove it.
179 if (isDead) {
Geoff Berryf8c29d62016-06-14 19:40:10 +0000180 NumTailDupRemoved += MBB->size();
Kyle Butt0846e562016-10-11 20:36:43 +0000181 removeDeadBlock(MBB, RemovalCallback);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000182 ++NumDeadBlocks;
183 }
184
185 // Update SSA form.
186 if (!SSAUpdateVRs.empty()) {
187 for (unsigned i = 0, e = SSAUpdateVRs.size(); i != e; ++i) {
188 unsigned VReg = SSAUpdateVRs[i];
189 SSAUpdate.Initialize(VReg);
190
191 // If the original definition is still around, add it as an available
192 // value.
193 MachineInstr *DefMI = MRI->getVRegDef(VReg);
194 MachineBasicBlock *DefBB = nullptr;
195 if (DefMI) {
196 DefBB = DefMI->getParent();
197 SSAUpdate.AddAvailableValue(DefBB, VReg);
198 }
199
200 // Add the new vregs as available values.
201 DenseMap<unsigned, AvailableValsTy>::iterator LI =
202 SSAUpdateVals.find(VReg);
203 for (unsigned j = 0, ee = LI->second.size(); j != ee; ++j) {
204 MachineBasicBlock *SrcBB = LI->second[j].first;
205 unsigned SrcReg = LI->second[j].second;
206 SSAUpdate.AddAvailableValue(SrcBB, SrcReg);
207 }
208
209 // Rewrite uses that are outside of the original def's block.
210 MachineRegisterInfo::use_iterator UI = MRI->use_begin(VReg);
211 while (UI != MRI->use_end()) {
212 MachineOperand &UseMO = *UI;
213 MachineInstr *UseMI = UseMO.getParent();
214 ++UI;
215 if (UseMI->isDebugValue()) {
216 // SSAUpdate can replace the use with an undef. That creates
217 // a debug instruction that is a kill.
218 // FIXME: Should it SSAUpdate job to delete debug instructions
219 // instead of replacing the use with undef?
220 UseMI->eraseFromParent();
221 continue;
222 }
223 if (UseMI->getParent() == DefBB && !UseMI->isPHI())
224 continue;
225 SSAUpdate.RewriteUse(UseMO);
226 }
227 }
228
229 SSAUpdateVRs.clear();
230 SSAUpdateVals.clear();
231 }
232
233 // Eliminate some of the copies inserted by tail duplication to maintain
234 // SSA form.
235 for (unsigned i = 0, e = Copies.size(); i != e; ++i) {
236 MachineInstr *Copy = Copies[i];
237 if (!Copy->isCopy())
238 continue;
239 unsigned Dst = Copy->getOperand(0).getReg();
240 unsigned Src = Copy->getOperand(1).getReg();
241 if (MRI->hasOneNonDBGUse(Src) &&
242 MRI->constrainRegClass(Src, MRI->getRegClass(Dst))) {
243 // Copy is the only use. Do trivial copy propagation here.
244 MRI->replaceRegWith(Dst, Src);
245 Copy->eraseFromParent();
246 }
247 }
248
249 if (NewPHIs.size())
250 NumAddedPHIs += NewPHIs.size();
251
Kyle Butt723aa132016-08-26 20:12:40 +0000252 if (DuplicatedPreds)
253 *DuplicatedPreds = std::move(TDBBs);
254
Kyle Butt3232dbb2016-04-08 20:35:01 +0000255 return true;
256}
257
258/// Look for small blocks that are unconditionally branched to and do not fall
259/// through. Tail-duplicate their instructions into their predecessors to
260/// eliminate (dynamic) branches.
Kyle Butt3ed42732016-08-25 01:37:03 +0000261bool TailDuplicator::tailDuplicateBlocks() {
Kyle Butt3232dbb2016-04-08 20:35:01 +0000262 bool MadeChange = false;
263
264 if (PreRegAlloc && TailDupVerify) {
265 DEBUG(dbgs() << "\n*** Before tail-duplicating\n");
Kyle Butt3ed42732016-08-25 01:37:03 +0000266 VerifyPHIs(*MF, true);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000267 }
268
Kyle Butt3ed42732016-08-25 01:37:03 +0000269 for (MachineFunction::iterator I = ++MF->begin(), E = MF->end(); I != E;) {
Kyle Butt3232dbb2016-04-08 20:35:01 +0000270 MachineBasicBlock *MBB = &*I++;
271
272 if (NumTails == TailDupLimit)
273 break;
274
275 bool IsSimple = isSimpleBB(MBB);
276
Kyle Butt3ed42732016-08-25 01:37:03 +0000277 if (!shouldTailDuplicate(IsSimple, *MBB))
Kyle Butt3232dbb2016-04-08 20:35:01 +0000278 continue;
279
Kyle Butt0846e562016-10-11 20:36:43 +0000280 MadeChange |= tailDuplicateAndUpdate(IsSimple, MBB, nullptr);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000281 }
282
283 if (PreRegAlloc && TailDupVerify)
Kyle Butt3ed42732016-08-25 01:37:03 +0000284 VerifyPHIs(*MF, false);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000285
286 return MadeChange;
287}
288
289static bool isDefLiveOut(unsigned Reg, MachineBasicBlock *BB,
290 const MachineRegisterInfo *MRI) {
291 for (MachineInstr &UseMI : MRI->use_instructions(Reg)) {
292 if (UseMI.isDebugValue())
293 continue;
294 if (UseMI.getParent() != BB)
295 return true;
296 }
297 return false;
298}
299
300static unsigned getPHISrcRegOpIdx(MachineInstr *MI, MachineBasicBlock *SrcBB) {
301 for (unsigned i = 1, e = MI->getNumOperands(); i != e; i += 2)
302 if (MI->getOperand(i + 1).getMBB() == SrcBB)
303 return i;
304 return 0;
305}
306
307// Remember which registers are used by phis in this block. This is
308// used to determine which registers are liveout while modifying the
309// block (which is why we need to copy the information).
310static void getRegsUsedByPHIs(const MachineBasicBlock &BB,
311 DenseSet<unsigned> *UsedByPhi) {
312 for (const auto &MI : BB) {
313 if (!MI.isPHI())
314 break;
315 for (unsigned i = 1, e = MI.getNumOperands(); i != e; i += 2) {
316 unsigned SrcReg = MI.getOperand(i).getReg();
317 UsedByPhi->insert(SrcReg);
318 }
319 }
320}
321
322/// Add a definition and source virtual registers pair for SSA update.
323void TailDuplicator::addSSAUpdateEntry(unsigned OrigReg, unsigned NewReg,
324 MachineBasicBlock *BB) {
325 DenseMap<unsigned, AvailableValsTy>::iterator LI =
326 SSAUpdateVals.find(OrigReg);
327 if (LI != SSAUpdateVals.end())
328 LI->second.push_back(std::make_pair(BB, NewReg));
329 else {
330 AvailableValsTy Vals;
331 Vals.push_back(std::make_pair(BB, NewReg));
332 SSAUpdateVals.insert(std::make_pair(OrigReg, Vals));
333 SSAUpdateVRs.push_back(OrigReg);
334 }
335}
336
337/// Process PHI node in TailBB by turning it into a copy in PredBB. Remember the
338/// source register that's contributed by PredBB and update SSA update map.
339void TailDuplicator::processPHI(
340 MachineInstr *MI, MachineBasicBlock *TailBB, MachineBasicBlock *PredBB,
Krzysztof Parzyszek4773f642016-04-26 18:36:34 +0000341 DenseMap<unsigned, RegSubRegPair> &LocalVRMap,
342 SmallVectorImpl<std::pair<unsigned, RegSubRegPair>> &Copies,
Kyle Butt3232dbb2016-04-08 20:35:01 +0000343 const DenseSet<unsigned> &RegsUsedByPhi, bool Remove) {
344 unsigned DefReg = MI->getOperand(0).getReg();
345 unsigned SrcOpIdx = getPHISrcRegOpIdx(MI, PredBB);
346 assert(SrcOpIdx && "Unable to find matching PHI source?");
347 unsigned SrcReg = MI->getOperand(SrcOpIdx).getReg();
Krzysztof Parzyszek4773f642016-04-26 18:36:34 +0000348 unsigned SrcSubReg = MI->getOperand(SrcOpIdx).getSubReg();
Kyle Butt3232dbb2016-04-08 20:35:01 +0000349 const TargetRegisterClass *RC = MRI->getRegClass(DefReg);
Krzysztof Parzyszek4773f642016-04-26 18:36:34 +0000350 LocalVRMap.insert(std::make_pair(DefReg, RegSubRegPair(SrcReg, SrcSubReg)));
Kyle Butt3232dbb2016-04-08 20:35:01 +0000351
352 // Insert a copy from source to the end of the block. The def register is the
353 // available value liveout of the block.
354 unsigned NewDef = MRI->createVirtualRegister(RC);
Krzysztof Parzyszek4773f642016-04-26 18:36:34 +0000355 Copies.push_back(std::make_pair(NewDef, RegSubRegPair(SrcReg, SrcSubReg)));
Kyle Butt3232dbb2016-04-08 20:35:01 +0000356 if (isDefLiveOut(DefReg, TailBB, MRI) || RegsUsedByPhi.count(DefReg))
357 addSSAUpdateEntry(DefReg, NewDef, PredBB);
358
359 if (!Remove)
360 return;
361
362 // Remove PredBB from the PHI node.
363 MI->RemoveOperand(SrcOpIdx + 1);
364 MI->RemoveOperand(SrcOpIdx);
365 if (MI->getNumOperands() == 1)
366 MI->eraseFromParent();
367}
368
369/// Duplicate a TailBB instruction to PredBB and update
370/// the source operands due to earlier PHI translation.
371void TailDuplicator::duplicateInstruction(
372 MachineInstr *MI, MachineBasicBlock *TailBB, MachineBasicBlock *PredBB,
Krzysztof Parzyszek4773f642016-04-26 18:36:34 +0000373 DenseMap<unsigned, RegSubRegPair> &LocalVRMap,
Kyle Butt3232dbb2016-04-08 20:35:01 +0000374 const DenseSet<unsigned> &UsedByPhi) {
Petar Jovanovic540f4cd2018-01-31 15:57:57 +0000375 // Allow duplication of CFI instructions.
376 if (MI->isCFIInstruction()) {
377 BuildMI(*PredBB, PredBB->end(), PredBB->findDebugLoc(PredBB->begin()),
378 TII->get(TargetOpcode::CFI_INSTRUCTION)).addCFIIndex(
379 MI->getOperand(0).getCFIIndex());
380 return;
381 }
Matthias Braun55bc9b32017-08-22 23:56:30 +0000382 MachineInstr &NewMI = TII->duplicate(*PredBB, PredBB->end(), *MI);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000383 if (PreRegAlloc) {
Matthias Braun55bc9b32017-08-22 23:56:30 +0000384 for (unsigned i = 0, e = NewMI.getNumOperands(); i != e; ++i) {
385 MachineOperand &MO = NewMI.getOperand(i);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000386 if (!MO.isReg())
387 continue;
388 unsigned Reg = MO.getReg();
389 if (!TargetRegisterInfo::isVirtualRegister(Reg))
390 continue;
391 if (MO.isDef()) {
392 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
393 unsigned NewReg = MRI->createVirtualRegister(RC);
394 MO.setReg(NewReg);
Krzysztof Parzyszek4773f642016-04-26 18:36:34 +0000395 LocalVRMap.insert(std::make_pair(Reg, RegSubRegPair(NewReg, 0)));
Kyle Butt3232dbb2016-04-08 20:35:01 +0000396 if (isDefLiveOut(Reg, TailBB, MRI) || UsedByPhi.count(Reg))
397 addSSAUpdateEntry(Reg, NewReg, PredBB);
398 } else {
Krzysztof Parzyszek4773f642016-04-26 18:36:34 +0000399 auto VI = LocalVRMap.find(Reg);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000400 if (VI != LocalVRMap.end()) {
Krzysztof Parzyszek4773f642016-04-26 18:36:34 +0000401 // Need to make sure that the register class of the mapped register
402 // will satisfy the constraints of the class of the register being
403 // replaced.
404 auto *OrigRC = MRI->getRegClass(Reg);
405 auto *MappedRC = MRI->getRegClass(VI->second.Reg);
406 const TargetRegisterClass *ConstrRC;
407 if (VI->second.SubReg != 0) {
408 ConstrRC = TRI->getMatchingSuperRegClass(MappedRC, OrigRC,
409 VI->second.SubReg);
410 if (ConstrRC) {
411 // The actual constraining (as in "find appropriate new class")
412 // is done by getMatchingSuperRegClass, so now we only need to
413 // change the class of the mapped register.
414 MRI->setRegClass(VI->second.Reg, ConstrRC);
415 }
416 } else {
417 // For mapped registers that do not have sub-registers, simply
418 // restrict their class to match the original one.
419 ConstrRC = MRI->constrainRegClass(VI->second.Reg, OrigRC);
420 }
421
422 if (ConstrRC) {
423 // If the class constraining succeeded, we can simply replace
424 // the old register with the mapped one.
425 MO.setReg(VI->second.Reg);
426 // We have Reg -> VI.Reg:VI.SubReg, so if Reg is used with a
427 // sub-register, we need to compose the sub-register indices.
428 MO.setSubReg(TRI->composeSubRegIndices(MO.getSubReg(),
429 VI->second.SubReg));
430 } else {
431 // The direct replacement is not possible, due to failing register
432 // class constraints. An explicit COPY is necessary. Create one
433 // that can be reused
434 auto *NewRC = MI->getRegClassConstraint(i, TII, TRI);
435 if (NewRC == nullptr)
436 NewRC = OrigRC;
437 unsigned NewReg = MRI->createVirtualRegister(NewRC);
438 BuildMI(*PredBB, MI, MI->getDebugLoc(),
439 TII->get(TargetOpcode::COPY), NewReg)
440 .addReg(VI->second.Reg, 0, VI->second.SubReg);
441 LocalVRMap.erase(VI);
442 LocalVRMap.insert(std::make_pair(Reg, RegSubRegPair(NewReg, 0)));
443 MO.setReg(NewReg);
444 // The composed VI.Reg:VI.SubReg is replaced with NewReg, which
445 // is equivalent to the whole register Reg. Hence, Reg:subreg
446 // is same as NewReg:subreg, so keep the sub-register index
447 // unchanged.
448 }
Kyle Butt3232dbb2016-04-08 20:35:01 +0000449 // Clear any kill flags from this operand. The new register could
450 // have uses after this one, so kills are not valid here.
451 MO.setIsKill(false);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000452 }
453 }
454 }
455 }
Kyle Butt3232dbb2016-04-08 20:35:01 +0000456}
457
458/// After FromBB is tail duplicated into its predecessor blocks, the successors
459/// have gained new predecessors. Update the PHI instructions in them
460/// accordingly.
461void TailDuplicator::updateSuccessorsPHIs(
462 MachineBasicBlock *FromBB, bool isDead,
463 SmallVectorImpl<MachineBasicBlock *> &TDBBs,
464 SmallSetVector<MachineBasicBlock *, 8> &Succs) {
Matt Arsenaultb8037a12016-08-16 20:38:05 +0000465 for (MachineBasicBlock *SuccBB : Succs) {
466 for (MachineInstr &MI : *SuccBB) {
467 if (!MI.isPHI())
Kyle Butt3232dbb2016-04-08 20:35:01 +0000468 break;
Matt Arsenaultb8037a12016-08-16 20:38:05 +0000469 MachineInstrBuilder MIB(*FromBB->getParent(), MI);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000470 unsigned Idx = 0;
Matt Arsenaultb8037a12016-08-16 20:38:05 +0000471 for (unsigned i = 1, e = MI.getNumOperands(); i != e; i += 2) {
472 MachineOperand &MO = MI.getOperand(i + 1);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000473 if (MO.getMBB() == FromBB) {
474 Idx = i;
475 break;
476 }
477 }
478
479 assert(Idx != 0);
Matt Arsenaultb8037a12016-08-16 20:38:05 +0000480 MachineOperand &MO0 = MI.getOperand(Idx);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000481 unsigned Reg = MO0.getReg();
482 if (isDead) {
483 // Folded into the previous BB.
484 // There could be duplicate phi source entries. FIXME: Should sdisel
485 // or earlier pass fixed this?
Matt Arsenaultb8037a12016-08-16 20:38:05 +0000486 for (unsigned i = MI.getNumOperands() - 2; i != Idx; i -= 2) {
487 MachineOperand &MO = MI.getOperand(i + 1);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000488 if (MO.getMBB() == FromBB) {
Matt Arsenaultb8037a12016-08-16 20:38:05 +0000489 MI.RemoveOperand(i + 1);
490 MI.RemoveOperand(i);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000491 }
492 }
493 } else
494 Idx = 0;
495
496 // If Idx is set, the operands at Idx and Idx+1 must be removed.
497 // We reuse the location to avoid expensive RemoveOperand calls.
498
499 DenseMap<unsigned, AvailableValsTy>::iterator LI =
500 SSAUpdateVals.find(Reg);
501 if (LI != SSAUpdateVals.end()) {
502 // This register is defined in the tail block.
503 for (unsigned j = 0, ee = LI->second.size(); j != ee; ++j) {
504 MachineBasicBlock *SrcBB = LI->second[j].first;
505 // If we didn't duplicate a bb into a particular predecessor, we
506 // might still have added an entry to SSAUpdateVals to correcly
507 // recompute SSA. If that case, avoid adding a dummy extra argument
508 // this PHI.
509 if (!SrcBB->isSuccessor(SuccBB))
510 continue;
511
512 unsigned SrcReg = LI->second[j].second;
513 if (Idx != 0) {
Matt Arsenaultb8037a12016-08-16 20:38:05 +0000514 MI.getOperand(Idx).setReg(SrcReg);
515 MI.getOperand(Idx + 1).setMBB(SrcBB);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000516 Idx = 0;
517 } else {
518 MIB.addReg(SrcReg).addMBB(SrcBB);
519 }
520 }
521 } else {
522 // Live in tail block, must also be live in predecessors.
523 for (unsigned j = 0, ee = TDBBs.size(); j != ee; ++j) {
524 MachineBasicBlock *SrcBB = TDBBs[j];
525 if (Idx != 0) {
Matt Arsenaultb8037a12016-08-16 20:38:05 +0000526 MI.getOperand(Idx).setReg(Reg);
527 MI.getOperand(Idx + 1).setMBB(SrcBB);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000528 Idx = 0;
529 } else {
530 MIB.addReg(Reg).addMBB(SrcBB);
531 }
532 }
533 }
534 if (Idx != 0) {
Matt Arsenaultb8037a12016-08-16 20:38:05 +0000535 MI.RemoveOperand(Idx + 1);
536 MI.RemoveOperand(Idx);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000537 }
538 }
539 }
540}
541
542/// Determine if it is profitable to duplicate this block.
Kyle Butt3ed42732016-08-25 01:37:03 +0000543bool TailDuplicator::shouldTailDuplicate(bool IsSimple,
Kyle Butt3232dbb2016-04-08 20:35:01 +0000544 MachineBasicBlock &TailBB) {
Kyle Butt0846e562016-10-11 20:36:43 +0000545 // When doing tail-duplication during layout, the block ordering is in flux,
546 // so canFallThrough returns a result based on incorrect information and
547 // should just be ignored.
548 if (!LayoutMode && TailBB.canFallThrough())
Kyle Butt3232dbb2016-04-08 20:35:01 +0000549 return false;
550
551 // Don't try to tail-duplicate single-block loops.
552 if (TailBB.isSuccessor(&TailBB))
553 return false;
554
555 // Set the limit on the cost to duplicate. When optimizing for size,
556 // duplicate only one, because one branch instruction can be eliminated to
557 // compensate for the duplication.
558 unsigned MaxDuplicateCount;
Kyle Buttdb3391e2016-08-17 21:07:35 +0000559 if (TailDupSize == 0 &&
560 TailDuplicateSize.getNumOccurrences() == 0 &&
Matthias Braunf1caa282017-12-15 22:22:58 +0000561 MF->getFunction().optForSize())
Kyle Butt3232dbb2016-04-08 20:35:01 +0000562 MaxDuplicateCount = 1;
Kyle Buttdb3391e2016-08-17 21:07:35 +0000563 else if (TailDupSize == 0)
Kyle Butt3232dbb2016-04-08 20:35:01 +0000564 MaxDuplicateCount = TailDuplicateSize;
Kyle Buttdb3391e2016-08-17 21:07:35 +0000565 else
566 MaxDuplicateCount = TailDupSize;
Kyle Butt3232dbb2016-04-08 20:35:01 +0000567
Kyle Butt07d61422016-08-16 22:56:14 +0000568 // If the block to be duplicated ends in an unanalyzable fallthrough, don't
569 // duplicate it.
570 // A similar check is necessary in MachineBlockPlacement to make sure pairs of
571 // blocks with unanalyzable fallthrough get layed out contiguously.
572 MachineBasicBlock *PredTBB = nullptr, *PredFBB = nullptr;
573 SmallVector<MachineOperand, 4> PredCond;
Sanjoy Dasd7389d62016-12-15 05:08:57 +0000574 if (TII->analyzeBranch(TailBB, PredTBB, PredFBB, PredCond) &&
575 TailBB.canFallThrough())
Kyle Butt07d61422016-08-16 22:56:14 +0000576 return false;
577
Kyle Butt3232dbb2016-04-08 20:35:01 +0000578 // If the target has hardware branch prediction that can handle indirect
579 // branches, duplicating them can often make them predictable when there
580 // are common paths through the code. The limit needs to be high enough
581 // to allow undoing the effects of tail merging and other optimizations
582 // that rearrange the predecessors of the indirect branch.
583
584 bool HasIndirectbr = false;
585 if (!TailBB.empty())
586 HasIndirectbr = TailBB.back().isIndirectBranch();
587
588 if (HasIndirectbr && PreRegAlloc)
Kyle Butt61aca6e2016-08-30 18:18:54 +0000589 MaxDuplicateCount = TailDupIndirectBranchSize;
Kyle Butt3232dbb2016-04-08 20:35:01 +0000590
591 // Check the instructions in the block to determine whether tail-duplication
592 // is invalid or unlikely to be profitable.
593 unsigned InstrCount = 0;
594 for (MachineInstr &MI : TailBB) {
595 // Non-duplicable things shouldn't be tail-duplicated.
Petar Jovanovic540f4cd2018-01-31 15:57:57 +0000596 // CFI instructions are marked as non-duplicable, because Darwin compact
597 // unwind info emission can't handle multiple prologue setups. In case of
598 // DWARF, allow them be duplicated, so that their existence doesn't prevent
599 // tail duplication of some basic blocks, that would be duplicated otherwise.
600 if (MI.isNotDuplicable() &&
601 (TailBB.getParent()->getTarget().getTargetTriple().isOSDarwin() ||
602 !MI.isCFIInstruction()))
Kyle Butt3232dbb2016-04-08 20:35:01 +0000603 return false;
604
605 // Convergent instructions can be duplicated only if doing so doesn't add
606 // new control dependencies, which is what we're going to do here.
607 if (MI.isConvergent())
608 return false;
609
610 // Do not duplicate 'return' instructions if this is a pre-regalloc run.
611 // A return may expand into a lot more instructions (e.g. reload of callee
612 // saved registers) after PEI.
613 if (PreRegAlloc && MI.isReturn())
614 return false;
615
616 // Avoid duplicating calls before register allocation. Calls presents a
617 // barrier to register allocation so duplicating them may end up increasing
618 // spills.
619 if (PreRegAlloc && MI.isCall())
620 return false;
621
Petar Jovanovic540f4cd2018-01-31 15:57:57 +0000622 if (!MI.isPHI() && !MI.isMetaInstruction())
Reid Kleckner7adb2fd2017-11-08 21:31:14 +0000623 InstrCount += 1;
Kyle Butt3232dbb2016-04-08 20:35:01 +0000624
625 if (InstrCount > MaxDuplicateCount)
626 return false;
627 }
628
629 // Check if any of the successors of TailBB has a PHI node in which the
630 // value corresponding to TailBB uses a subregister.
631 // If a phi node uses a register paired with a subregister, the actual
632 // "value type" of the phi may differ from the type of the register without
633 // any subregisters. Due to a bug, tail duplication may add a new operand
634 // without a necessary subregister, producing an invalid code. This is
635 // demonstrated by test/CodeGen/Hexagon/tail-dup-subreg-abort.ll.
636 // Disable tail duplication for this case for now, until the problem is
637 // fixed.
638 for (auto SB : TailBB.successors()) {
639 for (auto &I : *SB) {
640 if (!I.isPHI())
641 break;
642 unsigned Idx = getPHISrcRegOpIdx(&I, &TailBB);
643 assert(Idx != 0);
644 MachineOperand &PU = I.getOperand(Idx);
645 if (PU.getSubReg() != 0)
646 return false;
647 }
648 }
649
650 if (HasIndirectbr && PreRegAlloc)
651 return true;
652
653 if (IsSimple)
654 return true;
655
656 if (!PreRegAlloc)
657 return true;
658
659 return canCompletelyDuplicateBB(TailBB);
660}
661
662/// True if this BB has only one unconditional jump.
663bool TailDuplicator::isSimpleBB(MachineBasicBlock *TailBB) {
664 if (TailBB->succ_size() != 1)
665 return false;
666 if (TailBB->pred_empty())
667 return false;
668 MachineBasicBlock::iterator I = TailBB->getFirstNonDebugInstr();
669 if (I == TailBB->end())
670 return true;
671 return I->isUnconditionalBranch();
672}
673
674static bool bothUsedInPHI(const MachineBasicBlock &A,
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000675 const SmallPtrSet<MachineBasicBlock *, 8> &SuccsB) {
Kyle Butt3232dbb2016-04-08 20:35:01 +0000676 for (MachineBasicBlock *BB : A.successors())
677 if (SuccsB.count(BB) && !BB->empty() && BB->begin()->isPHI())
678 return true;
679
680 return false;
681}
682
683bool TailDuplicator::canCompletelyDuplicateBB(MachineBasicBlock &BB) {
684 for (MachineBasicBlock *PredBB : BB.predecessors()) {
685 if (PredBB->succ_size() > 1)
686 return false;
687
688 MachineBasicBlock *PredTBB = nullptr, *PredFBB = nullptr;
689 SmallVector<MachineOperand, 4> PredCond;
Sanjoy Dasd7389d62016-12-15 05:08:57 +0000690 if (TII->analyzeBranch(*PredBB, PredTBB, PredFBB, PredCond))
Kyle Butt3232dbb2016-04-08 20:35:01 +0000691 return false;
692
693 if (!PredCond.empty())
694 return false;
695 }
696 return true;
697}
698
699bool TailDuplicator::duplicateSimpleBB(
700 MachineBasicBlock *TailBB, SmallVectorImpl<MachineBasicBlock *> &TDBBs,
701 const DenseSet<unsigned> &UsedByPhi,
702 SmallVectorImpl<MachineInstr *> &Copies) {
703 SmallPtrSet<MachineBasicBlock *, 8> Succs(TailBB->succ_begin(),
704 TailBB->succ_end());
705 SmallVector<MachineBasicBlock *, 8> Preds(TailBB->pred_begin(),
706 TailBB->pred_end());
707 bool Changed = false;
Matt Arsenaultb8037a12016-08-16 20:38:05 +0000708 for (MachineBasicBlock *PredBB : Preds) {
Kyle Butt3232dbb2016-04-08 20:35:01 +0000709 if (PredBB->hasEHPadSuccessor())
710 continue;
711
712 if (bothUsedInPHI(*PredBB, Succs))
713 continue;
714
715 MachineBasicBlock *PredTBB = nullptr, *PredFBB = nullptr;
716 SmallVector<MachineOperand, 4> PredCond;
Sanjoy Dasd7389d62016-12-15 05:08:57 +0000717 if (TII->analyzeBranch(*PredBB, PredTBB, PredFBB, PredCond))
Kyle Butt3232dbb2016-04-08 20:35:01 +0000718 continue;
719
720 Changed = true;
721 DEBUG(dbgs() << "\nTail-duplicating into PredBB: " << *PredBB
722 << "From simple Succ: " << *TailBB);
723
724 MachineBasicBlock *NewTarget = *TailBB->succ_begin();
Matthias Braun6442fc12016-08-18 00:59:32 +0000725 MachineBasicBlock *NextBB = PredBB->getNextNode();
Kyle Butt3232dbb2016-04-08 20:35:01 +0000726
727 // Make PredFBB explicit.
728 if (PredCond.empty())
729 PredFBB = PredTBB;
730
731 // Make fall through explicit.
732 if (!PredTBB)
733 PredTBB = NextBB;
734 if (!PredFBB)
735 PredFBB = NextBB;
736
737 // Redirect
738 if (PredFBB == TailBB)
739 PredFBB = NewTarget;
740 if (PredTBB == TailBB)
741 PredTBB = NewTarget;
742
743 // Make the branch unconditional if possible
744 if (PredTBB == PredFBB) {
745 PredCond.clear();
746 PredFBB = nullptr;
747 }
748
749 // Avoid adding fall through branches.
750 if (PredFBB == NextBB)
751 PredFBB = nullptr;
752 if (PredTBB == NextBB && PredFBB == nullptr)
753 PredTBB = nullptr;
754
Taewook Oha49eb852017-02-27 19:30:01 +0000755 auto DL = PredBB->findBranchDebugLoc();
Matt Arsenault1b9fc8e2016-09-14 20:43:16 +0000756 TII->removeBranch(*PredBB);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000757
758 if (!PredBB->isSuccessor(NewTarget))
759 PredBB->replaceSuccessor(TailBB, NewTarget);
760 else {
761 PredBB->removeSuccessor(TailBB, true);
762 assert(PredBB->succ_size() <= 1);
763 }
764
765 if (PredTBB)
Taewook Oha49eb852017-02-27 19:30:01 +0000766 TII->insertBranch(*PredBB, PredTBB, PredFBB, PredCond, DL);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000767
768 TDBBs.push_back(PredBB);
769 }
770 return Changed;
771}
772
Kyle Butt9e52c062016-07-19 23:54:21 +0000773bool TailDuplicator::canTailDuplicate(MachineBasicBlock *TailBB,
774 MachineBasicBlock *PredBB) {
Kyle Butt0846e562016-10-11 20:36:43 +0000775 // EH edges are ignored by analyzeBranch.
Kyle Butt9e52c062016-07-19 23:54:21 +0000776 if (PredBB->succ_size() > 1)
777 return false;
778
Vitaly Bukab238cb82017-05-22 21:33:54 +0000779 MachineBasicBlock *PredTBB = nullptr, *PredFBB = nullptr;
Kyle Butt9e52c062016-07-19 23:54:21 +0000780 SmallVector<MachineOperand, 4> PredCond;
Sanjoy Dasd7389d62016-12-15 05:08:57 +0000781 if (TII->analyzeBranch(*PredBB, PredTBB, PredFBB, PredCond))
Kyle Butt9e52c062016-07-19 23:54:21 +0000782 return false;
783 if (!PredCond.empty())
784 return false;
785 return true;
786}
787
Kyle Butt3232dbb2016-04-08 20:35:01 +0000788/// If it is profitable, duplicate TailBB's contents in each
789/// of its predecessors.
Kyle Butt0846e562016-10-11 20:36:43 +0000790/// \p IsSimple result of isSimpleBB
791/// \p TailBB Block to be duplicated.
792/// \p ForcedLayoutPred When non-null, use this block as the layout predecessor
793/// instead of the previous block in MF's order.
794/// \p TDBBs A vector to keep track of all blocks tail-duplicated
795/// into.
796/// \p Copies A vector of copy instructions inserted. Used later to
797/// walk all the inserted copies and remove redundant ones.
Kyle Butt3ed42732016-08-25 01:37:03 +0000798bool TailDuplicator::tailDuplicate(bool IsSimple, MachineBasicBlock *TailBB,
Kyle Butt0846e562016-10-11 20:36:43 +0000799 MachineBasicBlock *ForcedLayoutPred,
Kyle Butt3232dbb2016-04-08 20:35:01 +0000800 SmallVectorImpl<MachineBasicBlock *> &TDBBs,
801 SmallVectorImpl<MachineInstr *> &Copies) {
Francis Visoiu Mistrih25528d62017-12-04 17:18:51 +0000802 DEBUG(dbgs() << "\n*** Tail-duplicating " << printMBBReference(*TailBB)
803 << '\n');
Kyle Butt3232dbb2016-04-08 20:35:01 +0000804
805 DenseSet<unsigned> UsedByPhi;
806 getRegsUsedByPHIs(*TailBB, &UsedByPhi);
807
808 if (IsSimple)
809 return duplicateSimpleBB(TailBB, TDBBs, UsedByPhi, Copies);
810
811 // Iterate through all the unique predecessors and tail-duplicate this
812 // block into them, if possible. Copying the list ahead of time also
813 // avoids trouble with the predecessor list reallocating.
814 bool Changed = false;
815 SmallSetVector<MachineBasicBlock *, 8> Preds(TailBB->pred_begin(),
816 TailBB->pred_end());
Matt Arsenaultb8037a12016-08-16 20:38:05 +0000817 for (MachineBasicBlock *PredBB : Preds) {
Kyle Butt3232dbb2016-04-08 20:35:01 +0000818 assert(TailBB != PredBB &&
819 "Single-block loop should have been rejected earlier!");
Kyle Butt9e52c062016-07-19 23:54:21 +0000820
821 if (!canTailDuplicate(TailBB, PredBB))
Kyle Butt3232dbb2016-04-08 20:35:01 +0000822 continue;
823
Kyle Butt3232dbb2016-04-08 20:35:01 +0000824 // Don't duplicate into a fall-through predecessor (at least for now).
Kyle Butt0846e562016-10-11 20:36:43 +0000825 bool IsLayoutSuccessor = false;
826 if (ForcedLayoutPred)
827 IsLayoutSuccessor = (ForcedLayoutPred == PredBB);
828 else if (PredBB->isLayoutSuccessor(TailBB) && PredBB->canFallThrough())
829 IsLayoutSuccessor = true;
830 if (IsLayoutSuccessor)
Kyle Butt3232dbb2016-04-08 20:35:01 +0000831 continue;
832
833 DEBUG(dbgs() << "\nTail-duplicating into PredBB: " << *PredBB
834 << "From Succ: " << *TailBB);
835
836 TDBBs.push_back(PredBB);
837
838 // Remove PredBB's unconditional branch.
Matt Arsenault1b9fc8e2016-09-14 20:43:16 +0000839 TII->removeBranch(*PredBB);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000840
Kyle Butt3232dbb2016-04-08 20:35:01 +0000841 // Clone the contents of TailBB into PredBB.
Krzysztof Parzyszek4773f642016-04-26 18:36:34 +0000842 DenseMap<unsigned, RegSubRegPair> LocalVRMap;
843 SmallVector<std::pair<unsigned, RegSubRegPair>, 4> CopyInfos;
Matthias Braun55bc9b32017-08-22 23:56:30 +0000844 for (MachineBasicBlock::iterator I = TailBB->begin(), E = TailBB->end();
845 I != E; /* empty */) {
Kyle Butt3232dbb2016-04-08 20:35:01 +0000846 MachineInstr *MI = &*I;
847 ++I;
848 if (MI->isPHI()) {
849 // Replace the uses of the def of the PHI with the register coming
850 // from PredBB.
851 processPHI(MI, TailBB, PredBB, LocalVRMap, CopyInfos, UsedByPhi, true);
852 } else {
853 // Replace def of virtual registers with new registers, and update
854 // uses with PHI source register or the new registers.
Kyle Butt3ed42732016-08-25 01:37:03 +0000855 duplicateInstruction(MI, TailBB, PredBB, LocalVRMap, UsedByPhi);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000856 }
857 }
Krzysztof Parzyszek4773f642016-04-26 18:36:34 +0000858 appendCopies(PredBB, CopyInfos, Copies);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000859
860 // Simplify
Vitaly Bukab238cb82017-05-22 21:33:54 +0000861 MachineBasicBlock *PredTBB = nullptr, *PredFBB = nullptr;
Kyle Butt9e52c062016-07-19 23:54:21 +0000862 SmallVector<MachineOperand, 4> PredCond;
Sanjoy Dasd7389d62016-12-15 05:08:57 +0000863 TII->analyzeBranch(*PredBB, PredTBB, PredFBB, PredCond);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000864
Geoff Berryf8c29d62016-06-14 19:40:10 +0000865 NumTailDupAdded += TailBB->size() - 1; // subtract one for removed branch
Kyle Butt3232dbb2016-04-08 20:35:01 +0000866
867 // Update the CFG.
868 PredBB->removeSuccessor(PredBB->succ_begin());
869 assert(PredBB->succ_empty() &&
870 "TailDuplicate called on block with multiple successors!");
Matt Arsenaultb8037a12016-08-16 20:38:05 +0000871 for (MachineBasicBlock *Succ : TailBB->successors())
872 PredBB->addSuccessor(Succ, MBPI->getEdgeProbability(TailBB, Succ));
Kyle Butt3232dbb2016-04-08 20:35:01 +0000873
874 Changed = true;
875 ++NumTailDups;
876 }
877
878 // If TailBB was duplicated into all its predecessors except for the prior
879 // block, which falls through unconditionally, move the contents of this
880 // block into the prior block.
Kyle Butt0846e562016-10-11 20:36:43 +0000881 MachineBasicBlock *PrevBB = ForcedLayoutPred;
882 if (!PrevBB)
883 PrevBB = &*std::prev(TailBB->getIterator());
Kyle Butt3232dbb2016-04-08 20:35:01 +0000884 MachineBasicBlock *PriorTBB = nullptr, *PriorFBB = nullptr;
885 SmallVector<MachineOperand, 4> PriorCond;
886 // This has to check PrevBB->succ_size() because EH edges are ignored by
Kyle Butt0846e562016-10-11 20:36:43 +0000887 // analyzeBranch.
Kyle Butt3232dbb2016-04-08 20:35:01 +0000888 if (PrevBB->succ_size() == 1 &&
Kyle Buttd2b886e2016-07-20 00:01:51 +0000889 // Layout preds are not always CFG preds. Check.
890 *PrevBB->succ_begin() == TailBB &&
Sanjoy Dasd7389d62016-12-15 05:08:57 +0000891 !TII->analyzeBranch(*PrevBB, PriorTBB, PriorFBB, PriorCond) &&
Kyle Butt0846e562016-10-11 20:36:43 +0000892 PriorCond.empty() &&
893 (!PriorTBB || PriorTBB == TailBB) &&
894 TailBB->pred_size() == 1 &&
Kyle Butt3232dbb2016-04-08 20:35:01 +0000895 !TailBB->hasAddressTaken()) {
896 DEBUG(dbgs() << "\nMerging into block: " << *PrevBB
897 << "From MBB: " << *TailBB);
Kyle Butt0846e562016-10-11 20:36:43 +0000898 // There may be a branch to the layout successor. This is unlikely but it
899 // happens. The correct thing to do is to remove the branch before
900 // duplicating the instructions in all cases.
901 TII->removeBranch(*PrevBB);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000902 if (PreRegAlloc) {
Krzysztof Parzyszek4773f642016-04-26 18:36:34 +0000903 DenseMap<unsigned, RegSubRegPair> LocalVRMap;
904 SmallVector<std::pair<unsigned, RegSubRegPair>, 4> CopyInfos;
Kyle Butt3232dbb2016-04-08 20:35:01 +0000905 MachineBasicBlock::iterator I = TailBB->begin();
906 // Process PHI instructions first.
907 while (I != TailBB->end() && I->isPHI()) {
908 // Replace the uses of the def of the PHI with the register coming
909 // from PredBB.
910 MachineInstr *MI = &*I++;
911 processPHI(MI, TailBB, PrevBB, LocalVRMap, CopyInfos, UsedByPhi, true);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000912 }
913
914 // Now copy the non-PHI instructions.
915 while (I != TailBB->end()) {
916 // Replace def of virtual registers with new registers, and update
917 // uses with PHI source register or the new registers.
918 MachineInstr *MI = &*I++;
919 assert(!MI->isBundle() && "Not expecting bundles before regalloc!");
Kyle Butt3ed42732016-08-25 01:37:03 +0000920 duplicateInstruction(MI, TailBB, PrevBB, LocalVRMap, UsedByPhi);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000921 MI->eraseFromParent();
922 }
Krzysztof Parzyszek4773f642016-04-26 18:36:34 +0000923 appendCopies(PrevBB, CopyInfos, Copies);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000924 } else {
Kyle Butt0846e562016-10-11 20:36:43 +0000925 TII->removeBranch(*PrevBB);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000926 // No PHIs to worry about, just splice the instructions over.
927 PrevBB->splice(PrevBB->end(), TailBB, TailBB->begin(), TailBB->end());
928 }
929 PrevBB->removeSuccessor(PrevBB->succ_begin());
930 assert(PrevBB->succ_empty());
931 PrevBB->transferSuccessors(TailBB);
932 TDBBs.push_back(PrevBB);
933 Changed = true;
934 }
935
936 // If this is after register allocation, there are no phis to fix.
937 if (!PreRegAlloc)
938 return Changed;
939
940 // If we made no changes so far, we are safe.
941 if (!Changed)
942 return Changed;
943
944 // Handle the nasty case in that we duplicated a block that is part of a loop
945 // into some but not all of its predecessors. For example:
946 // 1 -> 2 <-> 3 |
947 // \ |
948 // \---> rest |
949 // if we duplicate 2 into 1 but not into 3, we end up with
950 // 12 -> 3 <-> 2 -> rest |
951 // \ / |
952 // \----->-----/ |
953 // If there was a "var = phi(1, 3)" in 2, it has to be ultimately replaced
954 // with a phi in 3 (which now dominates 2).
955 // What we do here is introduce a copy in 3 of the register defined by the
956 // phi, just like when we are duplicating 2 into 3, but we don't copy any
957 // real instructions or remove the 3 -> 2 edge from the phi in 2.
Matt Arsenaultb8037a12016-08-16 20:38:05 +0000958 for (MachineBasicBlock *PredBB : Preds) {
David Majnemer0d955d02016-08-11 22:21:41 +0000959 if (is_contained(TDBBs, PredBB))
Kyle Butt3232dbb2016-04-08 20:35:01 +0000960 continue;
961
962 // EH edges
963 if (PredBB->succ_size() != 1)
964 continue;
965
Krzysztof Parzyszek4773f642016-04-26 18:36:34 +0000966 DenseMap<unsigned, RegSubRegPair> LocalVRMap;
967 SmallVector<std::pair<unsigned, RegSubRegPair>, 4> CopyInfos;
Kyle Butt3232dbb2016-04-08 20:35:01 +0000968 MachineBasicBlock::iterator I = TailBB->begin();
969 // Process PHI instructions first.
970 while (I != TailBB->end() && I->isPHI()) {
971 // Replace the uses of the def of the PHI with the register coming
972 // from PredBB.
973 MachineInstr *MI = &*I++;
974 processPHI(MI, TailBB, PredBB, LocalVRMap, CopyInfos, UsedByPhi, false);
975 }
Krzysztof Parzyszek4773f642016-04-26 18:36:34 +0000976 appendCopies(PredBB, CopyInfos, Copies);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000977 }
978
979 return Changed;
980}
981
Krzysztof Parzyszek4773f642016-04-26 18:36:34 +0000982/// At the end of the block \p MBB generate COPY instructions between registers
983/// described by \p CopyInfos. Append resulting instructions to \p Copies.
984void TailDuplicator::appendCopies(MachineBasicBlock *MBB,
985 SmallVectorImpl<std::pair<unsigned,RegSubRegPair>> &CopyInfos,
986 SmallVectorImpl<MachineInstr*> &Copies) {
987 MachineBasicBlock::iterator Loc = MBB->getFirstTerminator();
988 const MCInstrDesc &CopyD = TII->get(TargetOpcode::COPY);
989 for (auto &CI : CopyInfos) {
990 auto C = BuildMI(*MBB, Loc, DebugLoc(), CopyD, CI.first)
991 .addReg(CI.second.Reg, 0, CI.second.SubReg);
992 Copies.push_back(C);
993 }
994}
995
Kyle Butt3232dbb2016-04-08 20:35:01 +0000996/// Remove the specified dead machine basic block from the function, updating
997/// the CFG.
Kyle Butt0846e562016-10-11 20:36:43 +0000998void TailDuplicator::removeDeadBlock(
999 MachineBasicBlock *MBB,
Eugene Zelenko6ac7a342017-06-07 23:53:32 +00001000 function_ref<void(MachineBasicBlock *)> *RemovalCallback) {
Kyle Butt3232dbb2016-04-08 20:35:01 +00001001 assert(MBB->pred_empty() && "MBB must be dead!");
1002 DEBUG(dbgs() << "\nRemoving MBB: " << *MBB);
1003
Kyle Butt0846e562016-10-11 20:36:43 +00001004 if (RemovalCallback)
1005 (*RemovalCallback)(MBB);
1006
Kyle Butt3232dbb2016-04-08 20:35:01 +00001007 // Remove all successors.
1008 while (!MBB->succ_empty())
1009 MBB->removeSuccessor(MBB->succ_end() - 1);
1010
1011 // Remove the block.
1012 MBB->eraseFromParent();
1013}