xref: /freebsd/contrib/llvm-project/llvm/lib/CodeGen/TailDuplicator.cpp (revision 770cf0a5f02dc8983a89c6568d741fbc25baa999)
1 //===- TailDuplicator.cpp - Duplicate blocks into predecessors' tails -----===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This utility class duplicates basic blocks ending in unconditional branches
10 // into the tails of their predecessors.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/CodeGen/TailDuplicator.h"
15 #include "llvm/ADT/DenseMap.h"
16 #include "llvm/ADT/DenseSet.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/ADT/SetVector.h"
19 #include "llvm/ADT/SmallPtrSet.h"
20 #include "llvm/ADT/SmallVector.h"
21 #include "llvm/ADT/Statistic.h"
22 #include "llvm/CodeGen/MachineBasicBlock.h"
23 #include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
24 #include "llvm/CodeGen/MachineFunction.h"
25 #include "llvm/CodeGen/MachineInstr.h"
26 #include "llvm/CodeGen/MachineInstrBuilder.h"
27 #include "llvm/CodeGen/MachineOperand.h"
28 #include "llvm/CodeGen/MachineRegisterInfo.h"
29 #include "llvm/CodeGen/MachineSSAUpdater.h"
30 #include "llvm/CodeGen/MachineSizeOpts.h"
31 #include "llvm/CodeGen/TargetInstrInfo.h"
32 #include "llvm/CodeGen/TargetRegisterInfo.h"
33 #include "llvm/CodeGen/TargetSubtargetInfo.h"
34 #include "llvm/IR/DebugLoc.h"
35 #include "llvm/IR/Function.h"
36 #include "llvm/Support/CommandLine.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/Support/ErrorHandling.h"
39 #include "llvm/Support/raw_ostream.h"
40 #include "llvm/Target/TargetMachine.h"
41 #include <cassert>
42 #include <iterator>
43 #include <utility>
44 
45 using namespace llvm;
46 
47 #define DEBUG_TYPE "tailduplication"
48 
49 STATISTIC(NumTails, "Number of tails duplicated");
50 STATISTIC(NumTailDups, "Number of tail duplicated blocks");
51 STATISTIC(NumTailDupAdded,
52           "Number of instructions added due to tail duplication");
53 STATISTIC(NumTailDupRemoved,
54           "Number of instructions removed due to tail duplication");
55 STATISTIC(NumDeadBlocks, "Number of dead blocks removed");
56 STATISTIC(NumAddedPHIs, "Number of phis added");
57 
58 // Heuristic for tail duplication.
59 static cl::opt<unsigned> TailDuplicateSize(
60     "tail-dup-size",
61     cl::desc("Maximum instructions to consider tail duplicating"), cl::init(2),
62     cl::Hidden);
63 
64 static cl::opt<unsigned> TailDupIndirectBranchSize(
65     "tail-dup-indirect-size",
66     cl::desc("Maximum instructions to consider tail duplicating blocks that "
67              "end with indirect branches."), cl::init(20),
68     cl::Hidden);
69 
70 static cl::opt<unsigned>
71     TailDupPredSize("tail-dup-pred-size",
72                     cl::desc("Maximum predecessors (maximum successors at the "
73                              "same time) to consider tail duplicating blocks."),
74                     cl::init(16), cl::Hidden);
75 
76 static cl::opt<unsigned>
77     TailDupSuccSize("tail-dup-succ-size",
78                     cl::desc("Maximum successors (maximum predecessors at the "
79                              "same time) to consider tail duplicating blocks."),
80                     cl::init(16), cl::Hidden);
81 
82 static cl::opt<bool>
83     TailDupVerify("tail-dup-verify",
84                   cl::desc("Verify sanity of PHI instructions during taildup"),
85                   cl::init(false), cl::Hidden);
86 
87 static cl::opt<unsigned> TailDupLimit("tail-dup-limit", cl::init(~0U),
88                                       cl::Hidden);
89 
90 void TailDuplicator::initMF(MachineFunction &MFin, bool PreRegAlloc,
91                             const MachineBranchProbabilityInfo *MBPIin,
92                             MBFIWrapper *MBFIin,
93                             ProfileSummaryInfo *PSIin,
94                             bool LayoutModeIn, unsigned TailDupSizeIn) {
95   MF = &MFin;
96   TII = MF->getSubtarget().getInstrInfo();
97   TRI = MF->getSubtarget().getRegisterInfo();
98   MRI = &MF->getRegInfo();
99   MBPI = MBPIin;
100   MBFI = MBFIin;
101   PSI = PSIin;
102   TailDupSize = TailDupSizeIn;
103 
104   assert(MBPI != nullptr && "Machine Branch Probability Info required");
105 
106   LayoutMode = LayoutModeIn;
107   this->PreRegAlloc = PreRegAlloc;
108 }
109 
110 static void VerifyPHIs(MachineFunction &MF, bool CheckExtra) {
111   for (MachineBasicBlock &MBB : llvm::drop_begin(MF)) {
112     SmallSetVector<MachineBasicBlock *, 8> Preds(MBB.pred_begin(),
113                                                  MBB.pred_end());
114     MachineBasicBlock::iterator MI = MBB.begin();
115     while (MI != MBB.end()) {
116       if (!MI->isPHI())
117         break;
118       for (MachineBasicBlock *PredBB : Preds) {
119         bool Found = false;
120         for (unsigned i = 1, e = MI->getNumOperands(); i != e; i += 2) {
121           MachineBasicBlock *PHIBB = MI->getOperand(i + 1).getMBB();
122           if (PHIBB == PredBB) {
123             Found = true;
124             break;
125           }
126         }
127         if (!Found) {
128           dbgs() << "Malformed PHI in " << printMBBReference(MBB) << ": "
129                  << *MI;
130           dbgs() << "  missing input from predecessor "
131                  << printMBBReference(*PredBB) << '\n';
132           llvm_unreachable(nullptr);
133         }
134       }
135 
136       for (unsigned i = 1, e = MI->getNumOperands(); i != e; i += 2) {
137         MachineBasicBlock *PHIBB = MI->getOperand(i + 1).getMBB();
138         if (CheckExtra && !Preds.count(PHIBB)) {
139           dbgs() << "Warning: malformed PHI in " << printMBBReference(MBB)
140                  << ": " << *MI;
141           dbgs() << "  extra input from predecessor "
142                  << printMBBReference(*PHIBB) << '\n';
143           llvm_unreachable(nullptr);
144         }
145         if (PHIBB->getNumber() < 0) {
146           dbgs() << "Malformed PHI in " << printMBBReference(MBB) << ": "
147                  << *MI;
148           dbgs() << "  non-existing " << printMBBReference(*PHIBB) << '\n';
149           llvm_unreachable(nullptr);
150         }
151       }
152       ++MI;
153     }
154   }
155 }
156 
157 /// Tail duplicate the block and cleanup.
158 /// \p IsSimple - return value of isSimpleBB
159 /// \p MBB - block to be duplicated
160 /// \p ForcedLayoutPred - If non-null, treat this block as the layout
161 ///     predecessor, instead of using the ordering in MF
162 /// \p DuplicatedPreds - if non-null, \p DuplicatedPreds will contain a list of
163 ///     all Preds that received a copy of \p MBB.
164 /// \p RemovalCallback - if non-null, called just before MBB is deleted.
165 bool TailDuplicator::tailDuplicateAndUpdate(
166     bool IsSimple, MachineBasicBlock *MBB,
167     MachineBasicBlock *ForcedLayoutPred,
168     SmallVectorImpl<MachineBasicBlock*> *DuplicatedPreds,
169     function_ref<void(MachineBasicBlock *)> *RemovalCallback,
170     SmallVectorImpl<MachineBasicBlock *> *CandidatePtr) {
171   // Save the successors list.
172   SmallSetVector<MachineBasicBlock *, 8> Succs(MBB->succ_begin(),
173                                                MBB->succ_end());
174 
175   SmallVector<MachineBasicBlock *, 8> TDBBs;
176   SmallVector<MachineInstr *, 16> Copies;
177   if (!tailDuplicate(IsSimple, MBB, ForcedLayoutPred,
178                      TDBBs, Copies, CandidatePtr))
179     return false;
180 
181   ++NumTails;
182 
183   SmallVector<MachineInstr *, 8> NewPHIs;
184   MachineSSAUpdater SSAUpdate(*MF, &NewPHIs);
185 
186   // TailBB's immediate successors are now successors of those predecessors
187   // which duplicated TailBB. Add the predecessors as sources to the PHI
188   // instructions.
189   bool isDead = MBB->pred_empty() && !MBB->hasAddressTaken();
190   if (PreRegAlloc)
191     updateSuccessorsPHIs(MBB, isDead, TDBBs, Succs);
192 
193   // If it is dead, remove it.
194   if (isDead) {
195     NumTailDupRemoved += MBB->size();
196     removeDeadBlock(MBB, RemovalCallback);
197     ++NumDeadBlocks;
198   }
199 
200   // Update SSA form.
201   if (!SSAUpdateVRs.empty()) {
202     for (Register VReg : SSAUpdateVRs) {
203       SSAUpdate.Initialize(VReg);
204 
205       // If the original definition is still around, add it as an available
206       // value.
207       MachineInstr *DefMI = MRI->getVRegDef(VReg);
208       MachineBasicBlock *DefBB = nullptr;
209       if (DefMI) {
210         DefBB = DefMI->getParent();
211         SSAUpdate.AddAvailableValue(DefBB, VReg);
212       }
213 
214       // Add the new vregs as available values.
215       DenseMap<Register, AvailableValsTy>::iterator LI =
216           SSAUpdateVals.find(VReg);
217       for (std::pair<MachineBasicBlock *, Register> &J : LI->second) {
218         MachineBasicBlock *SrcBB = J.first;
219         Register SrcReg = J.second;
220         SSAUpdate.AddAvailableValue(SrcBB, SrcReg);
221       }
222 
223       SmallVector<MachineOperand *> DebugUses;
224       // Rewrite uses that are outside of the original def's block.
225       for (MachineOperand &UseMO :
226            llvm::make_early_inc_range(MRI->use_operands(VReg))) {
227         MachineInstr *UseMI = UseMO.getParent();
228         // Rewrite debug uses last so that they can take advantage of any
229         // register mappings introduced by other users in its BB, since we
230         // cannot create new register definitions specifically for the debug
231         // instruction (as debug instructions should not affect CodeGen).
232         if (UseMI->isDebugValue()) {
233           DebugUses.push_back(&UseMO);
234           continue;
235         }
236         if (UseMI->getParent() == DefBB && !UseMI->isPHI())
237           continue;
238         SSAUpdate.RewriteUse(UseMO);
239       }
240       for (auto *UseMO : DebugUses) {
241         MachineInstr *UseMI = UseMO->getParent();
242         UseMO->setReg(
243             SSAUpdate.GetValueInMiddleOfBlock(UseMI->getParent(), true));
244       }
245     }
246 
247     SSAUpdateVRs.clear();
248     SSAUpdateVals.clear();
249   }
250 
251   // Eliminate some of the copies inserted by tail duplication to maintain
252   // SSA form.
253   for (MachineInstr *Copy : Copies) {
254     if (!Copy->isCopy())
255       continue;
256     Register Dst = Copy->getOperand(0).getReg();
257     Register Src = Copy->getOperand(1).getReg();
258     if (MRI->hasOneNonDBGUse(Src) &&
259         MRI->constrainRegClass(Src, MRI->getRegClass(Dst))) {
260       // Copy is the only use. Do trivial copy propagation here.
261       MRI->replaceRegWith(Dst, Src);
262       Copy->eraseFromParent();
263     }
264   }
265 
266   if (NewPHIs.size())
267     NumAddedPHIs += NewPHIs.size();
268 
269   if (DuplicatedPreds)
270     *DuplicatedPreds = std::move(TDBBs);
271 
272   return true;
273 }
274 
275 /// Look for small blocks that are unconditionally branched to and do not fall
276 /// through. Tail-duplicate their instructions into their predecessors to
277 /// eliminate (dynamic) branches.
278 bool TailDuplicator::tailDuplicateBlocks() {
279   bool MadeChange = false;
280 
281   if (PreRegAlloc && TailDupVerify) {
282     LLVM_DEBUG(dbgs() << "\n*** Before tail-duplicating\n");
283     VerifyPHIs(*MF, true);
284   }
285 
286   for (MachineBasicBlock &MBB :
287        llvm::make_early_inc_range(llvm::drop_begin(*MF))) {
288     if (NumTails == TailDupLimit)
289       break;
290 
291     bool IsSimple = isSimpleBB(&MBB);
292 
293     if (!shouldTailDuplicate(IsSimple, MBB))
294       continue;
295 
296     MadeChange |= tailDuplicateAndUpdate(IsSimple, &MBB, nullptr);
297   }
298 
299   if (PreRegAlloc && TailDupVerify)
300     VerifyPHIs(*MF, false);
301 
302   return MadeChange;
303 }
304 
305 static bool isDefLiveOut(Register Reg, MachineBasicBlock *BB,
306                          const MachineRegisterInfo *MRI) {
307   for (MachineInstr &UseMI : MRI->use_instructions(Reg)) {
308     if (UseMI.isDebugValue())
309       continue;
310     if (UseMI.getParent() != BB)
311       return true;
312   }
313   return false;
314 }
315 
316 static unsigned getPHISrcRegOpIdx(MachineInstr *MI, MachineBasicBlock *SrcBB) {
317   for (unsigned i = 1, e = MI->getNumOperands(); i != e; i += 2)
318     if (MI->getOperand(i + 1).getMBB() == SrcBB)
319       return i;
320   return 0;
321 }
322 
323 // Remember which registers are used by phis in this block. This is
324 // used to determine which registers are liveout while modifying the
325 // block (which is why we need to copy the information).
326 static void getRegsUsedByPHIs(const MachineBasicBlock &BB,
327                               DenseSet<Register> *UsedByPhi) {
328   for (const auto &MI : BB) {
329     if (!MI.isPHI())
330       break;
331     for (unsigned i = 1, e = MI.getNumOperands(); i != e; i += 2) {
332       Register SrcReg = MI.getOperand(i).getReg();
333       UsedByPhi->insert(SrcReg);
334     }
335   }
336 }
337 
338 /// Add a definition and source virtual registers pair for SSA update.
339 void TailDuplicator::addSSAUpdateEntry(Register OrigReg, Register NewReg,
340                                        MachineBasicBlock *BB) {
341   DenseMap<Register, AvailableValsTy>::iterator LI =
342       SSAUpdateVals.find(OrigReg);
343   if (LI != SSAUpdateVals.end())
344     LI->second.push_back(std::make_pair(BB, NewReg));
345   else {
346     AvailableValsTy Vals;
347     Vals.push_back(std::make_pair(BB, NewReg));
348     SSAUpdateVals.insert(std::make_pair(OrigReg, Vals));
349     SSAUpdateVRs.push_back(OrigReg);
350   }
351 }
352 
353 /// Process PHI node in TailBB by turning it into a copy in PredBB. Remember the
354 /// source register that's contributed by PredBB and update SSA update map.
355 void TailDuplicator::processPHI(
356     MachineInstr *MI, MachineBasicBlock *TailBB, MachineBasicBlock *PredBB,
357     DenseMap<Register, RegSubRegPair> &LocalVRMap,
358     SmallVectorImpl<std::pair<Register, RegSubRegPair>> &Copies,
359     const DenseSet<Register> &RegsUsedByPhi, bool Remove) {
360   Register DefReg = MI->getOperand(0).getReg();
361   unsigned SrcOpIdx = getPHISrcRegOpIdx(MI, PredBB);
362   assert(SrcOpIdx && "Unable to find matching PHI source?");
363   Register SrcReg = MI->getOperand(SrcOpIdx).getReg();
364   unsigned SrcSubReg = MI->getOperand(SrcOpIdx).getSubReg();
365   const TargetRegisterClass *RC = MRI->getRegClass(DefReg);
366   LocalVRMap.insert(std::make_pair(DefReg, RegSubRegPair(SrcReg, SrcSubReg)));
367 
368   // Insert a copy from source to the end of the block. The def register is the
369   // available value liveout of the block.
370   Register NewDef = MRI->createVirtualRegister(RC);
371   Copies.push_back(std::make_pair(NewDef, RegSubRegPair(SrcReg, SrcSubReg)));
372   if (isDefLiveOut(DefReg, TailBB, MRI) || RegsUsedByPhi.count(DefReg))
373     addSSAUpdateEntry(DefReg, NewDef, PredBB);
374 
375   if (!Remove)
376     return;
377 
378   // Remove PredBB from the PHI node.
379   MI->removeOperand(SrcOpIdx + 1);
380   MI->removeOperand(SrcOpIdx);
381   if (MI->getNumOperands() == 1 && !TailBB->hasAddressTaken())
382     MI->eraseFromParent();
383   else if (MI->getNumOperands() == 1)
384     MI->setDesc(TII->get(TargetOpcode::IMPLICIT_DEF));
385 }
386 
387 /// Duplicate a TailBB instruction to PredBB and update
388 /// the source operands due to earlier PHI translation.
389 void TailDuplicator::duplicateInstruction(
390     MachineInstr *MI, MachineBasicBlock *TailBB, MachineBasicBlock *PredBB,
391     DenseMap<Register, RegSubRegPair> &LocalVRMap,
392     const DenseSet<Register> &UsedByPhi) {
393   // Allow duplication of CFI instructions.
394   if (MI->isCFIInstruction()) {
395     BuildMI(*PredBB, PredBB->end(), PredBB->findDebugLoc(PredBB->begin()),
396             TII->get(TargetOpcode::CFI_INSTRUCTION))
397         .addCFIIndex(MI->getOperand(0).getCFIIndex())
398         .setMIFlags(MI->getFlags());
399     return;
400   }
401   MachineInstr &NewMI = TII->duplicate(*PredBB, PredBB->end(), *MI);
402   if (!PreRegAlloc)
403     return;
404   for (unsigned i = 0, e = NewMI.getNumOperands(); i != e; ++i) {
405     MachineOperand &MO = NewMI.getOperand(i);
406     if (!MO.isReg())
407       continue;
408     Register Reg = MO.getReg();
409     if (!Reg.isVirtual())
410       continue;
411     if (MO.isDef()) {
412       const TargetRegisterClass *RC = MRI->getRegClass(Reg);
413       Register NewReg = MRI->createVirtualRegister(RC);
414       MO.setReg(NewReg);
415       LocalVRMap.insert(std::make_pair(Reg, RegSubRegPair(NewReg, 0)));
416       if (isDefLiveOut(Reg, TailBB, MRI) || UsedByPhi.count(Reg))
417         addSSAUpdateEntry(Reg, NewReg, PredBB);
418       continue;
419     }
420     auto VI = LocalVRMap.find(Reg);
421     if (VI == LocalVRMap.end())
422       continue;
423     // Need to make sure that the register class of the mapped register
424     // will satisfy the constraints of the class of the register being
425     // replaced.
426     auto *OrigRC = MRI->getRegClass(Reg);
427     auto *MappedRC = MRI->getRegClass(VI->second.Reg);
428     const TargetRegisterClass *ConstrRC;
429     if (VI->second.SubReg != 0) {
430       ConstrRC =
431           TRI->getMatchingSuperRegClass(MappedRC, OrigRC, VI->second.SubReg);
432       if (ConstrRC) {
433         // The actual constraining (as in "find appropriate new class")
434         // is done by getMatchingSuperRegClass, so now we only need to
435         // change the class of the mapped register.
436         MRI->setRegClass(VI->second.Reg, ConstrRC);
437       }
438     } else {
439       // For mapped registers that do not have sub-registers, simply
440       // restrict their class to match the original one.
441 
442       // We don't want debug instructions affecting the resulting code so
443       // if we're cloning a debug instruction then just use MappedRC
444       // rather than constraining the register class further.
445       ConstrRC = NewMI.isDebugInstr()
446                      ? MappedRC
447                      : MRI->constrainRegClass(VI->second.Reg, OrigRC);
448     }
449 
450     if (ConstrRC) {
451       // If the class constraining succeeded, we can simply replace
452       // the old register with the mapped one.
453       MO.setReg(VI->second.Reg);
454       // We have Reg -> VI.Reg:VI.SubReg, so if Reg is used with a
455       // sub-register, we need to compose the sub-register indices.
456       MO.setSubReg(
457           TRI->composeSubRegIndices(VI->second.SubReg, MO.getSubReg()));
458     } else {
459       // The direct replacement is not possible, due to failing register
460       // class constraints. An explicit COPY is necessary. Create one
461       // that can be reused.
462       Register NewReg = MRI->createVirtualRegister(OrigRC);
463       BuildMI(*PredBB, NewMI, NewMI.getDebugLoc(), TII->get(TargetOpcode::COPY),
464               NewReg)
465           .addReg(VI->second.Reg, 0, VI->second.SubReg);
466       LocalVRMap.erase(VI);
467       LocalVRMap.insert(std::make_pair(Reg, RegSubRegPair(NewReg, 0)));
468       MO.setReg(NewReg);
469       // The composed VI.Reg:VI.SubReg is replaced with NewReg, which
470       // is equivalent to the whole register Reg. Hence, Reg:subreg
471       // is same as NewReg:subreg, so keep the sub-register index
472       // unchanged.
473     }
474     // Clear any kill flags from this operand.  The new register could
475     // have uses after this one, so kills are not valid here.
476     MO.setIsKill(false);
477   }
478 }
479 
480 /// After FromBB is tail duplicated into its predecessor blocks, the successors
481 /// have gained new predecessors. Update the PHI instructions in them
482 /// accordingly.
483 void TailDuplicator::updateSuccessorsPHIs(
484     MachineBasicBlock *FromBB, bool isDead,
485     SmallVectorImpl<MachineBasicBlock *> &TDBBs,
486     SmallSetVector<MachineBasicBlock *, 8> &Succs) {
487   for (MachineBasicBlock *SuccBB : Succs) {
488     for (MachineInstr &MI : *SuccBB) {
489       if (!MI.isPHI())
490         break;
491       MachineInstrBuilder MIB(*FromBB->getParent(), MI);
492       unsigned Idx = 0;
493       for (unsigned i = 1, e = MI.getNumOperands(); i != e; i += 2) {
494         MachineOperand &MO = MI.getOperand(i + 1);
495         if (MO.getMBB() == FromBB) {
496           Idx = i;
497           break;
498         }
499       }
500 
501       assert(Idx != 0);
502       MachineOperand &MO0 = MI.getOperand(Idx);
503       Register Reg = MO0.getReg();
504       if (isDead) {
505         // Folded into the previous BB.
506         // There could be duplicate phi source entries. FIXME: Should sdisel
507         // or earlier pass fixed this?
508         for (unsigned i = MI.getNumOperands() - 2; i != Idx; i -= 2) {
509           MachineOperand &MO = MI.getOperand(i + 1);
510           if (MO.getMBB() == FromBB) {
511             MI.removeOperand(i + 1);
512             MI.removeOperand(i);
513           }
514         }
515       } else
516         Idx = 0;
517 
518       // If Idx is set, the operands at Idx and Idx+1 must be removed.
519       // We reuse the location to avoid expensive removeOperand calls.
520 
521       DenseMap<Register, AvailableValsTy>::iterator LI =
522           SSAUpdateVals.find(Reg);
523       if (LI != SSAUpdateVals.end()) {
524         // This register is defined in the tail block.
525         for (const std::pair<MachineBasicBlock *, Register> &J : LI->second) {
526           MachineBasicBlock *SrcBB = J.first;
527           // If we didn't duplicate a bb into a particular predecessor, we
528           // might still have added an entry to SSAUpdateVals to correcly
529           // recompute SSA. If that case, avoid adding a dummy extra argument
530           // this PHI.
531           if (!SrcBB->isSuccessor(SuccBB))
532             continue;
533 
534           Register SrcReg = J.second;
535           if (Idx != 0) {
536             MI.getOperand(Idx).setReg(SrcReg);
537             MI.getOperand(Idx + 1).setMBB(SrcBB);
538             Idx = 0;
539           } else {
540             MIB.addReg(SrcReg).addMBB(SrcBB);
541           }
542         }
543       } else {
544         // Live in tail block, must also be live in predecessors.
545         for (MachineBasicBlock *SrcBB : TDBBs) {
546           if (Idx != 0) {
547             MI.getOperand(Idx).setReg(Reg);
548             MI.getOperand(Idx + 1).setMBB(SrcBB);
549             Idx = 0;
550           } else {
551             MIB.addReg(Reg).addMBB(SrcBB);
552           }
553         }
554       }
555       if (Idx != 0) {
556         MI.removeOperand(Idx + 1);
557         MI.removeOperand(Idx);
558       }
559     }
560   }
561 }
562 
563 /// Determine if it is profitable to duplicate this block.
564 bool TailDuplicator::shouldTailDuplicate(bool IsSimple,
565                                          MachineBasicBlock &TailBB) {
566   // When doing tail-duplication during layout, the block ordering is in flux,
567   // so canFallThrough returns a result based on incorrect information and
568   // should just be ignored.
569   if (!LayoutMode && TailBB.canFallThrough())
570     return false;
571 
572   // Don't try to tail-duplicate single-block loops.
573   if (TailBB.isSuccessor(&TailBB))
574     return false;
575 
576   // Set the limit on the cost to duplicate. When optimizing for size,
577   // duplicate only one, because one branch instruction can be eliminated to
578   // compensate for the duplication.
579   unsigned MaxDuplicateCount;
580   if (TailDupSize == 0)
581     MaxDuplicateCount = TailDuplicateSize;
582   else
583     MaxDuplicateCount = TailDupSize;
584   if (llvm::shouldOptimizeForSize(&TailBB, PSI, MBFI))
585     MaxDuplicateCount = 1;
586 
587   // If the block to be duplicated ends in an unanalyzable fallthrough, don't
588   // duplicate it.
589   // A similar check is necessary in MachineBlockPlacement to make sure pairs of
590   // blocks with unanalyzable fallthrough get layed out contiguously.
591   MachineBasicBlock *PredTBB = nullptr, *PredFBB = nullptr;
592   SmallVector<MachineOperand, 4> PredCond;
593   if (TII->analyzeBranch(TailBB, PredTBB, PredFBB, PredCond) &&
594       TailBB.canFallThrough())
595     return false;
596 
597   // If the target has hardware branch prediction that can handle indirect
598   // branches, duplicating them can often make them predictable when there
599   // are common paths through the code.  The limit needs to be high enough
600   // to allow undoing the effects of tail merging and other optimizations
601   // that rearrange the predecessors of the indirect branch.
602 
603   bool HasIndirectbr = false;
604   bool HasComputedGoto = false;
605   if (!TailBB.empty()) {
606     HasIndirectbr = TailBB.back().isIndirectBranch();
607     HasComputedGoto = TailBB.terminatorIsComputedGoto();
608   }
609 
610   if (HasIndirectbr && PreRegAlloc)
611     MaxDuplicateCount = TailDupIndirectBranchSize;
612 
613   // Check the instructions in the block to determine whether tail-duplication
614   // is invalid or unlikely to be profitable.
615   unsigned InstrCount = 0;
616   unsigned NumPhis = 0;
617   for (MachineInstr &MI : TailBB) {
618     // Non-duplicable things shouldn't be tail-duplicated.
619     // CFI instructions are marked as non-duplicable, because Darwin compact
620     // unwind info emission can't handle multiple prologue setups. In case of
621     // DWARF, allow them be duplicated, so that their existence doesn't prevent
622     // tail duplication of some basic blocks, that would be duplicated otherwise.
623     if (MI.isNotDuplicable() &&
624         (TailBB.getParent()->getTarget().getTargetTriple().isOSDarwin() ||
625         !MI.isCFIInstruction()))
626       return false;
627 
628     // Convergent instructions can be duplicated only if doing so doesn't add
629     // new control dependencies, which is what we're going to do here.
630     if (MI.isConvergent())
631       return false;
632 
633     // Do not duplicate 'return' instructions if this is a pre-regalloc run.
634     // A return may expand into a lot more instructions (e.g. reload of callee
635     // saved registers) after PEI.
636     if (PreRegAlloc && MI.isReturn())
637       return false;
638 
639     // Avoid duplicating calls before register allocation. Calls presents a
640     // barrier to register allocation so duplicating them may end up increasing
641     // spills.
642     if (PreRegAlloc && MI.isCall())
643       return false;
644 
645     // TailDuplicator::appendCopies will erroneously place COPYs after
646     // INLINEASM_BR instructions after 4b0aa5724fea, which demonstrates the same
647     // bug that was fixed in f7a53d82c090.
648     // FIXME: Use findPHICopyInsertPoint() to find the correct insertion point
649     //        for the COPY when replacing PHIs.
650     if (MI.getOpcode() == TargetOpcode::INLINEASM_BR)
651       return false;
652 
653     if (MI.isBundle())
654       InstrCount += MI.getBundleSize();
655     else if (!MI.isPHI() && !MI.isMetaInstruction())
656       InstrCount += 1;
657 
658     if (InstrCount > MaxDuplicateCount)
659       return false;
660     NumPhis += MI.isPHI();
661   }
662 
663   // Duplicating a BB which has both multiple predecessors and successors will
664   // may cause huge amount of PHI nodes. If we want to remove this limitation,
665   // we have to address https://github.com/llvm/llvm-project/issues/78578.
666   // NB. This basically unfactors computed gotos that were factored early on in
667   // the compilation process to speed up edge based data flow. If we do not
668   // unfactor them again, it can seriously pessimize code with many computed
669   // jumps in the source code, such as interpreters. Therefore we do not
670   // restrict the computed gotos.
671   if (!HasComputedGoto && TailBB.pred_size() > TailDupPredSize &&
672       TailBB.succ_size() > TailDupSuccSize) {
673     // If TailBB or any of its successors contains a phi, we may have to add a
674     // large number of additional phis with additional incoming values.
675     if (NumPhis != 0 || any_of(TailBB.successors(), [](MachineBasicBlock *MBB) {
676           return any_of(*MBB, [](MachineInstr &MI) { return MI.isPHI(); });
677         }))
678       return false;
679   }
680 
681   // Check if any of the successors of TailBB has a PHI node in which the
682   // value corresponding to TailBB uses a subregister.
683   // If a phi node uses a register paired with a subregister, the actual
684   // "value type" of the phi may differ from the type of the register without
685   // any subregisters. Due to a bug, tail duplication may add a new operand
686   // without a necessary subregister, producing an invalid code. This is
687   // demonstrated by test/CodeGen/Hexagon/tail-dup-subreg-abort.ll.
688   // Disable tail duplication for this case for now, until the problem is
689   // fixed.
690   for (auto *SB : TailBB.successors()) {
691     for (auto &I : *SB) {
692       if (!I.isPHI())
693         break;
694       unsigned Idx = getPHISrcRegOpIdx(&I, &TailBB);
695       assert(Idx != 0);
696       MachineOperand &PU = I.getOperand(Idx);
697       if (PU.getSubReg() != 0)
698         return false;
699     }
700   }
701 
702   if (HasIndirectbr && PreRegAlloc)
703     return true;
704 
705   if (IsSimple)
706     return true;
707 
708   if (!PreRegAlloc)
709     return true;
710 
711   return canCompletelyDuplicateBB(TailBB);
712 }
713 
714 /// True if this BB has only one unconditional jump.
715 bool TailDuplicator::isSimpleBB(MachineBasicBlock *TailBB) {
716   if (TailBB->succ_size() != 1)
717     return false;
718   if (TailBB->pred_empty())
719     return false;
720   MachineBasicBlock::iterator I = TailBB->getFirstNonDebugInstr(true);
721   if (I == TailBB->end())
722     return true;
723   return I->isUnconditionalBranch();
724 }
725 
726 static bool bothUsedInPHI(const MachineBasicBlock &A,
727                           const SmallPtrSet<MachineBasicBlock *, 8> &SuccsB) {
728   for (MachineBasicBlock *BB : A.successors())
729     if (SuccsB.count(BB) && !BB->empty() && BB->begin()->isPHI())
730       return true;
731 
732   return false;
733 }
734 
735 bool TailDuplicator::canCompletelyDuplicateBB(MachineBasicBlock &BB) {
736   for (MachineBasicBlock *PredBB : BB.predecessors()) {
737     if (PredBB->succ_size() > 1)
738       return false;
739 
740     MachineBasicBlock *PredTBB = nullptr, *PredFBB = nullptr;
741     SmallVector<MachineOperand, 4> PredCond;
742     if (TII->analyzeBranch(*PredBB, PredTBB, PredFBB, PredCond))
743       return false;
744 
745     if (!PredCond.empty())
746       return false;
747   }
748   return true;
749 }
750 
751 bool TailDuplicator::duplicateSimpleBB(
752     MachineBasicBlock *TailBB, SmallVectorImpl<MachineBasicBlock *> &TDBBs,
753     const DenseSet<Register> &UsedByPhi) {
754   SmallPtrSet<MachineBasicBlock *, 8> Succs(llvm::from_range,
755                                             TailBB->successors());
756   SmallVector<MachineBasicBlock *, 8> Preds(TailBB->predecessors());
757   bool Changed = false;
758   for (MachineBasicBlock *PredBB : Preds) {
759     if (PredBB->hasEHPadSuccessor() || PredBB->mayHaveInlineAsmBr())
760       continue;
761 
762     if (bothUsedInPHI(*PredBB, Succs))
763       continue;
764 
765     MachineBasicBlock *PredTBB = nullptr, *PredFBB = nullptr;
766     SmallVector<MachineOperand, 4> PredCond;
767     if (TII->analyzeBranch(*PredBB, PredTBB, PredFBB, PredCond))
768       continue;
769 
770     Changed = true;
771     LLVM_DEBUG(dbgs() << "\nTail-duplicating into PredBB: " << *PredBB
772                       << "From simple Succ: " << *TailBB);
773 
774     MachineBasicBlock *NewTarget = *TailBB->succ_begin();
775     MachineBasicBlock *NextBB = PredBB->getNextNode();
776 
777     // Make PredFBB explicit.
778     if (PredCond.empty())
779       PredFBB = PredTBB;
780 
781     // Make fall through explicit.
782     if (!PredTBB)
783       PredTBB = NextBB;
784     if (!PredFBB)
785       PredFBB = NextBB;
786 
787     // Redirect
788     if (PredFBB == TailBB)
789       PredFBB = NewTarget;
790     if (PredTBB == TailBB)
791       PredTBB = NewTarget;
792 
793     // Make the branch unconditional if possible
794     if (PredTBB == PredFBB) {
795       PredCond.clear();
796       PredFBB = nullptr;
797     }
798 
799     // Avoid adding fall through branches.
800     if (PredFBB == NextBB)
801       PredFBB = nullptr;
802     if (PredTBB == NextBB && PredFBB == nullptr)
803       PredTBB = nullptr;
804 
805     auto DL = PredBB->findBranchDebugLoc();
806     TII->removeBranch(*PredBB);
807 
808     if (!PredBB->isSuccessor(NewTarget))
809       PredBB->replaceSuccessor(TailBB, NewTarget);
810     else {
811       PredBB->removeSuccessor(TailBB, true);
812       assert(PredBB->succ_size() <= 1);
813     }
814 
815     if (PredTBB)
816       TII->insertBranch(*PredBB, PredTBB, PredFBB, PredCond, DL);
817 
818     TDBBs.push_back(PredBB);
819   }
820   return Changed;
821 }
822 
823 bool TailDuplicator::canTailDuplicate(MachineBasicBlock *TailBB,
824                                       MachineBasicBlock *PredBB) {
825   // EH edges are ignored by analyzeBranch.
826   if (PredBB->succ_size() > 1)
827     return false;
828 
829   MachineBasicBlock *PredTBB = nullptr, *PredFBB = nullptr;
830   SmallVector<MachineOperand, 4> PredCond;
831   if (TII->analyzeBranch(*PredBB, PredTBB, PredFBB, PredCond))
832     return false;
833   if (!PredCond.empty())
834     return false;
835   // FIXME: This is overly conservative; it may be ok to relax this in the
836   // future under more specific conditions. If TailBB is an INLINEASM_BR
837   // indirect target, we need to see if the edge from PredBB to TailBB is from
838   // an INLINEASM_BR in PredBB, and then also if that edge was from the
839   // indirect target list, fallthrough/default target, or potentially both. If
840   // it's both, TailDuplicator::tailDuplicate will remove the edge, corrupting
841   // the successor list in PredBB and predecessor list in TailBB.
842   if (TailBB->isInlineAsmBrIndirectTarget())
843     return false;
844   return true;
845 }
846 
847 /// If it is profitable, duplicate TailBB's contents in each
848 /// of its predecessors.
849 /// \p IsSimple result of isSimpleBB
850 /// \p TailBB   Block to be duplicated.
851 /// \p ForcedLayoutPred  When non-null, use this block as the layout predecessor
852 ///                      instead of the previous block in MF's order.
853 /// \p TDBBs             A vector to keep track of all blocks tail-duplicated
854 ///                      into.
855 /// \p Copies            A vector of copy instructions inserted. Used later to
856 ///                      walk all the inserted copies and remove redundant ones.
857 bool TailDuplicator::tailDuplicate(bool IsSimple, MachineBasicBlock *TailBB,
858                           MachineBasicBlock *ForcedLayoutPred,
859                           SmallVectorImpl<MachineBasicBlock *> &TDBBs,
860                           SmallVectorImpl<MachineInstr *> &Copies,
861                           SmallVectorImpl<MachineBasicBlock *> *CandidatePtr) {
862   LLVM_DEBUG(dbgs() << "\n*** Tail-duplicating " << printMBBReference(*TailBB)
863                     << '\n');
864 
865   bool ShouldUpdateTerminators = TailBB->canFallThrough();
866 
867   DenseSet<Register> UsedByPhi;
868   getRegsUsedByPHIs(*TailBB, &UsedByPhi);
869 
870   if (IsSimple)
871     return duplicateSimpleBB(TailBB, TDBBs, UsedByPhi);
872 
873   // Iterate through all the unique predecessors and tail-duplicate this
874   // block into them, if possible. Copying the list ahead of time also
875   // avoids trouble with the predecessor list reallocating.
876   bool Changed = false;
877   SmallSetVector<MachineBasicBlock *, 8> Preds;
878   if (CandidatePtr)
879     Preds.insert_range(*CandidatePtr);
880   else
881     Preds.insert_range(TailBB->predecessors());
882 
883   for (MachineBasicBlock *PredBB : Preds) {
884     assert(TailBB != PredBB &&
885            "Single-block loop should have been rejected earlier!");
886 
887     if (!canTailDuplicate(TailBB, PredBB))
888       continue;
889 
890     // Don't duplicate into a fall-through predecessor (at least for now).
891     // If profile is available, findDuplicateCandidates can choose better
892     // fall-through predecessor.
893     if (!(MF->getFunction().hasProfileData() && LayoutMode)) {
894       bool IsLayoutSuccessor = false;
895       if (ForcedLayoutPred)
896         IsLayoutSuccessor = (ForcedLayoutPred == PredBB);
897       else if (PredBB->isLayoutSuccessor(TailBB) && PredBB->canFallThrough())
898         IsLayoutSuccessor = true;
899       if (IsLayoutSuccessor)
900         continue;
901     }
902 
903     LLVM_DEBUG(dbgs() << "\nTail-duplicating into PredBB: " << *PredBB
904                       << "From Succ: " << *TailBB);
905 
906     TDBBs.push_back(PredBB);
907 
908     // Remove PredBB's unconditional branch.
909     TII->removeBranch(*PredBB);
910 
911     // Clone the contents of TailBB into PredBB.
912     DenseMap<Register, RegSubRegPair> LocalVRMap;
913     SmallVector<std::pair<Register, RegSubRegPair>, 4> CopyInfos;
914     for (MachineInstr &MI : llvm::make_early_inc_range(*TailBB)) {
915       if (MI.isPHI()) {
916         // Replace the uses of the def of the PHI with the register coming
917         // from PredBB.
918         processPHI(&MI, TailBB, PredBB, LocalVRMap, CopyInfos, UsedByPhi, true);
919       } else {
920         // Replace def of virtual registers with new registers, and update
921         // uses with PHI source register or the new registers.
922         duplicateInstruction(&MI, TailBB, PredBB, LocalVRMap, UsedByPhi);
923       }
924     }
925     appendCopies(PredBB, CopyInfos, Copies);
926 
927     NumTailDupAdded += TailBB->size() - 1; // subtract one for removed branch
928 
929     // Update the CFG.
930     PredBB->removeSuccessor(PredBB->succ_begin());
931     assert(PredBB->succ_empty() &&
932            "TailDuplicate called on block with multiple successors!");
933     for (MachineBasicBlock *Succ : TailBB->successors())
934       PredBB->addSuccessor(Succ, MBPI->getEdgeProbability(TailBB, Succ));
935 
936     // Update branches in pred to jump to tail's layout successor if needed.
937     if (ShouldUpdateTerminators)
938       PredBB->updateTerminator(TailBB->getNextNode());
939 
940     Changed = true;
941     ++NumTailDups;
942   }
943 
944   // If TailBB was duplicated into all its predecessors except for the prior
945   // block, which falls through unconditionally, move the contents of this
946   // block into the prior block.
947   MachineBasicBlock *PrevBB = ForcedLayoutPred;
948   if (!PrevBB)
949     PrevBB = &*std::prev(TailBB->getIterator());
950   MachineBasicBlock *PriorTBB = nullptr, *PriorFBB = nullptr;
951   SmallVector<MachineOperand, 4> PriorCond;
952   // This has to check PrevBB->succ_size() because EH edges are ignored by
953   // analyzeBranch.
954   if (PrevBB->succ_size() == 1 &&
955       // Layout preds are not always CFG preds. Check.
956       *PrevBB->succ_begin() == TailBB &&
957       !TII->analyzeBranch(*PrevBB, PriorTBB, PriorFBB, PriorCond) &&
958       PriorCond.empty() &&
959       (!PriorTBB || PriorTBB == TailBB) &&
960       TailBB->pred_size() == 1 &&
961       !TailBB->hasAddressTaken()) {
962     LLVM_DEBUG(dbgs() << "\nMerging into block: " << *PrevBB
963                       << "From MBB: " << *TailBB);
964     // There may be a branch to the layout successor. This is unlikely but it
965     // happens. The correct thing to do is to remove the branch before
966     // duplicating the instructions in all cases.
967     bool RemovedBranches = TII->removeBranch(*PrevBB) != 0;
968 
969     // If there are still tail instructions, abort the merge
970     if (PrevBB->getFirstTerminator() == PrevBB->end()) {
971       if (PreRegAlloc) {
972         DenseMap<Register, RegSubRegPair> LocalVRMap;
973         SmallVector<std::pair<Register, RegSubRegPair>, 4> CopyInfos;
974         MachineBasicBlock::iterator I = TailBB->begin();
975         // Process PHI instructions first.
976         while (I != TailBB->end() && I->isPHI()) {
977           // Replace the uses of the def of the PHI with the register coming
978           // from PredBB.
979           MachineInstr *MI = &*I++;
980           processPHI(MI, TailBB, PrevBB, LocalVRMap, CopyInfos, UsedByPhi,
981                      true);
982         }
983 
984         // Now copy the non-PHI instructions.
985         while (I != TailBB->end()) {
986           // Replace def of virtual registers with new registers, and update
987           // uses with PHI source register or the new registers.
988           MachineInstr *MI = &*I++;
989           assert(!MI->isBundle() && "Not expecting bundles before regalloc!");
990           duplicateInstruction(MI, TailBB, PrevBB, LocalVRMap, UsedByPhi);
991           MI->eraseFromParent();
992         }
993         appendCopies(PrevBB, CopyInfos, Copies);
994       } else {
995         TII->removeBranch(*PrevBB);
996         // No PHIs to worry about, just splice the instructions over.
997         PrevBB->splice(PrevBB->end(), TailBB, TailBB->begin(), TailBB->end());
998       }
999       PrevBB->removeSuccessor(PrevBB->succ_begin());
1000       assert(PrevBB->succ_empty());
1001       PrevBB->transferSuccessors(TailBB);
1002 
1003       // Update branches in PrevBB based on Tail's layout successor.
1004       if (ShouldUpdateTerminators)
1005         PrevBB->updateTerminator(TailBB->getNextNode());
1006 
1007       TDBBs.push_back(PrevBB);
1008       Changed = true;
1009     } else {
1010       LLVM_DEBUG(dbgs() << "Abort merging blocks, the predecessor still "
1011                            "contains terminator instructions");
1012       // Return early if no changes were made
1013       if (!Changed)
1014         return RemovedBranches;
1015     }
1016     Changed |= RemovedBranches;
1017   }
1018 
1019   // If this is after register allocation, there are no phis to fix.
1020   if (!PreRegAlloc)
1021     return Changed;
1022 
1023   // If we made no changes so far, we are safe.
1024   if (!Changed)
1025     return Changed;
1026 
1027   // Handle the nasty case in that we duplicated a block that is part of a loop
1028   // into some but not all of its predecessors. For example:
1029   //    1 -> 2 <-> 3                 |
1030   //          \                      |
1031   //           \---> rest            |
1032   // if we duplicate 2 into 1 but not into 3, we end up with
1033   // 12 -> 3 <-> 2 -> rest           |
1034   //   \             /               |
1035   //    \----->-----/                |
1036   // If there was a "var = phi(1, 3)" in 2, it has to be ultimately replaced
1037   // with a phi in 3 (which now dominates 2).
1038   // What we do here is introduce a copy in 3 of the register defined by the
1039   // phi, just like when we are duplicating 2 into 3, but we don't copy any
1040   // real instructions or remove the 3 -> 2 edge from the phi in 2.
1041   for (MachineBasicBlock *PredBB : Preds) {
1042     if (is_contained(TDBBs, PredBB))
1043       continue;
1044 
1045     // EH edges
1046     if (PredBB->succ_size() != 1)
1047       continue;
1048 
1049     DenseMap<Register, RegSubRegPair> LocalVRMap;
1050     SmallVector<std::pair<Register, RegSubRegPair>, 4> CopyInfos;
1051     // Process PHI instructions first.
1052     for (MachineInstr &MI : make_early_inc_range(TailBB->phis())) {
1053       // Replace the uses of the def of the PHI with the register coming
1054       // from PredBB.
1055       processPHI(&MI, TailBB, PredBB, LocalVRMap, CopyInfos, UsedByPhi, false);
1056     }
1057     appendCopies(PredBB, CopyInfos, Copies);
1058   }
1059 
1060   return Changed;
1061 }
1062 
1063 /// At the end of the block \p MBB generate COPY instructions between registers
1064 /// described by \p CopyInfos. Append resulting instructions to \p Copies.
1065 void TailDuplicator::appendCopies(MachineBasicBlock *MBB,
1066       SmallVectorImpl<std::pair<Register, RegSubRegPair>> &CopyInfos,
1067       SmallVectorImpl<MachineInstr*> &Copies) {
1068   MachineBasicBlock::iterator Loc = MBB->getFirstTerminator();
1069   const MCInstrDesc &CopyD = TII->get(TargetOpcode::COPY);
1070   for (auto &CI : CopyInfos) {
1071     auto C = BuildMI(*MBB, Loc, DebugLoc(), CopyD, CI.first)
1072                 .addReg(CI.second.Reg, 0, CI.second.SubReg);
1073     Copies.push_back(C);
1074   }
1075 }
1076 
1077 /// Remove the specified dead machine basic block from the function, updating
1078 /// the CFG.
1079 void TailDuplicator::removeDeadBlock(
1080     MachineBasicBlock *MBB,
1081     function_ref<void(MachineBasicBlock *)> *RemovalCallback) {
1082   assert(MBB->pred_empty() && "MBB must be dead!");
1083   LLVM_DEBUG(dbgs() << "\nRemoving MBB: " << *MBB);
1084 
1085   MachineFunction *MF = MBB->getParent();
1086   // Update the call info.
1087   for (const MachineInstr &MI : *MBB)
1088     if (MI.shouldUpdateAdditionalCallInfo())
1089       MF->eraseAdditionalCallInfo(&MI);
1090 
1091   if (RemovalCallback)
1092     (*RemovalCallback)(MBB);
1093 
1094   // Remove all successors.
1095   while (!MBB->succ_empty())
1096     MBB->removeSuccessor(MBB->succ_end() - 1);
1097 
1098   // Remove the block.
1099   MBB->eraseFromParent();
1100 }
1101