1 //===- llvm/CodeGen/GlobalISel/RegBankSelect.cpp - RegBankSelect -*- C++ -*-==//
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 /// \file
10 /// This file implements the RegBankSelect class.
11 //===----------------------------------------------------------------------===//
12 
13 #include "llvm/CodeGen/GlobalISel/RegBankSelect.h"
14 #include "llvm/ADT/PostOrderIterator.h"
15 #include "llvm/CodeGen/GlobalISel/RegisterBank.h"
16 #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
17 #include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
18 #include "llvm/CodeGen/MachineRegisterInfo.h"
19 #include "llvm/IR/Function.h"
20 #include "llvm/Support/BlockFrequency.h"
21 #include "llvm/Support/Debug.h"
22 #include "llvm/Target/TargetSubtargetInfo.h"
23 
24 #define DEBUG_TYPE "regbankselect"
25 
26 using namespace llvm;
27 
28 char RegBankSelect::ID = 0;
29 INITIALIZE_PASS_BEGIN(RegBankSelect, "regbankselect",
30                       "Assign register bank of generic virtual registers",
31                       false, false);
32 INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo)
33 INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
34 INITIALIZE_PASS_END(RegBankSelect, "regbankselect",
35                     "Assign register bank of generic virtual registers", false,
36                     false);
37 
38 RegBankSelect::RegBankSelect(Mode RunningMode)
39     : MachineFunctionPass(ID), RBI(nullptr), MRI(nullptr), TRI(nullptr),
40       MBFI(nullptr), MBPI(nullptr), OptMode(RunningMode) {
41   initializeRegBankSelectPass(*PassRegistry::getPassRegistry());
42 }
43 
44 void RegBankSelect::init(MachineFunction &MF) {
45   RBI = MF.getSubtarget().getRegBankInfo();
46   assert(RBI && "Cannot work without RegisterBankInfo");
47   MRI = &MF.getRegInfo();
48   TRI = MF.getSubtarget().getRegisterInfo();
49   if (OptMode != Mode::Fast) {
50     MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
51     MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
52   } else {
53     MBFI = nullptr;
54     MBPI = nullptr;
55   }
56   MIRBuilder.setMF(MF);
57 }
58 
59 void RegBankSelect::getAnalysisUsage(AnalysisUsage &AU) const {
60   if (OptMode != Mode::Fast) {
61     // We could preserve the information from these two analysis but
62     // the APIs do not allow to do so yet.
63     AU.addRequired<MachineBlockFrequencyInfo>();
64     AU.addRequired<MachineBranchProbabilityInfo>();
65   }
66   MachineFunctionPass::getAnalysisUsage(AU);
67 }
68 
69 bool RegBankSelect::assignmentMatch(
70     unsigned Reg, const RegisterBankInfo::ValueMapping &ValMapping,
71     bool &OnlyAssign) const {
72   // By default we assume we will have to repair something.
73   OnlyAssign = false;
74   // Each part of a break down needs to end up in a different register.
75   // In other word, Reg assignement does not match.
76   if (ValMapping.BreakDown.size() > 1)
77     return false;
78 
79   const RegisterBank *CurRegBank = RBI->getRegBank(Reg, *MRI, *TRI);
80   const RegisterBank *DesiredRegBrank = ValMapping.BreakDown[0].RegBank;
81   // Reg is free of assignment, a simple assignment will make the
82   // register bank to match.
83   OnlyAssign = CurRegBank == nullptr;
84   DEBUG(dbgs() << "Does assignment already match: ";
85         if (CurRegBank) dbgs() << *CurRegBank; else dbgs() << "none";
86         dbgs() << " against ";
87         assert(DesiredRegBrank && "The mapping must be valid");
88         dbgs() << *DesiredRegBrank << '\n';);
89   return CurRegBank == DesiredRegBrank;
90 }
91 
92 void RegBankSelect::repairReg(
93     MachineOperand &MO, const RegisterBankInfo::ValueMapping &ValMapping,
94     RegBankSelect::RepairingPlacement &RepairPt,
95     const iterator_range<SmallVectorImpl<unsigned>::iterator> &NewVRegs) {
96   assert(ValMapping.BreakDown.size() == 1 && "Not yet implemented");
97   // Assume we are repairing a use and thus, the original reg will be
98   // the source of the repairing.
99   unsigned Src = MO.getReg();
100   unsigned Dst = *NewVRegs.begin();
101   if (ValMapping.BreakDown.size() == 1)
102     MO.setReg(Dst);
103 
104   // If we repair a definition, swap the source and destination for
105   // the repairing.
106   if (MO.isDef())
107     std::swap(Src, Dst);
108 
109   assert((RepairPt.getNumInsertPoints() == 1 ||
110           TargetRegisterInfo::isPhysicalRegister(Dst)) &&
111          "We are about to create several defs for Dst");
112 
113   // Build the instruction used to repair, then clone it at the right places.
114   MachineInstr *MI = MIRBuilder.buildInstr(TargetOpcode::COPY, Dst, Src);
115   MI->removeFromParent();
116   DEBUG(dbgs() << "Copy: " << PrintReg(Src) << " to: " << PrintReg(Dst)
117                << '\n');
118   // TODO:
119   // Check if MI is legal. if not, we need to legalize all the
120   // instructions we are going to insert.
121   std::unique_ptr<MachineInstr *[]> NewInstrs(
122       new MachineInstr *[RepairPt.getNumInsertPoints()]);
123   bool IsFirst = true;
124   unsigned Idx = 0;
125   for (const std::unique_ptr<InsertPoint> &InsertPt : RepairPt) {
126     MachineInstr *CurMI;
127     if (IsFirst)
128       CurMI = MI;
129     else
130       CurMI = MIRBuilder.getMF().CloneMachineInstr(MI);
131     InsertPt->insert(*CurMI);
132     NewInstrs[Idx++] = CurMI;
133     IsFirst = false;
134   }
135   // TODO:
136   // Legalize NewInstrs if need be.
137 }
138 
139 uint64_t RegBankSelect::getRepairCost(
140     const MachineOperand &MO,
141     const RegisterBankInfo::ValueMapping &ValMapping) const {
142   assert(MO.isReg() && "We should only repair register operand");
143   assert(!ValMapping.BreakDown.empty() && "Nothing to map??");
144 
145   bool IsSameNumOfValues = ValMapping.BreakDown.size() == 1;
146   const RegisterBank *CurRegBank = RBI->getRegBank(MO.getReg(), *MRI, *TRI);
147   // If MO does not have a register bank, we should have just been
148   // able to set one unless we have to break the value down.
149   assert((!IsSameNumOfValues || CurRegBank) && "We should not have to repair");
150   // Def: Val <- NewDefs
151   //     Same number of values: copy
152   //     Different number: Val = build_sequence Defs1, Defs2, ...
153   // Use: NewSources <- Val.
154   //     Same number of values: copy.
155   //     Different number: Src1, Src2, ... =
156   //           extract_value Val, Src1Begin, Src1Len, Src2Begin, Src2Len, ...
157   // We should remember that this value is available somewhere else to
158   // coalesce the value.
159 
160   if (IsSameNumOfValues) {
161     const RegisterBank *DesiredRegBrank = ValMapping.BreakDown[0].RegBank;
162     // If we repair a definition, swap the source and destination for
163     // the repairing.
164     if (MO.isDef())
165       std::swap(CurRegBank, DesiredRegBrank);
166     unsigned Cost = RBI->copyCost(*DesiredRegBrank, *CurRegBank);
167     // TODO: use a dedicated constant for ImpossibleCost.
168     if (Cost != UINT_MAX)
169       return Cost;
170     assert(false && "Legalization not available yet");
171     // Return the legalization cost of that repairing.
172   }
173   assert(false && "Complex repairing not implemented yet");
174   return 1;
175 }
176 
177 RegisterBankInfo::InstructionMapping &RegBankSelect::findBestMapping(
178     MachineInstr &MI, RegisterBankInfo::InstructionMappings &PossibleMappings,
179     SmallVectorImpl<RepairingPlacement> &RepairPts) {
180 
181   RegisterBankInfo::InstructionMapping *BestMapping = nullptr;
182   MappingCost Cost = MappingCost::ImpossibleCost();
183   SmallVector<RepairingPlacement, 4> LocalRepairPts;
184   for (RegisterBankInfo::InstructionMapping &CurMapping : PossibleMappings) {
185     MappingCost CurCost = computeMapping(MI, CurMapping, LocalRepairPts, &Cost);
186     if (CurCost < Cost) {
187       Cost = CurCost;
188       BestMapping = &CurMapping;
189       RepairPts.clear();
190       for (RepairingPlacement &RepairPt : LocalRepairPts)
191         RepairPts.emplace_back(std::move(RepairPt));
192     }
193   }
194   assert(BestMapping && "No suitable mapping for instruction");
195   return *BestMapping;
196 }
197 
198 void RegBankSelect::tryAvoidingSplit(
199     RegBankSelect::RepairingPlacement &RepairPt, const MachineOperand &MO,
200     const RegisterBankInfo::ValueMapping &ValMapping) const {
201   const MachineInstr &MI = *MO.getParent();
202   assert(RepairPt.hasSplit() && "We should not have to adjust for split");
203   // Splitting should only occur for PHIs or between terminators,
204   // because we only do local repairing.
205   assert((MI.isPHI() || MI.isTerminator()) && "Why do we split?");
206 
207   assert(&MI.getOperand(RepairPt.getOpIdx()) == &MO &&
208          "Repairing placement does not match operand");
209 
210   // If we need splitting for phis, that means it is because we
211   // could not find an insertion point before the terminators of
212   // the predecessor block for this argument. In other words,
213   // the input value is defined by one of the terminators.
214   assert((!MI.isPHI() || !MO.isDef()) && "Need split for phi def?");
215 
216   // We split to repair the use of a phi or a terminator.
217   if (!MO.isDef()) {
218     if (MI.isTerminator()) {
219       assert(&MI != &(*MI.getParent()->getFirstTerminator()) &&
220              "Need to split for the first terminator?!");
221     } else {
222       // For the PHI case, the split may not be actually required.
223       // In the copy case, a phi is already a copy on the incoming edge,
224       // therefore there is no need to split.
225       if (ValMapping.BreakDown.size() == 1)
226         // This is a already a copy, there is nothing to do.
227         RepairPt.switchTo(RepairingPlacement::RepairingKind::Reassign);
228     }
229     return;
230   }
231 
232   // At this point, we need to repair a defintion of a terminator.
233 
234   // Technically we need to fix the def of MI on all outgoing
235   // edges of MI to keep the repairing local. In other words, we
236   // will create several definitions of the same register. This
237   // does not work for SSA unless that definition is a physical
238   // register.
239   // However, there are other cases where we can get away with
240   // that while still keeping the repairing local.
241   assert(MI.isTerminator() && MO.isDef() &&
242          "This code is for the def of a terminator");
243 
244   // Since we use RPO traversal, if we need to repair a definition
245   // this means this definition could be:
246   // 1. Used by PHIs (i.e., this VReg has been visited as part of the
247   //    uses of a phi.), or
248   // 2. Part of a target specific instruction (i.e., the target applied
249   //    some register class constraints when creating the instruction.)
250   // If the constraints come for #2, the target said that another mapping
251   // is supported so we may just drop them. Indeed, if we do not change
252   // the number of registers holding that value, the uses will get fixed
253   // when we get to them.
254   // Uses in PHIs may have already been proceeded though.
255   // If the constraints come for #1, then, those are weak constraints and
256   // no actual uses may rely on them. However, the problem remains mainly
257   // the same as for #2. If the value stays in one register, we could
258   // just switch the register bank of the definition, but we would need to
259   // account for a repairing cost for each phi we silently change.
260   //
261   // In any case, if the value needs to be broken down into several
262   // registers, the repairing is not local anymore as we need to patch
263   // every uses to rebuild the value in just one register.
264   //
265   // To summarize:
266   // - If the value is in a physical register, we can do the split and
267   //   fix locally.
268   // Otherwise if the value is in a virtual register:
269   // - If the value remains in one register, we do not have to split
270   //   just switching the register bank would do, but we need to account
271   //   in the repairing cost all the phi we changed.
272   // - If the value spans several registers, then we cannot do a local
273   //   repairing.
274 
275   // Check if this is a physical or virtual register.
276   unsigned Reg = MO.getReg();
277   if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
278     // We are going to split every outgoing edges.
279     // Check that this is possible.
280     // FIXME: The machine representation is currently broken
281     // since it also several terminators in one basic block.
282     // Because of that we would technically need a way to get
283     // the targets of just one terminator to know which edges
284     // we have to split.
285     // Assert that we do not hit the ill-formed representation.
286 
287     // If there are other terminators before that one, some of
288     // the outgoing edges may not be dominated by this definition.
289     assert(&MI == &(*MI.getParent()->getFirstTerminator()) &&
290            "Do not know which outgoing edges are relevant");
291     const MachineInstr *Next = MI.getNextNode();
292     assert((!Next || Next->isUnconditionalBranch()) &&
293            "Do not know where each terminator ends up");
294     if (Next)
295       // If the next terminator uses Reg, this means we have
296       // to split right after MI and thus we need a way to ask
297       // which outgoing edges are affected.
298       assert(!Next->readsRegister(Reg) && "Need to split between terminators");
299     // We will split all the edges and repair there.
300   } else {
301     // This is a virtual register defined by a terminator.
302     if (ValMapping.BreakDown.size() == 1) {
303       // There is nothing to repair, but we may actually lie on
304       // the repairing cost because of the PHIs already proceeded
305       // as already stated.
306       // Though the code will be correct.
307       assert(0 && "Repairing cost may not be accurate");
308     } else {
309       // We need to do non-local repairing. Basically, patch all
310       // the uses (i.e., phis) that we already proceeded.
311       // For now, just say this mapping is not possible.
312       RepairPt.switchTo(RepairingPlacement::RepairingKind::Impossible);
313     }
314   }
315 }
316 
317 RegBankSelect::MappingCost RegBankSelect::computeMapping(
318     MachineInstr &MI, const RegisterBankInfo::InstructionMapping &InstrMapping,
319     SmallVectorImpl<RepairingPlacement> &RepairPts,
320     const RegBankSelect::MappingCost *BestCost) {
321   assert((MBFI || !BestCost) && "Costs comparison require MBFI");
322 
323   // If mapped with InstrMapping, MI will have the recorded cost.
324   MappingCost Cost(MBFI ? MBFI->getBlockFreq(MI.getParent()) : 1);
325   bool Saturated = Cost.addLocalCost(InstrMapping.getCost());
326   assert(!Saturated && "Possible mapping saturated the cost");
327   DEBUG(dbgs() << "Evaluating mapping cost for: " << MI);
328   DEBUG(dbgs() << "With: " << InstrMapping << '\n');
329   RepairPts.clear();
330   if (BestCost && Cost > *BestCost)
331     return Cost;
332 
333   // Moreover, to realize this mapping, the register bank of each operand must
334   // match this mapping. In other words, we may need to locally reassign the
335   // register banks. Account for that repairing cost as well.
336   // In this context, local means in the surrounding of MI.
337   for (unsigned OpIdx = 0, EndOpIdx = MI.getNumOperands(); OpIdx != EndOpIdx;
338        ++OpIdx) {
339     const MachineOperand &MO = MI.getOperand(OpIdx);
340     if (!MO.isReg())
341       continue;
342     unsigned Reg = MO.getReg();
343     if (!Reg)
344       continue;
345     DEBUG(dbgs() << "Opd" << OpIdx);
346     const RegisterBankInfo::ValueMapping &ValMapping =
347         InstrMapping.getOperandMapping(OpIdx);
348     // If Reg is already properly mapped, this is free.
349     bool Assign;
350     if (assignmentMatch(Reg, ValMapping, Assign)) {
351       DEBUG(dbgs() << " is free (match).\n");
352       continue;
353     }
354     if (Assign) {
355       DEBUG(dbgs() << " is free (simple assignment).\n");
356       RepairPts.emplace_back(RepairingPlacement(MI, OpIdx, *TRI, *this,
357                                                 RepairingPlacement::Reassign));
358       continue;
359     }
360 
361     // Find the insertion point for the repairing code.
362     RepairPts.emplace_back(
363         RepairingPlacement(MI, OpIdx, *TRI, *this, RepairingPlacement::Insert));
364     RepairingPlacement &RepairPt = RepairPts.back();
365 
366     // If we need to split a basic block to materialize this insertion point,
367     // we may give a higher cost to this mapping.
368     // Nevertheless, we may get away with the split, so try that first.
369     if (RepairPt.hasSplit())
370       tryAvoidingSplit(RepairPt, MO, ValMapping);
371 
372     // Check that the materialization of the repairing is possible.
373     if (!RepairPt.canMaterialize())
374       return MappingCost::ImpossibleCost();
375 
376     // Account for the split cost and repair cost.
377     // Unless the cost is already saturated or we do not care about the cost.
378     if (!BestCost || Saturated)
379       continue;
380 
381     // To get accurate information we need MBFI and MBPI.
382     // Thus, if we end up here this information should be here.
383     assert(MBFI && MBPI && "Cost computation requires MBFI and MBPI");
384 
385     // Sums up the repairing cost of MO at each insertion point.
386     uint64_t RepairCost = getRepairCost(MO, ValMapping);
387     // Bias used for splitting: 5%.
388     const uint64_t PercentageForBias = 5;
389     uint64_t Bias = (RepairCost * PercentageForBias + 99) / 100;
390     // We should not need more than a couple of instructions to repair
391     // an assignment. In other words, the computation should not
392     // overflow because the repairing cost is free of basic block
393     // frequency.
394     assert(((RepairCost < RepairCost * PercentageForBias) &&
395             (RepairCost * PercentageForBias <
396              RepairCost * PercentageForBias + 99)) &&
397            "Repairing involves more than a billion of instructions?!");
398     for (const std::unique_ptr<InsertPoint> &InsertPt : RepairPt) {
399       assert(InsertPt->canMaterialize() && "We should not have made it here");
400       // We will applied some basic block frequency and those uses uint64_t.
401       if (!InsertPt->isSplit())
402         Saturated = Cost.addLocalCost(RepairCost);
403       else {
404         uint64_t CostForInsertPt = RepairCost;
405         // Again we shouldn't overflow here givent that
406         // CostForInsertPt is frequency free at this point.
407         assert(CostForInsertPt + Bias > CostForInsertPt &&
408                "Repairing + split bias overflows");
409         CostForInsertPt += Bias;
410         uint64_t PtCost = InsertPt->frequency(*this) * CostForInsertPt;
411         // Check if we just overflowed.
412         if ((Saturated = PtCost < CostForInsertPt))
413           Cost.saturate();
414         else
415           Saturated = Cost.addNonLocalCost(PtCost);
416       }
417 
418       // Stop looking into what it takes to repair, this is already
419       // too expensive.
420       if (BestCost && Cost > *BestCost)
421         return Cost;
422 
423       // No need to accumulate more cost information.
424       // We need to still gather the repairing information though.
425       if (Saturated)
426         break;
427     }
428   }
429   return Cost;
430 }
431 
432 void RegBankSelect::applyMapping(
433     MachineInstr &MI, const RegisterBankInfo::InstructionMapping &InstrMapping,
434     SmallVectorImpl<RegBankSelect::RepairingPlacement> &RepairPts) {
435   assert(InstrMapping.getID() == RegisterBankInfo::DefaultMappingID &&
436          "Rewriting of MI not implemented yet");
437   // First, place the repairing code.
438   bool NeedRewrite = false;
439   SmallVector<unsigned, 8> NewVRegs;
440   for (RepairingPlacement &RepairPt : RepairPts) {
441     assert(RepairPt.canMaterialize() &&
442            RepairPt.getKind() != RepairingPlacement::Impossible &&
443            "This mapping is impossible");
444     assert(RepairPt.getKind() != RepairingPlacement::None &&
445            "This should not make its way in the list");
446     unsigned OpIdx = RepairPt.getOpIdx();
447     MachineOperand &MO = MI.getOperand(OpIdx);
448     const RegisterBankInfo::ValueMapping &ValMapping =
449         InstrMapping.getOperandMapping(OpIdx);
450     unsigned BreakDownSize = ValMapping.BreakDown.size();
451     unsigned Reg = MO.getReg();
452     NeedRewrite = BreakDownSize != 1;
453 
454     switch (RepairPt.getKind()) {
455     case RepairingPlacement::Reassign:
456       assert(BreakDownSize == 1 &&
457              "Reassignment should only be for simple mapping");
458       MRI->setRegBank(Reg, *ValMapping.BreakDown[0].RegBank);
459       break;
460     case RepairingPlacement::Insert:
461       // We need as many new virtual registers as the number of partial mapping.
462       for (const RegisterBankInfo::PartialMapping &PartMap :
463            ValMapping.BreakDown) {
464         unsigned Tmp = MRI->createGenericVirtualRegister(PartMap.Length);
465         MRI->setRegBank(Tmp, *PartMap.RegBank);
466         NewVRegs.push_back(Tmp);
467       }
468       repairReg(MO, ValMapping, RepairPt,
469                 make_range(NewVRegs.end() - BreakDownSize, NewVRegs.end()));
470       break;
471     default:
472       llvm_unreachable("Other kind should not happen");
473     }
474   }
475   // Second, rewrite the instruction.
476   (void)NeedRewrite;
477   assert(!NeedRewrite && "Not implemented yet");
478 }
479 
480 void RegBankSelect::assignInstr(MachineInstr &MI) {
481   DEBUG(dbgs() << "Assign: " << MI);
482   // Remember the repairing placement for all the operands.
483   SmallVector<RepairingPlacement, 4> RepairPts;
484 
485   RegisterBankInfo::InstructionMapping BestMapping;
486   if (OptMode == RegBankSelect::Mode::Fast) {
487     BestMapping = RBI->getInstrMapping(MI);
488     MappingCost DefaultCost = computeMapping(MI, BestMapping, RepairPts);
489     (void)DefaultCost;
490     assert(DefaultCost != MappingCost::ImpossibleCost() &&
491            "Default mapping is not suited");
492   } else {
493     RegisterBankInfo::InstructionMappings PossibleMappings =
494         RBI->getInstrPossibleMappings(MI);
495     assert(!PossibleMappings.empty() &&
496            "Do not know how to map this instruction");
497     BestMapping = std::move(findBestMapping(MI, PossibleMappings, RepairPts));
498   }
499   // Make sure the mapping is valid for MI.
500   assert(BestMapping.verify(MI) && "Invalid instruction mapping");
501 
502   DEBUG(dbgs() << "Mapping: " << BestMapping << '\n');
503 
504   applyMapping(MI, BestMapping, RepairPts);
505 
506   DEBUG(dbgs() << "Assigned: " << MI);
507 }
508 
509 bool RegBankSelect::runOnMachineFunction(MachineFunction &MF) {
510   DEBUG(dbgs() << "Assign register banks for: " << MF.getName() << '\n');
511   const Function *F = MF.getFunction();
512   Mode SaveOptMode = OptMode;
513   if (F->hasFnAttribute(Attribute::OptimizeNone))
514     OptMode = Mode::Fast;
515   init(MF);
516   // Walk the function and assign register banks to all operands.
517   // Use a RPOT to make sure all registers are assigned before we choose
518   // the best mapping of the current instruction.
519   ReversePostOrderTraversal<MachineFunction*> RPOT(&MF);
520   for (MachineBasicBlock *MBB : RPOT) {
521     // Set a sensible insertion point so that subsequent calls to
522     // MIRBuilder.
523     MIRBuilder.setMBB(*MBB);
524     for (MachineInstr &MI : *MBB)
525       assignInstr(MI);
526   }
527   OptMode = SaveOptMode;
528   return false;
529 }
530 
531 //------------------------------------------------------------------------------
532 //                  Helper Classes Implementation
533 //------------------------------------------------------------------------------
534 RegBankSelect::RepairingPlacement::RepairingPlacement(
535     MachineInstr &MI, unsigned OpIdx, const TargetRegisterInfo &TRI, Pass &P,
536     RepairingPlacement::RepairingKind Kind)
537     // Default is, we are going to insert code to repair OpIdx.
538     : Kind(Kind),
539       OpIdx(OpIdx),
540       CanMaterialize(Kind != RepairingKind::Impossible),
541       HasSplit(false),
542       P(P) {
543   const MachineOperand &MO = MI.getOperand(OpIdx);
544   assert(MO.isReg() && "Trying to repair a non-reg operand");
545 
546   if (Kind != RepairingKind::Insert)
547     return;
548 
549   // Repairings for definitions happen after MI, uses happen before.
550   bool Before = !MO.isDef();
551 
552   // Check if we are done with MI.
553   if (!MI.isPHI() && !MI.isTerminator()) {
554     addInsertPoint(MI, Before);
555     // We are done with the initialization.
556     return;
557   }
558 
559   // Now, look for the special cases.
560   if (MI.isPHI()) {
561     // - PHI must be the first instructions:
562     //   * Before, we have to split the related incoming edge.
563     //   * After, move the insertion point past the last phi.
564     if (!Before) {
565       MachineBasicBlock::iterator It = MI.getParent()->getFirstNonPHI();
566       if (It != MI.getParent()->end())
567         addInsertPoint(*It, /*Before*/ true);
568       else
569         addInsertPoint(*(--It), /*Before*/ false);
570       return;
571     }
572     // We repair a use of a phi, we may need to split the related edge.
573     MachineBasicBlock &Pred = *MI.getOperand(OpIdx + 1).getMBB();
574     // Check if we can move the insertion point prior to the
575     // terminators of the predecessor.
576     unsigned Reg = MO.getReg();
577     MachineBasicBlock::iterator It = Pred.getLastNonDebugInstr();
578     for (auto Begin = Pred.begin(); It != Begin && It->isTerminator(); --It)
579       if (It->modifiesRegister(Reg, &TRI)) {
580         // We cannot hoist the repairing code in the predecessor.
581         // Split the edge.
582         addInsertPoint(Pred, *MI.getParent());
583         return;
584       }
585     // At this point, we can insert in Pred.
586 
587     // - If It is invalid, Pred is empty and we can insert in Pred
588     //   wherever we want.
589     // - If It is valid, It is the first non-terminator, insert after It.
590     if (It == Pred.end())
591       addInsertPoint(Pred, /*Beginning*/ false);
592     else
593       addInsertPoint(*It, /*Before*/ false);
594   } else {
595     // - Terminators must be the last instructions:
596     //   * Before, move the insert point before the first terminator.
597     //   * After, we have to split the outcoming edges.
598     unsigned Reg = MO.getReg();
599     if (Before) {
600       // Check whether Reg is defined by any terminator.
601       MachineBasicBlock::iterator It = MI;
602       for (auto Begin = MI.getParent()->begin();
603            --It != Begin && It->isTerminator();)
604         if (It->modifiesRegister(Reg, &TRI)) {
605           // Insert the repairing code right after the definition.
606           addInsertPoint(*It, /*Before*/ false);
607           return;
608         }
609       addInsertPoint(*It, /*Before*/ true);
610       return;
611     }
612     // Make sure Reg is not redefined by other terminators, otherwise
613     // we do not know how to split.
614     for (MachineBasicBlock::iterator It = MI, End = MI.getParent()->end();
615          ++It != End;)
616       // The machine verifier should reject this kind of code.
617       assert(It->modifiesRegister(Reg, &TRI) && "Do not know where to split");
618     // Split each outcoming edges.
619     MachineBasicBlock &Src = *MI.getParent();
620     for (auto &Succ : Src.successors())
621       addInsertPoint(Src, Succ);
622   }
623 }
624 
625 void RegBankSelect::RepairingPlacement::addInsertPoint(MachineInstr &MI,
626                                                        bool Before) {
627   addInsertPoint(*new InstrInsertPoint(MI, Before));
628 }
629 
630 void RegBankSelect::RepairingPlacement::addInsertPoint(MachineBasicBlock &MBB,
631                                                        bool Beginning) {
632   addInsertPoint(*new MBBInsertPoint(MBB, Beginning));
633 }
634 
635 void RegBankSelect::RepairingPlacement::addInsertPoint(MachineBasicBlock &Src,
636                                                        MachineBasicBlock &Dst) {
637   addInsertPoint(*new EdgeInsertPoint(Src, Dst, P));
638 }
639 
640 void RegBankSelect::RepairingPlacement::addInsertPoint(
641     RegBankSelect::InsertPoint &Point) {
642   CanMaterialize &= Point.canMaterialize();
643   HasSplit |= Point.isSplit();
644   InsertPoints.emplace_back(&Point);
645 }
646 
647 RegBankSelect::InstrInsertPoint::InstrInsertPoint(MachineInstr &Instr,
648                                                   bool Before)
649     : InsertPoint(), Instr(Instr), Before(Before) {
650   // Since we do not support splitting, we do not need to update
651   // liveness and such, so do not do anything with P.
652   assert((!Before || !Instr.isPHI()) &&
653          "Splitting before phis requires more points");
654   assert((!Before || !Instr.getNextNode() || !Instr.getNextNode()->isPHI()) &&
655          "Splitting between phis does not make sense");
656 }
657 
658 void RegBankSelect::InstrInsertPoint::materialize() {
659   if (isSplit()) {
660     // Slice and return the beginning of the new block.
661     // If we need to split between the terminators, we theoritically
662     // need to know where the first and second set of terminators end
663     // to update the successors properly.
664     // Now, in pratice, we should have a maximum of 2 branch
665     // instructions; one conditional and one unconditional. Therefore
666     // we know how to update the successor by looking at the target of
667     // the unconditional branch.
668     // If we end up splitting at some point, then, we should update
669     // the liveness information and such. I.e., we would need to
670     // access P here.
671     // The machine verifier should actually make sure such cases
672     // cannot happen.
673     llvm_unreachable("Not yet implemented");
674   }
675   // Otherwise the insertion point is just the current or next
676   // instruction depending on Before. I.e., there is nothing to do
677   // here.
678 }
679 
680 bool RegBankSelect::InstrInsertPoint::isSplit() const {
681   // If the insertion point is after a terminator, we need to split.
682   if (!Before)
683     return Instr.isTerminator();
684   // If we insert before an instruction that is after a terminator,
685   // we are still after a terminator.
686   return Instr.getPrevNode() && Instr.getPrevNode()->isTerminator();
687 }
688 
689 uint64_t RegBankSelect::InstrInsertPoint::frequency(const Pass &P) const {
690   // Even if we need to split, because we insert between terminators,
691   // this split has actually the same frequency as the instruction.
692   const MachineBlockFrequencyInfo *MBFI =
693       P.getAnalysisIfAvailable<MachineBlockFrequencyInfo>();
694   if (!MBFI)
695     return 1;
696   return MBFI->getBlockFreq(Instr.getParent()).getFrequency();
697 }
698 
699 uint64_t RegBankSelect::MBBInsertPoint::frequency(const Pass &P) const {
700   const MachineBlockFrequencyInfo *MBFI =
701       P.getAnalysisIfAvailable<MachineBlockFrequencyInfo>();
702   if (!MBFI)
703     return 1;
704   return MBFI->getBlockFreq(&MBB).getFrequency();
705 }
706 
707 void RegBankSelect::EdgeInsertPoint::materialize() {
708   // If we end up repairing twice at the same place before materializing the
709   // insertion point, we may think we have to split an edge twice.
710   // We should have a factory for the insert point such that identical points
711   // are the same instance.
712   assert(Src.isSuccessor(DstOrSplit) && DstOrSplit->isPredecessor(&Src) &&
713          "This point has already been split");
714   MachineBasicBlock *NewBB = Src.SplitCriticalEdge(DstOrSplit, P);
715   assert(NewBB && "Invalid call to materialize");
716   // We reuse the destination block to hold the information of the new block.
717   DstOrSplit = NewBB;
718 }
719 
720 uint64_t RegBankSelect::EdgeInsertPoint::frequency(const Pass &P) const {
721   const MachineBlockFrequencyInfo *MBFI =
722       P.getAnalysisIfAvailable<MachineBlockFrequencyInfo>();
723   if (!MBFI)
724     return 1;
725   if (WasMaterialized)
726     return MBFI->getBlockFreq(DstOrSplit).getFrequency();
727 
728   const MachineBranchProbabilityInfo *MBPI =
729       P.getAnalysisIfAvailable<MachineBranchProbabilityInfo>();
730   if (!MBPI)
731     return 1;
732   // The basic block will be on the edge.
733   return (MBFI->getBlockFreq(&Src) * MBPI->getEdgeProbability(&Src, DstOrSplit))
734       .getFrequency();
735 }
736 
737 bool RegBankSelect::EdgeInsertPoint::canMaterialize() const {
738   // If this is not a critical edge, we should not have used this insert
739   // point. Indeed, either the successor or the predecessor should
740   // have do.
741   assert(Src.succ_size() > 1 && DstOrSplit->pred_size() > 1 &&
742          "Edge is not critical");
743   return Src.canSplitCriticalEdge(DstOrSplit);
744 }
745 
746 RegBankSelect::MappingCost::MappingCost(const BlockFrequency &LocalFreq)
747     : LocalCost(0), NonLocalCost(0), LocalFreq(LocalFreq.getFrequency()) {}
748 
749 bool RegBankSelect::MappingCost::addLocalCost(uint64_t Cost) {
750   // Check if this overflows.
751   if (LocalCost + Cost < LocalCost) {
752     saturate();
753     return true;
754   }
755   LocalCost += Cost;
756   return isSaturated();
757 }
758 
759 bool RegBankSelect::MappingCost::addNonLocalCost(uint64_t Cost) {
760   // Check if this overflows.
761   if (NonLocalCost + Cost < NonLocalCost) {
762     saturate();
763     return true;
764   }
765   NonLocalCost += Cost;
766   return isSaturated();
767 }
768 
769 bool RegBankSelect::MappingCost::isSaturated() const {
770   return LocalCost == UINT64_MAX - 1 && NonLocalCost == UINT64_MAX &&
771          LocalFreq == UINT64_MAX;
772 }
773 
774 void RegBankSelect::MappingCost::saturate() {
775   *this = ImpossibleCost();
776   --LocalCost;
777 }
778 
779 RegBankSelect::MappingCost RegBankSelect::MappingCost::ImpossibleCost() {
780   return MappingCost(UINT64_MAX, UINT64_MAX, UINT64_MAX);
781 }
782 
783 bool RegBankSelect::MappingCost::operator<(const MappingCost &Cost) const {
784   // Sort out the easy cases.
785   if (*this == Cost)
786     return false;
787   // If one is impossible to realize the other is cheaper unless it is
788   // impossible as well.
789   if ((*this == ImpossibleCost()) || (Cost == ImpossibleCost()))
790     return (*this == ImpossibleCost()) < (Cost == ImpossibleCost());
791   // If one is saturated the other is cheaper, unless it is saturated
792   // as well.
793   if (isSaturated() || Cost.isSaturated())
794     return isSaturated() < Cost.isSaturated();
795   // At this point we know both costs hold sensible values.
796 
797   // If both values have a different base frequency, there is no much
798   // we can do but to scale everything.
799   // However, if they have the same base frequency we can avoid making
800   // complicated computation.
801   uint64_t ThisLocalAdjust;
802   uint64_t OtherLocalAdjust;
803   if (LLVM_LIKELY(LocalFreq == Cost.LocalFreq)) {
804 
805     // At this point, we know the local costs are comparable.
806     // Do the case that do not involve potential overflow first.
807     if (NonLocalCost == Cost.NonLocalCost)
808       // Since the non-local costs do not discriminate on the result,
809       // just compare the local costs.
810       return LocalCost < Cost.LocalCost;
811 
812     // The base costs are comparable so we may only keep the relative
813     // value to increase our chances of avoiding overflows.
814     ThisLocalAdjust = 0;
815     OtherLocalAdjust = 0;
816     if (LocalCost < Cost.LocalCost)
817       OtherLocalAdjust = Cost.LocalCost - LocalCost;
818     else
819       ThisLocalAdjust = LocalCost - Cost.LocalCost;
820 
821   } else {
822     ThisLocalAdjust = LocalCost;
823     OtherLocalAdjust = Cost.LocalCost;
824   }
825 
826   // The non-local costs are comparable, just keep the relative value.
827   uint64_t ThisNonLocalAdjust = 0;
828   uint64_t OtherNonLocalAdjust = 0;
829   if (NonLocalCost < Cost.NonLocalCost)
830     OtherNonLocalAdjust = Cost.NonLocalCost - NonLocalCost;
831   else
832     ThisNonLocalAdjust = NonLocalCost - Cost.NonLocalCost;
833   // Scale everything to make them comparable.
834   uint64_t ThisScaledCost = ThisLocalAdjust * LocalFreq;
835   // Check for overflow on that operation.
836   bool ThisOverflows = ThisLocalAdjust && (ThisScaledCost < ThisLocalAdjust ||
837                                            ThisScaledCost < LocalFreq);
838   uint64_t OtherScaledCost = OtherLocalAdjust * Cost.LocalFreq;
839   // Check for overflow on the last operation.
840   bool OtherOverflows =
841       OtherLocalAdjust &&
842       (OtherScaledCost < OtherLocalAdjust || OtherScaledCost < Cost.LocalFreq);
843   // Add the non-local costs.
844   ThisOverflows |= ThisNonLocalAdjust &&
845                    ThisScaledCost + ThisNonLocalAdjust < ThisNonLocalAdjust;
846   ThisScaledCost += ThisNonLocalAdjust;
847   OtherOverflows |= OtherNonLocalAdjust &&
848                     OtherScaledCost + OtherNonLocalAdjust < OtherNonLocalAdjust;
849   OtherScaledCost += OtherNonLocalAdjust;
850   // If both overflows, we cannot compare without additional
851   // precision, e.g., APInt. Just give up on that case.
852   if (ThisOverflows && OtherOverflows)
853     return false;
854   // If one overflows but not the other, we can still compare.
855   if (ThisOverflows || OtherOverflows)
856     return ThisOverflows < OtherOverflows;
857   // Otherwise, just compare the values.
858   return ThisScaledCost < OtherScaledCost;
859 }
860 
861 bool RegBankSelect::MappingCost::operator==(const MappingCost &Cost) const {
862   return LocalCost == Cost.LocalCost && NonLocalCost == Cost.NonLocalCost &&
863          LocalFreq == Cost.LocalFreq;
864 }
865