blob: d40f7af431a9b7f2c278132578648a7a201068c1 [file] [log] [blame]
Kyle Butt3232dbb2016-04-08 20:35:01 +00001//===-- TailDuplicator.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 utility class duplicates basic blocks ending in unconditional branches
11// into the tails of their predecessors.
12//
13//===----------------------------------------------------------------------===//
14
15#include "llvm/CodeGen/TailDuplicator.h"
16#include "llvm/ADT/DenseSet.h"
17#include "llvm/ADT/SetVector.h"
18#include "llvm/ADT/SmallSet.h"
19#include "llvm/ADT/Statistic.h"
20#include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
21#include "llvm/CodeGen/MachineFunctionPass.h"
22#include "llvm/CodeGen/MachineInstrBuilder.h"
Kyle Butt0846e562016-10-11 20:36:43 +000023#include "llvm/CodeGen/MachineLoopInfo.h"
Kyle Butt3232dbb2016-04-08 20:35:01 +000024#include "llvm/CodeGen/MachineModuleInfo.h"
25#include "llvm/CodeGen/Passes.h"
26#include "llvm/IR/Function.h"
27#include "llvm/Support/CommandLine.h"
28#include "llvm/Support/Debug.h"
29#include "llvm/Support/ErrorHandling.h"
30#include "llvm/Support/raw_ostream.h"
31using namespace llvm;
32
33#define DEBUG_TYPE "tailduplication"
34
35STATISTIC(NumTails, "Number of tails duplicated");
36STATISTIC(NumTailDups, "Number of tail duplicated blocks");
Geoff Berryf8c29d62016-06-14 19:40:10 +000037STATISTIC(NumTailDupAdded,
38 "Number of instructions added due to tail duplication");
39STATISTIC(NumTailDupRemoved,
40 "Number of instructions removed due to tail duplication");
Kyle Butt3232dbb2016-04-08 20:35:01 +000041STATISTIC(NumDeadBlocks, "Number of dead blocks removed");
42STATISTIC(NumAddedPHIs, "Number of phis added");
43
Kyle Butt61aca6e2016-08-30 18:18:54 +000044namespace llvm {
45
Kyle Butt3232dbb2016-04-08 20:35:01 +000046// Heuristic for tail duplication.
47static cl::opt<unsigned> TailDuplicateSize(
48 "tail-dup-size",
49 cl::desc("Maximum instructions to consider tail duplicating"), cl::init(2),
50 cl::Hidden);
51
Kyle Butt61aca6e2016-08-30 18:18:54 +000052cl::opt<unsigned> TailDupIndirectBranchSize(
53 "tail-dup-indirect-size",
54 cl::desc("Maximum instructions to consider tail duplicating blocks that "
55 "end with indirect branches."), cl::init(20),
56 cl::Hidden);
57
Kyle Butt3232dbb2016-04-08 20:35:01 +000058static cl::opt<bool>
59 TailDupVerify("tail-dup-verify",
60 cl::desc("Verify sanity of PHI instructions during taildup"),
61 cl::init(false), cl::Hidden);
62
63static cl::opt<unsigned> TailDupLimit("tail-dup-limit", cl::init(~0U),
64 cl::Hidden);
65
Kyle Butt3ed42732016-08-25 01:37:03 +000066void TailDuplicator::initMF(MachineFunction &MFin,
Kyle Buttdb3391e2016-08-17 21:07:35 +000067 const MachineBranchProbabilityInfo *MBPIin,
Kyle Butt0846e562016-10-11 20:36:43 +000068 bool LayoutModeIn, unsigned TailDupSizeIn) {
Kyle Butt3ed42732016-08-25 01:37:03 +000069 MF = &MFin;
70 TII = MF->getSubtarget().getInstrInfo();
71 TRI = MF->getSubtarget().getRegisterInfo();
72 MRI = &MF->getRegInfo();
Kyle Buttc7f1eac2016-08-25 01:37:07 +000073 MMI = &MF->getMMI();
Kyle Butt3232dbb2016-04-08 20:35:01 +000074 MBPI = MBPIin;
Kyle Buttdb3391e2016-08-17 21:07:35 +000075 TailDupSize = TailDupSizeIn;
Kyle Butt3232dbb2016-04-08 20:35:01 +000076
77 assert(MBPI != nullptr && "Machine Branch Probability Info required");
78
Kyle Butt0846e562016-10-11 20:36:43 +000079 LayoutMode = LayoutModeIn;
Kyle Butt3232dbb2016-04-08 20:35:01 +000080 PreRegAlloc = MRI->isSSA();
Kyle Butt3232dbb2016-04-08 20:35:01 +000081}
82
83static void VerifyPHIs(MachineFunction &MF, bool CheckExtra) {
84 for (MachineFunction::iterator I = ++MF.begin(), E = MF.end(); I != E; ++I) {
85 MachineBasicBlock *MBB = &*I;
86 SmallSetVector<MachineBasicBlock *, 8> Preds(MBB->pred_begin(),
87 MBB->pred_end());
88 MachineBasicBlock::iterator MI = MBB->begin();
89 while (MI != MBB->end()) {
90 if (!MI->isPHI())
91 break;
Matt Arsenaultb8037a12016-08-16 20:38:05 +000092 for (MachineBasicBlock *PredBB : Preds) {
Kyle Butt3232dbb2016-04-08 20:35:01 +000093 bool Found = false;
94 for (unsigned i = 1, e = MI->getNumOperands(); i != e; i += 2) {
95 MachineBasicBlock *PHIBB = MI->getOperand(i + 1).getMBB();
96 if (PHIBB == PredBB) {
97 Found = true;
98 break;
99 }
100 }
101 if (!Found) {
102 dbgs() << "Malformed PHI in BB#" << MBB->getNumber() << ": " << *MI;
103 dbgs() << " missing input from predecessor BB#"
104 << PredBB->getNumber() << '\n';
105 llvm_unreachable(nullptr);
106 }
107 }
108
109 for (unsigned i = 1, e = MI->getNumOperands(); i != e; i += 2) {
110 MachineBasicBlock *PHIBB = MI->getOperand(i + 1).getMBB();
111 if (CheckExtra && !Preds.count(PHIBB)) {
112 dbgs() << "Warning: malformed PHI in BB#" << MBB->getNumber() << ": "
113 << *MI;
114 dbgs() << " extra input from predecessor BB#" << PHIBB->getNumber()
115 << '\n';
116 llvm_unreachable(nullptr);
117 }
118 if (PHIBB->getNumber() < 0) {
119 dbgs() << "Malformed PHI in BB#" << MBB->getNumber() << ": " << *MI;
120 dbgs() << " non-existing BB#" << PHIBB->getNumber() << '\n';
121 llvm_unreachable(nullptr);
122 }
123 }
124 ++MI;
125 }
126 }
127}
128
129/// Tail duplicate the block and cleanup.
Kyle Butt723aa132016-08-26 20:12:40 +0000130/// \p IsSimple - return value of isSimpleBB
131/// \p MBB - block to be duplicated
Kyle Butt0846e562016-10-11 20:36:43 +0000132/// \p ForcedLayoutPred - If non-null, treat this block as the layout
133/// predecessor, instead of using the ordering in MF
Kyle Butt723aa132016-08-26 20:12:40 +0000134/// \p DuplicatedPreds - if non-null, \p DuplicatedPreds will contain a list of
135/// all Preds that received a copy of \p MBB.
Kyle Butt0846e562016-10-11 20:36:43 +0000136/// \p RemovalCallback - if non-null, called just before MBB is deleted.
Kyle Butt723aa132016-08-26 20:12:40 +0000137bool TailDuplicator::tailDuplicateAndUpdate(
138 bool IsSimple, MachineBasicBlock *MBB,
Kyle Butt0846e562016-10-11 20:36:43 +0000139 MachineBasicBlock *ForcedLayoutPred,
140 SmallVectorImpl<MachineBasicBlock*> *DuplicatedPreds,
141 llvm::function_ref<void(MachineBasicBlock *)> *RemovalCallback) {
Kyle Butt3232dbb2016-04-08 20:35:01 +0000142 // Save the successors list.
143 SmallSetVector<MachineBasicBlock *, 8> Succs(MBB->succ_begin(),
144 MBB->succ_end());
145
146 SmallVector<MachineBasicBlock *, 8> TDBBs;
147 SmallVector<MachineInstr *, 16> Copies;
Kyle Butt0846e562016-10-11 20:36:43 +0000148 if (!tailDuplicate(IsSimple, MBB, ForcedLayoutPred, TDBBs, Copies))
Kyle Butt3232dbb2016-04-08 20:35:01 +0000149 return false;
150
151 ++NumTails;
152
153 SmallVector<MachineInstr *, 8> NewPHIs;
Kyle Butt3ed42732016-08-25 01:37:03 +0000154 MachineSSAUpdater SSAUpdate(*MF, &NewPHIs);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000155
156 // TailBB's immediate successors are now successors of those predecessors
157 // which duplicated TailBB. Add the predecessors as sources to the PHI
158 // instructions.
159 bool isDead = MBB->pred_empty() && !MBB->hasAddressTaken();
160 if (PreRegAlloc)
161 updateSuccessorsPHIs(MBB, isDead, TDBBs, Succs);
162
163 // If it is dead, remove it.
164 if (isDead) {
Geoff Berryf8c29d62016-06-14 19:40:10 +0000165 NumTailDupRemoved += MBB->size();
Kyle Butt0846e562016-10-11 20:36:43 +0000166 removeDeadBlock(MBB, RemovalCallback);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000167 ++NumDeadBlocks;
168 }
169
170 // Update SSA form.
171 if (!SSAUpdateVRs.empty()) {
172 for (unsigned i = 0, e = SSAUpdateVRs.size(); i != e; ++i) {
173 unsigned VReg = SSAUpdateVRs[i];
174 SSAUpdate.Initialize(VReg);
175
176 // If the original definition is still around, add it as an available
177 // value.
178 MachineInstr *DefMI = MRI->getVRegDef(VReg);
179 MachineBasicBlock *DefBB = nullptr;
180 if (DefMI) {
181 DefBB = DefMI->getParent();
182 SSAUpdate.AddAvailableValue(DefBB, VReg);
183 }
184
185 // Add the new vregs as available values.
186 DenseMap<unsigned, AvailableValsTy>::iterator LI =
187 SSAUpdateVals.find(VReg);
188 for (unsigned j = 0, ee = LI->second.size(); j != ee; ++j) {
189 MachineBasicBlock *SrcBB = LI->second[j].first;
190 unsigned SrcReg = LI->second[j].second;
191 SSAUpdate.AddAvailableValue(SrcBB, SrcReg);
192 }
193
194 // Rewrite uses that are outside of the original def's block.
195 MachineRegisterInfo::use_iterator UI = MRI->use_begin(VReg);
196 while (UI != MRI->use_end()) {
197 MachineOperand &UseMO = *UI;
198 MachineInstr *UseMI = UseMO.getParent();
199 ++UI;
200 if (UseMI->isDebugValue()) {
201 // SSAUpdate can replace the use with an undef. That creates
202 // a debug instruction that is a kill.
203 // FIXME: Should it SSAUpdate job to delete debug instructions
204 // instead of replacing the use with undef?
205 UseMI->eraseFromParent();
206 continue;
207 }
208 if (UseMI->getParent() == DefBB && !UseMI->isPHI())
209 continue;
210 SSAUpdate.RewriteUse(UseMO);
211 }
212 }
213
214 SSAUpdateVRs.clear();
215 SSAUpdateVals.clear();
216 }
217
218 // Eliminate some of the copies inserted by tail duplication to maintain
219 // SSA form.
220 for (unsigned i = 0, e = Copies.size(); i != e; ++i) {
221 MachineInstr *Copy = Copies[i];
222 if (!Copy->isCopy())
223 continue;
224 unsigned Dst = Copy->getOperand(0).getReg();
225 unsigned Src = Copy->getOperand(1).getReg();
226 if (MRI->hasOneNonDBGUse(Src) &&
227 MRI->constrainRegClass(Src, MRI->getRegClass(Dst))) {
228 // Copy is the only use. Do trivial copy propagation here.
229 MRI->replaceRegWith(Dst, Src);
230 Copy->eraseFromParent();
231 }
232 }
233
234 if (NewPHIs.size())
235 NumAddedPHIs += NewPHIs.size();
236
Kyle Butt723aa132016-08-26 20:12:40 +0000237 if (DuplicatedPreds)
238 *DuplicatedPreds = std::move(TDBBs);
239
Kyle Butt3232dbb2016-04-08 20:35:01 +0000240 return true;
241}
242
243/// Look for small blocks that are unconditionally branched to and do not fall
244/// through. Tail-duplicate their instructions into their predecessors to
245/// eliminate (dynamic) branches.
Kyle Butt3ed42732016-08-25 01:37:03 +0000246bool TailDuplicator::tailDuplicateBlocks() {
Kyle Butt3232dbb2016-04-08 20:35:01 +0000247 bool MadeChange = false;
248
249 if (PreRegAlloc && TailDupVerify) {
250 DEBUG(dbgs() << "\n*** Before tail-duplicating\n");
Kyle Butt3ed42732016-08-25 01:37:03 +0000251 VerifyPHIs(*MF, true);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000252 }
253
Kyle Butt3ed42732016-08-25 01:37:03 +0000254 for (MachineFunction::iterator I = ++MF->begin(), E = MF->end(); I != E;) {
Kyle Butt3232dbb2016-04-08 20:35:01 +0000255 MachineBasicBlock *MBB = &*I++;
256
257 if (NumTails == TailDupLimit)
258 break;
259
260 bool IsSimple = isSimpleBB(MBB);
261
Kyle Butt3ed42732016-08-25 01:37:03 +0000262 if (!shouldTailDuplicate(IsSimple, *MBB))
Kyle Butt3232dbb2016-04-08 20:35:01 +0000263 continue;
264
Kyle Butt0846e562016-10-11 20:36:43 +0000265 MadeChange |= tailDuplicateAndUpdate(IsSimple, MBB, nullptr);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000266 }
267
268 if (PreRegAlloc && TailDupVerify)
Kyle Butt3ed42732016-08-25 01:37:03 +0000269 VerifyPHIs(*MF, false);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000270
271 return MadeChange;
272}
273
274static bool isDefLiveOut(unsigned Reg, MachineBasicBlock *BB,
275 const MachineRegisterInfo *MRI) {
276 for (MachineInstr &UseMI : MRI->use_instructions(Reg)) {
277 if (UseMI.isDebugValue())
278 continue;
279 if (UseMI.getParent() != BB)
280 return true;
281 }
282 return false;
283}
284
285static unsigned getPHISrcRegOpIdx(MachineInstr *MI, MachineBasicBlock *SrcBB) {
286 for (unsigned i = 1, e = MI->getNumOperands(); i != e; i += 2)
287 if (MI->getOperand(i + 1).getMBB() == SrcBB)
288 return i;
289 return 0;
290}
291
292// Remember which registers are used by phis in this block. This is
293// used to determine which registers are liveout while modifying the
294// block (which is why we need to copy the information).
295static void getRegsUsedByPHIs(const MachineBasicBlock &BB,
296 DenseSet<unsigned> *UsedByPhi) {
297 for (const auto &MI : BB) {
298 if (!MI.isPHI())
299 break;
300 for (unsigned i = 1, e = MI.getNumOperands(); i != e; i += 2) {
301 unsigned SrcReg = MI.getOperand(i).getReg();
302 UsedByPhi->insert(SrcReg);
303 }
304 }
305}
306
307/// Add a definition and source virtual registers pair for SSA update.
308void TailDuplicator::addSSAUpdateEntry(unsigned OrigReg, unsigned NewReg,
309 MachineBasicBlock *BB) {
310 DenseMap<unsigned, AvailableValsTy>::iterator LI =
311 SSAUpdateVals.find(OrigReg);
312 if (LI != SSAUpdateVals.end())
313 LI->second.push_back(std::make_pair(BB, NewReg));
314 else {
315 AvailableValsTy Vals;
316 Vals.push_back(std::make_pair(BB, NewReg));
317 SSAUpdateVals.insert(std::make_pair(OrigReg, Vals));
318 SSAUpdateVRs.push_back(OrigReg);
319 }
320}
321
322/// Process PHI node in TailBB by turning it into a copy in PredBB. Remember the
323/// source register that's contributed by PredBB and update SSA update map.
324void TailDuplicator::processPHI(
325 MachineInstr *MI, MachineBasicBlock *TailBB, MachineBasicBlock *PredBB,
Krzysztof Parzyszek4773f642016-04-26 18:36:34 +0000326 DenseMap<unsigned, RegSubRegPair> &LocalVRMap,
327 SmallVectorImpl<std::pair<unsigned, RegSubRegPair>> &Copies,
Kyle Butt3232dbb2016-04-08 20:35:01 +0000328 const DenseSet<unsigned> &RegsUsedByPhi, bool Remove) {
329 unsigned DefReg = MI->getOperand(0).getReg();
330 unsigned SrcOpIdx = getPHISrcRegOpIdx(MI, PredBB);
331 assert(SrcOpIdx && "Unable to find matching PHI source?");
332 unsigned SrcReg = MI->getOperand(SrcOpIdx).getReg();
Krzysztof Parzyszek4773f642016-04-26 18:36:34 +0000333 unsigned SrcSubReg = MI->getOperand(SrcOpIdx).getSubReg();
Kyle Butt3232dbb2016-04-08 20:35:01 +0000334 const TargetRegisterClass *RC = MRI->getRegClass(DefReg);
Krzysztof Parzyszek4773f642016-04-26 18:36:34 +0000335 LocalVRMap.insert(std::make_pair(DefReg, RegSubRegPair(SrcReg, SrcSubReg)));
Kyle Butt3232dbb2016-04-08 20:35:01 +0000336
337 // Insert a copy from source to the end of the block. The def register is the
338 // available value liveout of the block.
339 unsigned NewDef = MRI->createVirtualRegister(RC);
Krzysztof Parzyszek4773f642016-04-26 18:36:34 +0000340 Copies.push_back(std::make_pair(NewDef, RegSubRegPair(SrcReg, SrcSubReg)));
Kyle Butt3232dbb2016-04-08 20:35:01 +0000341 if (isDefLiveOut(DefReg, TailBB, MRI) || RegsUsedByPhi.count(DefReg))
342 addSSAUpdateEntry(DefReg, NewDef, PredBB);
343
344 if (!Remove)
345 return;
346
347 // Remove PredBB from the PHI node.
348 MI->RemoveOperand(SrcOpIdx + 1);
349 MI->RemoveOperand(SrcOpIdx);
350 if (MI->getNumOperands() == 1)
351 MI->eraseFromParent();
352}
353
354/// Duplicate a TailBB instruction to PredBB and update
355/// the source operands due to earlier PHI translation.
356void TailDuplicator::duplicateInstruction(
357 MachineInstr *MI, MachineBasicBlock *TailBB, MachineBasicBlock *PredBB,
Krzysztof Parzyszek4773f642016-04-26 18:36:34 +0000358 DenseMap<unsigned, RegSubRegPair> &LocalVRMap,
Kyle Butt3232dbb2016-04-08 20:35:01 +0000359 const DenseSet<unsigned> &UsedByPhi) {
Kyle Butt3ed42732016-08-25 01:37:03 +0000360 MachineInstr *NewMI = TII->duplicate(*MI, *MF);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000361 if (PreRegAlloc) {
362 for (unsigned i = 0, e = NewMI->getNumOperands(); i != e; ++i) {
363 MachineOperand &MO = NewMI->getOperand(i);
364 if (!MO.isReg())
365 continue;
366 unsigned Reg = MO.getReg();
367 if (!TargetRegisterInfo::isVirtualRegister(Reg))
368 continue;
369 if (MO.isDef()) {
370 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
371 unsigned NewReg = MRI->createVirtualRegister(RC);
372 MO.setReg(NewReg);
Krzysztof Parzyszek4773f642016-04-26 18:36:34 +0000373 LocalVRMap.insert(std::make_pair(Reg, RegSubRegPair(NewReg, 0)));
Kyle Butt3232dbb2016-04-08 20:35:01 +0000374 if (isDefLiveOut(Reg, TailBB, MRI) || UsedByPhi.count(Reg))
375 addSSAUpdateEntry(Reg, NewReg, PredBB);
376 } else {
Krzysztof Parzyszek4773f642016-04-26 18:36:34 +0000377 auto VI = LocalVRMap.find(Reg);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000378 if (VI != LocalVRMap.end()) {
Krzysztof Parzyszek4773f642016-04-26 18:36:34 +0000379 // Need to make sure that the register class of the mapped register
380 // will satisfy the constraints of the class of the register being
381 // replaced.
382 auto *OrigRC = MRI->getRegClass(Reg);
383 auto *MappedRC = MRI->getRegClass(VI->second.Reg);
384 const TargetRegisterClass *ConstrRC;
385 if (VI->second.SubReg != 0) {
386 ConstrRC = TRI->getMatchingSuperRegClass(MappedRC, OrigRC,
387 VI->second.SubReg);
388 if (ConstrRC) {
389 // The actual constraining (as in "find appropriate new class")
390 // is done by getMatchingSuperRegClass, so now we only need to
391 // change the class of the mapped register.
392 MRI->setRegClass(VI->second.Reg, ConstrRC);
393 }
394 } else {
395 // For mapped registers that do not have sub-registers, simply
396 // restrict their class to match the original one.
397 ConstrRC = MRI->constrainRegClass(VI->second.Reg, OrigRC);
398 }
399
400 if (ConstrRC) {
401 // If the class constraining succeeded, we can simply replace
402 // the old register with the mapped one.
403 MO.setReg(VI->second.Reg);
404 // We have Reg -> VI.Reg:VI.SubReg, so if Reg is used with a
405 // sub-register, we need to compose the sub-register indices.
406 MO.setSubReg(TRI->composeSubRegIndices(MO.getSubReg(),
407 VI->second.SubReg));
408 } else {
409 // The direct replacement is not possible, due to failing register
410 // class constraints. An explicit COPY is necessary. Create one
411 // that can be reused
412 auto *NewRC = MI->getRegClassConstraint(i, TII, TRI);
413 if (NewRC == nullptr)
414 NewRC = OrigRC;
415 unsigned NewReg = MRI->createVirtualRegister(NewRC);
416 BuildMI(*PredBB, MI, MI->getDebugLoc(),
417 TII->get(TargetOpcode::COPY), NewReg)
418 .addReg(VI->second.Reg, 0, VI->second.SubReg);
419 LocalVRMap.erase(VI);
420 LocalVRMap.insert(std::make_pair(Reg, RegSubRegPair(NewReg, 0)));
421 MO.setReg(NewReg);
422 // The composed VI.Reg:VI.SubReg is replaced with NewReg, which
423 // is equivalent to the whole register Reg. Hence, Reg:subreg
424 // is same as NewReg:subreg, so keep the sub-register index
425 // unchanged.
426 }
Kyle Butt3232dbb2016-04-08 20:35:01 +0000427 // Clear any kill flags from this operand. The new register could
428 // have uses after this one, so kills are not valid here.
429 MO.setIsKill(false);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000430 }
431 }
432 }
433 }
434 PredBB->insert(PredBB->instr_end(), NewMI);
435}
436
437/// After FromBB is tail duplicated into its predecessor blocks, the successors
438/// have gained new predecessors. Update the PHI instructions in them
439/// accordingly.
440void TailDuplicator::updateSuccessorsPHIs(
441 MachineBasicBlock *FromBB, bool isDead,
442 SmallVectorImpl<MachineBasicBlock *> &TDBBs,
443 SmallSetVector<MachineBasicBlock *, 8> &Succs) {
Matt Arsenaultb8037a12016-08-16 20:38:05 +0000444 for (MachineBasicBlock *SuccBB : Succs) {
445 for (MachineInstr &MI : *SuccBB) {
446 if (!MI.isPHI())
Kyle Butt3232dbb2016-04-08 20:35:01 +0000447 break;
Matt Arsenaultb8037a12016-08-16 20:38:05 +0000448 MachineInstrBuilder MIB(*FromBB->getParent(), MI);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000449 unsigned Idx = 0;
Matt Arsenaultb8037a12016-08-16 20:38:05 +0000450 for (unsigned i = 1, e = MI.getNumOperands(); i != e; i += 2) {
451 MachineOperand &MO = MI.getOperand(i + 1);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000452 if (MO.getMBB() == FromBB) {
453 Idx = i;
454 break;
455 }
456 }
457
458 assert(Idx != 0);
Matt Arsenaultb8037a12016-08-16 20:38:05 +0000459 MachineOperand &MO0 = MI.getOperand(Idx);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000460 unsigned Reg = MO0.getReg();
461 if (isDead) {
462 // Folded into the previous BB.
463 // There could be duplicate phi source entries. FIXME: Should sdisel
464 // or earlier pass fixed this?
Matt Arsenaultb8037a12016-08-16 20:38:05 +0000465 for (unsigned i = MI.getNumOperands() - 2; i != Idx; i -= 2) {
466 MachineOperand &MO = MI.getOperand(i + 1);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000467 if (MO.getMBB() == FromBB) {
Matt Arsenaultb8037a12016-08-16 20:38:05 +0000468 MI.RemoveOperand(i + 1);
469 MI.RemoveOperand(i);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000470 }
471 }
472 } else
473 Idx = 0;
474
475 // If Idx is set, the operands at Idx and Idx+1 must be removed.
476 // We reuse the location to avoid expensive RemoveOperand calls.
477
478 DenseMap<unsigned, AvailableValsTy>::iterator LI =
479 SSAUpdateVals.find(Reg);
480 if (LI != SSAUpdateVals.end()) {
481 // This register is defined in the tail block.
482 for (unsigned j = 0, ee = LI->second.size(); j != ee; ++j) {
483 MachineBasicBlock *SrcBB = LI->second[j].first;
484 // If we didn't duplicate a bb into a particular predecessor, we
485 // might still have added an entry to SSAUpdateVals to correcly
486 // recompute SSA. If that case, avoid adding a dummy extra argument
487 // this PHI.
488 if (!SrcBB->isSuccessor(SuccBB))
489 continue;
490
491 unsigned SrcReg = LI->second[j].second;
492 if (Idx != 0) {
Matt Arsenaultb8037a12016-08-16 20:38:05 +0000493 MI.getOperand(Idx).setReg(SrcReg);
494 MI.getOperand(Idx + 1).setMBB(SrcBB);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000495 Idx = 0;
496 } else {
497 MIB.addReg(SrcReg).addMBB(SrcBB);
498 }
499 }
500 } else {
501 // Live in tail block, must also be live in predecessors.
502 for (unsigned j = 0, ee = TDBBs.size(); j != ee; ++j) {
503 MachineBasicBlock *SrcBB = TDBBs[j];
504 if (Idx != 0) {
Matt Arsenaultb8037a12016-08-16 20:38:05 +0000505 MI.getOperand(Idx).setReg(Reg);
506 MI.getOperand(Idx + 1).setMBB(SrcBB);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000507 Idx = 0;
508 } else {
509 MIB.addReg(Reg).addMBB(SrcBB);
510 }
511 }
512 }
513 if (Idx != 0) {
Matt Arsenaultb8037a12016-08-16 20:38:05 +0000514 MI.RemoveOperand(Idx + 1);
515 MI.RemoveOperand(Idx);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000516 }
517 }
518 }
519}
520
521/// Determine if it is profitable to duplicate this block.
Kyle Butt3ed42732016-08-25 01:37:03 +0000522bool TailDuplicator::shouldTailDuplicate(bool IsSimple,
Kyle Butt3232dbb2016-04-08 20:35:01 +0000523 MachineBasicBlock &TailBB) {
Kyle Butt0846e562016-10-11 20:36:43 +0000524 // When doing tail-duplication during layout, the block ordering is in flux,
525 // so canFallThrough returns a result based on incorrect information and
526 // should just be ignored.
527 if (!LayoutMode && TailBB.canFallThrough())
Kyle Butt3232dbb2016-04-08 20:35:01 +0000528 return false;
529
530 // Don't try to tail-duplicate single-block loops.
531 if (TailBB.isSuccessor(&TailBB))
532 return false;
533
534 // Set the limit on the cost to duplicate. When optimizing for size,
535 // duplicate only one, because one branch instruction can be eliminated to
536 // compensate for the duplication.
537 unsigned MaxDuplicateCount;
Kyle Buttdb3391e2016-08-17 21:07:35 +0000538 if (TailDupSize == 0 &&
539 TailDuplicateSize.getNumOccurrences() == 0 &&
Kyle Butt3ed42732016-08-25 01:37:03 +0000540 MF->getFunction()->optForSize())
Kyle Butt3232dbb2016-04-08 20:35:01 +0000541 MaxDuplicateCount = 1;
Kyle Buttdb3391e2016-08-17 21:07:35 +0000542 else if (TailDupSize == 0)
Kyle Butt3232dbb2016-04-08 20:35:01 +0000543 MaxDuplicateCount = TailDuplicateSize;
Kyle Buttdb3391e2016-08-17 21:07:35 +0000544 else
545 MaxDuplicateCount = TailDupSize;
Kyle Butt3232dbb2016-04-08 20:35:01 +0000546
Kyle Butt07d61422016-08-16 22:56:14 +0000547 // If the block to be duplicated ends in an unanalyzable fallthrough, don't
548 // duplicate it.
549 // A similar check is necessary in MachineBlockPlacement to make sure pairs of
550 // blocks with unanalyzable fallthrough get layed out contiguously.
551 MachineBasicBlock *PredTBB = nullptr, *PredFBB = nullptr;
552 SmallVector<MachineOperand, 4> PredCond;
Sanjoy Dasd7389d62016-12-15 05:08:57 +0000553 if (TII->analyzeBranch(TailBB, PredTBB, PredFBB, PredCond) &&
554 TailBB.canFallThrough())
Kyle Butt07d61422016-08-16 22:56:14 +0000555 return false;
556
Kyle Butt3232dbb2016-04-08 20:35:01 +0000557 // If the target has hardware branch prediction that can handle indirect
558 // branches, duplicating them can often make them predictable when there
559 // are common paths through the code. The limit needs to be high enough
560 // to allow undoing the effects of tail merging and other optimizations
561 // that rearrange the predecessors of the indirect branch.
562
563 bool HasIndirectbr = false;
564 if (!TailBB.empty())
565 HasIndirectbr = TailBB.back().isIndirectBranch();
566
567 if (HasIndirectbr && PreRegAlloc)
Kyle Butt61aca6e2016-08-30 18:18:54 +0000568 MaxDuplicateCount = TailDupIndirectBranchSize;
Kyle Butt3232dbb2016-04-08 20:35:01 +0000569
570 // Check the instructions in the block to determine whether tail-duplication
571 // is invalid or unlikely to be profitable.
572 unsigned InstrCount = 0;
573 for (MachineInstr &MI : TailBB) {
574 // Non-duplicable things shouldn't be tail-duplicated.
575 if (MI.isNotDuplicable())
576 return false;
577
578 // Convergent instructions can be duplicated only if doing so doesn't add
579 // new control dependencies, which is what we're going to do here.
580 if (MI.isConvergent())
581 return false;
582
583 // Do not duplicate 'return' instructions if this is a pre-regalloc run.
584 // A return may expand into a lot more instructions (e.g. reload of callee
585 // saved registers) after PEI.
586 if (PreRegAlloc && MI.isReturn())
587 return false;
588
589 // Avoid duplicating calls before register allocation. Calls presents a
590 // barrier to register allocation so duplicating them may end up increasing
591 // spills.
592 if (PreRegAlloc && MI.isCall())
593 return false;
594
595 if (!MI.isPHI() && !MI.isDebugValue())
596 InstrCount += 1;
597
598 if (InstrCount > MaxDuplicateCount)
599 return false;
600 }
601
602 // Check if any of the successors of TailBB has a PHI node in which the
603 // value corresponding to TailBB uses a subregister.
604 // If a phi node uses a register paired with a subregister, the actual
605 // "value type" of the phi may differ from the type of the register without
606 // any subregisters. Due to a bug, tail duplication may add a new operand
607 // without a necessary subregister, producing an invalid code. This is
608 // demonstrated by test/CodeGen/Hexagon/tail-dup-subreg-abort.ll.
609 // Disable tail duplication for this case for now, until the problem is
610 // fixed.
611 for (auto SB : TailBB.successors()) {
612 for (auto &I : *SB) {
613 if (!I.isPHI())
614 break;
615 unsigned Idx = getPHISrcRegOpIdx(&I, &TailBB);
616 assert(Idx != 0);
617 MachineOperand &PU = I.getOperand(Idx);
618 if (PU.getSubReg() != 0)
619 return false;
620 }
621 }
622
623 if (HasIndirectbr && PreRegAlloc)
624 return true;
625
626 if (IsSimple)
627 return true;
628
629 if (!PreRegAlloc)
630 return true;
631
632 return canCompletelyDuplicateBB(TailBB);
633}
634
635/// True if this BB has only one unconditional jump.
636bool TailDuplicator::isSimpleBB(MachineBasicBlock *TailBB) {
637 if (TailBB->succ_size() != 1)
638 return false;
639 if (TailBB->pred_empty())
640 return false;
641 MachineBasicBlock::iterator I = TailBB->getFirstNonDebugInstr();
642 if (I == TailBB->end())
643 return true;
644 return I->isUnconditionalBranch();
645}
646
647static bool bothUsedInPHI(const MachineBasicBlock &A,
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000648 const SmallPtrSet<MachineBasicBlock *, 8> &SuccsB) {
Kyle Butt3232dbb2016-04-08 20:35:01 +0000649 for (MachineBasicBlock *BB : A.successors())
650 if (SuccsB.count(BB) && !BB->empty() && BB->begin()->isPHI())
651 return true;
652
653 return false;
654}
655
656bool TailDuplicator::canCompletelyDuplicateBB(MachineBasicBlock &BB) {
657 for (MachineBasicBlock *PredBB : BB.predecessors()) {
658 if (PredBB->succ_size() > 1)
659 return false;
660
661 MachineBasicBlock *PredTBB = nullptr, *PredFBB = nullptr;
662 SmallVector<MachineOperand, 4> PredCond;
Sanjoy Dasd7389d62016-12-15 05:08:57 +0000663 if (TII->analyzeBranch(*PredBB, PredTBB, PredFBB, PredCond))
Kyle Butt3232dbb2016-04-08 20:35:01 +0000664 return false;
665
666 if (!PredCond.empty())
667 return false;
668 }
669 return true;
670}
671
672bool TailDuplicator::duplicateSimpleBB(
673 MachineBasicBlock *TailBB, SmallVectorImpl<MachineBasicBlock *> &TDBBs,
674 const DenseSet<unsigned> &UsedByPhi,
675 SmallVectorImpl<MachineInstr *> &Copies) {
676 SmallPtrSet<MachineBasicBlock *, 8> Succs(TailBB->succ_begin(),
677 TailBB->succ_end());
678 SmallVector<MachineBasicBlock *, 8> Preds(TailBB->pred_begin(),
679 TailBB->pred_end());
680 bool Changed = false;
Matt Arsenaultb8037a12016-08-16 20:38:05 +0000681 for (MachineBasicBlock *PredBB : Preds) {
Kyle Butt3232dbb2016-04-08 20:35:01 +0000682 if (PredBB->hasEHPadSuccessor())
683 continue;
684
685 if (bothUsedInPHI(*PredBB, Succs))
686 continue;
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 continue;
692
693 Changed = true;
694 DEBUG(dbgs() << "\nTail-duplicating into PredBB: " << *PredBB
695 << "From simple Succ: " << *TailBB);
696
697 MachineBasicBlock *NewTarget = *TailBB->succ_begin();
Matthias Braun6442fc12016-08-18 00:59:32 +0000698 MachineBasicBlock *NextBB = PredBB->getNextNode();
Kyle Butt3232dbb2016-04-08 20:35:01 +0000699
700 // Make PredFBB explicit.
701 if (PredCond.empty())
702 PredFBB = PredTBB;
703
704 // Make fall through explicit.
705 if (!PredTBB)
706 PredTBB = NextBB;
707 if (!PredFBB)
708 PredFBB = NextBB;
709
710 // Redirect
711 if (PredFBB == TailBB)
712 PredFBB = NewTarget;
713 if (PredTBB == TailBB)
714 PredTBB = NewTarget;
715
716 // Make the branch unconditional if possible
717 if (PredTBB == PredFBB) {
718 PredCond.clear();
719 PredFBB = nullptr;
720 }
721
722 // Avoid adding fall through branches.
723 if (PredFBB == NextBB)
724 PredFBB = nullptr;
725 if (PredTBB == NextBB && PredFBB == nullptr)
726 PredTBB = nullptr;
727
Taewook Oha49eb852017-02-27 19:30:01 +0000728 auto DL = PredBB->findBranchDebugLoc();
Matt Arsenault1b9fc8e2016-09-14 20:43:16 +0000729 TII->removeBranch(*PredBB);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000730
731 if (!PredBB->isSuccessor(NewTarget))
732 PredBB->replaceSuccessor(TailBB, NewTarget);
733 else {
734 PredBB->removeSuccessor(TailBB, true);
735 assert(PredBB->succ_size() <= 1);
736 }
737
738 if (PredTBB)
Taewook Oha49eb852017-02-27 19:30:01 +0000739 TII->insertBranch(*PredBB, PredTBB, PredFBB, PredCond, DL);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000740
741 TDBBs.push_back(PredBB);
742 }
743 return Changed;
744}
745
Kyle Butt9e52c062016-07-19 23:54:21 +0000746bool TailDuplicator::canTailDuplicate(MachineBasicBlock *TailBB,
747 MachineBasicBlock *PredBB) {
Kyle Butt0846e562016-10-11 20:36:43 +0000748 // EH edges are ignored by analyzeBranch.
Kyle Butt9e52c062016-07-19 23:54:21 +0000749 if (PredBB->succ_size() > 1)
750 return false;
751
Vitaly Bukab238cb82017-05-22 21:33:54 +0000752 MachineBasicBlock *PredTBB = nullptr, *PredFBB = nullptr;
Kyle Butt9e52c062016-07-19 23:54:21 +0000753 SmallVector<MachineOperand, 4> PredCond;
Sanjoy Dasd7389d62016-12-15 05:08:57 +0000754 if (TII->analyzeBranch(*PredBB, PredTBB, PredFBB, PredCond))
Kyle Butt9e52c062016-07-19 23:54:21 +0000755 return false;
756 if (!PredCond.empty())
757 return false;
758 return true;
759}
760
Kyle Butt3232dbb2016-04-08 20:35:01 +0000761/// If it is profitable, duplicate TailBB's contents in each
762/// of its predecessors.
Kyle Butt0846e562016-10-11 20:36:43 +0000763/// \p IsSimple result of isSimpleBB
764/// \p TailBB Block to be duplicated.
765/// \p ForcedLayoutPred When non-null, use this block as the layout predecessor
766/// instead of the previous block in MF's order.
767/// \p TDBBs A vector to keep track of all blocks tail-duplicated
768/// into.
769/// \p Copies A vector of copy instructions inserted. Used later to
770/// walk all the inserted copies and remove redundant ones.
Kyle Butt3ed42732016-08-25 01:37:03 +0000771bool TailDuplicator::tailDuplicate(bool IsSimple, MachineBasicBlock *TailBB,
Kyle Butt0846e562016-10-11 20:36:43 +0000772 MachineBasicBlock *ForcedLayoutPred,
Kyle Butt3232dbb2016-04-08 20:35:01 +0000773 SmallVectorImpl<MachineBasicBlock *> &TDBBs,
774 SmallVectorImpl<MachineInstr *> &Copies) {
775 DEBUG(dbgs() << "\n*** Tail-duplicating BB#" << TailBB->getNumber() << '\n');
776
777 DenseSet<unsigned> UsedByPhi;
778 getRegsUsedByPHIs(*TailBB, &UsedByPhi);
779
780 if (IsSimple)
781 return duplicateSimpleBB(TailBB, TDBBs, UsedByPhi, Copies);
782
783 // Iterate through all the unique predecessors and tail-duplicate this
784 // block into them, if possible. Copying the list ahead of time also
785 // avoids trouble with the predecessor list reallocating.
786 bool Changed = false;
787 SmallSetVector<MachineBasicBlock *, 8> Preds(TailBB->pred_begin(),
788 TailBB->pred_end());
Matt Arsenaultb8037a12016-08-16 20:38:05 +0000789 for (MachineBasicBlock *PredBB : Preds) {
Kyle Butt3232dbb2016-04-08 20:35:01 +0000790 assert(TailBB != PredBB &&
791 "Single-block loop should have been rejected earlier!");
Kyle Butt9e52c062016-07-19 23:54:21 +0000792
793 if (!canTailDuplicate(TailBB, PredBB))
Kyle Butt3232dbb2016-04-08 20:35:01 +0000794 continue;
795
Kyle Butt3232dbb2016-04-08 20:35:01 +0000796 // Don't duplicate into a fall-through predecessor (at least for now).
Kyle Butt0846e562016-10-11 20:36:43 +0000797 bool IsLayoutSuccessor = false;
798 if (ForcedLayoutPred)
799 IsLayoutSuccessor = (ForcedLayoutPred == PredBB);
800 else if (PredBB->isLayoutSuccessor(TailBB) && PredBB->canFallThrough())
801 IsLayoutSuccessor = true;
802 if (IsLayoutSuccessor)
Kyle Butt3232dbb2016-04-08 20:35:01 +0000803 continue;
804
805 DEBUG(dbgs() << "\nTail-duplicating into PredBB: " << *PredBB
806 << "From Succ: " << *TailBB);
807
808 TDBBs.push_back(PredBB);
809
810 // Remove PredBB's unconditional branch.
Matt Arsenault1b9fc8e2016-09-14 20:43:16 +0000811 TII->removeBranch(*PredBB);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000812
Kyle Butt3232dbb2016-04-08 20:35:01 +0000813 // Clone the contents of TailBB into PredBB.
Krzysztof Parzyszek4773f642016-04-26 18:36:34 +0000814 DenseMap<unsigned, RegSubRegPair> LocalVRMap;
815 SmallVector<std::pair<unsigned, RegSubRegPair>, 4> CopyInfos;
Kyle Butt3232dbb2016-04-08 20:35:01 +0000816 // Use instr_iterator here to properly handle bundles, e.g.
817 // ARM Thumb2 IT block.
818 MachineBasicBlock::instr_iterator I = TailBB->instr_begin();
819 while (I != TailBB->instr_end()) {
820 MachineInstr *MI = &*I;
821 ++I;
822 if (MI->isPHI()) {
823 // Replace the uses of the def of the PHI with the register coming
824 // from PredBB.
825 processPHI(MI, TailBB, PredBB, LocalVRMap, CopyInfos, UsedByPhi, true);
826 } else {
827 // Replace def of virtual registers with new registers, and update
828 // uses with PHI source register or the new registers.
Kyle Butt3ed42732016-08-25 01:37:03 +0000829 duplicateInstruction(MI, TailBB, PredBB, LocalVRMap, UsedByPhi);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000830 }
831 }
Krzysztof Parzyszek4773f642016-04-26 18:36:34 +0000832 appendCopies(PredBB, CopyInfos, Copies);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000833
834 // Simplify
Vitaly Bukab238cb82017-05-22 21:33:54 +0000835 MachineBasicBlock *PredTBB = nullptr, *PredFBB = nullptr;
Kyle Butt9e52c062016-07-19 23:54:21 +0000836 SmallVector<MachineOperand, 4> PredCond;
Sanjoy Dasd7389d62016-12-15 05:08:57 +0000837 TII->analyzeBranch(*PredBB, PredTBB, PredFBB, PredCond);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000838
Geoff Berryf8c29d62016-06-14 19:40:10 +0000839 NumTailDupAdded += TailBB->size() - 1; // subtract one for removed branch
Kyle Butt3232dbb2016-04-08 20:35:01 +0000840
841 // Update the CFG.
842 PredBB->removeSuccessor(PredBB->succ_begin());
843 assert(PredBB->succ_empty() &&
844 "TailDuplicate called on block with multiple successors!");
Matt Arsenaultb8037a12016-08-16 20:38:05 +0000845 for (MachineBasicBlock *Succ : TailBB->successors())
846 PredBB->addSuccessor(Succ, MBPI->getEdgeProbability(TailBB, Succ));
Kyle Butt3232dbb2016-04-08 20:35:01 +0000847
848 Changed = true;
849 ++NumTailDups;
850 }
851
852 // If TailBB was duplicated into all its predecessors except for the prior
853 // block, which falls through unconditionally, move the contents of this
854 // block into the prior block.
Kyle Butt0846e562016-10-11 20:36:43 +0000855 MachineBasicBlock *PrevBB = ForcedLayoutPred;
856 if (!PrevBB)
857 PrevBB = &*std::prev(TailBB->getIterator());
Kyle Butt3232dbb2016-04-08 20:35:01 +0000858 MachineBasicBlock *PriorTBB = nullptr, *PriorFBB = nullptr;
859 SmallVector<MachineOperand, 4> PriorCond;
860 // This has to check PrevBB->succ_size() because EH edges are ignored by
Kyle Butt0846e562016-10-11 20:36:43 +0000861 // analyzeBranch.
Kyle Butt3232dbb2016-04-08 20:35:01 +0000862 if (PrevBB->succ_size() == 1 &&
Kyle Buttd2b886e2016-07-20 00:01:51 +0000863 // Layout preds are not always CFG preds. Check.
864 *PrevBB->succ_begin() == TailBB &&
Sanjoy Dasd7389d62016-12-15 05:08:57 +0000865 !TII->analyzeBranch(*PrevBB, PriorTBB, PriorFBB, PriorCond) &&
Kyle Butt0846e562016-10-11 20:36:43 +0000866 PriorCond.empty() &&
867 (!PriorTBB || PriorTBB == TailBB) &&
868 TailBB->pred_size() == 1 &&
Kyle Butt3232dbb2016-04-08 20:35:01 +0000869 !TailBB->hasAddressTaken()) {
870 DEBUG(dbgs() << "\nMerging into block: " << *PrevBB
871 << "From MBB: " << *TailBB);
Kyle Butt0846e562016-10-11 20:36:43 +0000872 // There may be a branch to the layout successor. This is unlikely but it
873 // happens. The correct thing to do is to remove the branch before
874 // duplicating the instructions in all cases.
875 TII->removeBranch(*PrevBB);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000876 if (PreRegAlloc) {
Krzysztof Parzyszek4773f642016-04-26 18:36:34 +0000877 DenseMap<unsigned, RegSubRegPair> LocalVRMap;
878 SmallVector<std::pair<unsigned, RegSubRegPair>, 4> CopyInfos;
Kyle Butt3232dbb2016-04-08 20:35:01 +0000879 MachineBasicBlock::iterator I = TailBB->begin();
880 // Process PHI instructions first.
881 while (I != TailBB->end() && I->isPHI()) {
882 // Replace the uses of the def of the PHI with the register coming
883 // from PredBB.
884 MachineInstr *MI = &*I++;
885 processPHI(MI, TailBB, PrevBB, LocalVRMap, CopyInfos, UsedByPhi, true);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000886 }
887
888 // Now copy the non-PHI instructions.
889 while (I != TailBB->end()) {
890 // Replace def of virtual registers with new registers, and update
891 // uses with PHI source register or the new registers.
892 MachineInstr *MI = &*I++;
893 assert(!MI->isBundle() && "Not expecting bundles before regalloc!");
Kyle Butt3ed42732016-08-25 01:37:03 +0000894 duplicateInstruction(MI, TailBB, PrevBB, LocalVRMap, UsedByPhi);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000895 MI->eraseFromParent();
896 }
Krzysztof Parzyszek4773f642016-04-26 18:36:34 +0000897 appendCopies(PrevBB, CopyInfos, Copies);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000898 } else {
Kyle Butt0846e562016-10-11 20:36:43 +0000899 TII->removeBranch(*PrevBB);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000900 // No PHIs to worry about, just splice the instructions over.
901 PrevBB->splice(PrevBB->end(), TailBB, TailBB->begin(), TailBB->end());
902 }
903 PrevBB->removeSuccessor(PrevBB->succ_begin());
904 assert(PrevBB->succ_empty());
905 PrevBB->transferSuccessors(TailBB);
906 TDBBs.push_back(PrevBB);
907 Changed = true;
908 }
909
910 // If this is after register allocation, there are no phis to fix.
911 if (!PreRegAlloc)
912 return Changed;
913
914 // If we made no changes so far, we are safe.
915 if (!Changed)
916 return Changed;
917
918 // Handle the nasty case in that we duplicated a block that is part of a loop
919 // into some but not all of its predecessors. For example:
920 // 1 -> 2 <-> 3 |
921 // \ |
922 // \---> rest |
923 // if we duplicate 2 into 1 but not into 3, we end up with
924 // 12 -> 3 <-> 2 -> rest |
925 // \ / |
926 // \----->-----/ |
927 // If there was a "var = phi(1, 3)" in 2, it has to be ultimately replaced
928 // with a phi in 3 (which now dominates 2).
929 // What we do here is introduce a copy in 3 of the register defined by the
930 // phi, just like when we are duplicating 2 into 3, but we don't copy any
931 // real instructions or remove the 3 -> 2 edge from the phi in 2.
Matt Arsenaultb8037a12016-08-16 20:38:05 +0000932 for (MachineBasicBlock *PredBB : Preds) {
David Majnemer0d955d02016-08-11 22:21:41 +0000933 if (is_contained(TDBBs, PredBB))
Kyle Butt3232dbb2016-04-08 20:35:01 +0000934 continue;
935
936 // EH edges
937 if (PredBB->succ_size() != 1)
938 continue;
939
Krzysztof Parzyszek4773f642016-04-26 18:36:34 +0000940 DenseMap<unsigned, RegSubRegPair> LocalVRMap;
941 SmallVector<std::pair<unsigned, RegSubRegPair>, 4> CopyInfos;
Kyle Butt3232dbb2016-04-08 20:35:01 +0000942 MachineBasicBlock::iterator I = TailBB->begin();
943 // Process PHI instructions first.
944 while (I != TailBB->end() && I->isPHI()) {
945 // Replace the uses of the def of the PHI with the register coming
946 // from PredBB.
947 MachineInstr *MI = &*I++;
948 processPHI(MI, TailBB, PredBB, LocalVRMap, CopyInfos, UsedByPhi, false);
949 }
Krzysztof Parzyszek4773f642016-04-26 18:36:34 +0000950 appendCopies(PredBB, CopyInfos, Copies);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000951 }
952
953 return Changed;
954}
955
Krzysztof Parzyszek4773f642016-04-26 18:36:34 +0000956/// At the end of the block \p MBB generate COPY instructions between registers
957/// described by \p CopyInfos. Append resulting instructions to \p Copies.
958void TailDuplicator::appendCopies(MachineBasicBlock *MBB,
959 SmallVectorImpl<std::pair<unsigned,RegSubRegPair>> &CopyInfos,
960 SmallVectorImpl<MachineInstr*> &Copies) {
961 MachineBasicBlock::iterator Loc = MBB->getFirstTerminator();
962 const MCInstrDesc &CopyD = TII->get(TargetOpcode::COPY);
963 for (auto &CI : CopyInfos) {
964 auto C = BuildMI(*MBB, Loc, DebugLoc(), CopyD, CI.first)
965 .addReg(CI.second.Reg, 0, CI.second.SubReg);
966 Copies.push_back(C);
967 }
968}
969
Kyle Butt3232dbb2016-04-08 20:35:01 +0000970/// Remove the specified dead machine basic block from the function, updating
971/// the CFG.
Kyle Butt0846e562016-10-11 20:36:43 +0000972void TailDuplicator::removeDeadBlock(
973 MachineBasicBlock *MBB,
974 llvm::function_ref<void(MachineBasicBlock *)> *RemovalCallback) {
Kyle Butt3232dbb2016-04-08 20:35:01 +0000975 assert(MBB->pred_empty() && "MBB must be dead!");
976 DEBUG(dbgs() << "\nRemoving MBB: " << *MBB);
977
Kyle Butt0846e562016-10-11 20:36:43 +0000978 if (RemovalCallback)
979 (*RemovalCallback)(MBB);
980
Kyle Butt3232dbb2016-04-08 20:35:01 +0000981 // Remove all successors.
982 while (!MBB->succ_empty())
983 MBB->removeSuccessor(MBB->succ_end() - 1);
984
985 // Remove the block.
986 MBB->eraseFromParent();
987}
988
989} // End llvm namespace