blob: c460a7226f029cb94d9bae312c3e2031b4807465 [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"
23#include "llvm/CodeGen/MachineModuleInfo.h"
24#include "llvm/CodeGen/Passes.h"
25#include "llvm/IR/Function.h"
26#include "llvm/Support/CommandLine.h"
27#include "llvm/Support/Debug.h"
28#include "llvm/Support/ErrorHandling.h"
29#include "llvm/Support/raw_ostream.h"
30using namespace llvm;
31
32#define DEBUG_TYPE "tailduplication"
33
34STATISTIC(NumTails, "Number of tails duplicated");
35STATISTIC(NumTailDups, "Number of tail duplicated blocks");
Geoff Berryf8c29d62016-06-14 19:40:10 +000036STATISTIC(NumTailDupAdded,
37 "Number of instructions added due to tail duplication");
38STATISTIC(NumTailDupRemoved,
39 "Number of instructions removed due to tail duplication");
Kyle Butt3232dbb2016-04-08 20:35:01 +000040STATISTIC(NumDeadBlocks, "Number of dead blocks removed");
41STATISTIC(NumAddedPHIs, "Number of phis added");
42
43// Heuristic for tail duplication.
44static cl::opt<unsigned> TailDuplicateSize(
45 "tail-dup-size",
46 cl::desc("Maximum instructions to consider tail duplicating"), cl::init(2),
47 cl::Hidden);
48
49static cl::opt<bool>
50 TailDupVerify("tail-dup-verify",
51 cl::desc("Verify sanity of PHI instructions during taildup"),
52 cl::init(false), cl::Hidden);
53
54static cl::opt<unsigned> TailDupLimit("tail-dup-limit", cl::init(~0U),
55 cl::Hidden);
56
57namespace llvm {
58
59void TailDuplicator::initMF(MachineFunction &MF, const MachineModuleInfo *MMIin,
60 const MachineBranchProbabilityInfo *MBPIin) {
61 TII = MF.getSubtarget().getInstrInfo();
62 TRI = MF.getSubtarget().getRegisterInfo();
63 MRI = &MF.getRegInfo();
64 MMI = MMIin;
65 MBPI = MBPIin;
66
67 assert(MBPI != nullptr && "Machine Branch Probability Info required");
68
69 PreRegAlloc = MRI->isSSA();
Kyle Butt3232dbb2016-04-08 20:35:01 +000070}
71
72static void VerifyPHIs(MachineFunction &MF, bool CheckExtra) {
73 for (MachineFunction::iterator I = ++MF.begin(), E = MF.end(); I != E; ++I) {
74 MachineBasicBlock *MBB = &*I;
75 SmallSetVector<MachineBasicBlock *, 8> Preds(MBB->pred_begin(),
76 MBB->pred_end());
77 MachineBasicBlock::iterator MI = MBB->begin();
78 while (MI != MBB->end()) {
79 if (!MI->isPHI())
80 break;
Matt Arsenaultb8037a12016-08-16 20:38:05 +000081 for (MachineBasicBlock *PredBB : Preds) {
Kyle Butt3232dbb2016-04-08 20:35:01 +000082 bool Found = false;
83 for (unsigned i = 1, e = MI->getNumOperands(); i != e; i += 2) {
84 MachineBasicBlock *PHIBB = MI->getOperand(i + 1).getMBB();
85 if (PHIBB == PredBB) {
86 Found = true;
87 break;
88 }
89 }
90 if (!Found) {
91 dbgs() << "Malformed PHI in BB#" << MBB->getNumber() << ": " << *MI;
92 dbgs() << " missing input from predecessor BB#"
93 << PredBB->getNumber() << '\n';
94 llvm_unreachable(nullptr);
95 }
96 }
97
98 for (unsigned i = 1, e = MI->getNumOperands(); i != e; i += 2) {
99 MachineBasicBlock *PHIBB = MI->getOperand(i + 1).getMBB();
100 if (CheckExtra && !Preds.count(PHIBB)) {
101 dbgs() << "Warning: malformed PHI in BB#" << MBB->getNumber() << ": "
102 << *MI;
103 dbgs() << " extra input from predecessor BB#" << PHIBB->getNumber()
104 << '\n';
105 llvm_unreachable(nullptr);
106 }
107 if (PHIBB->getNumber() < 0) {
108 dbgs() << "Malformed PHI in BB#" << MBB->getNumber() << ": " << *MI;
109 dbgs() << " non-existing BB#" << PHIBB->getNumber() << '\n';
110 llvm_unreachable(nullptr);
111 }
112 }
113 ++MI;
114 }
115 }
116}
117
118/// Tail duplicate the block and cleanup.
119bool TailDuplicator::tailDuplicateAndUpdate(MachineFunction &MF, bool IsSimple,
120 MachineBasicBlock *MBB) {
121 // Save the successors list.
122 SmallSetVector<MachineBasicBlock *, 8> Succs(MBB->succ_begin(),
123 MBB->succ_end());
124
125 SmallVector<MachineBasicBlock *, 8> TDBBs;
126 SmallVector<MachineInstr *, 16> Copies;
127 if (!tailDuplicate(MF, IsSimple, MBB, TDBBs, Copies))
128 return false;
129
130 ++NumTails;
131
132 SmallVector<MachineInstr *, 8> NewPHIs;
133 MachineSSAUpdater SSAUpdate(MF, &NewPHIs);
134
135 // TailBB's immediate successors are now successors of those predecessors
136 // which duplicated TailBB. Add the predecessors as sources to the PHI
137 // instructions.
138 bool isDead = MBB->pred_empty() && !MBB->hasAddressTaken();
139 if (PreRegAlloc)
140 updateSuccessorsPHIs(MBB, isDead, TDBBs, Succs);
141
142 // If it is dead, remove it.
143 if (isDead) {
Geoff Berryf8c29d62016-06-14 19:40:10 +0000144 NumTailDupRemoved += MBB->size();
Kyle Butt3232dbb2016-04-08 20:35:01 +0000145 removeDeadBlock(MBB);
146 ++NumDeadBlocks;
147 }
148
149 // Update SSA form.
150 if (!SSAUpdateVRs.empty()) {
151 for (unsigned i = 0, e = SSAUpdateVRs.size(); i != e; ++i) {
152 unsigned VReg = SSAUpdateVRs[i];
153 SSAUpdate.Initialize(VReg);
154
155 // If the original definition is still around, add it as an available
156 // value.
157 MachineInstr *DefMI = MRI->getVRegDef(VReg);
158 MachineBasicBlock *DefBB = nullptr;
159 if (DefMI) {
160 DefBB = DefMI->getParent();
161 SSAUpdate.AddAvailableValue(DefBB, VReg);
162 }
163
164 // Add the new vregs as available values.
165 DenseMap<unsigned, AvailableValsTy>::iterator LI =
166 SSAUpdateVals.find(VReg);
167 for (unsigned j = 0, ee = LI->second.size(); j != ee; ++j) {
168 MachineBasicBlock *SrcBB = LI->second[j].first;
169 unsigned SrcReg = LI->second[j].second;
170 SSAUpdate.AddAvailableValue(SrcBB, SrcReg);
171 }
172
173 // Rewrite uses that are outside of the original def's block.
174 MachineRegisterInfo::use_iterator UI = MRI->use_begin(VReg);
175 while (UI != MRI->use_end()) {
176 MachineOperand &UseMO = *UI;
177 MachineInstr *UseMI = UseMO.getParent();
178 ++UI;
179 if (UseMI->isDebugValue()) {
180 // SSAUpdate can replace the use with an undef. That creates
181 // a debug instruction that is a kill.
182 // FIXME: Should it SSAUpdate job to delete debug instructions
183 // instead of replacing the use with undef?
184 UseMI->eraseFromParent();
185 continue;
186 }
187 if (UseMI->getParent() == DefBB && !UseMI->isPHI())
188 continue;
189 SSAUpdate.RewriteUse(UseMO);
190 }
191 }
192
193 SSAUpdateVRs.clear();
194 SSAUpdateVals.clear();
195 }
196
197 // Eliminate some of the copies inserted by tail duplication to maintain
198 // SSA form.
199 for (unsigned i = 0, e = Copies.size(); i != e; ++i) {
200 MachineInstr *Copy = Copies[i];
201 if (!Copy->isCopy())
202 continue;
203 unsigned Dst = Copy->getOperand(0).getReg();
204 unsigned Src = Copy->getOperand(1).getReg();
205 if (MRI->hasOneNonDBGUse(Src) &&
206 MRI->constrainRegClass(Src, MRI->getRegClass(Dst))) {
207 // Copy is the only use. Do trivial copy propagation here.
208 MRI->replaceRegWith(Dst, Src);
209 Copy->eraseFromParent();
210 }
211 }
212
213 if (NewPHIs.size())
214 NumAddedPHIs += NewPHIs.size();
215
216 return true;
217}
218
219/// Look for small blocks that are unconditionally branched to and do not fall
220/// through. Tail-duplicate their instructions into their predecessors to
221/// eliminate (dynamic) branches.
222bool TailDuplicator::tailDuplicateBlocks(MachineFunction &MF) {
223 bool MadeChange = false;
224
225 if (PreRegAlloc && TailDupVerify) {
226 DEBUG(dbgs() << "\n*** Before tail-duplicating\n");
227 VerifyPHIs(MF, true);
228 }
229
230 for (MachineFunction::iterator I = ++MF.begin(), E = MF.end(); I != E;) {
231 MachineBasicBlock *MBB = &*I++;
232
233 if (NumTails == TailDupLimit)
234 break;
235
236 bool IsSimple = isSimpleBB(MBB);
237
238 if (!shouldTailDuplicate(MF, IsSimple, *MBB))
239 continue;
240
241 MadeChange |= tailDuplicateAndUpdate(MF, IsSimple, MBB);
242 }
243
244 if (PreRegAlloc && TailDupVerify)
245 VerifyPHIs(MF, false);
246
247 return MadeChange;
248}
249
250static bool isDefLiveOut(unsigned Reg, MachineBasicBlock *BB,
251 const MachineRegisterInfo *MRI) {
252 for (MachineInstr &UseMI : MRI->use_instructions(Reg)) {
253 if (UseMI.isDebugValue())
254 continue;
255 if (UseMI.getParent() != BB)
256 return true;
257 }
258 return false;
259}
260
261static unsigned getPHISrcRegOpIdx(MachineInstr *MI, MachineBasicBlock *SrcBB) {
262 for (unsigned i = 1, e = MI->getNumOperands(); i != e; i += 2)
263 if (MI->getOperand(i + 1).getMBB() == SrcBB)
264 return i;
265 return 0;
266}
267
268// Remember which registers are used by phis in this block. This is
269// used to determine which registers are liveout while modifying the
270// block (which is why we need to copy the information).
271static void getRegsUsedByPHIs(const MachineBasicBlock &BB,
272 DenseSet<unsigned> *UsedByPhi) {
273 for (const auto &MI : BB) {
274 if (!MI.isPHI())
275 break;
276 for (unsigned i = 1, e = MI.getNumOperands(); i != e; i += 2) {
277 unsigned SrcReg = MI.getOperand(i).getReg();
278 UsedByPhi->insert(SrcReg);
279 }
280 }
281}
282
283/// Add a definition and source virtual registers pair for SSA update.
284void TailDuplicator::addSSAUpdateEntry(unsigned OrigReg, unsigned NewReg,
285 MachineBasicBlock *BB) {
286 DenseMap<unsigned, AvailableValsTy>::iterator LI =
287 SSAUpdateVals.find(OrigReg);
288 if (LI != SSAUpdateVals.end())
289 LI->second.push_back(std::make_pair(BB, NewReg));
290 else {
291 AvailableValsTy Vals;
292 Vals.push_back(std::make_pair(BB, NewReg));
293 SSAUpdateVals.insert(std::make_pair(OrigReg, Vals));
294 SSAUpdateVRs.push_back(OrigReg);
295 }
296}
297
298/// Process PHI node in TailBB by turning it into a copy in PredBB. Remember the
299/// source register that's contributed by PredBB and update SSA update map.
300void TailDuplicator::processPHI(
301 MachineInstr *MI, MachineBasicBlock *TailBB, MachineBasicBlock *PredBB,
Krzysztof Parzyszek4773f642016-04-26 18:36:34 +0000302 DenseMap<unsigned, RegSubRegPair> &LocalVRMap,
303 SmallVectorImpl<std::pair<unsigned, RegSubRegPair>> &Copies,
Kyle Butt3232dbb2016-04-08 20:35:01 +0000304 const DenseSet<unsigned> &RegsUsedByPhi, bool Remove) {
305 unsigned DefReg = MI->getOperand(0).getReg();
306 unsigned SrcOpIdx = getPHISrcRegOpIdx(MI, PredBB);
307 assert(SrcOpIdx && "Unable to find matching PHI source?");
308 unsigned SrcReg = MI->getOperand(SrcOpIdx).getReg();
Krzysztof Parzyszek4773f642016-04-26 18:36:34 +0000309 unsigned SrcSubReg = MI->getOperand(SrcOpIdx).getSubReg();
Kyle Butt3232dbb2016-04-08 20:35:01 +0000310 const TargetRegisterClass *RC = MRI->getRegClass(DefReg);
Krzysztof Parzyszek4773f642016-04-26 18:36:34 +0000311 LocalVRMap.insert(std::make_pair(DefReg, RegSubRegPair(SrcReg, SrcSubReg)));
Kyle Butt3232dbb2016-04-08 20:35:01 +0000312
313 // Insert a copy from source to the end of the block. The def register is the
314 // available value liveout of the block.
315 unsigned NewDef = MRI->createVirtualRegister(RC);
Krzysztof Parzyszek4773f642016-04-26 18:36:34 +0000316 Copies.push_back(std::make_pair(NewDef, RegSubRegPair(SrcReg, SrcSubReg)));
Kyle Butt3232dbb2016-04-08 20:35:01 +0000317 if (isDefLiveOut(DefReg, TailBB, MRI) || RegsUsedByPhi.count(DefReg))
318 addSSAUpdateEntry(DefReg, NewDef, PredBB);
319
320 if (!Remove)
321 return;
322
323 // Remove PredBB from the PHI node.
324 MI->RemoveOperand(SrcOpIdx + 1);
325 MI->RemoveOperand(SrcOpIdx);
326 if (MI->getNumOperands() == 1)
327 MI->eraseFromParent();
328}
329
330/// Duplicate a TailBB instruction to PredBB and update
331/// the source operands due to earlier PHI translation.
332void TailDuplicator::duplicateInstruction(
333 MachineInstr *MI, MachineBasicBlock *TailBB, MachineBasicBlock *PredBB,
Krzysztof Parzyszek4773f642016-04-26 18:36:34 +0000334 MachineFunction &MF,
335 DenseMap<unsigned, RegSubRegPair> &LocalVRMap,
Kyle Butt3232dbb2016-04-08 20:35:01 +0000336 const DenseSet<unsigned> &UsedByPhi) {
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +0000337 MachineInstr *NewMI = TII->duplicate(*MI, MF);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000338 if (PreRegAlloc) {
339 for (unsigned i = 0, e = NewMI->getNumOperands(); i != e; ++i) {
340 MachineOperand &MO = NewMI->getOperand(i);
341 if (!MO.isReg())
342 continue;
343 unsigned Reg = MO.getReg();
344 if (!TargetRegisterInfo::isVirtualRegister(Reg))
345 continue;
346 if (MO.isDef()) {
347 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
348 unsigned NewReg = MRI->createVirtualRegister(RC);
349 MO.setReg(NewReg);
Krzysztof Parzyszek4773f642016-04-26 18:36:34 +0000350 LocalVRMap.insert(std::make_pair(Reg, RegSubRegPair(NewReg, 0)));
Kyle Butt3232dbb2016-04-08 20:35:01 +0000351 if (isDefLiveOut(Reg, TailBB, MRI) || UsedByPhi.count(Reg))
352 addSSAUpdateEntry(Reg, NewReg, PredBB);
353 } else {
Krzysztof Parzyszek4773f642016-04-26 18:36:34 +0000354 auto VI = LocalVRMap.find(Reg);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000355 if (VI != LocalVRMap.end()) {
Krzysztof Parzyszek4773f642016-04-26 18:36:34 +0000356 // Need to make sure that the register class of the mapped register
357 // will satisfy the constraints of the class of the register being
358 // replaced.
359 auto *OrigRC = MRI->getRegClass(Reg);
360 auto *MappedRC = MRI->getRegClass(VI->second.Reg);
361 const TargetRegisterClass *ConstrRC;
362 if (VI->second.SubReg != 0) {
363 ConstrRC = TRI->getMatchingSuperRegClass(MappedRC, OrigRC,
364 VI->second.SubReg);
365 if (ConstrRC) {
366 // The actual constraining (as in "find appropriate new class")
367 // is done by getMatchingSuperRegClass, so now we only need to
368 // change the class of the mapped register.
369 MRI->setRegClass(VI->second.Reg, ConstrRC);
370 }
371 } else {
372 // For mapped registers that do not have sub-registers, simply
373 // restrict their class to match the original one.
374 ConstrRC = MRI->constrainRegClass(VI->second.Reg, OrigRC);
375 }
376
377 if (ConstrRC) {
378 // If the class constraining succeeded, we can simply replace
379 // the old register with the mapped one.
380 MO.setReg(VI->second.Reg);
381 // We have Reg -> VI.Reg:VI.SubReg, so if Reg is used with a
382 // sub-register, we need to compose the sub-register indices.
383 MO.setSubReg(TRI->composeSubRegIndices(MO.getSubReg(),
384 VI->second.SubReg));
385 } else {
386 // The direct replacement is not possible, due to failing register
387 // class constraints. An explicit COPY is necessary. Create one
388 // that can be reused
389 auto *NewRC = MI->getRegClassConstraint(i, TII, TRI);
390 if (NewRC == nullptr)
391 NewRC = OrigRC;
392 unsigned NewReg = MRI->createVirtualRegister(NewRC);
393 BuildMI(*PredBB, MI, MI->getDebugLoc(),
394 TII->get(TargetOpcode::COPY), NewReg)
395 .addReg(VI->second.Reg, 0, VI->second.SubReg);
396 LocalVRMap.erase(VI);
397 LocalVRMap.insert(std::make_pair(Reg, RegSubRegPair(NewReg, 0)));
398 MO.setReg(NewReg);
399 // The composed VI.Reg:VI.SubReg is replaced with NewReg, which
400 // is equivalent to the whole register Reg. Hence, Reg:subreg
401 // is same as NewReg:subreg, so keep the sub-register index
402 // unchanged.
403 }
Kyle Butt3232dbb2016-04-08 20:35:01 +0000404 // Clear any kill flags from this operand. The new register could
405 // have uses after this one, so kills are not valid here.
406 MO.setIsKill(false);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000407 }
408 }
409 }
410 }
411 PredBB->insert(PredBB->instr_end(), NewMI);
412}
413
414/// After FromBB is tail duplicated into its predecessor blocks, the successors
415/// have gained new predecessors. Update the PHI instructions in them
416/// accordingly.
417void TailDuplicator::updateSuccessorsPHIs(
418 MachineBasicBlock *FromBB, bool isDead,
419 SmallVectorImpl<MachineBasicBlock *> &TDBBs,
420 SmallSetVector<MachineBasicBlock *, 8> &Succs) {
Matt Arsenaultb8037a12016-08-16 20:38:05 +0000421 for (MachineBasicBlock *SuccBB : Succs) {
422 for (MachineInstr &MI : *SuccBB) {
423 if (!MI.isPHI())
Kyle Butt3232dbb2016-04-08 20:35:01 +0000424 break;
Matt Arsenaultb8037a12016-08-16 20:38:05 +0000425 MachineInstrBuilder MIB(*FromBB->getParent(), MI);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000426 unsigned Idx = 0;
Matt Arsenaultb8037a12016-08-16 20:38:05 +0000427 for (unsigned i = 1, e = MI.getNumOperands(); i != e; i += 2) {
428 MachineOperand &MO = MI.getOperand(i + 1);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000429 if (MO.getMBB() == FromBB) {
430 Idx = i;
431 break;
432 }
433 }
434
435 assert(Idx != 0);
Matt Arsenaultb8037a12016-08-16 20:38:05 +0000436 MachineOperand &MO0 = MI.getOperand(Idx);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000437 unsigned Reg = MO0.getReg();
438 if (isDead) {
439 // Folded into the previous BB.
440 // There could be duplicate phi source entries. FIXME: Should sdisel
441 // or earlier pass fixed this?
Matt Arsenaultb8037a12016-08-16 20:38:05 +0000442 for (unsigned i = MI.getNumOperands() - 2; i != Idx; i -= 2) {
443 MachineOperand &MO = MI.getOperand(i + 1);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000444 if (MO.getMBB() == FromBB) {
Matt Arsenaultb8037a12016-08-16 20:38:05 +0000445 MI.RemoveOperand(i + 1);
446 MI.RemoveOperand(i);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000447 }
448 }
449 } else
450 Idx = 0;
451
452 // If Idx is set, the operands at Idx and Idx+1 must be removed.
453 // We reuse the location to avoid expensive RemoveOperand calls.
454
455 DenseMap<unsigned, AvailableValsTy>::iterator LI =
456 SSAUpdateVals.find(Reg);
457 if (LI != SSAUpdateVals.end()) {
458 // This register is defined in the tail block.
459 for (unsigned j = 0, ee = LI->second.size(); j != ee; ++j) {
460 MachineBasicBlock *SrcBB = LI->second[j].first;
461 // If we didn't duplicate a bb into a particular predecessor, we
462 // might still have added an entry to SSAUpdateVals to correcly
463 // recompute SSA. If that case, avoid adding a dummy extra argument
464 // this PHI.
465 if (!SrcBB->isSuccessor(SuccBB))
466 continue;
467
468 unsigned SrcReg = LI->second[j].second;
469 if (Idx != 0) {
Matt Arsenaultb8037a12016-08-16 20:38:05 +0000470 MI.getOperand(Idx).setReg(SrcReg);
471 MI.getOperand(Idx + 1).setMBB(SrcBB);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000472 Idx = 0;
473 } else {
474 MIB.addReg(SrcReg).addMBB(SrcBB);
475 }
476 }
477 } else {
478 // Live in tail block, must also be live in predecessors.
479 for (unsigned j = 0, ee = TDBBs.size(); j != ee; ++j) {
480 MachineBasicBlock *SrcBB = TDBBs[j];
481 if (Idx != 0) {
Matt Arsenaultb8037a12016-08-16 20:38:05 +0000482 MI.getOperand(Idx).setReg(Reg);
483 MI.getOperand(Idx + 1).setMBB(SrcBB);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000484 Idx = 0;
485 } else {
486 MIB.addReg(Reg).addMBB(SrcBB);
487 }
488 }
489 }
490 if (Idx != 0) {
Matt Arsenaultb8037a12016-08-16 20:38:05 +0000491 MI.RemoveOperand(Idx + 1);
492 MI.RemoveOperand(Idx);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000493 }
494 }
495 }
496}
497
498/// Determine if it is profitable to duplicate this block.
499bool TailDuplicator::shouldTailDuplicate(const MachineFunction &MF,
500 bool IsSimple,
501 MachineBasicBlock &TailBB) {
502 // Only duplicate blocks that end with unconditional branches.
503 if (TailBB.canFallThrough())
504 return false;
505
506 // Don't try to tail-duplicate single-block loops.
507 if (TailBB.isSuccessor(&TailBB))
508 return false;
509
510 // Set the limit on the cost to duplicate. When optimizing for size,
511 // duplicate only one, because one branch instruction can be eliminated to
512 // compensate for the duplication.
513 unsigned MaxDuplicateCount;
514 if (TailDuplicateSize.getNumOccurrences() == 0 &&
515 // FIXME: Use Function::optForSize().
516 MF.getFunction()->hasFnAttribute(Attribute::OptimizeForSize))
517 MaxDuplicateCount = 1;
518 else
519 MaxDuplicateCount = TailDuplicateSize;
520
521 // If the target has hardware branch prediction that can handle indirect
522 // branches, duplicating them can often make them predictable when there
523 // are common paths through the code. The limit needs to be high enough
524 // to allow undoing the effects of tail merging and other optimizations
525 // that rearrange the predecessors of the indirect branch.
526
527 bool HasIndirectbr = false;
528 if (!TailBB.empty())
529 HasIndirectbr = TailBB.back().isIndirectBranch();
530
531 if (HasIndirectbr && PreRegAlloc)
532 MaxDuplicateCount = 20;
533
534 // Check the instructions in the block to determine whether tail-duplication
535 // is invalid or unlikely to be profitable.
536 unsigned InstrCount = 0;
537 for (MachineInstr &MI : TailBB) {
538 // Non-duplicable things shouldn't be tail-duplicated.
539 if (MI.isNotDuplicable())
540 return false;
541
542 // Convergent instructions can be duplicated only if doing so doesn't add
543 // new control dependencies, which is what we're going to do here.
544 if (MI.isConvergent())
545 return false;
546
547 // Do not duplicate 'return' instructions if this is a pre-regalloc run.
548 // A return may expand into a lot more instructions (e.g. reload of callee
549 // saved registers) after PEI.
550 if (PreRegAlloc && MI.isReturn())
551 return false;
552
553 // Avoid duplicating calls before register allocation. Calls presents a
554 // barrier to register allocation so duplicating them may end up increasing
555 // spills.
556 if (PreRegAlloc && MI.isCall())
557 return false;
558
559 if (!MI.isPHI() && !MI.isDebugValue())
560 InstrCount += 1;
561
562 if (InstrCount > MaxDuplicateCount)
563 return false;
564 }
565
566 // Check if any of the successors of TailBB has a PHI node in which the
567 // value corresponding to TailBB uses a subregister.
568 // If a phi node uses a register paired with a subregister, the actual
569 // "value type" of the phi may differ from the type of the register without
570 // any subregisters. Due to a bug, tail duplication may add a new operand
571 // without a necessary subregister, producing an invalid code. This is
572 // demonstrated by test/CodeGen/Hexagon/tail-dup-subreg-abort.ll.
573 // Disable tail duplication for this case for now, until the problem is
574 // fixed.
575 for (auto SB : TailBB.successors()) {
576 for (auto &I : *SB) {
577 if (!I.isPHI())
578 break;
579 unsigned Idx = getPHISrcRegOpIdx(&I, &TailBB);
580 assert(Idx != 0);
581 MachineOperand &PU = I.getOperand(Idx);
582 if (PU.getSubReg() != 0)
583 return false;
584 }
585 }
586
587 if (HasIndirectbr && PreRegAlloc)
588 return true;
589
590 if (IsSimple)
591 return true;
592
593 if (!PreRegAlloc)
594 return true;
595
596 return canCompletelyDuplicateBB(TailBB);
597}
598
599/// True if this BB has only one unconditional jump.
600bool TailDuplicator::isSimpleBB(MachineBasicBlock *TailBB) {
601 if (TailBB->succ_size() != 1)
602 return false;
603 if (TailBB->pred_empty())
604 return false;
605 MachineBasicBlock::iterator I = TailBB->getFirstNonDebugInstr();
606 if (I == TailBB->end())
607 return true;
608 return I->isUnconditionalBranch();
609}
610
611static bool bothUsedInPHI(const MachineBasicBlock &A,
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000612 const SmallPtrSet<MachineBasicBlock *, 8> &SuccsB) {
Kyle Butt3232dbb2016-04-08 20:35:01 +0000613 for (MachineBasicBlock *BB : A.successors())
614 if (SuccsB.count(BB) && !BB->empty() && BB->begin()->isPHI())
615 return true;
616
617 return false;
618}
619
620bool TailDuplicator::canCompletelyDuplicateBB(MachineBasicBlock &BB) {
621 for (MachineBasicBlock *PredBB : BB.predecessors()) {
622 if (PredBB->succ_size() > 1)
623 return false;
624
625 MachineBasicBlock *PredTBB = nullptr, *PredFBB = nullptr;
626 SmallVector<MachineOperand, 4> PredCond;
Jacques Pienaar71c30a12016-07-15 14:41:04 +0000627 if (TII->analyzeBranch(*PredBB, PredTBB, PredFBB, PredCond, true))
Kyle Butt3232dbb2016-04-08 20:35:01 +0000628 return false;
629
630 if (!PredCond.empty())
631 return false;
632 }
633 return true;
634}
635
636bool TailDuplicator::duplicateSimpleBB(
637 MachineBasicBlock *TailBB, SmallVectorImpl<MachineBasicBlock *> &TDBBs,
638 const DenseSet<unsigned> &UsedByPhi,
639 SmallVectorImpl<MachineInstr *> &Copies) {
640 SmallPtrSet<MachineBasicBlock *, 8> Succs(TailBB->succ_begin(),
641 TailBB->succ_end());
642 SmallVector<MachineBasicBlock *, 8> Preds(TailBB->pred_begin(),
643 TailBB->pred_end());
644 bool Changed = false;
Matt Arsenaultb8037a12016-08-16 20:38:05 +0000645 for (MachineBasicBlock *PredBB : Preds) {
Kyle Butt3232dbb2016-04-08 20:35:01 +0000646 if (PredBB->hasEHPadSuccessor())
647 continue;
648
649 if (bothUsedInPHI(*PredBB, Succs))
650 continue;
651
652 MachineBasicBlock *PredTBB = nullptr, *PredFBB = nullptr;
653 SmallVector<MachineOperand, 4> PredCond;
Jacques Pienaar71c30a12016-07-15 14:41:04 +0000654 if (TII->analyzeBranch(*PredBB, PredTBB, PredFBB, PredCond, true))
Kyle Butt3232dbb2016-04-08 20:35:01 +0000655 continue;
656
657 Changed = true;
658 DEBUG(dbgs() << "\nTail-duplicating into PredBB: " << *PredBB
659 << "From simple Succ: " << *TailBB);
660
661 MachineBasicBlock *NewTarget = *TailBB->succ_begin();
662 MachineBasicBlock *NextBB = &*std::next(PredBB->getIterator());
663
664 // Make PredFBB explicit.
665 if (PredCond.empty())
666 PredFBB = PredTBB;
667
668 // Make fall through explicit.
669 if (!PredTBB)
670 PredTBB = NextBB;
671 if (!PredFBB)
672 PredFBB = NextBB;
673
674 // Redirect
675 if (PredFBB == TailBB)
676 PredFBB = NewTarget;
677 if (PredTBB == TailBB)
678 PredTBB = NewTarget;
679
680 // Make the branch unconditional if possible
681 if (PredTBB == PredFBB) {
682 PredCond.clear();
683 PredFBB = nullptr;
684 }
685
686 // Avoid adding fall through branches.
687 if (PredFBB == NextBB)
688 PredFBB = nullptr;
689 if (PredTBB == NextBB && PredFBB == nullptr)
690 PredTBB = nullptr;
691
692 TII->RemoveBranch(*PredBB);
693
694 if (!PredBB->isSuccessor(NewTarget))
695 PredBB->replaceSuccessor(TailBB, NewTarget);
696 else {
697 PredBB->removeSuccessor(TailBB, true);
698 assert(PredBB->succ_size() <= 1);
699 }
700
701 if (PredTBB)
702 TII->InsertBranch(*PredBB, PredTBB, PredFBB, PredCond, DebugLoc());
703
704 TDBBs.push_back(PredBB);
705 }
706 return Changed;
707}
708
Kyle Butt9e52c062016-07-19 23:54:21 +0000709bool TailDuplicator::canTailDuplicate(MachineBasicBlock *TailBB,
710 MachineBasicBlock *PredBB) {
711 // EH edges are ignored by AnalyzeBranch.
712 if (PredBB->succ_size() > 1)
713 return false;
714
715 MachineBasicBlock *PredTBB, *PredFBB;
716 SmallVector<MachineOperand, 4> PredCond;
717 if (TII->analyzeBranch(*PredBB, PredTBB, PredFBB, PredCond, true))
718 return false;
719 if (!PredCond.empty())
720 return false;
721 return true;
722}
723
Kyle Butt3232dbb2016-04-08 20:35:01 +0000724/// If it is profitable, duplicate TailBB's contents in each
725/// of its predecessors.
726bool TailDuplicator::tailDuplicate(MachineFunction &MF, bool IsSimple,
727 MachineBasicBlock *TailBB,
728 SmallVectorImpl<MachineBasicBlock *> &TDBBs,
729 SmallVectorImpl<MachineInstr *> &Copies) {
730 DEBUG(dbgs() << "\n*** Tail-duplicating BB#" << TailBB->getNumber() << '\n');
731
732 DenseSet<unsigned> UsedByPhi;
733 getRegsUsedByPHIs(*TailBB, &UsedByPhi);
734
735 if (IsSimple)
736 return duplicateSimpleBB(TailBB, TDBBs, UsedByPhi, Copies);
737
738 // Iterate through all the unique predecessors and tail-duplicate this
739 // block into them, if possible. Copying the list ahead of time also
740 // avoids trouble with the predecessor list reallocating.
741 bool Changed = false;
742 SmallSetVector<MachineBasicBlock *, 8> Preds(TailBB->pred_begin(),
743 TailBB->pred_end());
Matt Arsenaultb8037a12016-08-16 20:38:05 +0000744 for (MachineBasicBlock *PredBB : Preds) {
Kyle Butt3232dbb2016-04-08 20:35:01 +0000745 assert(TailBB != PredBB &&
746 "Single-block loop should have been rejected earlier!");
Kyle Butt9e52c062016-07-19 23:54:21 +0000747
748 if (!canTailDuplicate(TailBB, PredBB))
Kyle Butt3232dbb2016-04-08 20:35:01 +0000749 continue;
750
Kyle Butt3232dbb2016-04-08 20:35:01 +0000751 // Don't duplicate into a fall-through predecessor (at least for now).
752 if (PredBB->isLayoutSuccessor(TailBB) && PredBB->canFallThrough())
753 continue;
754
755 DEBUG(dbgs() << "\nTail-duplicating into PredBB: " << *PredBB
756 << "From Succ: " << *TailBB);
757
758 TDBBs.push_back(PredBB);
759
760 // Remove PredBB's unconditional branch.
761 TII->RemoveBranch(*PredBB);
762
Kyle Butt3232dbb2016-04-08 20:35:01 +0000763 // Clone the contents of TailBB into PredBB.
Krzysztof Parzyszek4773f642016-04-26 18:36:34 +0000764 DenseMap<unsigned, RegSubRegPair> LocalVRMap;
765 SmallVector<std::pair<unsigned, RegSubRegPair>, 4> CopyInfos;
Kyle Butt3232dbb2016-04-08 20:35:01 +0000766 // Use instr_iterator here to properly handle bundles, e.g.
767 // ARM Thumb2 IT block.
768 MachineBasicBlock::instr_iterator I = TailBB->instr_begin();
769 while (I != TailBB->instr_end()) {
770 MachineInstr *MI = &*I;
771 ++I;
772 if (MI->isPHI()) {
773 // Replace the uses of the def of the PHI with the register coming
774 // from PredBB.
775 processPHI(MI, TailBB, PredBB, LocalVRMap, CopyInfos, UsedByPhi, true);
776 } else {
777 // Replace def of virtual registers with new registers, and update
778 // uses with PHI source register or the new registers.
779 duplicateInstruction(MI, TailBB, PredBB, MF, LocalVRMap, UsedByPhi);
780 }
781 }
Krzysztof Parzyszek4773f642016-04-26 18:36:34 +0000782 appendCopies(PredBB, CopyInfos, Copies);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000783
784 // Simplify
Kyle Butt9e52c062016-07-19 23:54:21 +0000785 MachineBasicBlock *PredTBB, *PredFBB;
786 SmallVector<MachineOperand, 4> PredCond;
Jacques Pienaar71c30a12016-07-15 14:41:04 +0000787 TII->analyzeBranch(*PredBB, PredTBB, PredFBB, PredCond, true);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000788
Geoff Berryf8c29d62016-06-14 19:40:10 +0000789 NumTailDupAdded += TailBB->size() - 1; // subtract one for removed branch
Kyle Butt3232dbb2016-04-08 20:35:01 +0000790
791 // Update the CFG.
792 PredBB->removeSuccessor(PredBB->succ_begin());
793 assert(PredBB->succ_empty() &&
794 "TailDuplicate called on block with multiple successors!");
Matt Arsenaultb8037a12016-08-16 20:38:05 +0000795 for (MachineBasicBlock *Succ : TailBB->successors())
796 PredBB->addSuccessor(Succ, MBPI->getEdgeProbability(TailBB, Succ));
Kyle Butt3232dbb2016-04-08 20:35:01 +0000797
798 Changed = true;
799 ++NumTailDups;
800 }
801
802 // If TailBB was duplicated into all its predecessors except for the prior
803 // block, which falls through unconditionally, move the contents of this
804 // block into the prior block.
805 MachineBasicBlock *PrevBB = &*std::prev(TailBB->getIterator());
806 MachineBasicBlock *PriorTBB = nullptr, *PriorFBB = nullptr;
807 SmallVector<MachineOperand, 4> PriorCond;
808 // This has to check PrevBB->succ_size() because EH edges are ignored by
809 // AnalyzeBranch.
810 if (PrevBB->succ_size() == 1 &&
Kyle Buttd2b886e2016-07-20 00:01:51 +0000811 // Layout preds are not always CFG preds. Check.
812 *PrevBB->succ_begin() == TailBB &&
Jacques Pienaar71c30a12016-07-15 14:41:04 +0000813 !TII->analyzeBranch(*PrevBB, PriorTBB, PriorFBB, PriorCond, true) &&
Kyle Butt3232dbb2016-04-08 20:35:01 +0000814 PriorCond.empty() && !PriorTBB && TailBB->pred_size() == 1 &&
815 !TailBB->hasAddressTaken()) {
816 DEBUG(dbgs() << "\nMerging into block: " << *PrevBB
817 << "From MBB: " << *TailBB);
818 if (PreRegAlloc) {
Krzysztof Parzyszek4773f642016-04-26 18:36:34 +0000819 DenseMap<unsigned, RegSubRegPair> LocalVRMap;
820 SmallVector<std::pair<unsigned, RegSubRegPair>, 4> CopyInfos;
Kyle Butt3232dbb2016-04-08 20:35:01 +0000821 MachineBasicBlock::iterator I = TailBB->begin();
822 // Process PHI instructions first.
823 while (I != TailBB->end() && I->isPHI()) {
824 // Replace the uses of the def of the PHI with the register coming
825 // from PredBB.
826 MachineInstr *MI = &*I++;
827 processPHI(MI, TailBB, PrevBB, LocalVRMap, CopyInfos, UsedByPhi, true);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000828 }
829
830 // Now copy the non-PHI instructions.
831 while (I != TailBB->end()) {
832 // Replace def of virtual registers with new registers, and update
833 // uses with PHI source register or the new registers.
834 MachineInstr *MI = &*I++;
835 assert(!MI->isBundle() && "Not expecting bundles before regalloc!");
836 duplicateInstruction(MI, TailBB, PrevBB, MF, LocalVRMap, UsedByPhi);
837 MI->eraseFromParent();
838 }
Krzysztof Parzyszek4773f642016-04-26 18:36:34 +0000839 appendCopies(PrevBB, CopyInfos, Copies);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000840 } else {
841 // No PHIs to worry about, just splice the instructions over.
842 PrevBB->splice(PrevBB->end(), TailBB, TailBB->begin(), TailBB->end());
843 }
844 PrevBB->removeSuccessor(PrevBB->succ_begin());
845 assert(PrevBB->succ_empty());
846 PrevBB->transferSuccessors(TailBB);
847 TDBBs.push_back(PrevBB);
848 Changed = true;
849 }
850
851 // If this is after register allocation, there are no phis to fix.
852 if (!PreRegAlloc)
853 return Changed;
854
855 // If we made no changes so far, we are safe.
856 if (!Changed)
857 return Changed;
858
859 // Handle the nasty case in that we duplicated a block that is part of a loop
860 // into some but not all of its predecessors. For example:
861 // 1 -> 2 <-> 3 |
862 // \ |
863 // \---> rest |
864 // if we duplicate 2 into 1 but not into 3, we end up with
865 // 12 -> 3 <-> 2 -> rest |
866 // \ / |
867 // \----->-----/ |
868 // If there was a "var = phi(1, 3)" in 2, it has to be ultimately replaced
869 // with a phi in 3 (which now dominates 2).
870 // What we do here is introduce a copy in 3 of the register defined by the
871 // phi, just like when we are duplicating 2 into 3, but we don't copy any
872 // real instructions or remove the 3 -> 2 edge from the phi in 2.
Matt Arsenaultb8037a12016-08-16 20:38:05 +0000873 for (MachineBasicBlock *PredBB : Preds) {
David Majnemer0d955d02016-08-11 22:21:41 +0000874 if (is_contained(TDBBs, PredBB))
Kyle Butt3232dbb2016-04-08 20:35:01 +0000875 continue;
876
877 // EH edges
878 if (PredBB->succ_size() != 1)
879 continue;
880
Krzysztof Parzyszek4773f642016-04-26 18:36:34 +0000881 DenseMap<unsigned, RegSubRegPair> LocalVRMap;
882 SmallVector<std::pair<unsigned, RegSubRegPair>, 4> CopyInfos;
Kyle Butt3232dbb2016-04-08 20:35:01 +0000883 MachineBasicBlock::iterator I = TailBB->begin();
884 // Process PHI instructions first.
885 while (I != TailBB->end() && I->isPHI()) {
886 // Replace the uses of the def of the PHI with the register coming
887 // from PredBB.
888 MachineInstr *MI = &*I++;
889 processPHI(MI, TailBB, PredBB, LocalVRMap, CopyInfos, UsedByPhi, false);
890 }
Krzysztof Parzyszek4773f642016-04-26 18:36:34 +0000891 appendCopies(PredBB, CopyInfos, Copies);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000892 }
893
894 return Changed;
895}
896
Krzysztof Parzyszek4773f642016-04-26 18:36:34 +0000897/// At the end of the block \p MBB generate COPY instructions between registers
898/// described by \p CopyInfos. Append resulting instructions to \p Copies.
899void TailDuplicator::appendCopies(MachineBasicBlock *MBB,
900 SmallVectorImpl<std::pair<unsigned,RegSubRegPair>> &CopyInfos,
901 SmallVectorImpl<MachineInstr*> &Copies) {
902 MachineBasicBlock::iterator Loc = MBB->getFirstTerminator();
903 const MCInstrDesc &CopyD = TII->get(TargetOpcode::COPY);
904 for (auto &CI : CopyInfos) {
905 auto C = BuildMI(*MBB, Loc, DebugLoc(), CopyD, CI.first)
906 .addReg(CI.second.Reg, 0, CI.second.SubReg);
907 Copies.push_back(C);
908 }
909}
910
Kyle Butt3232dbb2016-04-08 20:35:01 +0000911/// Remove the specified dead machine basic block from the function, updating
912/// the CFG.
913void TailDuplicator::removeDeadBlock(MachineBasicBlock *MBB) {
914 assert(MBB->pred_empty() && "MBB must be dead!");
915 DEBUG(dbgs() << "\nRemoving MBB: " << *MBB);
916
917 // Remove all successors.
918 while (!MBB->succ_empty())
919 MBB->removeSuccessor(MBB->succ_end() - 1);
920
921 // Remove the block.
922 MBB->eraseFromParent();
923}
924
925} // End llvm namespace