blob: bf3379eb576faced64fb0614916a743b2ffb4f84 [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
Kyle Butt3ed42732016-08-25 01:37:03 +000059void TailDuplicator::initMF(MachineFunction &MFin,
Kyle Buttdb3391e2016-08-17 21:07:35 +000060 const MachineBranchProbabilityInfo *MBPIin,
61 unsigned TailDupSizeIn) {
Kyle Butt3ed42732016-08-25 01:37:03 +000062 MF = &MFin;
63 TII = MF->getSubtarget().getInstrInfo();
64 TRI = MF->getSubtarget().getRegisterInfo();
65 MRI = &MF->getRegInfo();
Kyle Buttc7f1eac2016-08-25 01:37:07 +000066 MMI = &MF->getMMI();
Kyle Butt3232dbb2016-04-08 20:35:01 +000067 MBPI = MBPIin;
Kyle Buttdb3391e2016-08-17 21:07:35 +000068 TailDupSize = TailDupSizeIn;
Kyle Butt3232dbb2016-04-08 20:35:01 +000069
70 assert(MBPI != nullptr && "Machine Branch Probability Info required");
71
72 PreRegAlloc = MRI->isSSA();
Kyle Butt3232dbb2016-04-08 20:35:01 +000073}
74
75static void VerifyPHIs(MachineFunction &MF, bool CheckExtra) {
76 for (MachineFunction::iterator I = ++MF.begin(), E = MF.end(); I != E; ++I) {
77 MachineBasicBlock *MBB = &*I;
78 SmallSetVector<MachineBasicBlock *, 8> Preds(MBB->pred_begin(),
79 MBB->pred_end());
80 MachineBasicBlock::iterator MI = MBB->begin();
81 while (MI != MBB->end()) {
82 if (!MI->isPHI())
83 break;
Matt Arsenaultb8037a12016-08-16 20:38:05 +000084 for (MachineBasicBlock *PredBB : Preds) {
Kyle Butt3232dbb2016-04-08 20:35:01 +000085 bool Found = false;
86 for (unsigned i = 1, e = MI->getNumOperands(); i != e; i += 2) {
87 MachineBasicBlock *PHIBB = MI->getOperand(i + 1).getMBB();
88 if (PHIBB == PredBB) {
89 Found = true;
90 break;
91 }
92 }
93 if (!Found) {
94 dbgs() << "Malformed PHI in BB#" << MBB->getNumber() << ": " << *MI;
95 dbgs() << " missing input from predecessor BB#"
96 << PredBB->getNumber() << '\n';
97 llvm_unreachable(nullptr);
98 }
99 }
100
101 for (unsigned i = 1, e = MI->getNumOperands(); i != e; i += 2) {
102 MachineBasicBlock *PHIBB = MI->getOperand(i + 1).getMBB();
103 if (CheckExtra && !Preds.count(PHIBB)) {
104 dbgs() << "Warning: malformed PHI in BB#" << MBB->getNumber() << ": "
105 << *MI;
106 dbgs() << " extra input from predecessor BB#" << PHIBB->getNumber()
107 << '\n';
108 llvm_unreachable(nullptr);
109 }
110 if (PHIBB->getNumber() < 0) {
111 dbgs() << "Malformed PHI in BB#" << MBB->getNumber() << ": " << *MI;
112 dbgs() << " non-existing BB#" << PHIBB->getNumber() << '\n';
113 llvm_unreachable(nullptr);
114 }
115 }
116 ++MI;
117 }
118 }
119}
120
121/// Tail duplicate the block and cleanup.
Kyle Butt3ed42732016-08-25 01:37:03 +0000122bool TailDuplicator::tailDuplicateAndUpdate(bool IsSimple,
Kyle Butt3232dbb2016-04-08 20:35:01 +0000123 MachineBasicBlock *MBB) {
124 // Save the successors list.
125 SmallSetVector<MachineBasicBlock *, 8> Succs(MBB->succ_begin(),
126 MBB->succ_end());
127
128 SmallVector<MachineBasicBlock *, 8> TDBBs;
129 SmallVector<MachineInstr *, 16> Copies;
Kyle Butt3ed42732016-08-25 01:37:03 +0000130 if (!tailDuplicate(IsSimple, MBB, TDBBs, Copies))
Kyle Butt3232dbb2016-04-08 20:35:01 +0000131 return false;
132
133 ++NumTails;
134
135 SmallVector<MachineInstr *, 8> NewPHIs;
Kyle Butt3ed42732016-08-25 01:37:03 +0000136 MachineSSAUpdater SSAUpdate(*MF, &NewPHIs);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000137
138 // TailBB's immediate successors are now successors of those predecessors
139 // which duplicated TailBB. Add the predecessors as sources to the PHI
140 // instructions.
141 bool isDead = MBB->pred_empty() && !MBB->hasAddressTaken();
142 if (PreRegAlloc)
143 updateSuccessorsPHIs(MBB, isDead, TDBBs, Succs);
144
145 // If it is dead, remove it.
146 if (isDead) {
Geoff Berryf8c29d62016-06-14 19:40:10 +0000147 NumTailDupRemoved += MBB->size();
Kyle Butt3232dbb2016-04-08 20:35:01 +0000148 removeDeadBlock(MBB);
149 ++NumDeadBlocks;
150 }
151
152 // Update SSA form.
153 if (!SSAUpdateVRs.empty()) {
154 for (unsigned i = 0, e = SSAUpdateVRs.size(); i != e; ++i) {
155 unsigned VReg = SSAUpdateVRs[i];
156 SSAUpdate.Initialize(VReg);
157
158 // If the original definition is still around, add it as an available
159 // value.
160 MachineInstr *DefMI = MRI->getVRegDef(VReg);
161 MachineBasicBlock *DefBB = nullptr;
162 if (DefMI) {
163 DefBB = DefMI->getParent();
164 SSAUpdate.AddAvailableValue(DefBB, VReg);
165 }
166
167 // Add the new vregs as available values.
168 DenseMap<unsigned, AvailableValsTy>::iterator LI =
169 SSAUpdateVals.find(VReg);
170 for (unsigned j = 0, ee = LI->second.size(); j != ee; ++j) {
171 MachineBasicBlock *SrcBB = LI->second[j].first;
172 unsigned SrcReg = LI->second[j].second;
173 SSAUpdate.AddAvailableValue(SrcBB, SrcReg);
174 }
175
176 // Rewrite uses that are outside of the original def's block.
177 MachineRegisterInfo::use_iterator UI = MRI->use_begin(VReg);
178 while (UI != MRI->use_end()) {
179 MachineOperand &UseMO = *UI;
180 MachineInstr *UseMI = UseMO.getParent();
181 ++UI;
182 if (UseMI->isDebugValue()) {
183 // SSAUpdate can replace the use with an undef. That creates
184 // a debug instruction that is a kill.
185 // FIXME: Should it SSAUpdate job to delete debug instructions
186 // instead of replacing the use with undef?
187 UseMI->eraseFromParent();
188 continue;
189 }
190 if (UseMI->getParent() == DefBB && !UseMI->isPHI())
191 continue;
192 SSAUpdate.RewriteUse(UseMO);
193 }
194 }
195
196 SSAUpdateVRs.clear();
197 SSAUpdateVals.clear();
198 }
199
200 // Eliminate some of the copies inserted by tail duplication to maintain
201 // SSA form.
202 for (unsigned i = 0, e = Copies.size(); i != e; ++i) {
203 MachineInstr *Copy = Copies[i];
204 if (!Copy->isCopy())
205 continue;
206 unsigned Dst = Copy->getOperand(0).getReg();
207 unsigned Src = Copy->getOperand(1).getReg();
208 if (MRI->hasOneNonDBGUse(Src) &&
209 MRI->constrainRegClass(Src, MRI->getRegClass(Dst))) {
210 // Copy is the only use. Do trivial copy propagation here.
211 MRI->replaceRegWith(Dst, Src);
212 Copy->eraseFromParent();
213 }
214 }
215
216 if (NewPHIs.size())
217 NumAddedPHIs += NewPHIs.size();
218
219 return true;
220}
221
222/// Look for small blocks that are unconditionally branched to and do not fall
223/// through. Tail-duplicate their instructions into their predecessors to
224/// eliminate (dynamic) branches.
Kyle Butt3ed42732016-08-25 01:37:03 +0000225bool TailDuplicator::tailDuplicateBlocks() {
Kyle Butt3232dbb2016-04-08 20:35:01 +0000226 bool MadeChange = false;
227
228 if (PreRegAlloc && TailDupVerify) {
229 DEBUG(dbgs() << "\n*** Before tail-duplicating\n");
Kyle Butt3ed42732016-08-25 01:37:03 +0000230 VerifyPHIs(*MF, true);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000231 }
232
Kyle Butt3ed42732016-08-25 01:37:03 +0000233 for (MachineFunction::iterator I = ++MF->begin(), E = MF->end(); I != E;) {
Kyle Butt3232dbb2016-04-08 20:35:01 +0000234 MachineBasicBlock *MBB = &*I++;
235
236 if (NumTails == TailDupLimit)
237 break;
238
239 bool IsSimple = isSimpleBB(MBB);
240
Kyle Butt3ed42732016-08-25 01:37:03 +0000241 if (!shouldTailDuplicate(IsSimple, *MBB))
Kyle Butt3232dbb2016-04-08 20:35:01 +0000242 continue;
243
Kyle Butt3ed42732016-08-25 01:37:03 +0000244 MadeChange |= tailDuplicateAndUpdate(IsSimple, MBB);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000245 }
246
247 if (PreRegAlloc && TailDupVerify)
Kyle Butt3ed42732016-08-25 01:37:03 +0000248 VerifyPHIs(*MF, false);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000249
250 return MadeChange;
251}
252
253static bool isDefLiveOut(unsigned Reg, MachineBasicBlock *BB,
254 const MachineRegisterInfo *MRI) {
255 for (MachineInstr &UseMI : MRI->use_instructions(Reg)) {
256 if (UseMI.isDebugValue())
257 continue;
258 if (UseMI.getParent() != BB)
259 return true;
260 }
261 return false;
262}
263
264static unsigned getPHISrcRegOpIdx(MachineInstr *MI, MachineBasicBlock *SrcBB) {
265 for (unsigned i = 1, e = MI->getNumOperands(); i != e; i += 2)
266 if (MI->getOperand(i + 1).getMBB() == SrcBB)
267 return i;
268 return 0;
269}
270
271// Remember which registers are used by phis in this block. This is
272// used to determine which registers are liveout while modifying the
273// block (which is why we need to copy the information).
274static void getRegsUsedByPHIs(const MachineBasicBlock &BB,
275 DenseSet<unsigned> *UsedByPhi) {
276 for (const auto &MI : BB) {
277 if (!MI.isPHI())
278 break;
279 for (unsigned i = 1, e = MI.getNumOperands(); i != e; i += 2) {
280 unsigned SrcReg = MI.getOperand(i).getReg();
281 UsedByPhi->insert(SrcReg);
282 }
283 }
284}
285
286/// Add a definition and source virtual registers pair for SSA update.
287void TailDuplicator::addSSAUpdateEntry(unsigned OrigReg, unsigned NewReg,
288 MachineBasicBlock *BB) {
289 DenseMap<unsigned, AvailableValsTy>::iterator LI =
290 SSAUpdateVals.find(OrigReg);
291 if (LI != SSAUpdateVals.end())
292 LI->second.push_back(std::make_pair(BB, NewReg));
293 else {
294 AvailableValsTy Vals;
295 Vals.push_back(std::make_pair(BB, NewReg));
296 SSAUpdateVals.insert(std::make_pair(OrigReg, Vals));
297 SSAUpdateVRs.push_back(OrigReg);
298 }
299}
300
301/// Process PHI node in TailBB by turning it into a copy in PredBB. Remember the
302/// source register that's contributed by PredBB and update SSA update map.
303void TailDuplicator::processPHI(
304 MachineInstr *MI, MachineBasicBlock *TailBB, MachineBasicBlock *PredBB,
Krzysztof Parzyszek4773f642016-04-26 18:36:34 +0000305 DenseMap<unsigned, RegSubRegPair> &LocalVRMap,
306 SmallVectorImpl<std::pair<unsigned, RegSubRegPair>> &Copies,
Kyle Butt3232dbb2016-04-08 20:35:01 +0000307 const DenseSet<unsigned> &RegsUsedByPhi, bool Remove) {
308 unsigned DefReg = MI->getOperand(0).getReg();
309 unsigned SrcOpIdx = getPHISrcRegOpIdx(MI, PredBB);
310 assert(SrcOpIdx && "Unable to find matching PHI source?");
311 unsigned SrcReg = MI->getOperand(SrcOpIdx).getReg();
Krzysztof Parzyszek4773f642016-04-26 18:36:34 +0000312 unsigned SrcSubReg = MI->getOperand(SrcOpIdx).getSubReg();
Kyle Butt3232dbb2016-04-08 20:35:01 +0000313 const TargetRegisterClass *RC = MRI->getRegClass(DefReg);
Krzysztof Parzyszek4773f642016-04-26 18:36:34 +0000314 LocalVRMap.insert(std::make_pair(DefReg, RegSubRegPair(SrcReg, SrcSubReg)));
Kyle Butt3232dbb2016-04-08 20:35:01 +0000315
316 // Insert a copy from source to the end of the block. The def register is the
317 // available value liveout of the block.
318 unsigned NewDef = MRI->createVirtualRegister(RC);
Krzysztof Parzyszek4773f642016-04-26 18:36:34 +0000319 Copies.push_back(std::make_pair(NewDef, RegSubRegPair(SrcReg, SrcSubReg)));
Kyle Butt3232dbb2016-04-08 20:35:01 +0000320 if (isDefLiveOut(DefReg, TailBB, MRI) || RegsUsedByPhi.count(DefReg))
321 addSSAUpdateEntry(DefReg, NewDef, PredBB);
322
323 if (!Remove)
324 return;
325
326 // Remove PredBB from the PHI node.
327 MI->RemoveOperand(SrcOpIdx + 1);
328 MI->RemoveOperand(SrcOpIdx);
329 if (MI->getNumOperands() == 1)
330 MI->eraseFromParent();
331}
332
333/// Duplicate a TailBB instruction to PredBB and update
334/// the source operands due to earlier PHI translation.
335void TailDuplicator::duplicateInstruction(
336 MachineInstr *MI, MachineBasicBlock *TailBB, MachineBasicBlock *PredBB,
Krzysztof Parzyszek4773f642016-04-26 18:36:34 +0000337 DenseMap<unsigned, RegSubRegPair> &LocalVRMap,
Kyle Butt3232dbb2016-04-08 20:35:01 +0000338 const DenseSet<unsigned> &UsedByPhi) {
Kyle Butt3ed42732016-08-25 01:37:03 +0000339 MachineInstr *NewMI = TII->duplicate(*MI, *MF);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000340 if (PreRegAlloc) {
341 for (unsigned i = 0, e = NewMI->getNumOperands(); i != e; ++i) {
342 MachineOperand &MO = NewMI->getOperand(i);
343 if (!MO.isReg())
344 continue;
345 unsigned Reg = MO.getReg();
346 if (!TargetRegisterInfo::isVirtualRegister(Reg))
347 continue;
348 if (MO.isDef()) {
349 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
350 unsigned NewReg = MRI->createVirtualRegister(RC);
351 MO.setReg(NewReg);
Krzysztof Parzyszek4773f642016-04-26 18:36:34 +0000352 LocalVRMap.insert(std::make_pair(Reg, RegSubRegPair(NewReg, 0)));
Kyle Butt3232dbb2016-04-08 20:35:01 +0000353 if (isDefLiveOut(Reg, TailBB, MRI) || UsedByPhi.count(Reg))
354 addSSAUpdateEntry(Reg, NewReg, PredBB);
355 } else {
Krzysztof Parzyszek4773f642016-04-26 18:36:34 +0000356 auto VI = LocalVRMap.find(Reg);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000357 if (VI != LocalVRMap.end()) {
Krzysztof Parzyszek4773f642016-04-26 18:36:34 +0000358 // Need to make sure that the register class of the mapped register
359 // will satisfy the constraints of the class of the register being
360 // replaced.
361 auto *OrigRC = MRI->getRegClass(Reg);
362 auto *MappedRC = MRI->getRegClass(VI->second.Reg);
363 const TargetRegisterClass *ConstrRC;
364 if (VI->second.SubReg != 0) {
365 ConstrRC = TRI->getMatchingSuperRegClass(MappedRC, OrigRC,
366 VI->second.SubReg);
367 if (ConstrRC) {
368 // The actual constraining (as in "find appropriate new class")
369 // is done by getMatchingSuperRegClass, so now we only need to
370 // change the class of the mapped register.
371 MRI->setRegClass(VI->second.Reg, ConstrRC);
372 }
373 } else {
374 // For mapped registers that do not have sub-registers, simply
375 // restrict their class to match the original one.
376 ConstrRC = MRI->constrainRegClass(VI->second.Reg, OrigRC);
377 }
378
379 if (ConstrRC) {
380 // If the class constraining succeeded, we can simply replace
381 // the old register with the mapped one.
382 MO.setReg(VI->second.Reg);
383 // We have Reg -> VI.Reg:VI.SubReg, so if Reg is used with a
384 // sub-register, we need to compose the sub-register indices.
385 MO.setSubReg(TRI->composeSubRegIndices(MO.getSubReg(),
386 VI->second.SubReg));
387 } else {
388 // The direct replacement is not possible, due to failing register
389 // class constraints. An explicit COPY is necessary. Create one
390 // that can be reused
391 auto *NewRC = MI->getRegClassConstraint(i, TII, TRI);
392 if (NewRC == nullptr)
393 NewRC = OrigRC;
394 unsigned NewReg = MRI->createVirtualRegister(NewRC);
395 BuildMI(*PredBB, MI, MI->getDebugLoc(),
396 TII->get(TargetOpcode::COPY), NewReg)
397 .addReg(VI->second.Reg, 0, VI->second.SubReg);
398 LocalVRMap.erase(VI);
399 LocalVRMap.insert(std::make_pair(Reg, RegSubRegPair(NewReg, 0)));
400 MO.setReg(NewReg);
401 // The composed VI.Reg:VI.SubReg is replaced with NewReg, which
402 // is equivalent to the whole register Reg. Hence, Reg:subreg
403 // is same as NewReg:subreg, so keep the sub-register index
404 // unchanged.
405 }
Kyle Butt3232dbb2016-04-08 20:35:01 +0000406 // Clear any kill flags from this operand. The new register could
407 // have uses after this one, so kills are not valid here.
408 MO.setIsKill(false);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000409 }
410 }
411 }
412 }
413 PredBB->insert(PredBB->instr_end(), NewMI);
414}
415
416/// After FromBB is tail duplicated into its predecessor blocks, the successors
417/// have gained new predecessors. Update the PHI instructions in them
418/// accordingly.
419void TailDuplicator::updateSuccessorsPHIs(
420 MachineBasicBlock *FromBB, bool isDead,
421 SmallVectorImpl<MachineBasicBlock *> &TDBBs,
422 SmallSetVector<MachineBasicBlock *, 8> &Succs) {
Matt Arsenaultb8037a12016-08-16 20:38:05 +0000423 for (MachineBasicBlock *SuccBB : Succs) {
424 for (MachineInstr &MI : *SuccBB) {
425 if (!MI.isPHI())
Kyle Butt3232dbb2016-04-08 20:35:01 +0000426 break;
Matt Arsenaultb8037a12016-08-16 20:38:05 +0000427 MachineInstrBuilder MIB(*FromBB->getParent(), MI);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000428 unsigned Idx = 0;
Matt Arsenaultb8037a12016-08-16 20:38:05 +0000429 for (unsigned i = 1, e = MI.getNumOperands(); i != e; i += 2) {
430 MachineOperand &MO = MI.getOperand(i + 1);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000431 if (MO.getMBB() == FromBB) {
432 Idx = i;
433 break;
434 }
435 }
436
437 assert(Idx != 0);
Matt Arsenaultb8037a12016-08-16 20:38:05 +0000438 MachineOperand &MO0 = MI.getOperand(Idx);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000439 unsigned Reg = MO0.getReg();
440 if (isDead) {
441 // Folded into the previous BB.
442 // There could be duplicate phi source entries. FIXME: Should sdisel
443 // or earlier pass fixed this?
Matt Arsenaultb8037a12016-08-16 20:38:05 +0000444 for (unsigned i = MI.getNumOperands() - 2; i != Idx; i -= 2) {
445 MachineOperand &MO = MI.getOperand(i + 1);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000446 if (MO.getMBB() == FromBB) {
Matt Arsenaultb8037a12016-08-16 20:38:05 +0000447 MI.RemoveOperand(i + 1);
448 MI.RemoveOperand(i);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000449 }
450 }
451 } else
452 Idx = 0;
453
454 // If Idx is set, the operands at Idx and Idx+1 must be removed.
455 // We reuse the location to avoid expensive RemoveOperand calls.
456
457 DenseMap<unsigned, AvailableValsTy>::iterator LI =
458 SSAUpdateVals.find(Reg);
459 if (LI != SSAUpdateVals.end()) {
460 // This register is defined in the tail block.
461 for (unsigned j = 0, ee = LI->second.size(); j != ee; ++j) {
462 MachineBasicBlock *SrcBB = LI->second[j].first;
463 // If we didn't duplicate a bb into a particular predecessor, we
464 // might still have added an entry to SSAUpdateVals to correcly
465 // recompute SSA. If that case, avoid adding a dummy extra argument
466 // this PHI.
467 if (!SrcBB->isSuccessor(SuccBB))
468 continue;
469
470 unsigned SrcReg = LI->second[j].second;
471 if (Idx != 0) {
Matt Arsenaultb8037a12016-08-16 20:38:05 +0000472 MI.getOperand(Idx).setReg(SrcReg);
473 MI.getOperand(Idx + 1).setMBB(SrcBB);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000474 Idx = 0;
475 } else {
476 MIB.addReg(SrcReg).addMBB(SrcBB);
477 }
478 }
479 } else {
480 // Live in tail block, must also be live in predecessors.
481 for (unsigned j = 0, ee = TDBBs.size(); j != ee; ++j) {
482 MachineBasicBlock *SrcBB = TDBBs[j];
483 if (Idx != 0) {
Matt Arsenaultb8037a12016-08-16 20:38:05 +0000484 MI.getOperand(Idx).setReg(Reg);
485 MI.getOperand(Idx + 1).setMBB(SrcBB);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000486 Idx = 0;
487 } else {
488 MIB.addReg(Reg).addMBB(SrcBB);
489 }
490 }
491 }
492 if (Idx != 0) {
Matt Arsenaultb8037a12016-08-16 20:38:05 +0000493 MI.RemoveOperand(Idx + 1);
494 MI.RemoveOperand(Idx);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000495 }
496 }
497 }
498}
499
500/// Determine if it is profitable to duplicate this block.
Kyle Butt3ed42732016-08-25 01:37:03 +0000501bool TailDuplicator::shouldTailDuplicate(bool IsSimple,
Kyle Butt3232dbb2016-04-08 20:35:01 +0000502 MachineBasicBlock &TailBB) {
503 // Only duplicate blocks that end with unconditional branches.
504 if (TailBB.canFallThrough())
505 return false;
506
507 // Don't try to tail-duplicate single-block loops.
508 if (TailBB.isSuccessor(&TailBB))
509 return false;
510
511 // Set the limit on the cost to duplicate. When optimizing for size,
512 // duplicate only one, because one branch instruction can be eliminated to
513 // compensate for the duplication.
514 unsigned MaxDuplicateCount;
Kyle Buttdb3391e2016-08-17 21:07:35 +0000515 if (TailDupSize == 0 &&
516 TailDuplicateSize.getNumOccurrences() == 0 &&
Kyle Butt3ed42732016-08-25 01:37:03 +0000517 MF->getFunction()->optForSize())
Kyle Butt3232dbb2016-04-08 20:35:01 +0000518 MaxDuplicateCount = 1;
Kyle Buttdb3391e2016-08-17 21:07:35 +0000519 else if (TailDupSize == 0)
Kyle Butt3232dbb2016-04-08 20:35:01 +0000520 MaxDuplicateCount = TailDuplicateSize;
Kyle Buttdb3391e2016-08-17 21:07:35 +0000521 else
522 MaxDuplicateCount = TailDupSize;
Kyle Butt3232dbb2016-04-08 20:35:01 +0000523
Kyle Butt07d61422016-08-16 22:56:14 +0000524 // If the block to be duplicated ends in an unanalyzable fallthrough, don't
525 // duplicate it.
526 // A similar check is necessary in MachineBlockPlacement to make sure pairs of
527 // blocks with unanalyzable fallthrough get layed out contiguously.
528 MachineBasicBlock *PredTBB = nullptr, *PredFBB = nullptr;
529 SmallVector<MachineOperand, 4> PredCond;
530 if (TII->analyzeBranch(TailBB, PredTBB, PredFBB, PredCond, true)
531 && TailBB.canFallThrough())
532 return false;
533
Kyle Butt3232dbb2016-04-08 20:35:01 +0000534 // If the target has hardware branch prediction that can handle indirect
535 // branches, duplicating them can often make them predictable when there
536 // are common paths through the code. The limit needs to be high enough
537 // to allow undoing the effects of tail merging and other optimizations
538 // that rearrange the predecessors of the indirect branch.
539
540 bool HasIndirectbr = false;
541 if (!TailBB.empty())
542 HasIndirectbr = TailBB.back().isIndirectBranch();
543
544 if (HasIndirectbr && PreRegAlloc)
545 MaxDuplicateCount = 20;
546
547 // Check the instructions in the block to determine whether tail-duplication
548 // is invalid or unlikely to be profitable.
549 unsigned InstrCount = 0;
550 for (MachineInstr &MI : TailBB) {
551 // Non-duplicable things shouldn't be tail-duplicated.
552 if (MI.isNotDuplicable())
553 return false;
554
555 // Convergent instructions can be duplicated only if doing so doesn't add
556 // new control dependencies, which is what we're going to do here.
557 if (MI.isConvergent())
558 return false;
559
560 // Do not duplicate 'return' instructions if this is a pre-regalloc run.
561 // A return may expand into a lot more instructions (e.g. reload of callee
562 // saved registers) after PEI.
563 if (PreRegAlloc && MI.isReturn())
564 return false;
565
566 // Avoid duplicating calls before register allocation. Calls presents a
567 // barrier to register allocation so duplicating them may end up increasing
568 // spills.
569 if (PreRegAlloc && MI.isCall())
570 return false;
571
572 if (!MI.isPHI() && !MI.isDebugValue())
573 InstrCount += 1;
574
575 if (InstrCount > MaxDuplicateCount)
576 return false;
577 }
578
579 // Check if any of the successors of TailBB has a PHI node in which the
580 // value corresponding to TailBB uses a subregister.
581 // If a phi node uses a register paired with a subregister, the actual
582 // "value type" of the phi may differ from the type of the register without
583 // any subregisters. Due to a bug, tail duplication may add a new operand
584 // without a necessary subregister, producing an invalid code. This is
585 // demonstrated by test/CodeGen/Hexagon/tail-dup-subreg-abort.ll.
586 // Disable tail duplication for this case for now, until the problem is
587 // fixed.
588 for (auto SB : TailBB.successors()) {
589 for (auto &I : *SB) {
590 if (!I.isPHI())
591 break;
592 unsigned Idx = getPHISrcRegOpIdx(&I, &TailBB);
593 assert(Idx != 0);
594 MachineOperand &PU = I.getOperand(Idx);
595 if (PU.getSubReg() != 0)
596 return false;
597 }
598 }
599
600 if (HasIndirectbr && PreRegAlloc)
601 return true;
602
603 if (IsSimple)
604 return true;
605
606 if (!PreRegAlloc)
607 return true;
608
609 return canCompletelyDuplicateBB(TailBB);
610}
611
612/// True if this BB has only one unconditional jump.
613bool TailDuplicator::isSimpleBB(MachineBasicBlock *TailBB) {
614 if (TailBB->succ_size() != 1)
615 return false;
616 if (TailBB->pred_empty())
617 return false;
618 MachineBasicBlock::iterator I = TailBB->getFirstNonDebugInstr();
619 if (I == TailBB->end())
620 return true;
621 return I->isUnconditionalBranch();
622}
623
624static bool bothUsedInPHI(const MachineBasicBlock &A,
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000625 const SmallPtrSet<MachineBasicBlock *, 8> &SuccsB) {
Kyle Butt3232dbb2016-04-08 20:35:01 +0000626 for (MachineBasicBlock *BB : A.successors())
627 if (SuccsB.count(BB) && !BB->empty() && BB->begin()->isPHI())
628 return true;
629
630 return false;
631}
632
633bool TailDuplicator::canCompletelyDuplicateBB(MachineBasicBlock &BB) {
634 for (MachineBasicBlock *PredBB : BB.predecessors()) {
635 if (PredBB->succ_size() > 1)
636 return false;
637
638 MachineBasicBlock *PredTBB = nullptr, *PredFBB = nullptr;
639 SmallVector<MachineOperand, 4> PredCond;
Jacques Pienaar71c30a12016-07-15 14:41:04 +0000640 if (TII->analyzeBranch(*PredBB, PredTBB, PredFBB, PredCond, true))
Kyle Butt3232dbb2016-04-08 20:35:01 +0000641 return false;
642
643 if (!PredCond.empty())
644 return false;
645 }
646 return true;
647}
648
649bool TailDuplicator::duplicateSimpleBB(
650 MachineBasicBlock *TailBB, SmallVectorImpl<MachineBasicBlock *> &TDBBs,
651 const DenseSet<unsigned> &UsedByPhi,
652 SmallVectorImpl<MachineInstr *> &Copies) {
653 SmallPtrSet<MachineBasicBlock *, 8> Succs(TailBB->succ_begin(),
654 TailBB->succ_end());
655 SmallVector<MachineBasicBlock *, 8> Preds(TailBB->pred_begin(),
656 TailBB->pred_end());
657 bool Changed = false;
Matt Arsenaultb8037a12016-08-16 20:38:05 +0000658 for (MachineBasicBlock *PredBB : Preds) {
Kyle Butt3232dbb2016-04-08 20:35:01 +0000659 if (PredBB->hasEHPadSuccessor())
660 continue;
661
662 if (bothUsedInPHI(*PredBB, Succs))
663 continue;
664
665 MachineBasicBlock *PredTBB = nullptr, *PredFBB = nullptr;
666 SmallVector<MachineOperand, 4> PredCond;
Jacques Pienaar71c30a12016-07-15 14:41:04 +0000667 if (TII->analyzeBranch(*PredBB, PredTBB, PredFBB, PredCond, true))
Kyle Butt3232dbb2016-04-08 20:35:01 +0000668 continue;
669
670 Changed = true;
671 DEBUG(dbgs() << "\nTail-duplicating into PredBB: " << *PredBB
672 << "From simple Succ: " << *TailBB);
673
674 MachineBasicBlock *NewTarget = *TailBB->succ_begin();
Matthias Braun6442fc12016-08-18 00:59:32 +0000675 MachineBasicBlock *NextBB = PredBB->getNextNode();
Kyle Butt3232dbb2016-04-08 20:35:01 +0000676
677 // Make PredFBB explicit.
678 if (PredCond.empty())
679 PredFBB = PredTBB;
680
681 // Make fall through explicit.
682 if (!PredTBB)
683 PredTBB = NextBB;
684 if (!PredFBB)
685 PredFBB = NextBB;
686
687 // Redirect
688 if (PredFBB == TailBB)
689 PredFBB = NewTarget;
690 if (PredTBB == TailBB)
691 PredTBB = NewTarget;
692
693 // Make the branch unconditional if possible
694 if (PredTBB == PredFBB) {
695 PredCond.clear();
696 PredFBB = nullptr;
697 }
698
699 // Avoid adding fall through branches.
700 if (PredFBB == NextBB)
701 PredFBB = nullptr;
702 if (PredTBB == NextBB && PredFBB == nullptr)
703 PredTBB = nullptr;
704
705 TII->RemoveBranch(*PredBB);
706
707 if (!PredBB->isSuccessor(NewTarget))
708 PredBB->replaceSuccessor(TailBB, NewTarget);
709 else {
710 PredBB->removeSuccessor(TailBB, true);
711 assert(PredBB->succ_size() <= 1);
712 }
713
714 if (PredTBB)
715 TII->InsertBranch(*PredBB, PredTBB, PredFBB, PredCond, DebugLoc());
716
717 TDBBs.push_back(PredBB);
718 }
719 return Changed;
720}
721
Kyle Butt9e52c062016-07-19 23:54:21 +0000722bool TailDuplicator::canTailDuplicate(MachineBasicBlock *TailBB,
723 MachineBasicBlock *PredBB) {
724 // EH edges are ignored by AnalyzeBranch.
725 if (PredBB->succ_size() > 1)
726 return false;
727
728 MachineBasicBlock *PredTBB, *PredFBB;
729 SmallVector<MachineOperand, 4> PredCond;
730 if (TII->analyzeBranch(*PredBB, PredTBB, PredFBB, PredCond, true))
731 return false;
732 if (!PredCond.empty())
733 return false;
734 return true;
735}
736
Kyle Butt3232dbb2016-04-08 20:35:01 +0000737/// If it is profitable, duplicate TailBB's contents in each
738/// of its predecessors.
Kyle Butt3ed42732016-08-25 01:37:03 +0000739bool TailDuplicator::tailDuplicate(bool IsSimple, MachineBasicBlock *TailBB,
Kyle Butt3232dbb2016-04-08 20:35:01 +0000740 SmallVectorImpl<MachineBasicBlock *> &TDBBs,
741 SmallVectorImpl<MachineInstr *> &Copies) {
742 DEBUG(dbgs() << "\n*** Tail-duplicating BB#" << TailBB->getNumber() << '\n');
743
744 DenseSet<unsigned> UsedByPhi;
745 getRegsUsedByPHIs(*TailBB, &UsedByPhi);
746
747 if (IsSimple)
748 return duplicateSimpleBB(TailBB, TDBBs, UsedByPhi, Copies);
749
750 // Iterate through all the unique predecessors and tail-duplicate this
751 // block into them, if possible. Copying the list ahead of time also
752 // avoids trouble with the predecessor list reallocating.
753 bool Changed = false;
754 SmallSetVector<MachineBasicBlock *, 8> Preds(TailBB->pred_begin(),
755 TailBB->pred_end());
Matt Arsenaultb8037a12016-08-16 20:38:05 +0000756 for (MachineBasicBlock *PredBB : Preds) {
Kyle Butt3232dbb2016-04-08 20:35:01 +0000757 assert(TailBB != PredBB &&
758 "Single-block loop should have been rejected earlier!");
Kyle Butt9e52c062016-07-19 23:54:21 +0000759
760 if (!canTailDuplicate(TailBB, PredBB))
Kyle Butt3232dbb2016-04-08 20:35:01 +0000761 continue;
762
Kyle Butt3232dbb2016-04-08 20:35:01 +0000763 // Don't duplicate into a fall-through predecessor (at least for now).
764 if (PredBB->isLayoutSuccessor(TailBB) && PredBB->canFallThrough())
765 continue;
766
767 DEBUG(dbgs() << "\nTail-duplicating into PredBB: " << *PredBB
768 << "From Succ: " << *TailBB);
769
770 TDBBs.push_back(PredBB);
771
772 // Remove PredBB's unconditional branch.
773 TII->RemoveBranch(*PredBB);
774
Kyle Butt3232dbb2016-04-08 20:35:01 +0000775 // Clone the contents of TailBB into PredBB.
Krzysztof Parzyszek4773f642016-04-26 18:36:34 +0000776 DenseMap<unsigned, RegSubRegPair> LocalVRMap;
777 SmallVector<std::pair<unsigned, RegSubRegPair>, 4> CopyInfos;
Kyle Butt3232dbb2016-04-08 20:35:01 +0000778 // Use instr_iterator here to properly handle bundles, e.g.
779 // ARM Thumb2 IT block.
780 MachineBasicBlock::instr_iterator I = TailBB->instr_begin();
781 while (I != TailBB->instr_end()) {
782 MachineInstr *MI = &*I;
783 ++I;
784 if (MI->isPHI()) {
785 // Replace the uses of the def of the PHI with the register coming
786 // from PredBB.
787 processPHI(MI, TailBB, PredBB, LocalVRMap, CopyInfos, UsedByPhi, true);
788 } else {
789 // Replace def of virtual registers with new registers, and update
790 // uses with PHI source register or the new registers.
Kyle Butt3ed42732016-08-25 01:37:03 +0000791 duplicateInstruction(MI, TailBB, PredBB, LocalVRMap, UsedByPhi);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000792 }
793 }
Krzysztof Parzyszek4773f642016-04-26 18:36:34 +0000794 appendCopies(PredBB, CopyInfos, Copies);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000795
796 // Simplify
Kyle Butt9e52c062016-07-19 23:54:21 +0000797 MachineBasicBlock *PredTBB, *PredFBB;
798 SmallVector<MachineOperand, 4> PredCond;
Jacques Pienaar71c30a12016-07-15 14:41:04 +0000799 TII->analyzeBranch(*PredBB, PredTBB, PredFBB, PredCond, true);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000800
Geoff Berryf8c29d62016-06-14 19:40:10 +0000801 NumTailDupAdded += TailBB->size() - 1; // subtract one for removed branch
Kyle Butt3232dbb2016-04-08 20:35:01 +0000802
803 // Update the CFG.
804 PredBB->removeSuccessor(PredBB->succ_begin());
805 assert(PredBB->succ_empty() &&
806 "TailDuplicate called on block with multiple successors!");
Matt Arsenaultb8037a12016-08-16 20:38:05 +0000807 for (MachineBasicBlock *Succ : TailBB->successors())
808 PredBB->addSuccessor(Succ, MBPI->getEdgeProbability(TailBB, Succ));
Kyle Butt3232dbb2016-04-08 20:35:01 +0000809
810 Changed = true;
811 ++NumTailDups;
812 }
813
814 // If TailBB was duplicated into all its predecessors except for the prior
815 // block, which falls through unconditionally, move the contents of this
816 // block into the prior block.
817 MachineBasicBlock *PrevBB = &*std::prev(TailBB->getIterator());
818 MachineBasicBlock *PriorTBB = nullptr, *PriorFBB = nullptr;
819 SmallVector<MachineOperand, 4> PriorCond;
820 // This has to check PrevBB->succ_size() because EH edges are ignored by
821 // AnalyzeBranch.
822 if (PrevBB->succ_size() == 1 &&
Kyle Buttd2b886e2016-07-20 00:01:51 +0000823 // Layout preds are not always CFG preds. Check.
824 *PrevBB->succ_begin() == TailBB &&
Jacques Pienaar71c30a12016-07-15 14:41:04 +0000825 !TII->analyzeBranch(*PrevBB, PriorTBB, PriorFBB, PriorCond, true) &&
Kyle Butt3232dbb2016-04-08 20:35:01 +0000826 PriorCond.empty() && !PriorTBB && TailBB->pred_size() == 1 &&
827 !TailBB->hasAddressTaken()) {
828 DEBUG(dbgs() << "\nMerging into block: " << *PrevBB
829 << "From MBB: " << *TailBB);
830 if (PreRegAlloc) {
Krzysztof Parzyszek4773f642016-04-26 18:36:34 +0000831 DenseMap<unsigned, RegSubRegPair> LocalVRMap;
832 SmallVector<std::pair<unsigned, RegSubRegPair>, 4> CopyInfos;
Kyle Butt3232dbb2016-04-08 20:35:01 +0000833 MachineBasicBlock::iterator I = TailBB->begin();
834 // Process PHI instructions first.
835 while (I != TailBB->end() && I->isPHI()) {
836 // Replace the uses of the def of the PHI with the register coming
837 // from PredBB.
838 MachineInstr *MI = &*I++;
839 processPHI(MI, TailBB, PrevBB, LocalVRMap, CopyInfos, UsedByPhi, true);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000840 }
841
842 // Now copy the non-PHI instructions.
843 while (I != TailBB->end()) {
844 // Replace def of virtual registers with new registers, and update
845 // uses with PHI source register or the new registers.
846 MachineInstr *MI = &*I++;
847 assert(!MI->isBundle() && "Not expecting bundles before regalloc!");
Kyle Butt3ed42732016-08-25 01:37:03 +0000848 duplicateInstruction(MI, TailBB, PrevBB, LocalVRMap, UsedByPhi);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000849 MI->eraseFromParent();
850 }
Krzysztof Parzyszek4773f642016-04-26 18:36:34 +0000851 appendCopies(PrevBB, CopyInfos, Copies);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000852 } else {
853 // No PHIs to worry about, just splice the instructions over.
854 PrevBB->splice(PrevBB->end(), TailBB, TailBB->begin(), TailBB->end());
855 }
856 PrevBB->removeSuccessor(PrevBB->succ_begin());
857 assert(PrevBB->succ_empty());
858 PrevBB->transferSuccessors(TailBB);
859 TDBBs.push_back(PrevBB);
860 Changed = true;
861 }
862
863 // If this is after register allocation, there are no phis to fix.
864 if (!PreRegAlloc)
865 return Changed;
866
867 // If we made no changes so far, we are safe.
868 if (!Changed)
869 return Changed;
870
871 // Handle the nasty case in that we duplicated a block that is part of a loop
872 // into some but not all of its predecessors. For example:
873 // 1 -> 2 <-> 3 |
874 // \ |
875 // \---> rest |
876 // if we duplicate 2 into 1 but not into 3, we end up with
877 // 12 -> 3 <-> 2 -> rest |
878 // \ / |
879 // \----->-----/ |
880 // If there was a "var = phi(1, 3)" in 2, it has to be ultimately replaced
881 // with a phi in 3 (which now dominates 2).
882 // What we do here is introduce a copy in 3 of the register defined by the
883 // phi, just like when we are duplicating 2 into 3, but we don't copy any
884 // real instructions or remove the 3 -> 2 edge from the phi in 2.
Matt Arsenaultb8037a12016-08-16 20:38:05 +0000885 for (MachineBasicBlock *PredBB : Preds) {
David Majnemer0d955d02016-08-11 22:21:41 +0000886 if (is_contained(TDBBs, PredBB))
Kyle Butt3232dbb2016-04-08 20:35:01 +0000887 continue;
888
889 // EH edges
890 if (PredBB->succ_size() != 1)
891 continue;
892
Krzysztof Parzyszek4773f642016-04-26 18:36:34 +0000893 DenseMap<unsigned, RegSubRegPair> LocalVRMap;
894 SmallVector<std::pair<unsigned, RegSubRegPair>, 4> CopyInfos;
Kyle Butt3232dbb2016-04-08 20:35:01 +0000895 MachineBasicBlock::iterator I = TailBB->begin();
896 // Process PHI instructions first.
897 while (I != TailBB->end() && I->isPHI()) {
898 // Replace the uses of the def of the PHI with the register coming
899 // from PredBB.
900 MachineInstr *MI = &*I++;
901 processPHI(MI, TailBB, PredBB, LocalVRMap, CopyInfos, UsedByPhi, false);
902 }
Krzysztof Parzyszek4773f642016-04-26 18:36:34 +0000903 appendCopies(PredBB, CopyInfos, Copies);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000904 }
905
906 return Changed;
907}
908
Krzysztof Parzyszek4773f642016-04-26 18:36:34 +0000909/// At the end of the block \p MBB generate COPY instructions between registers
910/// described by \p CopyInfos. Append resulting instructions to \p Copies.
911void TailDuplicator::appendCopies(MachineBasicBlock *MBB,
912 SmallVectorImpl<std::pair<unsigned,RegSubRegPair>> &CopyInfos,
913 SmallVectorImpl<MachineInstr*> &Copies) {
914 MachineBasicBlock::iterator Loc = MBB->getFirstTerminator();
915 const MCInstrDesc &CopyD = TII->get(TargetOpcode::COPY);
916 for (auto &CI : CopyInfos) {
917 auto C = BuildMI(*MBB, Loc, DebugLoc(), CopyD, CI.first)
918 .addReg(CI.second.Reg, 0, CI.second.SubReg);
919 Copies.push_back(C);
920 }
921}
922
Kyle Butt3232dbb2016-04-08 20:35:01 +0000923/// Remove the specified dead machine basic block from the function, updating
924/// the CFG.
925void TailDuplicator::removeDeadBlock(MachineBasicBlock *MBB) {
926 assert(MBB->pred_empty() && "MBB must be dead!");
927 DEBUG(dbgs() << "\nRemoving MBB: " << *MBB);
928
929 // Remove all successors.
930 while (!MBB->succ_empty())
931 MBB->removeSuccessor(MBB->succ_end() - 1);
932
933 // Remove the block.
934 MBB->eraseFromParent();
935}
936
937} // End llvm namespace