[Modules] Remove potential ODR violations by sinking the DEBUG_TYPE
[oota-llvm.git] / lib / CodeGen / TailDuplication.cpp
1 //===-- TailDuplication.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 pass duplicates basic blocks ending in unconditional branches into
11 // the tails of their predecessors.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "llvm/CodeGen/Passes.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/MachineRegisterInfo.h"
25 #include "llvm/CodeGen/MachineSSAUpdater.h"
26 #include "llvm/CodeGen/RegisterScavenging.h"
27 #include "llvm/IR/Function.h"
28 #include "llvm/Support/CommandLine.h"
29 #include "llvm/Support/Debug.h"
30 #include "llvm/Support/ErrorHandling.h"
31 #include "llvm/Support/raw_ostream.h"
32 #include "llvm/Target/TargetInstrInfo.h"
33 #include "llvm/Target/TargetRegisterInfo.h"
34 using namespace llvm;
35
36 #define DEBUG_TYPE "tailduplication"
37
38 STATISTIC(NumTails     , "Number of tails duplicated");
39 STATISTIC(NumTailDups  , "Number of tail duplicated blocks");
40 STATISTIC(NumInstrDups , "Additional instructions due to tail duplication");
41 STATISTIC(NumDeadBlocks, "Number of dead blocks removed");
42 STATISTIC(NumAddedPHIs , "Number of phis added");
43
44 // Heuristic for tail duplication.
45 static cl::opt<unsigned>
46 TailDuplicateSize("tail-dup-size",
47                   cl::desc("Maximum instructions to consider tail duplicating"),
48                   cl::init(2), cl::Hidden);
49
50 static cl::opt<bool>
51 TailDupVerify("tail-dup-verify",
52               cl::desc("Verify sanity of PHI instructions during taildup"),
53               cl::init(false), cl::Hidden);
54
55 static cl::opt<unsigned>
56 TailDupLimit("tail-dup-limit", cl::init(~0U), cl::Hidden);
57
58 typedef std::vector<std::pair<MachineBasicBlock*,unsigned> > AvailableValsTy;
59
60 namespace {
61   /// TailDuplicatePass - Perform tail duplication.
62   class TailDuplicatePass : public MachineFunctionPass {
63     const TargetInstrInfo *TII;
64     const TargetRegisterInfo *TRI;
65     const MachineBranchProbabilityInfo *MBPI;
66     MachineModuleInfo *MMI;
67     MachineRegisterInfo *MRI;
68     std::unique_ptr<RegScavenger> RS;
69     bool PreRegAlloc;
70
71     // SSAUpdateVRs - A list of virtual registers for which to update SSA form.
72     SmallVector<unsigned, 16> SSAUpdateVRs;
73
74     // SSAUpdateVals - For each virtual register in SSAUpdateVals keep a list of
75     // source virtual registers.
76     DenseMap<unsigned, AvailableValsTy> SSAUpdateVals;
77
78   public:
79     static char ID;
80     explicit TailDuplicatePass() :
81       MachineFunctionPass(ID), PreRegAlloc(false) {}
82
83     bool runOnMachineFunction(MachineFunction &MF) override;
84
85     void getAnalysisUsage(AnalysisUsage &AU) const override;
86
87   private:
88     void AddSSAUpdateEntry(unsigned OrigReg, unsigned NewReg,
89                            MachineBasicBlock *BB);
90     void ProcessPHI(MachineInstr *MI, MachineBasicBlock *TailBB,
91                     MachineBasicBlock *PredBB,
92                     DenseMap<unsigned, unsigned> &LocalVRMap,
93                     SmallVectorImpl<std::pair<unsigned,unsigned> > &Copies,
94                     const DenseSet<unsigned> &UsedByPhi,
95                     bool Remove);
96     void DuplicateInstruction(MachineInstr *MI,
97                               MachineBasicBlock *TailBB,
98                               MachineBasicBlock *PredBB,
99                               MachineFunction &MF,
100                               DenseMap<unsigned, unsigned> &LocalVRMap,
101                               const DenseSet<unsigned> &UsedByPhi);
102     void UpdateSuccessorsPHIs(MachineBasicBlock *FromBB, bool isDead,
103                               SmallVectorImpl<MachineBasicBlock *> &TDBBs,
104                               SmallSetVector<MachineBasicBlock*, 8> &Succs);
105     bool TailDuplicateBlocks(MachineFunction &MF);
106     bool shouldTailDuplicate(const MachineFunction &MF,
107                              bool IsSimple, MachineBasicBlock &TailBB);
108     bool isSimpleBB(MachineBasicBlock *TailBB);
109     bool canCompletelyDuplicateBB(MachineBasicBlock &BB);
110     bool duplicateSimpleBB(MachineBasicBlock *TailBB,
111                            SmallVectorImpl<MachineBasicBlock *> &TDBBs,
112                            const DenseSet<unsigned> &RegsUsedByPhi,
113                            SmallVectorImpl<MachineInstr *> &Copies);
114     bool TailDuplicate(MachineBasicBlock *TailBB,
115                        bool IsSimple,
116                        MachineFunction &MF,
117                        SmallVectorImpl<MachineBasicBlock *> &TDBBs,
118                        SmallVectorImpl<MachineInstr *> &Copies);
119     bool TailDuplicateAndUpdate(MachineBasicBlock *MBB,
120                                 bool IsSimple,
121                                 MachineFunction &MF);
122
123     void RemoveDeadBlock(MachineBasicBlock *MBB);
124   };
125
126   char TailDuplicatePass::ID = 0;
127 }
128
129 char &llvm::TailDuplicateID = TailDuplicatePass::ID;
130
131 INITIALIZE_PASS(TailDuplicatePass, "tailduplication", "Tail Duplication",
132                 false, false)
133
134 bool TailDuplicatePass::runOnMachineFunction(MachineFunction &MF) {
135   if (skipOptnoneFunction(*MF.getFunction()))
136     return false;
137
138   TII = MF.getTarget().getInstrInfo();
139   TRI = MF.getTarget().getRegisterInfo();
140   MRI = &MF.getRegInfo();
141   MMI = getAnalysisIfAvailable<MachineModuleInfo>();
142   MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
143
144   PreRegAlloc = MRI->isSSA();
145   RS.reset();
146   if (MRI->tracksLiveness() && TRI->trackLivenessAfterRegAlloc(MF))
147     RS.reset(new RegScavenger());
148
149   bool MadeChange = false;
150   while (TailDuplicateBlocks(MF))
151     MadeChange = true;
152
153   return MadeChange;
154 }
155
156 void TailDuplicatePass::getAnalysisUsage(AnalysisUsage &AU) const {
157   AU.addRequired<MachineBranchProbabilityInfo>();
158   MachineFunctionPass::getAnalysisUsage(AU);
159 }
160
161 static void VerifyPHIs(MachineFunction &MF, bool CheckExtra) {
162   for (MachineFunction::iterator I = ++MF.begin(), E = MF.end(); I != E; ++I) {
163     MachineBasicBlock *MBB = I;
164     SmallSetVector<MachineBasicBlock*, 8> Preds(MBB->pred_begin(),
165                                                 MBB->pred_end());
166     MachineBasicBlock::iterator MI = MBB->begin();
167     while (MI != MBB->end()) {
168       if (!MI->isPHI())
169         break;
170       for (SmallSetVector<MachineBasicBlock *, 8>::iterator PI = Preds.begin(),
171              PE = Preds.end(); PI != PE; ++PI) {
172         MachineBasicBlock *PredBB = *PI;
173         bool Found = false;
174         for (unsigned i = 1, e = MI->getNumOperands(); i != e; i += 2) {
175           MachineBasicBlock *PHIBB = MI->getOperand(i+1).getMBB();
176           if (PHIBB == PredBB) {
177             Found = true;
178             break;
179           }
180         }
181         if (!Found) {
182           dbgs() << "Malformed PHI in BB#" << MBB->getNumber() << ": " << *MI;
183           dbgs() << "  missing input from predecessor BB#"
184                  << PredBB->getNumber() << '\n';
185           llvm_unreachable(nullptr);
186         }
187       }
188
189       for (unsigned i = 1, e = MI->getNumOperands(); i != e; i += 2) {
190         MachineBasicBlock *PHIBB = MI->getOperand(i+1).getMBB();
191         if (CheckExtra && !Preds.count(PHIBB)) {
192           dbgs() << "Warning: malformed PHI in BB#" << MBB->getNumber()
193                  << ": " << *MI;
194           dbgs() << "  extra input from predecessor BB#"
195                  << PHIBB->getNumber() << '\n';
196           llvm_unreachable(nullptr);
197         }
198         if (PHIBB->getNumber() < 0) {
199           dbgs() << "Malformed PHI in BB#" << MBB->getNumber() << ": " << *MI;
200           dbgs() << "  non-existing BB#" << PHIBB->getNumber() << '\n';
201           llvm_unreachable(nullptr);
202         }
203       }
204       ++MI;
205     }
206   }
207 }
208
209 /// TailDuplicateAndUpdate - Tail duplicate the block and cleanup.
210 bool
211 TailDuplicatePass::TailDuplicateAndUpdate(MachineBasicBlock *MBB,
212                                           bool IsSimple,
213                                           MachineFunction &MF) {
214   // Save the successors list.
215   SmallSetVector<MachineBasicBlock*, 8> Succs(MBB->succ_begin(),
216                                               MBB->succ_end());
217
218   SmallVector<MachineBasicBlock*, 8> TDBBs;
219   SmallVector<MachineInstr*, 16> Copies;
220   if (!TailDuplicate(MBB, IsSimple, MF, TDBBs, Copies))
221     return false;
222
223   ++NumTails;
224
225   SmallVector<MachineInstr*, 8> NewPHIs;
226   MachineSSAUpdater SSAUpdate(MF, &NewPHIs);
227
228   // TailBB's immediate successors are now successors of those predecessors
229   // which duplicated TailBB. Add the predecessors as sources to the PHI
230   // instructions.
231   bool isDead = MBB->pred_empty() && !MBB->hasAddressTaken();
232   if (PreRegAlloc)
233     UpdateSuccessorsPHIs(MBB, isDead, TDBBs, Succs);
234
235   // If it is dead, remove it.
236   if (isDead) {
237     NumInstrDups -= MBB->size();
238     RemoveDeadBlock(MBB);
239     ++NumDeadBlocks;
240   }
241
242   // Update SSA form.
243   if (!SSAUpdateVRs.empty()) {
244     for (unsigned i = 0, e = SSAUpdateVRs.size(); i != e; ++i) {
245       unsigned VReg = SSAUpdateVRs[i];
246       SSAUpdate.Initialize(VReg);
247
248       // If the original definition is still around, add it as an available
249       // value.
250       MachineInstr *DefMI = MRI->getVRegDef(VReg);
251       MachineBasicBlock *DefBB = nullptr;
252       if (DefMI) {
253         DefBB = DefMI->getParent();
254         SSAUpdate.AddAvailableValue(DefBB, VReg);
255       }
256
257       // Add the new vregs as available values.
258       DenseMap<unsigned, AvailableValsTy>::iterator LI =
259         SSAUpdateVals.find(VReg);
260       for (unsigned j = 0, ee = LI->second.size(); j != ee; ++j) {
261         MachineBasicBlock *SrcBB = LI->second[j].first;
262         unsigned SrcReg = LI->second[j].second;
263         SSAUpdate.AddAvailableValue(SrcBB, SrcReg);
264       }
265
266       // Rewrite uses that are outside of the original def's block.
267       MachineRegisterInfo::use_iterator UI = MRI->use_begin(VReg);
268       while (UI != MRI->use_end()) {
269         MachineOperand &UseMO = *UI;
270         MachineInstr *UseMI = UseMO.getParent();
271         ++UI;
272         if (UseMI->isDebugValue()) {
273           // SSAUpdate can replace the use with an undef. That creates
274           // a debug instruction that is a kill.
275           // FIXME: Should it SSAUpdate job to delete debug instructions
276           // instead of replacing the use with undef?
277           UseMI->eraseFromParent();
278           continue;
279         }
280         if (UseMI->getParent() == DefBB && !UseMI->isPHI())
281           continue;
282         SSAUpdate.RewriteUse(UseMO);
283       }
284     }
285
286     SSAUpdateVRs.clear();
287     SSAUpdateVals.clear();
288   }
289
290   // Eliminate some of the copies inserted by tail duplication to maintain
291   // SSA form.
292   for (unsigned i = 0, e = Copies.size(); i != e; ++i) {
293     MachineInstr *Copy = Copies[i];
294     if (!Copy->isCopy())
295       continue;
296     unsigned Dst = Copy->getOperand(0).getReg();
297     unsigned Src = Copy->getOperand(1).getReg();
298     if (MRI->hasOneNonDBGUse(Src) &&
299         MRI->constrainRegClass(Src, MRI->getRegClass(Dst))) {
300       // Copy is the only use. Do trivial copy propagation here.
301       MRI->replaceRegWith(Dst, Src);
302       Copy->eraseFromParent();
303     }
304   }
305
306   if (NewPHIs.size())
307     NumAddedPHIs += NewPHIs.size();
308
309   return true;
310 }
311
312 /// TailDuplicateBlocks - Look for small blocks that are unconditionally
313 /// branched to and do not fall through. Tail-duplicate their instructions
314 /// into their predecessors to eliminate (dynamic) branches.
315 bool TailDuplicatePass::TailDuplicateBlocks(MachineFunction &MF) {
316   bool MadeChange = false;
317
318   if (PreRegAlloc && TailDupVerify) {
319     DEBUG(dbgs() << "\n*** Before tail-duplicating\n");
320     VerifyPHIs(MF, true);
321   }
322
323   for (MachineFunction::iterator I = ++MF.begin(), E = MF.end(); I != E; ) {
324     MachineBasicBlock *MBB = I++;
325
326     if (NumTails == TailDupLimit)
327       break;
328
329     bool IsSimple = isSimpleBB(MBB);
330
331     if (!shouldTailDuplicate(MF, IsSimple, *MBB))
332       continue;
333
334     MadeChange |= TailDuplicateAndUpdate(MBB, IsSimple, MF);
335   }
336
337   if (PreRegAlloc && TailDupVerify)
338     VerifyPHIs(MF, false);
339
340   return MadeChange;
341 }
342
343 static bool isDefLiveOut(unsigned Reg, MachineBasicBlock *BB,
344                          const MachineRegisterInfo *MRI) {
345   for (MachineInstr &UseMI : MRI->use_instructions(Reg)) {
346     if (UseMI.isDebugValue())
347       continue;
348     if (UseMI.getParent() != BB)
349       return true;
350   }
351   return false;
352 }
353
354 static unsigned getPHISrcRegOpIdx(MachineInstr *MI, MachineBasicBlock *SrcBB) {
355   for (unsigned i = 1, e = MI->getNumOperands(); i != e; i += 2)
356     if (MI->getOperand(i+1).getMBB() == SrcBB)
357       return i;
358   return 0;
359 }
360
361
362 // Remember which registers are used by phis in this block. This is
363 // used to determine which registers are liveout while modifying the
364 // block (which is why we need to copy the information).
365 static void getRegsUsedByPHIs(const MachineBasicBlock &BB,
366                               DenseSet<unsigned> *UsedByPhi) {
367   for(MachineBasicBlock::const_iterator I = BB.begin(), E = BB.end();
368       I != E; ++I) {
369     const MachineInstr &MI = *I;
370     if (!MI.isPHI())
371       break;
372     for (unsigned i = 1, e = MI.getNumOperands(); i != e; i += 2) {
373       unsigned SrcReg = MI.getOperand(i).getReg();
374       UsedByPhi->insert(SrcReg);
375     }
376   }
377 }
378
379 /// AddSSAUpdateEntry - Add a definition and source virtual registers pair for
380 /// SSA update.
381 void TailDuplicatePass::AddSSAUpdateEntry(unsigned OrigReg, unsigned NewReg,
382                                           MachineBasicBlock *BB) {
383   DenseMap<unsigned, AvailableValsTy>::iterator LI= SSAUpdateVals.find(OrigReg);
384   if (LI != SSAUpdateVals.end())
385     LI->second.push_back(std::make_pair(BB, NewReg));
386   else {
387     AvailableValsTy Vals;
388     Vals.push_back(std::make_pair(BB, NewReg));
389     SSAUpdateVals.insert(std::make_pair(OrigReg, Vals));
390     SSAUpdateVRs.push_back(OrigReg);
391   }
392 }
393
394 /// ProcessPHI - Process PHI node in TailBB by turning it into a copy in PredBB.
395 /// Remember the source register that's contributed by PredBB and update SSA
396 /// update map.
397 void TailDuplicatePass::ProcessPHI(
398     MachineInstr *MI, MachineBasicBlock *TailBB, MachineBasicBlock *PredBB,
399     DenseMap<unsigned, unsigned> &LocalVRMap,
400     SmallVectorImpl<std::pair<unsigned, unsigned> > &Copies,
401     const DenseSet<unsigned> &RegsUsedByPhi, bool Remove) {
402   unsigned DefReg = MI->getOperand(0).getReg();
403   unsigned SrcOpIdx = getPHISrcRegOpIdx(MI, PredBB);
404   assert(SrcOpIdx && "Unable to find matching PHI source?");
405   unsigned SrcReg = MI->getOperand(SrcOpIdx).getReg();
406   const TargetRegisterClass *RC = MRI->getRegClass(DefReg);
407   LocalVRMap.insert(std::make_pair(DefReg, SrcReg));
408
409   // Insert a copy from source to the end of the block. The def register is the
410   // available value liveout of the block.
411   unsigned NewDef = MRI->createVirtualRegister(RC);
412   Copies.push_back(std::make_pair(NewDef, SrcReg));
413   if (isDefLiveOut(DefReg, TailBB, MRI) || RegsUsedByPhi.count(DefReg))
414     AddSSAUpdateEntry(DefReg, NewDef, PredBB);
415
416   if (!Remove)
417     return;
418
419   // Remove PredBB from the PHI node.
420   MI->RemoveOperand(SrcOpIdx+1);
421   MI->RemoveOperand(SrcOpIdx);
422   if (MI->getNumOperands() == 1)
423     MI->eraseFromParent();
424 }
425
426 /// DuplicateInstruction - Duplicate a TailBB instruction to PredBB and update
427 /// the source operands due to earlier PHI translation.
428 void TailDuplicatePass::DuplicateInstruction(MachineInstr *MI,
429                                      MachineBasicBlock *TailBB,
430                                      MachineBasicBlock *PredBB,
431                                      MachineFunction &MF,
432                                      DenseMap<unsigned, unsigned> &LocalVRMap,
433                                      const DenseSet<unsigned> &UsedByPhi) {
434   MachineInstr *NewMI = TII->duplicate(MI, MF);
435   for (unsigned i = 0, e = NewMI->getNumOperands(); i != e; ++i) {
436     MachineOperand &MO = NewMI->getOperand(i);
437     if (!MO.isReg())
438       continue;
439     unsigned Reg = MO.getReg();
440     if (!TargetRegisterInfo::isVirtualRegister(Reg))
441       continue;
442     if (MO.isDef()) {
443       const TargetRegisterClass *RC = MRI->getRegClass(Reg);
444       unsigned NewReg = MRI->createVirtualRegister(RC);
445       MO.setReg(NewReg);
446       LocalVRMap.insert(std::make_pair(Reg, NewReg));
447       if (isDefLiveOut(Reg, TailBB, MRI) || UsedByPhi.count(Reg))
448         AddSSAUpdateEntry(Reg, NewReg, PredBB);
449     } else {
450       DenseMap<unsigned, unsigned>::iterator VI = LocalVRMap.find(Reg);
451       if (VI != LocalVRMap.end()) {
452         MO.setReg(VI->second);
453         MRI->constrainRegClass(VI->second, MRI->getRegClass(Reg));
454       }
455     }
456   }
457   PredBB->insert(PredBB->instr_end(), NewMI);
458 }
459
460 /// UpdateSuccessorsPHIs - After FromBB is tail duplicated into its predecessor
461 /// blocks, the successors have gained new predecessors. Update the PHI
462 /// instructions in them accordingly.
463 void
464 TailDuplicatePass::UpdateSuccessorsPHIs(MachineBasicBlock *FromBB, bool isDead,
465                                   SmallVectorImpl<MachineBasicBlock *> &TDBBs,
466                                   SmallSetVector<MachineBasicBlock*,8> &Succs) {
467   for (SmallSetVector<MachineBasicBlock*, 8>::iterator SI = Succs.begin(),
468          SE = Succs.end(); SI != SE; ++SI) {
469     MachineBasicBlock *SuccBB = *SI;
470     for (MachineBasicBlock::iterator II = SuccBB->begin(), EE = SuccBB->end();
471          II != EE; ++II) {
472       if (!II->isPHI())
473         break;
474       MachineInstrBuilder MIB(*FromBB->getParent(), II);
475       unsigned Idx = 0;
476       for (unsigned i = 1, e = II->getNumOperands(); i != e; i += 2) {
477         MachineOperand &MO = II->getOperand(i+1);
478         if (MO.getMBB() == FromBB) {
479           Idx = i;
480           break;
481         }
482       }
483
484       assert(Idx != 0);
485       MachineOperand &MO0 = II->getOperand(Idx);
486       unsigned Reg = MO0.getReg();
487       if (isDead) {
488         // Folded into the previous BB.
489         // There could be duplicate phi source entries. FIXME: Should sdisel
490         // or earlier pass fixed this?
491         for (unsigned i = II->getNumOperands()-2; i != Idx; i -= 2) {
492           MachineOperand &MO = II->getOperand(i+1);
493           if (MO.getMBB() == FromBB) {
494             II->RemoveOperand(i+1);
495             II->RemoveOperand(i);
496           }
497         }
498       } else
499         Idx = 0;
500
501       // If Idx is set, the operands at Idx and Idx+1 must be removed.
502       // We reuse the location to avoid expensive RemoveOperand calls.
503
504       DenseMap<unsigned,AvailableValsTy>::iterator LI=SSAUpdateVals.find(Reg);
505       if (LI != SSAUpdateVals.end()) {
506         // This register is defined in the tail block.
507         for (unsigned j = 0, ee = LI->second.size(); j != ee; ++j) {
508           MachineBasicBlock *SrcBB = LI->second[j].first;
509           // If we didn't duplicate a bb into a particular predecessor, we
510           // might still have added an entry to SSAUpdateVals to correcly
511           // recompute SSA. If that case, avoid adding a dummy extra argument
512           // this PHI.
513           if (!SrcBB->isSuccessor(SuccBB))
514             continue;
515
516           unsigned SrcReg = LI->second[j].second;
517           if (Idx != 0) {
518             II->getOperand(Idx).setReg(SrcReg);
519             II->getOperand(Idx+1).setMBB(SrcBB);
520             Idx = 0;
521           } else {
522             MIB.addReg(SrcReg).addMBB(SrcBB);
523           }
524         }
525       } else {
526         // Live in tail block, must also be live in predecessors.
527         for (unsigned j = 0, ee = TDBBs.size(); j != ee; ++j) {
528           MachineBasicBlock *SrcBB = TDBBs[j];
529           if (Idx != 0) {
530             II->getOperand(Idx).setReg(Reg);
531             II->getOperand(Idx+1).setMBB(SrcBB);
532             Idx = 0;
533           } else {
534             MIB.addReg(Reg).addMBB(SrcBB);
535           }
536         }
537       }
538       if (Idx != 0) {
539         II->RemoveOperand(Idx+1);
540         II->RemoveOperand(Idx);
541       }
542     }
543   }
544 }
545
546 /// shouldTailDuplicate - Determine if it is profitable to duplicate this block.
547 bool
548 TailDuplicatePass::shouldTailDuplicate(const MachineFunction &MF,
549                                        bool IsSimple,
550                                        MachineBasicBlock &TailBB) {
551   // Only duplicate blocks that end with unconditional branches.
552   if (TailBB.canFallThrough())
553     return false;
554
555   // Don't try to tail-duplicate single-block loops.
556   if (TailBB.isSuccessor(&TailBB))
557     return false;
558
559   // Set the limit on the cost to duplicate. When optimizing for size,
560   // duplicate only one, because one branch instruction can be eliminated to
561   // compensate for the duplication.
562   unsigned MaxDuplicateCount;
563   if (TailDuplicateSize.getNumOccurrences() == 0 &&
564       MF.getFunction()->getAttributes().
565         hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize))
566     MaxDuplicateCount = 1;
567   else
568     MaxDuplicateCount = TailDuplicateSize;
569
570   // If the target has hardware branch prediction that can handle indirect
571   // branches, duplicating them can often make them predictable when there
572   // are common paths through the code.  The limit needs to be high enough
573   // to allow undoing the effects of tail merging and other optimizations
574   // that rearrange the predecessors of the indirect branch.
575
576   bool HasIndirectbr = false;
577   if (!TailBB.empty())
578     HasIndirectbr = TailBB.back().isIndirectBranch();
579
580   if (HasIndirectbr && PreRegAlloc)
581     MaxDuplicateCount = 20;
582
583   // Check the instructions in the block to determine whether tail-duplication
584   // is invalid or unlikely to be profitable.
585   unsigned InstrCount = 0;
586   for (MachineBasicBlock::iterator I = TailBB.begin(); I != TailBB.end(); ++I) {
587     // Non-duplicable things shouldn't be tail-duplicated.
588     if (I->isNotDuplicable())
589       return false;
590
591     // Do not duplicate 'return' instructions if this is a pre-regalloc run.
592     // A return may expand into a lot more instructions (e.g. reload of callee
593     // saved registers) after PEI.
594     if (PreRegAlloc && I->isReturn())
595       return false;
596
597     // Avoid duplicating calls before register allocation. Calls presents a
598     // barrier to register allocation so duplicating them may end up increasing
599     // spills.
600     if (PreRegAlloc && I->isCall())
601       return false;
602
603     if (!I->isPHI() && !I->isDebugValue())
604       InstrCount += 1;
605
606     if (InstrCount > MaxDuplicateCount)
607       return false;
608   }
609
610   if (HasIndirectbr && PreRegAlloc)
611     return true;
612
613   if (IsSimple)
614     return true;
615
616   if (!PreRegAlloc)
617     return true;
618
619   return canCompletelyDuplicateBB(TailBB);
620 }
621
622 /// isSimpleBB - True if this BB has only one unconditional jump.
623 bool
624 TailDuplicatePass::isSimpleBB(MachineBasicBlock *TailBB) {
625   if (TailBB->succ_size() != 1)
626     return false;
627   if (TailBB->pred_empty())
628     return false;
629   MachineBasicBlock::iterator I = TailBB->begin();
630   MachineBasicBlock::iterator E = TailBB->end();
631   while (I != E && I->isDebugValue())
632     ++I;
633   if (I == E)
634     return true;
635   return I->isUnconditionalBranch();
636 }
637
638 static bool
639 bothUsedInPHI(const MachineBasicBlock &A,
640               SmallPtrSet<MachineBasicBlock*, 8> SuccsB) {
641   for (MachineBasicBlock::const_succ_iterator SI = A.succ_begin(),
642          SE = A.succ_end(); SI != SE; ++SI) {
643     MachineBasicBlock *BB = *SI;
644     if (SuccsB.count(BB) && !BB->empty() && BB->begin()->isPHI())
645       return true;
646   }
647
648   return false;
649 }
650
651 bool
652 TailDuplicatePass::canCompletelyDuplicateBB(MachineBasicBlock &BB) {
653   for (MachineBasicBlock::pred_iterator PI = BB.pred_begin(),
654        PE = BB.pred_end(); PI != PE; ++PI) {
655     MachineBasicBlock *PredBB = *PI;
656
657     if (PredBB->succ_size() > 1)
658       return false;
659
660     MachineBasicBlock *PredTBB = nullptr, *PredFBB = nullptr;
661     SmallVector<MachineOperand, 4> PredCond;
662     if (TII->AnalyzeBranch(*PredBB, PredTBB, PredFBB, PredCond, true))
663       return false;
664
665     if (!PredCond.empty())
666       return false;
667   }
668   return true;
669 }
670
671 bool
672 TailDuplicatePass::duplicateSimpleBB(MachineBasicBlock *TailBB,
673                                     SmallVectorImpl<MachineBasicBlock *> &TDBBs,
674                                     const DenseSet<unsigned> &UsedByPhi,
675                                     SmallVectorImpl<MachineInstr *> &Copies) {
676   SmallPtrSet<MachineBasicBlock*, 8> Succs(TailBB->succ_begin(),
677                                            TailBB->succ_end());
678   SmallVector<MachineBasicBlock*, 8> Preds(TailBB->pred_begin(),
679                                            TailBB->pred_end());
680   bool Changed = false;
681   for (SmallSetVector<MachineBasicBlock *, 8>::iterator PI = Preds.begin(),
682        PE = Preds.end(); PI != PE; ++PI) {
683     MachineBasicBlock *PredBB = *PI;
684
685     if (PredBB->getLandingPadSuccessor())
686       continue;
687
688     if (bothUsedInPHI(*PredBB, Succs))
689       continue;
690
691     MachineBasicBlock *PredTBB = nullptr, *PredFBB = nullptr;
692     SmallVector<MachineOperand, 4> PredCond;
693     if (TII->AnalyzeBranch(*PredBB, PredTBB, PredFBB, PredCond, true))
694       continue;
695
696     Changed = true;
697     DEBUG(dbgs() << "\nTail-duplicating into PredBB: " << *PredBB
698                  << "From simple Succ: " << *TailBB);
699
700     MachineBasicBlock *NewTarget = *TailBB->succ_begin();
701     MachineBasicBlock *NextBB = std::next(MachineFunction::iterator(PredBB));
702
703     // Make PredFBB explicit.
704     if (PredCond.empty())
705       PredFBB = PredTBB;
706
707     // Make fall through explicit.
708     if (!PredTBB)
709       PredTBB = NextBB;
710     if (!PredFBB)
711       PredFBB = NextBB;
712
713     // Redirect
714     if (PredFBB == TailBB)
715       PredFBB = NewTarget;
716     if (PredTBB == TailBB)
717       PredTBB = NewTarget;
718
719     // Make the branch unconditional if possible
720     if (PredTBB == PredFBB) {
721       PredCond.clear();
722       PredFBB = nullptr;
723     }
724
725     // Avoid adding fall through branches.
726     if (PredFBB == NextBB)
727       PredFBB = nullptr;
728     if (PredTBB == NextBB && PredFBB == nullptr)
729       PredTBB = nullptr;
730
731     TII->RemoveBranch(*PredBB);
732
733     if (PredTBB)
734       TII->InsertBranch(*PredBB, PredTBB, PredFBB, PredCond, DebugLoc());
735
736     uint32_t Weight = MBPI->getEdgeWeight(PredBB, TailBB);
737     PredBB->removeSuccessor(TailBB);
738     unsigned NumSuccessors = PredBB->succ_size();
739     assert(NumSuccessors <= 1);
740     if (NumSuccessors == 0 || *PredBB->succ_begin() != NewTarget)
741       PredBB->addSuccessor(NewTarget, Weight);
742
743     TDBBs.push_back(PredBB);
744   }
745   return Changed;
746 }
747
748 /// TailDuplicate - If it is profitable, duplicate TailBB's contents in each
749 /// of its predecessors.
750 bool
751 TailDuplicatePass::TailDuplicate(MachineBasicBlock *TailBB,
752                                  bool IsSimple,
753                                  MachineFunction &MF,
754                                  SmallVectorImpl<MachineBasicBlock *> &TDBBs,
755                                  SmallVectorImpl<MachineInstr *> &Copies) {
756   DEBUG(dbgs() << "\n*** Tail-duplicating BB#" << TailBB->getNumber() << '\n');
757
758   DenseSet<unsigned> UsedByPhi;
759   getRegsUsedByPHIs(*TailBB, &UsedByPhi);
760
761   if (IsSimple)
762     return duplicateSimpleBB(TailBB, TDBBs, UsedByPhi, Copies);
763
764   // Iterate through all the unique predecessors and tail-duplicate this
765   // block into them, if possible. Copying the list ahead of time also
766   // avoids trouble with the predecessor list reallocating.
767   bool Changed = false;
768   SmallSetVector<MachineBasicBlock*, 8> Preds(TailBB->pred_begin(),
769                                               TailBB->pred_end());
770   for (SmallSetVector<MachineBasicBlock *, 8>::iterator PI = Preds.begin(),
771        PE = Preds.end(); PI != PE; ++PI) {
772     MachineBasicBlock *PredBB = *PI;
773
774     assert(TailBB != PredBB &&
775            "Single-block loop should have been rejected earlier!");
776     // EH edges are ignored by AnalyzeBranch.
777     if (PredBB->succ_size() > 1)
778       continue;
779
780     MachineBasicBlock *PredTBB, *PredFBB;
781     SmallVector<MachineOperand, 4> PredCond;
782     if (TII->AnalyzeBranch(*PredBB, PredTBB, PredFBB, PredCond, true))
783       continue;
784     if (!PredCond.empty())
785       continue;
786     // Don't duplicate into a fall-through predecessor (at least for now).
787     if (PredBB->isLayoutSuccessor(TailBB) && PredBB->canFallThrough())
788       continue;
789
790     DEBUG(dbgs() << "\nTail-duplicating into PredBB: " << *PredBB
791                  << "From Succ: " << *TailBB);
792
793     TDBBs.push_back(PredBB);
794
795     // Remove PredBB's unconditional branch.
796     TII->RemoveBranch(*PredBB);
797
798     if (RS && !TailBB->livein_empty()) {
799       // Update PredBB livein.
800       RS->enterBasicBlock(PredBB);
801       if (!PredBB->empty())
802         RS->forward(std::prev(PredBB->end()));
803       BitVector RegsLiveAtExit(TRI->getNumRegs());
804       RS->getRegsUsed(RegsLiveAtExit, false);
805       for (MachineBasicBlock::livein_iterator I = TailBB->livein_begin(),
806              E = TailBB->livein_end(); I != E; ++I) {
807         if (!RegsLiveAtExit[*I])
808           // If a register is previously livein to the tail but it's not live
809           // at the end of predecessor BB, then it should be added to its
810           // livein list.
811           PredBB->addLiveIn(*I);
812       }
813     }
814
815     // Clone the contents of TailBB into PredBB.
816     DenseMap<unsigned, unsigned> LocalVRMap;
817     SmallVector<std::pair<unsigned,unsigned>, 4> CopyInfos;
818     // Use instr_iterator here to properly handle bundles, e.g.
819     // ARM Thumb2 IT block.
820     MachineBasicBlock::instr_iterator I = TailBB->instr_begin();
821     while (I != TailBB->instr_end()) {
822       MachineInstr *MI = &*I;
823       ++I;
824       if (MI->isPHI()) {
825         // Replace the uses of the def of the PHI with the register coming
826         // from PredBB.
827         ProcessPHI(MI, TailBB, PredBB, LocalVRMap, CopyInfos, UsedByPhi, true);
828       } else {
829         // Replace def of virtual registers with new registers, and update
830         // uses with PHI source register or the new registers.
831         DuplicateInstruction(MI, TailBB, PredBB, MF, LocalVRMap, UsedByPhi);
832       }
833     }
834     MachineBasicBlock::iterator Loc = PredBB->getFirstTerminator();
835     for (unsigned i = 0, e = CopyInfos.size(); i != e; ++i) {
836       Copies.push_back(BuildMI(*PredBB, Loc, DebugLoc(),
837                                TII->get(TargetOpcode::COPY),
838                                CopyInfos[i].first).addReg(CopyInfos[i].second));
839     }
840
841     // Simplify
842     TII->AnalyzeBranch(*PredBB, PredTBB, PredFBB, PredCond, true);
843
844     NumInstrDups += TailBB->size() - 1; // subtract one for removed branch
845
846     // Update the CFG.
847     PredBB->removeSuccessor(PredBB->succ_begin());
848     assert(PredBB->succ_empty() &&
849            "TailDuplicate called on block with multiple successors!");
850     for (MachineBasicBlock::succ_iterator I = TailBB->succ_begin(),
851            E = TailBB->succ_end(); I != E; ++I)
852       PredBB->addSuccessor(*I, MBPI->getEdgeWeight(TailBB, I));
853
854     Changed = true;
855     ++NumTailDups;
856   }
857
858   // If TailBB was duplicated into all its predecessors except for the prior
859   // block, which falls through unconditionally, move the contents of this
860   // block into the prior block.
861   MachineBasicBlock *PrevBB = std::prev(MachineFunction::iterator(TailBB));
862   MachineBasicBlock *PriorTBB = nullptr, *PriorFBB = nullptr;
863   SmallVector<MachineOperand, 4> PriorCond;
864   // This has to check PrevBB->succ_size() because EH edges are ignored by
865   // AnalyzeBranch.
866   if (PrevBB->succ_size() == 1 &&
867       !TII->AnalyzeBranch(*PrevBB, PriorTBB, PriorFBB, PriorCond, true) &&
868       PriorCond.empty() && !PriorTBB && TailBB->pred_size() == 1 &&
869       !TailBB->hasAddressTaken()) {
870     DEBUG(dbgs() << "\nMerging into block: " << *PrevBB
871           << "From MBB: " << *TailBB);
872     if (PreRegAlloc) {
873       DenseMap<unsigned, unsigned> LocalVRMap;
874       SmallVector<std::pair<unsigned,unsigned>, 4> CopyInfos;
875       MachineBasicBlock::iterator I = TailBB->begin();
876       // Process PHI instructions first.
877       while (I != TailBB->end() && I->isPHI()) {
878         // Replace the uses of the def of the PHI with the register coming
879         // from PredBB.
880         MachineInstr *MI = &*I++;
881         ProcessPHI(MI, TailBB, PrevBB, LocalVRMap, CopyInfos, UsedByPhi, true);
882         if (MI->getParent())
883           MI->eraseFromParent();
884       }
885
886       // Now copy the non-PHI instructions.
887       while (I != TailBB->end()) {
888         // Replace def of virtual registers with new registers, and update
889         // uses with PHI source register or the new registers.
890         MachineInstr *MI = &*I++;
891         assert(!MI->isBundle() && "Not expecting bundles before regalloc!");
892         DuplicateInstruction(MI, TailBB, PrevBB, MF, LocalVRMap, UsedByPhi);
893         MI->eraseFromParent();
894       }
895       MachineBasicBlock::iterator Loc = PrevBB->getFirstTerminator();
896       for (unsigned i = 0, e = CopyInfos.size(); i != e; ++i) {
897         Copies.push_back(BuildMI(*PrevBB, Loc, DebugLoc(),
898                                  TII->get(TargetOpcode::COPY),
899                                  CopyInfos[i].first)
900                            .addReg(CopyInfos[i].second));
901       }
902     } else {
903       // No PHIs to worry about, just splice the instructions over.
904       PrevBB->splice(PrevBB->end(), TailBB, TailBB->begin(), TailBB->end());
905     }
906     PrevBB->removeSuccessor(PrevBB->succ_begin());
907     assert(PrevBB->succ_empty());
908     PrevBB->transferSuccessors(TailBB);
909     TDBBs.push_back(PrevBB);
910     Changed = true;
911   }
912
913   // If this is after register allocation, there are no phis to fix.
914   if (!PreRegAlloc)
915     return Changed;
916
917   // If we made no changes so far, we are safe.
918   if (!Changed)
919     return Changed;
920
921
922   // Handle the nasty case in that we duplicated a block that is part of a loop
923   // into some but not all of its predecessors. For example:
924   //    1 -> 2 <-> 3                 |
925   //          \                      |
926   //           \---> rest            |
927   // if we duplicate 2 into 1 but not into 3, we end up with
928   // 12 -> 3 <-> 2 -> rest           |
929   //   \             /               |
930   //    \----->-----/                |
931   // If there was a "var = phi(1, 3)" in 2, it has to be ultimately replaced
932   // with a phi in 3 (which now dominates 2).
933   // What we do here is introduce a copy in 3 of the register defined by the
934   // phi, just like when we are duplicating 2 into 3, but we don't copy any
935   // real instructions or remove the 3 -> 2 edge from the phi in 2.
936   for (SmallSetVector<MachineBasicBlock *, 8>::iterator PI = Preds.begin(),
937        PE = Preds.end(); PI != PE; ++PI) {
938     MachineBasicBlock *PredBB = *PI;
939     if (std::find(TDBBs.begin(), TDBBs.end(), PredBB) != TDBBs.end())
940       continue;
941
942     // EH edges
943     if (PredBB->succ_size() != 1)
944       continue;
945
946     DenseMap<unsigned, unsigned> LocalVRMap;
947     SmallVector<std::pair<unsigned,unsigned>, 4> CopyInfos;
948     MachineBasicBlock::iterator I = TailBB->begin();
949     // Process PHI instructions first.
950     while (I != TailBB->end() && I->isPHI()) {
951       // Replace the uses of the def of the PHI with the register coming
952       // from PredBB.
953       MachineInstr *MI = &*I++;
954       ProcessPHI(MI, TailBB, PredBB, LocalVRMap, CopyInfos, UsedByPhi, false);
955     }
956     MachineBasicBlock::iterator Loc = PredBB->getFirstTerminator();
957     for (unsigned i = 0, e = CopyInfos.size(); i != e; ++i) {
958       Copies.push_back(BuildMI(*PredBB, Loc, DebugLoc(),
959                                TII->get(TargetOpcode::COPY),
960                                CopyInfos[i].first).addReg(CopyInfos[i].second));
961     }
962   }
963
964   return Changed;
965 }
966
967 /// RemoveDeadBlock - Remove the specified dead machine basic block from the
968 /// function, updating the CFG.
969 void TailDuplicatePass::RemoveDeadBlock(MachineBasicBlock *MBB) {
970   assert(MBB->pred_empty() && "MBB must be dead!");
971   DEBUG(dbgs() << "\nRemoving MBB: " << *MBB);
972
973   // Remove all successors.
974   while (!MBB->succ_empty())
975     MBB->removeSuccessor(MBB->succ_end()-1);
976
977   // Remove the block.
978   MBB->eraseFromParent();
979 }