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