176bf48d9SEugene Zelenko //==- llvm/CodeGen/GlobalISel/RegBankSelect.cpp - RegBankSelect --*- C++ -*-==//
28e8e85c1SQuentin Colombet //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
68e8e85c1SQuentin Colombet //
78e8e85c1SQuentin Colombet //===----------------------------------------------------------------------===//
88e8e85c1SQuentin Colombet /// \file
98e8e85c1SQuentin Colombet /// This file implements the RegBankSelect class.
108e8e85c1SQuentin Colombet //===----------------------------------------------------------------------===//
118e8e85c1SQuentin Colombet 
128e8e85c1SQuentin Colombet #include "llvm/CodeGen/GlobalISel/RegBankSelect.h"
13cfd97b93SQuentin Colombet #include "llvm/ADT/PostOrderIterator.h"
1476bf48d9SEugene Zelenko #include "llvm/ADT/STLExtras.h"
1576bf48d9SEugene Zelenko #include "llvm/ADT/SmallVector.h"
1669fa84a6STim Northover #include "llvm/CodeGen/GlobalISel/LegalizerInfo.h"
17ae9dadecSAhmed Bougacha #include "llvm/CodeGen/GlobalISel/Utils.h"
1876bf48d9SEugene Zelenko #include "llvm/CodeGen/MachineBasicBlock.h"
1955650754SQuentin Colombet #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
2055650754SQuentin Colombet #include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
2176bf48d9SEugene Zelenko #include "llvm/CodeGen/MachineFunction.h"
2276bf48d9SEugene Zelenko #include "llvm/CodeGen/MachineInstr.h"
2376bf48d9SEugene Zelenko #include "llvm/CodeGen/MachineOperand.h"
2476bf48d9SEugene Zelenko #include "llvm/CodeGen/MachineOptimizationRemarkEmitter.h"
2540ad573dSQuentin Colombet #include "llvm/CodeGen/MachineRegisterInfo.h"
26cb216076SMircea Trofin #include "llvm/CodeGen/RegisterBank.h"
27cb216076SMircea Trofin #include "llvm/CodeGen/RegisterBankInfo.h"
28b3bde2eaSDavid Blaikie #include "llvm/CodeGen/TargetOpcodes.h"
29acb857b8SQuentin Colombet #include "llvm/CodeGen/TargetPassConfig.h"
30b3bde2eaSDavid Blaikie #include "llvm/CodeGen/TargetRegisterInfo.h"
31b3bde2eaSDavid Blaikie #include "llvm/CodeGen/TargetSubtargetInfo.h"
32432a3883SNico Weber #include "llvm/Config/llvm-config.h"
33b3bde2eaSDavid Blaikie #include "llvm/IR/Function.h"
3405da2fe5SReid Kleckner #include "llvm/InitializePasses.h"
3576bf48d9SEugene Zelenko #include "llvm/Pass.h"
36cfd97b93SQuentin Colombet #include "llvm/Support/BlockFrequency.h"
37a41272fbSQuentin Colombet #include "llvm/Support/CommandLine.h"
3876bf48d9SEugene Zelenko #include "llvm/Support/Compiler.h"
39e16f561dSQuentin Colombet #include "llvm/Support/Debug.h"
4076bf48d9SEugene Zelenko #include "llvm/Support/ErrorHandling.h"
4176bf48d9SEugene Zelenko #include "llvm/Support/raw_ostream.h"
4276bf48d9SEugene Zelenko #include <algorithm>
4376bf48d9SEugene Zelenko #include <cassert>
4476bf48d9SEugene Zelenko #include <cstdint>
4576bf48d9SEugene Zelenko #include <limits>
4676bf48d9SEugene Zelenko #include <memory>
4776bf48d9SEugene Zelenko #include <utility>
488e8e85c1SQuentin Colombet 
498e8e85c1SQuentin Colombet #define DEBUG_TYPE "regbankselect"
508e8e85c1SQuentin Colombet 
518e8e85c1SQuentin Colombet using namespace llvm;
528e8e85c1SQuentin Colombet 
53a41272fbSQuentin Colombet static cl::opt<RegBankSelect::Mode> RegBankSelectMode(
54a41272fbSQuentin Colombet     cl::desc("Mode of the RegBankSelect pass"), cl::Hidden, cl::Optional,
55a41272fbSQuentin Colombet     cl::values(clEnumValN(RegBankSelect::Mode::Fast, "regbankselect-fast",
56a41272fbSQuentin Colombet                           "Run the Fast mode (default mapping)"),
57a41272fbSQuentin Colombet                clEnumValN(RegBankSelect::Mode::Greedy, "regbankselect-greedy",
58732afdd0SMehdi Amini                           "Use the Greedy mode (best local mapping)")));
59a41272fbSQuentin Colombet 
608e8e85c1SQuentin Colombet char RegBankSelect::ID = 0;
6176bf48d9SEugene Zelenko 
62c13ea88aSQuentin Colombet INITIALIZE_PASS_BEGIN(RegBankSelect, DEBUG_TYPE,
638e8e85c1SQuentin Colombet                       "Assign register bank of generic virtual registers",
648e8e85c1SQuentin Colombet                       false, false);
6525fcef73SQuentin Colombet INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo)
INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)6625fcef73SQuentin Colombet INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
67acb857b8SQuentin Colombet INITIALIZE_PASS_DEPENDENCY(TargetPassConfig)
68c13ea88aSQuentin Colombet INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE,
6925fcef73SQuentin Colombet                     "Assign register bank of generic virtual registers", false,
70884b47ecSTim Northover                     false)
718e8e85c1SQuentin Colombet 
7246df722eSQuentin Colombet RegBankSelect::RegBankSelect(Mode RunningMode)
7376bf48d9SEugene Zelenko     : MachineFunctionPass(ID), OptMode(RunningMode) {
74a41272fbSQuentin Colombet   if (RegBankSelectMode.getNumOccurrences() != 0) {
75a41272fbSQuentin Colombet     OptMode = RegBankSelectMode;
76a41272fbSQuentin Colombet     if (RegBankSelectMode != RunningMode)
77d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "RegBankSelect mode overrided by command line\n");
78a41272fbSQuentin Colombet   }
798e8e85c1SQuentin Colombet }
808e8e85c1SQuentin Colombet 
init(MachineFunction & MF)8140ad573dSQuentin Colombet void RegBankSelect::init(MachineFunction &MF) {
8240ad573dSQuentin Colombet   RBI = MF.getSubtarget().getRegBankInfo();
8340ad573dSQuentin Colombet   assert(RBI && "Cannot work without RegisterBankInfo");
8440ad573dSQuentin Colombet   MRI = &MF.getRegInfo();
85aac71a4aSQuentin Colombet   TRI = MF.getSubtarget().getRegisterInfo();
86acb857b8SQuentin Colombet   TPC = &getAnalysis<TargetPassConfig>();
8725fcef73SQuentin Colombet   if (OptMode != Mode::Fast) {
8825fcef73SQuentin Colombet     MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
8925fcef73SQuentin Colombet     MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
9025fcef73SQuentin Colombet   } else {
9125fcef73SQuentin Colombet     MBFI = nullptr;
9225fcef73SQuentin Colombet     MBPI = nullptr;
9325fcef73SQuentin Colombet   }
9440ad573dSQuentin Colombet   MIRBuilder.setMF(MF);
950eaee545SJonas Devlieghere   MORE = std::make_unique<MachineOptimizationRemarkEmitter>(MF, MBFI);
9640ad573dSQuentin Colombet }
9740ad573dSQuentin Colombet 
getAnalysisUsage(AnalysisUsage & AU) const9825fcef73SQuentin Colombet void RegBankSelect::getAnalysisUsage(AnalysisUsage &AU) const {
9925fcef73SQuentin Colombet   if (OptMode != Mode::Fast) {
10025fcef73SQuentin Colombet     // We could preserve the information from these two analysis but
10125fcef73SQuentin Colombet     // the APIs do not allow to do so yet.
10225fcef73SQuentin Colombet     AU.addRequired<MachineBlockFrequencyInfo>();
10325fcef73SQuentin Colombet     AU.addRequired<MachineBranchProbabilityInfo>();
10425fcef73SQuentin Colombet   }
105acb857b8SQuentin Colombet   AU.addRequired<TargetPassConfig>();
10690ad6835SMatthias Braun   getSelectionDAGFallbackAnalysisUsage(AU);
10725fcef73SQuentin Colombet   MachineFunctionPass::getAnalysisUsage(AU);
10825fcef73SQuentin Colombet }
10925fcef73SQuentin Colombet 
assignmentMatch(Register Reg,const RegisterBankInfo::ValueMapping & ValMapping,bool & OnlyAssign) const11040ad573dSQuentin Colombet bool RegBankSelect::assignmentMatch(
1113018d184SMatt Arsenault     Register Reg, const RegisterBankInfo::ValueMapping &ValMapping,
1120d77da4eSQuentin Colombet     bool &OnlyAssign) const {
1130d77da4eSQuentin Colombet   // By default we assume we will have to repair something.
1140d77da4eSQuentin Colombet   OnlyAssign = false;
11540ad573dSQuentin Colombet   // Each part of a break down needs to end up in a different register.
116376f2ef2SMatt Arsenault   // In other word, Reg assignment does not match.
1171ac38ba7SMatt Arsenault   if (ValMapping.NumBreakDowns != 1)
11840ad573dSQuentin Colombet     return false;
11940ad573dSQuentin Colombet 
1206d6d6af2SQuentin Colombet   const RegisterBank *CurRegBank = RBI->getRegBank(Reg, *MRI, *TRI);
1219b616415SMatt Arsenault   const RegisterBank *DesiredRegBank = ValMapping.BreakDown[0].RegBank;
1220d77da4eSQuentin Colombet   // Reg is free of assignment, a simple assignment will make the
1230d77da4eSQuentin Colombet   // register bank to match.
1240d77da4eSQuentin Colombet   OnlyAssign = CurRegBank == nullptr;
125d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "Does assignment already match: ";
1266d6d6af2SQuentin Colombet              if (CurRegBank) dbgs() << *CurRegBank; else dbgs() << "none";
1276d6d6af2SQuentin Colombet              dbgs() << " against ";
1289b616415SMatt Arsenault              assert(DesiredRegBank && "The mapping must be valid");
1299b616415SMatt Arsenault              dbgs() << *DesiredRegBank << '\n';);
1309b616415SMatt Arsenault   return CurRegBank == DesiredRegBank;
13140ad573dSQuentin Colombet }
13240ad573dSQuentin Colombet 
repairReg(MachineOperand & MO,const RegisterBankInfo::ValueMapping & ValMapping,RegBankSelect::RepairingPlacement & RepairPt,const iterator_range<SmallVectorImpl<Register>::const_iterator> & NewVRegs)133acb857b8SQuentin Colombet bool RegBankSelect::repairReg(
134d84d00baSQuentin Colombet     MachineOperand &MO, const RegisterBankInfo::ValueMapping &ValMapping,
135d84d00baSQuentin Colombet     RegBankSelect::RepairingPlacement &RepairPt,
1363018d184SMatt Arsenault     const iterator_range<SmallVectorImpl<Register>::const_iterator> &NewVRegs) {
137baa5d2e6SMatt Arsenault 
138ec6dc308SFangrui Song   assert(ValMapping.NumBreakDowns == (unsigned)size(NewVRegs) &&
139ec6dc308SFangrui Song          "need new vreg for each breakdown");
140baa5d2e6SMatt Arsenault 
141f33e3654SQuentin Colombet   // An empty range of new register means no repairing.
142fdaa7421SJordan Rose   assert(!NewVRegs.empty() && "We should not have to repair");
143f33e3654SQuentin Colombet 
144baa5d2e6SMatt Arsenault   MachineInstr *MI;
145baa5d2e6SMatt Arsenault   if (ValMapping.NumBreakDowns == 1) {
146d84d00baSQuentin Colombet     // Assume we are repairing a use and thus, the original reg will be
147d84d00baSQuentin Colombet     // the source of the repairing.
1483018d184SMatt Arsenault     Register Src = MO.getReg();
1493018d184SMatt Arsenault     Register Dst = *NewVRegs.begin();
150904a2c74SQuentin Colombet 
151d84d00baSQuentin Colombet     // If we repair a definition, swap the source and destination for
152d84d00baSQuentin Colombet     // the repairing.
153d84d00baSQuentin Colombet     if (MO.isDef())
154904a2c74SQuentin Colombet       std::swap(Src, Dst);
155904a2c74SQuentin Colombet 
156d84d00baSQuentin Colombet     assert((RepairPt.getNumInsertPoints() == 1 ||
1572bea69bfSDaniel Sanders             Register::isPhysicalRegister(Dst)) &&
158d84d00baSQuentin Colombet            "We are about to create several defs for Dst");
159904a2c74SQuentin Colombet 
160849fcca0STim Northover     // Build the instruction used to repair, then clone it at the right
161849fcca0STim Northover     // places. Avoiding buildCopy bypasses the check that Src and Dst have the
162849fcca0STim Northover     // same types because the type is a placeholder when this function is called.
163baa5d2e6SMatt Arsenault     MI = MIRBuilder.buildInstrNoInsert(TargetOpcode::COPY)
164baa5d2e6SMatt Arsenault       .addDef(Dst)
165baa5d2e6SMatt Arsenault       .addUse(Src);
166d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "Copy: " << printReg(Src) << " to: " << printReg(Dst)
167d84d00baSQuentin Colombet                << '\n');
168baa5d2e6SMatt Arsenault   } else {
169baa5d2e6SMatt Arsenault     // TODO: Support with G_IMPLICIT_DEF + G_INSERT sequence or G_EXTRACT
170baa5d2e6SMatt Arsenault     // sequence.
171baa5d2e6SMatt Arsenault     assert(ValMapping.partsAllUniform() && "irregular breakdowns not supported");
172baa5d2e6SMatt Arsenault 
173baa5d2e6SMatt Arsenault     LLT RegTy = MRI->getType(MO.getReg());
174baa5d2e6SMatt Arsenault     if (MO.isDef()) {
17575257973SMatt Arsenault       unsigned MergeOp;
17675257973SMatt Arsenault       if (RegTy.isVector()) {
17775257973SMatt Arsenault         if (ValMapping.NumBreakDowns == RegTy.getNumElements())
17875257973SMatt Arsenault           MergeOp = TargetOpcode::G_BUILD_VECTOR;
17975257973SMatt Arsenault         else {
18075257973SMatt Arsenault           assert(
18175257973SMatt Arsenault               (ValMapping.BreakDown[0].Length * ValMapping.NumBreakDowns ==
18275257973SMatt Arsenault                RegTy.getSizeInBits()) &&
18375257973SMatt Arsenault               (ValMapping.BreakDown[0].Length % RegTy.getScalarSizeInBits() ==
18475257973SMatt Arsenault                0) &&
18575257973SMatt Arsenault               "don't understand this value breakdown");
18675257973SMatt Arsenault 
18775257973SMatt Arsenault           MergeOp = TargetOpcode::G_CONCAT_VECTORS;
18875257973SMatt Arsenault         }
18975257973SMatt Arsenault       } else
19075257973SMatt Arsenault         MergeOp = TargetOpcode::G_MERGE_VALUES;
191baa5d2e6SMatt Arsenault 
1926bab7ab1SMatt Arsenault       auto MergeBuilder =
193baa5d2e6SMatt Arsenault         MIRBuilder.buildInstrNoInsert(MergeOp)
194baa5d2e6SMatt Arsenault         .addDef(MO.getReg());
195baa5d2e6SMatt Arsenault 
1963018d184SMatt Arsenault       for (Register SrcReg : NewVRegs)
197baa5d2e6SMatt Arsenault         MergeBuilder.addUse(SrcReg);
198baa5d2e6SMatt Arsenault 
199baa5d2e6SMatt Arsenault       MI = MergeBuilder;
200baa5d2e6SMatt Arsenault     } else {
201baa5d2e6SMatt Arsenault       MachineInstrBuilder UnMergeBuilder =
202baa5d2e6SMatt Arsenault         MIRBuilder.buildInstrNoInsert(TargetOpcode::G_UNMERGE_VALUES);
2033018d184SMatt Arsenault       for (Register DefReg : NewVRegs)
204baa5d2e6SMatt Arsenault         UnMergeBuilder.addDef(DefReg);
205baa5d2e6SMatt Arsenault 
206baa5d2e6SMatt Arsenault       UnMergeBuilder.addUse(MO.getReg());
207baa5d2e6SMatt Arsenault       MI = UnMergeBuilder;
208baa5d2e6SMatt Arsenault     }
209baa5d2e6SMatt Arsenault   }
210baa5d2e6SMatt Arsenault 
211baa5d2e6SMatt Arsenault   if (RepairPt.getNumInsertPoints() != 1)
212baa5d2e6SMatt Arsenault     report_fatal_error("need testcase to support multiple insertion points");
213baa5d2e6SMatt Arsenault 
214d84d00baSQuentin Colombet   // TODO:
215d84d00baSQuentin Colombet   // Check if MI is legal. if not, we need to legalize all the
216d84d00baSQuentin Colombet   // instructions we are going to insert.
217d84d00baSQuentin Colombet   std::unique_ptr<MachineInstr *[]> NewInstrs(
218d84d00baSQuentin Colombet       new MachineInstr *[RepairPt.getNumInsertPoints()]);
219d84d00baSQuentin Colombet   bool IsFirst = true;
220d84d00baSQuentin Colombet   unsigned Idx = 0;
221d84d00baSQuentin Colombet   for (const std::unique_ptr<InsertPoint> &InsertPt : RepairPt) {
222d84d00baSQuentin Colombet     MachineInstr *CurMI;
223d84d00baSQuentin Colombet     if (IsFirst)
224d84d00baSQuentin Colombet       CurMI = MI;
225d84d00baSQuentin Colombet     else
226d84d00baSQuentin Colombet       CurMI = MIRBuilder.getMF().CloneMachineInstr(MI);
227d84d00baSQuentin Colombet     InsertPt->insert(*CurMI);
228d84d00baSQuentin Colombet     NewInstrs[Idx++] = CurMI;
229d84d00baSQuentin Colombet     IsFirst = false;
230d84d00baSQuentin Colombet   }
231d84d00baSQuentin Colombet   // TODO:
232d84d00baSQuentin Colombet   // Legalize NewInstrs if need be.
233acb857b8SQuentin Colombet   return true;
23440ad573dSQuentin Colombet }
23540ad573dSQuentin Colombet 
getRepairCost(const MachineOperand & MO,const RegisterBankInfo::ValueMapping & ValMapping) const236f2723a2aSQuentin Colombet uint64_t RegBankSelect::getRepairCost(
237f2723a2aSQuentin Colombet     const MachineOperand &MO,
238f2723a2aSQuentin Colombet     const RegisterBankInfo::ValueMapping &ValMapping) const {
239f2723a2aSQuentin Colombet   assert(MO.isReg() && "We should only repair register operand");
2400afa7d6bSQuentin Colombet   assert(ValMapping.NumBreakDowns && "Nothing to map??");
241f2723a2aSQuentin Colombet 
2420afa7d6bSQuentin Colombet   bool IsSameNumOfValues = ValMapping.NumBreakDowns == 1;
243f2723a2aSQuentin Colombet   const RegisterBank *CurRegBank = RBI->getRegBank(MO.getReg(), *MRI, *TRI);
244f2723a2aSQuentin Colombet   // If MO does not have a register bank, we should have just been
245f2723a2aSQuentin Colombet   // able to set one unless we have to break the value down.
246baa5d2e6SMatt Arsenault   assert(CurRegBank || MO.isDef());
247baa5d2e6SMatt Arsenault 
248f2723a2aSQuentin Colombet   // Def: Val <- NewDefs
249f2723a2aSQuentin Colombet   //     Same number of values: copy
250f2723a2aSQuentin Colombet   //     Different number: Val = build_sequence Defs1, Defs2, ...
251f2723a2aSQuentin Colombet   // Use: NewSources <- Val.
252f2723a2aSQuentin Colombet   //     Same number of values: copy.
253f2723a2aSQuentin Colombet   //     Different number: Src1, Src2, ... =
254f2723a2aSQuentin Colombet   //           extract_value Val, Src1Begin, Src1Len, Src2Begin, Src2Len, ...
255f2723a2aSQuentin Colombet   // We should remember that this value is available somewhere else to
256f2723a2aSQuentin Colombet   // coalesce the value.
257f2723a2aSQuentin Colombet 
258baa5d2e6SMatt Arsenault   if (ValMapping.NumBreakDowns != 1)
259baa5d2e6SMatt Arsenault     return RBI->getBreakDownCost(ValMapping, CurRegBank);
260baa5d2e6SMatt Arsenault 
261f2723a2aSQuentin Colombet   if (IsSameNumOfValues) {
2629b616415SMatt Arsenault     const RegisterBank *DesiredRegBank = ValMapping.BreakDown[0].RegBank;
263f2723a2aSQuentin Colombet     // If we repair a definition, swap the source and destination for
264f2723a2aSQuentin Colombet     // the repairing.
265f2723a2aSQuentin Colombet     if (MO.isDef())
2669b616415SMatt Arsenault       std::swap(CurRegBank, DesiredRegBank);
267d6886bd2SQuentin Colombet     // TODO: It may be possible to actually avoid the copy.
268d6886bd2SQuentin Colombet     // If we repair something where the source is defined by a copy
269d6886bd2SQuentin Colombet     // and the source of that copy is on the right bank, we can reuse
270d6886bd2SQuentin Colombet     // it for free.
271d6886bd2SQuentin Colombet     // E.g.,
272d6886bd2SQuentin Colombet     // RegToRepair<BankA> = copy AlternativeSrc<BankB>
273d6886bd2SQuentin Colombet     // = op RegToRepair<BankA>
274d6886bd2SQuentin Colombet     // We can simply propagate AlternativeSrc instead of copying RegToRepair
275d6886bd2SQuentin Colombet     // into a new virtual register.
276d6886bd2SQuentin Colombet     // We would also need to propagate this information in the
277d6886bd2SQuentin Colombet     // repairing placement.
2789b616415SMatt Arsenault     unsigned Cost = RBI->copyCost(*DesiredRegBank, *CurRegBank,
2794a6b7501SQuentin Colombet                                   RBI->getSizeInBits(MO.getReg(), *MRI, *TRI));
280f2723a2aSQuentin Colombet     // TODO: use a dedicated constant for ImpossibleCost.
28176bf48d9SEugene Zelenko     if (Cost != std::numeric_limits<unsigned>::max())
282f2723a2aSQuentin Colombet       return Cost;
283f2723a2aSQuentin Colombet     // Return the legalization cost of that repairing.
284f2723a2aSQuentin Colombet   }
28576bf48d9SEugene Zelenko   return std::numeric_limits<unsigned>::max();
286f2723a2aSQuentin Colombet }
287f2723a2aSQuentin Colombet 
findBestMapping(MachineInstr & MI,RegisterBankInfo::InstructionMappings & PossibleMappings,SmallVectorImpl<RepairingPlacement> & RepairPts)288245994d9SQuentin Colombet const RegisterBankInfo::InstructionMapping &RegBankSelect::findBestMapping(
28979fe1beaSQuentin Colombet     MachineInstr &MI, RegisterBankInfo::InstructionMappings &PossibleMappings,
29079fe1beaSQuentin Colombet     SmallVectorImpl<RepairingPlacement> &RepairPts) {
291acb857b8SQuentin Colombet   assert(!PossibleMappings.empty() &&
292acb857b8SQuentin Colombet          "Do not know how to map this instruction");
29379fe1beaSQuentin Colombet 
294245994d9SQuentin Colombet   const RegisterBankInfo::InstructionMapping *BestMapping = nullptr;
29579fe1beaSQuentin Colombet   MappingCost Cost = MappingCost::ImpossibleCost();
29679fe1beaSQuentin Colombet   SmallVector<RepairingPlacement, 4> LocalRepairPts;
297245994d9SQuentin Colombet   for (const RegisterBankInfo::InstructionMapping *CurMapping :
298245994d9SQuentin Colombet        PossibleMappings) {
299245994d9SQuentin Colombet     MappingCost CurCost =
300245994d9SQuentin Colombet         computeMapping(MI, *CurMapping, LocalRepairPts, &Cost);
30179fe1beaSQuentin Colombet     if (CurCost < Cost) {
302d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "New best: " << CurCost << '\n');
30379fe1beaSQuentin Colombet       Cost = CurCost;
304245994d9SQuentin Colombet       BestMapping = CurMapping;
30579fe1beaSQuentin Colombet       RepairPts.clear();
30679fe1beaSQuentin Colombet       for (RepairingPlacement &RepairPt : LocalRepairPts)
30779fe1beaSQuentin Colombet         RepairPts.emplace_back(std::move(RepairPt));
30879fe1beaSQuentin Colombet     }
30979fe1beaSQuentin Colombet   }
310acb857b8SQuentin Colombet   if (!BestMapping && !TPC->isGlobalISelAbortEnabled()) {
311acb857b8SQuentin Colombet     // If none of the mapping worked that means they are all impossible.
312acb857b8SQuentin Colombet     // Thus, pick the first one and set an impossible repairing point.
313acb857b8SQuentin Colombet     // It will trigger the failed isel mode.
314245994d9SQuentin Colombet     BestMapping = *PossibleMappings.begin();
315acb857b8SQuentin Colombet     RepairPts.emplace_back(
316acb857b8SQuentin Colombet         RepairingPlacement(MI, 0, *TRI, *this, RepairingPlacement::Impossible));
317acb857b8SQuentin Colombet   } else
31879fe1beaSQuentin Colombet     assert(BestMapping && "No suitable mapping for instruction");
31979fe1beaSQuentin Colombet   return *BestMapping;
32079fe1beaSQuentin Colombet }
32179fe1beaSQuentin Colombet 
tryAvoidingSplit(RegBankSelect::RepairingPlacement & RepairPt,const MachineOperand & MO,const RegisterBankInfo::ValueMapping & ValMapping) const322f75c2bfcSQuentin Colombet void RegBankSelect::tryAvoidingSplit(
323f75c2bfcSQuentin Colombet     RegBankSelect::RepairingPlacement &RepairPt, const MachineOperand &MO,
324f75c2bfcSQuentin Colombet     const RegisterBankInfo::ValueMapping &ValMapping) const {
325f75c2bfcSQuentin Colombet   const MachineInstr &MI = *MO.getParent();
326f75c2bfcSQuentin Colombet   assert(RepairPt.hasSplit() && "We should not have to adjust for split");
327f75c2bfcSQuentin Colombet   // Splitting should only occur for PHIs or between terminators,
328f75c2bfcSQuentin Colombet   // because we only do local repairing.
329f75c2bfcSQuentin Colombet   assert((MI.isPHI() || MI.isTerminator()) && "Why do we split?");
330f75c2bfcSQuentin Colombet 
331f75c2bfcSQuentin Colombet   assert(&MI.getOperand(RepairPt.getOpIdx()) == &MO &&
332f75c2bfcSQuentin Colombet          "Repairing placement does not match operand");
333f75c2bfcSQuentin Colombet 
334f75c2bfcSQuentin Colombet   // If we need splitting for phis, that means it is because we
335f75c2bfcSQuentin Colombet   // could not find an insertion point before the terminators of
336f75c2bfcSQuentin Colombet   // the predecessor block for this argument. In other words,
337f75c2bfcSQuentin Colombet   // the input value is defined by one of the terminators.
338f75c2bfcSQuentin Colombet   assert((!MI.isPHI() || !MO.isDef()) && "Need split for phi def?");
339f75c2bfcSQuentin Colombet 
340f75c2bfcSQuentin Colombet   // We split to repair the use of a phi or a terminator.
341f75c2bfcSQuentin Colombet   if (!MO.isDef()) {
342f75c2bfcSQuentin Colombet     if (MI.isTerminator()) {
343f75c2bfcSQuentin Colombet       assert(&MI != &(*MI.getParent()->getFirstTerminator()) &&
344f75c2bfcSQuentin Colombet              "Need to split for the first terminator?!");
345f75c2bfcSQuentin Colombet     } else {
346f75c2bfcSQuentin Colombet       // For the PHI case, the split may not be actually required.
347f75c2bfcSQuentin Colombet       // In the copy case, a phi is already a copy on the incoming edge,
348f75c2bfcSQuentin Colombet       // therefore there is no need to split.
3490afa7d6bSQuentin Colombet       if (ValMapping.NumBreakDowns == 1)
350f75c2bfcSQuentin Colombet         // This is a already a copy, there is nothing to do.
351f75c2bfcSQuentin Colombet         RepairPt.switchTo(RepairingPlacement::RepairingKind::Reassign);
352f75c2bfcSQuentin Colombet     }
353f75c2bfcSQuentin Colombet     return;
354f75c2bfcSQuentin Colombet   }
355f75c2bfcSQuentin Colombet 
356f75c2bfcSQuentin Colombet   // At this point, we need to repair a defintion of a terminator.
357f75c2bfcSQuentin Colombet 
358f75c2bfcSQuentin Colombet   // Technically we need to fix the def of MI on all outgoing
359f75c2bfcSQuentin Colombet   // edges of MI to keep the repairing local. In other words, we
360f75c2bfcSQuentin Colombet   // will create several definitions of the same register. This
361f75c2bfcSQuentin Colombet   // does not work for SSA unless that definition is a physical
362f75c2bfcSQuentin Colombet   // register.
363f75c2bfcSQuentin Colombet   // However, there are other cases where we can get away with
364f75c2bfcSQuentin Colombet   // that while still keeping the repairing local.
365f75c2bfcSQuentin Colombet   assert(MI.isTerminator() && MO.isDef() &&
366f75c2bfcSQuentin Colombet          "This code is for the def of a terminator");
367f75c2bfcSQuentin Colombet 
368f75c2bfcSQuentin Colombet   // Since we use RPO traversal, if we need to repair a definition
369f75c2bfcSQuentin Colombet   // this means this definition could be:
370f75c2bfcSQuentin Colombet   // 1. Used by PHIs (i.e., this VReg has been visited as part of the
371f75c2bfcSQuentin Colombet   //    uses of a phi.), or
372f75c2bfcSQuentin Colombet   // 2. Part of a target specific instruction (i.e., the target applied
373f75c2bfcSQuentin Colombet   //    some register class constraints when creating the instruction.)
374f75c2bfcSQuentin Colombet   // If the constraints come for #2, the target said that another mapping
375f75c2bfcSQuentin Colombet   // is supported so we may just drop them. Indeed, if we do not change
376f75c2bfcSQuentin Colombet   // the number of registers holding that value, the uses will get fixed
377f75c2bfcSQuentin Colombet   // when we get to them.
378f75c2bfcSQuentin Colombet   // Uses in PHIs may have already been proceeded though.
379f75c2bfcSQuentin Colombet   // If the constraints come for #1, then, those are weak constraints and
380f75c2bfcSQuentin Colombet   // no actual uses may rely on them. However, the problem remains mainly
381f75c2bfcSQuentin Colombet   // the same as for #2. If the value stays in one register, we could
382f75c2bfcSQuentin Colombet   // just switch the register bank of the definition, but we would need to
383f75c2bfcSQuentin Colombet   // account for a repairing cost for each phi we silently change.
384f75c2bfcSQuentin Colombet   //
385f75c2bfcSQuentin Colombet   // In any case, if the value needs to be broken down into several
386f75c2bfcSQuentin Colombet   // registers, the repairing is not local anymore as we need to patch
387f75c2bfcSQuentin Colombet   // every uses to rebuild the value in just one register.
388f75c2bfcSQuentin Colombet   //
389f75c2bfcSQuentin Colombet   // To summarize:
390f75c2bfcSQuentin Colombet   // - If the value is in a physical register, we can do the split and
391f75c2bfcSQuentin Colombet   //   fix locally.
392f75c2bfcSQuentin Colombet   // Otherwise if the value is in a virtual register:
393f75c2bfcSQuentin Colombet   // - If the value remains in one register, we do not have to split
394f75c2bfcSQuentin Colombet   //   just switching the register bank would do, but we need to account
395f75c2bfcSQuentin Colombet   //   in the repairing cost all the phi we changed.
396f75c2bfcSQuentin Colombet   // - If the value spans several registers, then we cannot do a local
397f75c2bfcSQuentin Colombet   //   repairing.
398f75c2bfcSQuentin Colombet 
399f75c2bfcSQuentin Colombet   // Check if this is a physical or virtual register.
4003018d184SMatt Arsenault   Register Reg = MO.getReg();
4012bea69bfSDaniel Sanders   if (Register::isPhysicalRegister(Reg)) {
402f75c2bfcSQuentin Colombet     // We are going to split every outgoing edges.
403f75c2bfcSQuentin Colombet     // Check that this is possible.
404f75c2bfcSQuentin Colombet     // FIXME: The machine representation is currently broken
405f75c2bfcSQuentin Colombet     // since it also several terminators in one basic block.
406f75c2bfcSQuentin Colombet     // Because of that we would technically need a way to get
407f75c2bfcSQuentin Colombet     // the targets of just one terminator to know which edges
408f75c2bfcSQuentin Colombet     // we have to split.
409f75c2bfcSQuentin Colombet     // Assert that we do not hit the ill-formed representation.
410f75c2bfcSQuentin Colombet 
411f75c2bfcSQuentin Colombet     // If there are other terminators before that one, some of
412f75c2bfcSQuentin Colombet     // the outgoing edges may not be dominated by this definition.
413f75c2bfcSQuentin Colombet     assert(&MI == &(*MI.getParent()->getFirstTerminator()) &&
414f75c2bfcSQuentin Colombet            "Do not know which outgoing edges are relevant");
415f75c2bfcSQuentin Colombet     const MachineInstr *Next = MI.getNextNode();
416f75c2bfcSQuentin Colombet     assert((!Next || Next->isUnconditionalBranch()) &&
417f75c2bfcSQuentin Colombet            "Do not know where each terminator ends up");
418f75c2bfcSQuentin Colombet     if (Next)
419f75c2bfcSQuentin Colombet       // If the next terminator uses Reg, this means we have
420f75c2bfcSQuentin Colombet       // to split right after MI and thus we need a way to ask
421f75c2bfcSQuentin Colombet       // which outgoing edges are affected.
422f75c2bfcSQuentin Colombet       assert(!Next->readsRegister(Reg) && "Need to split between terminators");
423f75c2bfcSQuentin Colombet     // We will split all the edges and repair there.
424f75c2bfcSQuentin Colombet   } else {
425f75c2bfcSQuentin Colombet     // This is a virtual register defined by a terminator.
4260afa7d6bSQuentin Colombet     if (ValMapping.NumBreakDowns == 1) {
427f75c2bfcSQuentin Colombet       // There is nothing to repair, but we may actually lie on
428f75c2bfcSQuentin Colombet       // the repairing cost because of the PHIs already proceeded
429f75c2bfcSQuentin Colombet       // as already stated.
430f75c2bfcSQuentin Colombet       // Though the code will be correct.
43176bf48d9SEugene Zelenko       assert(false && "Repairing cost may not be accurate");
432f75c2bfcSQuentin Colombet     } else {
433f75c2bfcSQuentin Colombet       // We need to do non-local repairing. Basically, patch all
434f75c2bfcSQuentin Colombet       // the uses (i.e., phis) that we already proceeded.
435f75c2bfcSQuentin Colombet       // For now, just say this mapping is not possible.
436f75c2bfcSQuentin Colombet       RepairPt.switchTo(RepairingPlacement::RepairingKind::Impossible);
437f75c2bfcSQuentin Colombet     }
438f75c2bfcSQuentin Colombet   }
439f75c2bfcSQuentin Colombet }
440f75c2bfcSQuentin Colombet 
computeMapping(MachineInstr & MI,const RegisterBankInfo::InstructionMapping & InstrMapping,SmallVectorImpl<RepairingPlacement> & RepairPts,const RegBankSelect::MappingCost * BestCost)441d84d00baSQuentin Colombet RegBankSelect::MappingCost RegBankSelect::computeMapping(
442d84d00baSQuentin Colombet     MachineInstr &MI, const RegisterBankInfo::InstructionMapping &InstrMapping,
4436e80dbcdSQuentin Colombet     SmallVectorImpl<RepairingPlacement> &RepairPts,
4446e80dbcdSQuentin Colombet     const RegBankSelect::MappingCost *BestCost) {
4456e80dbcdSQuentin Colombet   assert((MBFI || !BestCost) && "Costs comparison require MBFI");
446e16f561dSQuentin Colombet 
447c1a23854STim Northover   if (!InstrMapping.isValid())
448c1a23854STim Northover     return MappingCost::ImpossibleCost();
449c1a23854STim Northover 
450d84d00baSQuentin Colombet   // If mapped with InstrMapping, MI will have the recorded cost.
45125fcef73SQuentin Colombet   MappingCost Cost(MBFI ? MBFI->getBlockFreq(MI.getParent()) : 1);
452d84d00baSQuentin Colombet   bool Saturated = Cost.addLocalCost(InstrMapping.getCost());
453d84d00baSQuentin Colombet   assert(!Saturated && "Possible mapping saturated the cost");
454d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "Evaluating mapping cost for: " << MI);
455d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "With: " << InstrMapping << '\n');
456d84d00baSQuentin Colombet   RepairPts.clear();
4570b63b31bSQuentin Colombet   if (BestCost && Cost > *BestCost) {
458d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "Mapping is too expensive from the start\n");
4596e80dbcdSQuentin Colombet     return Cost;
4600b63b31bSQuentin Colombet   }
4616e80dbcdSQuentin Colombet 
462d84d00baSQuentin Colombet   // Moreover, to realize this mapping, the register bank of each operand must
463d84d00baSQuentin Colombet   // match this mapping. In other words, we may need to locally reassign the
464d84d00baSQuentin Colombet   // register banks. Account for that repairing cost as well.
465d84d00baSQuentin Colombet   // In this context, local means in the surrounding of MI.
4661b01677eSQuentin Colombet   for (unsigned OpIdx = 0, EndOpIdx = InstrMapping.getNumOperands();
4671b01677eSQuentin Colombet        OpIdx != EndOpIdx; ++OpIdx) {
468d84d00baSQuentin Colombet     const MachineOperand &MO = MI.getOperand(OpIdx);
46940ad573dSQuentin Colombet     if (!MO.isReg())
47040ad573dSQuentin Colombet       continue;
4713018d184SMatt Arsenault     Register Reg = MO.getReg();
47240ad573dSQuentin Colombet     if (!Reg)
47340ad573dSQuentin Colombet       continue;
474d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "Opd" << OpIdx << '\n');
47540ad573dSQuentin Colombet     const RegisterBankInfo::ValueMapping &ValMapping =
476d84d00baSQuentin Colombet         InstrMapping.getOperandMapping(OpIdx);
477d84d00baSQuentin Colombet     // If Reg is already properly mapped, this is free.
478d84d00baSQuentin Colombet     bool Assign;
479d84d00baSQuentin Colombet     if (assignmentMatch(Reg, ValMapping, Assign)) {
480d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "=> is free (match).\n");
481904a2c74SQuentin Colombet       continue;
48240ad573dSQuentin Colombet     }
483d84d00baSQuentin Colombet     if (Assign) {
484d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "=> is free (simple assignment).\n");
485d84d00baSQuentin Colombet       RepairPts.emplace_back(RepairingPlacement(MI, OpIdx, *TRI, *this,
486d84d00baSQuentin Colombet                                                 RepairingPlacement::Reassign));
487d84d00baSQuentin Colombet       continue;
488904a2c74SQuentin Colombet     }
489904a2c74SQuentin Colombet 
490d84d00baSQuentin Colombet     // Find the insertion point for the repairing code.
491d84d00baSQuentin Colombet     RepairPts.emplace_back(
492d84d00baSQuentin Colombet         RepairingPlacement(MI, OpIdx, *TRI, *this, RepairingPlacement::Insert));
493d84d00baSQuentin Colombet     RepairingPlacement &RepairPt = RepairPts.back();
494d84d00baSQuentin Colombet 
495f75c2bfcSQuentin Colombet     // If we need to split a basic block to materialize this insertion point,
496f75c2bfcSQuentin Colombet     // we may give a higher cost to this mapping.
497f75c2bfcSQuentin Colombet     // Nevertheless, we may get away with the split, so try that first.
498f75c2bfcSQuentin Colombet     if (RepairPt.hasSplit())
499f75c2bfcSQuentin Colombet       tryAvoidingSplit(RepairPt, MO, ValMapping);
500f75c2bfcSQuentin Colombet 
501d84d00baSQuentin Colombet     // Check that the materialization of the repairing is possible.
5020b63b31bSQuentin Colombet     if (!RepairPt.canMaterialize()) {
503d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "Mapping involves impossible repairing\n");
504d84d00baSQuentin Colombet       return MappingCost::ImpossibleCost();
5050b63b31bSQuentin Colombet     }
506d84d00baSQuentin Colombet 
507d84d00baSQuentin Colombet     // Account for the split cost and repair cost.
5086e80dbcdSQuentin Colombet     // Unless the cost is already saturated or we do not care about the cost.
5096e80dbcdSQuentin Colombet     if (!BestCost || Saturated)
510d84d00baSQuentin Colombet       continue;
511d84d00baSQuentin Colombet 
5126e80dbcdSQuentin Colombet     // To get accurate information we need MBFI and MBPI.
5136e80dbcdSQuentin Colombet     // Thus, if we end up here this information should be here.
5146e80dbcdSQuentin Colombet     assert(MBFI && MBPI && "Cost computation requires MBFI and MBPI");
5156e80dbcdSQuentin Colombet 
5166feaf820SQuentin Colombet     // FIXME: We will have to rework the repairing cost model.
5176feaf820SQuentin Colombet     // The repairing cost depends on the register bank that MO has.
5186feaf820SQuentin Colombet     // However, when we break down the value into different values,
5196feaf820SQuentin Colombet     // MO may not have a register bank while still needing repairing.
5206feaf820SQuentin Colombet     // For the fast mode, we don't compute the cost so that is fine,
5216feaf820SQuentin Colombet     // but still for the repairing code, we will have to make a choice.
5226feaf820SQuentin Colombet     // For the greedy mode, we should choose greedily what is the best
5236feaf820SQuentin Colombet     // choice based on the next use of MO.
5246feaf820SQuentin Colombet 
525f2723a2aSQuentin Colombet     // Sums up the repairing cost of MO at each insertion point.
526f2723a2aSQuentin Colombet     uint64_t RepairCost = getRepairCost(MO, ValMapping);
527049e7e07STom Stellard 
528049e7e07STom Stellard     // This is an impossible to repair cost.
52976bf48d9SEugene Zelenko     if (RepairCost == std::numeric_limits<unsigned>::max())
530179757efSTom Stellard       return MappingCost::ImpossibleCost();
531049e7e07STom Stellard 
532d84d00baSQuentin Colombet     // Bias used for splitting: 5%.
533d84d00baSQuentin Colombet     const uint64_t PercentageForBias = 5;
534d84d00baSQuentin Colombet     uint64_t Bias = (RepairCost * PercentageForBias + 99) / 100;
535d84d00baSQuentin Colombet     // We should not need more than a couple of instructions to repair
536d84d00baSQuentin Colombet     // an assignment. In other words, the computation should not
537d84d00baSQuentin Colombet     // overflow because the repairing cost is free of basic block
538d84d00baSQuentin Colombet     // frequency.
539d84d00baSQuentin Colombet     assert(((RepairCost < RepairCost * PercentageForBias) &&
540d84d00baSQuentin Colombet             (RepairCost * PercentageForBias <
541d84d00baSQuentin Colombet              RepairCost * PercentageForBias + 99)) &&
542d84d00baSQuentin Colombet            "Repairing involves more than a billion of instructions?!");
543d84d00baSQuentin Colombet     for (const std::unique_ptr<InsertPoint> &InsertPt : RepairPt) {
544d84d00baSQuentin Colombet       assert(InsertPt->canMaterialize() && "We should not have made it here");
545d84d00baSQuentin Colombet       // We will applied some basic block frequency and those uses uint64_t.
546d84d00baSQuentin Colombet       if (!InsertPt->isSplit())
547d84d00baSQuentin Colombet         Saturated = Cost.addLocalCost(RepairCost);
548d84d00baSQuentin Colombet       else {
549d84d00baSQuentin Colombet         uint64_t CostForInsertPt = RepairCost;
550d84d00baSQuentin Colombet         // Again we shouldn't overflow here givent that
551d84d00baSQuentin Colombet         // CostForInsertPt is frequency free at this point.
552d84d00baSQuentin Colombet         assert(CostForInsertPt + Bias > CostForInsertPt &&
553d84d00baSQuentin Colombet                "Repairing + split bias overflows");
554d84d00baSQuentin Colombet         CostForInsertPt += Bias;
555d84d00baSQuentin Colombet         uint64_t PtCost = InsertPt->frequency(*this) * CostForInsertPt;
556d84d00baSQuentin Colombet         // Check if we just overflowed.
557d84d00baSQuentin Colombet         if ((Saturated = PtCost < CostForInsertPt))
558d84d00baSQuentin Colombet           Cost.saturate();
559d84d00baSQuentin Colombet         else
560d84d00baSQuentin Colombet           Saturated = Cost.addNonLocalCost(PtCost);
561d84d00baSQuentin Colombet       }
5626e80dbcdSQuentin Colombet 
5636e80dbcdSQuentin Colombet       // Stop looking into what it takes to repair, this is already
5646e80dbcdSQuentin Colombet       // too expensive.
5650b63b31bSQuentin Colombet       if (BestCost && Cost > *BestCost) {
566d34e60caSNicola Zaghen         LLVM_DEBUG(dbgs() << "Mapping is too expensive, stop processing\n");
5676e80dbcdSQuentin Colombet         return Cost;
5680b63b31bSQuentin Colombet       }
5696e80dbcdSQuentin Colombet 
570d84d00baSQuentin Colombet       // No need to accumulate more cost information.
571d84d00baSQuentin Colombet       // We need to still gather the repairing information though.
572d84d00baSQuentin Colombet       if (Saturated)
573d84d00baSQuentin Colombet         break;
574d84d00baSQuentin Colombet     }
575d84d00baSQuentin Colombet   }
576d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "Total cost is: " << Cost << "\n");
577d84d00baSQuentin Colombet   return Cost;
578d84d00baSQuentin Colombet }
579d84d00baSQuentin Colombet 
applyMapping(MachineInstr & MI,const RegisterBankInfo::InstructionMapping & InstrMapping,SmallVectorImpl<RegBankSelect::RepairingPlacement> & RepairPts)580acb857b8SQuentin Colombet bool RegBankSelect::applyMapping(
581d84d00baSQuentin Colombet     MachineInstr &MI, const RegisterBankInfo::InstructionMapping &InstrMapping,
582d84d00baSQuentin Colombet     SmallVectorImpl<RegBankSelect::RepairingPlacement> &RepairPts) {
583376f2ef2SMatt Arsenault   // OpdMapper will hold all the information needed for the rewriting.
584f33e3654SQuentin Colombet   RegisterBankInfo::OperandsMapper OpdMapper(MI, InstrMapping, *MRI);
585f33e3654SQuentin Colombet 
586ec5c93d3SQuentin Colombet   // First, place the repairing code.
587d84d00baSQuentin Colombet   for (RepairingPlacement &RepairPt : RepairPts) {
588acb857b8SQuentin Colombet     if (!RepairPt.canMaterialize() ||
589acb857b8SQuentin Colombet         RepairPt.getKind() == RepairingPlacement::Impossible)
590acb857b8SQuentin Colombet       return false;
591d84d00baSQuentin Colombet     assert(RepairPt.getKind() != RepairingPlacement::None &&
592d84d00baSQuentin Colombet            "This should not make its way in the list");
593d84d00baSQuentin Colombet     unsigned OpIdx = RepairPt.getOpIdx();
594d84d00baSQuentin Colombet     MachineOperand &MO = MI.getOperand(OpIdx);
595d84d00baSQuentin Colombet     const RegisterBankInfo::ValueMapping &ValMapping =
596d84d00baSQuentin Colombet         InstrMapping.getOperandMapping(OpIdx);
5973018d184SMatt Arsenault     Register Reg = MO.getReg();
598d84d00baSQuentin Colombet 
599d84d00baSQuentin Colombet     switch (RepairPt.getKind()) {
600d84d00baSQuentin Colombet     case RepairingPlacement::Reassign:
6010afa7d6bSQuentin Colombet       assert(ValMapping.NumBreakDowns == 1 &&
602d84d00baSQuentin Colombet              "Reassignment should only be for simple mapping");
60340ad573dSQuentin Colombet       MRI->setRegBank(Reg, *ValMapping.BreakDown[0].RegBank);
604d84d00baSQuentin Colombet       break;
605d84d00baSQuentin Colombet     case RepairingPlacement::Insert:
606f33e3654SQuentin Colombet       OpdMapper.createVRegs(OpIdx);
607acb857b8SQuentin Colombet       if (!repairReg(MO, ValMapping, RepairPt, OpdMapper.getVRegs(OpIdx)))
608acb857b8SQuentin Colombet         return false;
609d84d00baSQuentin Colombet       break;
610d84d00baSQuentin Colombet     default:
611d84d00baSQuentin Colombet       llvm_unreachable("Other kind should not happen");
612d84d00baSQuentin Colombet     }
613d84d00baSQuentin Colombet   }
614849fcca0STim Northover 
615d84d00baSQuentin Colombet   // Second, rewrite the instruction.
616d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "Actual mapping of the operands: " << OpdMapper << '\n');
617ec5c93d3SQuentin Colombet   RBI->applyMapping(OpdMapper);
618849fcca0STim Northover 
619acb857b8SQuentin Colombet   return true;
620d84d00baSQuentin Colombet }
621d84d00baSQuentin Colombet 
assignInstr(MachineInstr & MI)622acb857b8SQuentin Colombet bool RegBankSelect::assignInstr(MachineInstr &MI) {
623d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "Assign: " << MI);
624d5736a27SJessica Paquette 
62560aa6464SJessica Paquette   unsigned Opc = MI.getOpcode();
62660aa6464SJessica Paquette   if (isPreISelGenericOptimizationHint(Opc)) {
62760aa6464SJessica Paquette     assert((Opc == TargetOpcode::G_ASSERT_ZEXT ||
62899e8e173SMatt Arsenault             Opc == TargetOpcode::G_ASSERT_SEXT ||
62999e8e173SMatt Arsenault             Opc == TargetOpcode::G_ASSERT_ALIGN) &&
63060aa6464SJessica Paquette            "Unexpected hint opcode!");
631d5736a27SJessica Paquette     // The only correct mapping for these is to always use the source register
632d5736a27SJessica Paquette     // bank.
633*40bc9112SMatt Arsenault     const RegisterBank *RB =
634*40bc9112SMatt Arsenault         RBI->getRegBank(MI.getOperand(1).getReg(), *MRI, *TRI);
635d5736a27SJessica Paquette     // We can assume every instruction above this one has a selected register
636d5736a27SJessica Paquette     // bank.
637d5736a27SJessica Paquette     assert(RB && "Expected source register to have a register bank?");
63860aa6464SJessica Paquette     LLVM_DEBUG(dbgs() << "... Hint always uses source's register bank.\n");
639d5736a27SJessica Paquette     MRI->setRegBank(MI.getOperand(0).getReg(), *RB);
640d5736a27SJessica Paquette     return true;
641d5736a27SJessica Paquette   }
642d5736a27SJessica Paquette 
643d84d00baSQuentin Colombet   // Remember the repairing placement for all the operands.
644d84d00baSQuentin Colombet   SmallVector<RepairingPlacement, 4> RepairPts;
645d84d00baSQuentin Colombet 
646245994d9SQuentin Colombet   const RegisterBankInfo::InstructionMapping *BestMapping;
64779fe1beaSQuentin Colombet   if (OptMode == RegBankSelect::Mode::Fast) {
648245994d9SQuentin Colombet     BestMapping = &RBI->getInstrMapping(MI);
649245994d9SQuentin Colombet     MappingCost DefaultCost = computeMapping(MI, *BestMapping, RepairPts);
650d84d00baSQuentin Colombet     (void)DefaultCost;
651acb857b8SQuentin Colombet     if (DefaultCost == MappingCost::ImpossibleCost())
652acb857b8SQuentin Colombet       return false;
65379fe1beaSQuentin Colombet   } else {
65479fe1beaSQuentin Colombet     RegisterBankInfo::InstructionMappings PossibleMappings =
65579fe1beaSQuentin Colombet         RBI->getInstrPossibleMappings(MI);
656acb857b8SQuentin Colombet     if (PossibleMappings.empty())
657acb857b8SQuentin Colombet       return false;
658245994d9SQuentin Colombet     BestMapping = &findBestMapping(MI, PossibleMappings, RepairPts);
65979fe1beaSQuentin Colombet   }
660d84d00baSQuentin Colombet   // Make sure the mapping is valid for MI.
661245994d9SQuentin Colombet   assert(BestMapping->verify(MI) && "Invalid instruction mapping");
662d84d00baSQuentin Colombet 
663d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "Best Mapping: " << *BestMapping << '\n');
664d84d00baSQuentin Colombet 
6659400bfbfSQuentin Colombet   // After this call, MI may not be valid anymore.
6669400bfbfSQuentin Colombet   // Do not use it.
667245994d9SQuentin Colombet   return applyMapping(MI, *BestMapping, RepairPts);
66840ad573dSQuentin Colombet }
66940ad573dSQuentin Colombet 
runOnMachineFunction(MachineFunction & MF)6708e8e85c1SQuentin Colombet bool RegBankSelect::runOnMachineFunction(MachineFunction &MF) {
6716049524dSQuentin Colombet   // If the ISel pipeline failed, do not bother running that pass.
6726049524dSQuentin Colombet   if (MF.getProperties().hasProperty(
6736049524dSQuentin Colombet           MachineFunctionProperties::Property::FailedISel))
6746049524dSQuentin Colombet     return false;
6756049524dSQuentin Colombet 
676d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "Assign register banks for: " << MF.getName() << '\n');
677f1caa283SMatthias Braun   const Function &F = MF.getFunction();
678a5530128SQuentin Colombet   Mode SaveOptMode = OptMode;
67985bd3978SEvandro Menezes   if (F.hasOptNone())
680a5530128SQuentin Colombet     OptMode = Mode::Fast;
68140ad573dSQuentin Colombet   init(MF);
68224d0d4d2SAhmed Bougacha 
68324d0d4d2SAhmed Bougacha #ifndef NDEBUG
68424d0d4d2SAhmed Bougacha   // Check that our input is fully legal: we require the function to have the
68524d0d4d2SAhmed Bougacha   // Legalized property, so it should be.
6862b94972eSRoman Tereshin   // FIXME: This should be in the MachineVerifier.
6872b94972eSRoman Tereshin   if (!DisableGISelLegalityCheck)
6882b94972eSRoman Tereshin     if (const MachineInstr *MI = machineFunctionIsIllegal(MF)) {
689ae9dadecSAhmed Bougacha       reportGISelFailure(MF, *TPC, *MORE, "gisel-regbankselect",
6902b94972eSRoman Tereshin                          "instruction is not legal", *MI);
691acb857b8SQuentin Colombet       return false;
692acb857b8SQuentin Colombet     }
69324d0d4d2SAhmed Bougacha #endif
69424d0d4d2SAhmed Bougacha 
69540ad573dSQuentin Colombet   // Walk the function and assign register banks to all operands.
696ab8c21f7SQuentin Colombet   // Use a RPOT to make sure all registers are assigned before we choose
697ab8c21f7SQuentin Colombet   // the best mapping of the current instruction.
698ab8c21f7SQuentin Colombet   ReversePostOrderTraversal<MachineFunction*> RPOT(&MF);
699d84d00baSQuentin Colombet   for (MachineBasicBlock *MBB : RPOT) {
700d84d00baSQuentin Colombet     // Set a sensible insertion point so that subsequent calls to
701d84d00baSQuentin Colombet     // MIRBuilder.
702d84d00baSQuentin Colombet     MIRBuilder.setMBB(*MBB);
70350d8d963SNeubauer, Sebastian     SmallVector<MachineInstr *> WorkList(
70450d8d963SNeubauer, Sebastian         make_pointer_range(reverse(MBB->instrs())));
70550d8d963SNeubauer, Sebastian 
70650d8d963SNeubauer, Sebastian     while (!WorkList.empty()) {
70750d8d963SNeubauer, Sebastian       MachineInstr &MI = *WorkList.pop_back_val();
70845eb3b94SAhmed Bougacha 
70927269054SMatt Arsenault       // Ignore target-specific post-isel instructions: they should use proper
71027269054SMatt Arsenault       // regclasses.
71127269054SMatt Arsenault       if (isTargetSpecificOpcode(MI.getOpcode()) && !MI.isPreISelOpcode())
71245eb3b94SAhmed Bougacha         continue;
71345eb3b94SAhmed Bougacha 
714e82b0e9aSKonstantin Schwarz       // Ignore inline asm instructions: they should use physical
715e82b0e9aSKonstantin Schwarz       // registers/regclasses
716e82b0e9aSKonstantin Schwarz       if (MI.isInlineAsm())
717e82b0e9aSKonstantin Schwarz         continue;
718e82b0e9aSKonstantin Schwarz 
7195bae2775SVedant Kumar       // Ignore debug info.
7205bae2775SVedant Kumar       if (MI.isDebugInstr())
7215bae2775SVedant Kumar         continue;
7225bae2775SVedant Kumar 
7230d2c4db6SAmara Emerson       // Ignore IMPLICIT_DEF which must have a regclass.
7240d2c4db6SAmara Emerson       if (MI.isImplicitDef())
7250d2c4db6SAmara Emerson         continue;
7260d2c4db6SAmara Emerson 
727acb857b8SQuentin Colombet       if (!assignInstr(MI)) {
728ae9dadecSAhmed Bougacha         reportGISelFailure(MF, *TPC, *MORE, "gisel-regbankselect",
729ae9dadecSAhmed Bougacha                            "unable to map instruction", MI);
730acb857b8SQuentin Colombet         return false;
731acb857b8SQuentin Colombet       }
7328df2f3daSMatt Arsenault     }
7338df2f3daSMatt Arsenault   }
7348df2f3daSMatt Arsenault 
735a5530128SQuentin Colombet   OptMode = SaveOptMode;
7368e8e85c1SQuentin Colombet   return false;
7378e8e85c1SQuentin Colombet }
738cfd97b93SQuentin Colombet 
739cfd97b93SQuentin Colombet //------------------------------------------------------------------------------
74055650754SQuentin Colombet //                  Helper Classes Implementation
741cfd97b93SQuentin Colombet //------------------------------------------------------------------------------
RepairingPlacement(MachineInstr & MI,unsigned OpIdx,const TargetRegisterInfo & TRI,Pass & P,RepairingPlacement::RepairingKind Kind)74255650754SQuentin Colombet RegBankSelect::RepairingPlacement::RepairingPlacement(
74355650754SQuentin Colombet     MachineInstr &MI, unsigned OpIdx, const TargetRegisterInfo &TRI, Pass &P,
74455650754SQuentin Colombet     RepairingPlacement::RepairingKind Kind)
74555650754SQuentin Colombet     // Default is, we are going to insert code to repair OpIdx.
74676bf48d9SEugene Zelenko     : Kind(Kind), OpIdx(OpIdx),
74776bf48d9SEugene Zelenko       CanMaterialize(Kind != RepairingKind::Impossible), P(P) {
74855650754SQuentin Colombet   const MachineOperand &MO = MI.getOperand(OpIdx);
74955650754SQuentin Colombet   assert(MO.isReg() && "Trying to repair a non-reg operand");
75055650754SQuentin Colombet 
75155650754SQuentin Colombet   if (Kind != RepairingKind::Insert)
75255650754SQuentin Colombet     return;
75355650754SQuentin Colombet 
75455650754SQuentin Colombet   // Repairings for definitions happen after MI, uses happen before.
75555650754SQuentin Colombet   bool Before = !MO.isDef();
75655650754SQuentin Colombet 
75755650754SQuentin Colombet   // Check if we are done with MI.
75855650754SQuentin Colombet   if (!MI.isPHI() && !MI.isTerminator()) {
75955650754SQuentin Colombet     addInsertPoint(MI, Before);
76055650754SQuentin Colombet     // We are done with the initialization.
76155650754SQuentin Colombet     return;
76255650754SQuentin Colombet   }
76355650754SQuentin Colombet 
76455650754SQuentin Colombet   // Now, look for the special cases.
76555650754SQuentin Colombet   if (MI.isPHI()) {
76655650754SQuentin Colombet     // - PHI must be the first instructions:
76755650754SQuentin Colombet     //   * Before, we have to split the related incoming edge.
76855650754SQuentin Colombet     //   * After, move the insertion point past the last phi.
76955650754SQuentin Colombet     if (!Before) {
77055650754SQuentin Colombet       MachineBasicBlock::iterator It = MI.getParent()->getFirstNonPHI();
77155650754SQuentin Colombet       if (It != MI.getParent()->end())
77255650754SQuentin Colombet         addInsertPoint(*It, /*Before*/ true);
77355650754SQuentin Colombet       else
77455650754SQuentin Colombet         addInsertPoint(*(--It), /*Before*/ false);
77555650754SQuentin Colombet       return;
77655650754SQuentin Colombet     }
77755650754SQuentin Colombet     // We repair a use of a phi, we may need to split the related edge.
77855650754SQuentin Colombet     MachineBasicBlock &Pred = *MI.getOperand(OpIdx + 1).getMBB();
77955650754SQuentin Colombet     // Check if we can move the insertion point prior to the
78055650754SQuentin Colombet     // terminators of the predecessor.
7813018d184SMatt Arsenault     Register Reg = MO.getReg();
78255650754SQuentin Colombet     MachineBasicBlock::iterator It = Pred.getLastNonDebugInstr();
78355650754SQuentin Colombet     for (auto Begin = Pred.begin(); It != Begin && It->isTerminator(); --It)
78455650754SQuentin Colombet       if (It->modifiesRegister(Reg, &TRI)) {
78555650754SQuentin Colombet         // We cannot hoist the repairing code in the predecessor.
78655650754SQuentin Colombet         // Split the edge.
78755650754SQuentin Colombet         addInsertPoint(Pred, *MI.getParent());
78855650754SQuentin Colombet         return;
78955650754SQuentin Colombet       }
79055650754SQuentin Colombet     // At this point, we can insert in Pred.
79155650754SQuentin Colombet 
79255650754SQuentin Colombet     // - If It is invalid, Pred is empty and we can insert in Pred
79355650754SQuentin Colombet     //   wherever we want.
79455650754SQuentin Colombet     // - If It is valid, It is the first non-terminator, insert after It.
79555650754SQuentin Colombet     if (It == Pred.end())
79655650754SQuentin Colombet       addInsertPoint(Pred, /*Beginning*/ false);
79755650754SQuentin Colombet     else
79855650754SQuentin Colombet       addInsertPoint(*It, /*Before*/ false);
79955650754SQuentin Colombet   } else {
80055650754SQuentin Colombet     // - Terminators must be the last instructions:
80155650754SQuentin Colombet     //   * Before, move the insert point before the first terminator.
80255650754SQuentin Colombet     //   * After, we have to split the outcoming edges.
80355650754SQuentin Colombet     if (Before) {
80455650754SQuentin Colombet       // Check whether Reg is defined by any terminator.
805adc40baaSMatt Arsenault       MachineBasicBlock::reverse_iterator It = MI;
806adc40baaSMatt Arsenault       auto REnd = MI.getParent()->rend();
807adc40baaSMatt Arsenault 
808adc40baaSMatt Arsenault       for (; It != REnd && It->isTerminator(); ++It) {
809a480523cSBenjamin Kramer         assert(!It->modifiesRegister(MO.getReg(), &TRI) &&
810adc40baaSMatt Arsenault                "copy insertion in middle of terminators not handled");
811adc40baaSMatt Arsenault       }
812adc40baaSMatt Arsenault 
813adc40baaSMatt Arsenault       if (It == REnd) {
814adc40baaSMatt Arsenault         addInsertPoint(*MI.getParent()->begin(), true);
81555650754SQuentin Colombet         return;
81655650754SQuentin Colombet       }
817adc40baaSMatt Arsenault 
818adc40baaSMatt Arsenault       // We are sure to be right before the first terminator.
819adc40baaSMatt Arsenault       addInsertPoint(*It, /*Before*/ false);
82055650754SQuentin Colombet       return;
82155650754SQuentin Colombet     }
82255650754SQuentin Colombet     // Make sure Reg is not redefined by other terminators, otherwise
82355650754SQuentin Colombet     // we do not know how to split.
82455650754SQuentin Colombet     for (MachineBasicBlock::iterator It = MI, End = MI.getParent()->end();
82555650754SQuentin Colombet          ++It != End;)
82655650754SQuentin Colombet       // The machine verifier should reject this kind of code.
827a480523cSBenjamin Kramer       assert(It->modifiesRegister(MO.getReg(), &TRI) &&
828a480523cSBenjamin Kramer              "Do not know where to split");
82955650754SQuentin Colombet     // Split each outcoming edges.
83055650754SQuentin Colombet     MachineBasicBlock &Src = *MI.getParent();
83155650754SQuentin Colombet     for (auto &Succ : Src.successors())
83255650754SQuentin Colombet       addInsertPoint(Src, Succ);
83355650754SQuentin Colombet   }
83455650754SQuentin Colombet }
83555650754SQuentin Colombet 
addInsertPoint(MachineInstr & MI,bool Before)83655650754SQuentin Colombet void RegBankSelect::RepairingPlacement::addInsertPoint(MachineInstr &MI,
83755650754SQuentin Colombet                                                        bool Before) {
83855650754SQuentin Colombet   addInsertPoint(*new InstrInsertPoint(MI, Before));
83955650754SQuentin Colombet }
84055650754SQuentin Colombet 
addInsertPoint(MachineBasicBlock & MBB,bool Beginning)84155650754SQuentin Colombet void RegBankSelect::RepairingPlacement::addInsertPoint(MachineBasicBlock &MBB,
84255650754SQuentin Colombet                                                        bool Beginning) {
84355650754SQuentin Colombet   addInsertPoint(*new MBBInsertPoint(MBB, Beginning));
84455650754SQuentin Colombet }
84555650754SQuentin Colombet 
addInsertPoint(MachineBasicBlock & Src,MachineBasicBlock & Dst)84655650754SQuentin Colombet void RegBankSelect::RepairingPlacement::addInsertPoint(MachineBasicBlock &Src,
84755650754SQuentin Colombet                                                        MachineBasicBlock &Dst) {
84855650754SQuentin Colombet   addInsertPoint(*new EdgeInsertPoint(Src, Dst, P));
84955650754SQuentin Colombet }
85055650754SQuentin Colombet 
addInsertPoint(RegBankSelect::InsertPoint & Point)85155650754SQuentin Colombet void RegBankSelect::RepairingPlacement::addInsertPoint(
85255650754SQuentin Colombet     RegBankSelect::InsertPoint &Point) {
85355650754SQuentin Colombet   CanMaterialize &= Point.canMaterialize();
85455650754SQuentin Colombet   HasSplit |= Point.isSplit();
85555650754SQuentin Colombet   InsertPoints.emplace_back(&Point);
85655650754SQuentin Colombet }
85755650754SQuentin Colombet 
InstrInsertPoint(MachineInstr & Instr,bool Before)85855650754SQuentin Colombet RegBankSelect::InstrInsertPoint::InstrInsertPoint(MachineInstr &Instr,
85955650754SQuentin Colombet                                                   bool Before)
860b932bdf5SKazu Hirata     : Instr(Instr), Before(Before) {
86155650754SQuentin Colombet   // Since we do not support splitting, we do not need to update
86255650754SQuentin Colombet   // liveness and such, so do not do anything with P.
86355650754SQuentin Colombet   assert((!Before || !Instr.isPHI()) &&
86455650754SQuentin Colombet          "Splitting before phis requires more points");
86555650754SQuentin Colombet   assert((!Before || !Instr.getNextNode() || !Instr.getNextNode()->isPHI()) &&
86655650754SQuentin Colombet          "Splitting between phis does not make sense");
86755650754SQuentin Colombet }
86855650754SQuentin Colombet 
materialize()86955650754SQuentin Colombet void RegBankSelect::InstrInsertPoint::materialize() {
87055650754SQuentin Colombet   if (isSplit()) {
87155650754SQuentin Colombet     // Slice and return the beginning of the new block.
87255650754SQuentin Colombet     // If we need to split between the terminators, we theoritically
87355650754SQuentin Colombet     // need to know where the first and second set of terminators end
87455650754SQuentin Colombet     // to update the successors properly.
87555650754SQuentin Colombet     // Now, in pratice, we should have a maximum of 2 branch
87655650754SQuentin Colombet     // instructions; one conditional and one unconditional. Therefore
87755650754SQuentin Colombet     // we know how to update the successor by looking at the target of
87855650754SQuentin Colombet     // the unconditional branch.
87955650754SQuentin Colombet     // If we end up splitting at some point, then, we should update
88055650754SQuentin Colombet     // the liveness information and such. I.e., we would need to
88155650754SQuentin Colombet     // access P here.
88255650754SQuentin Colombet     // The machine verifier should actually make sure such cases
88355650754SQuentin Colombet     // cannot happen.
88455650754SQuentin Colombet     llvm_unreachable("Not yet implemented");
88555650754SQuentin Colombet   }
88655650754SQuentin Colombet   // Otherwise the insertion point is just the current or next
88755650754SQuentin Colombet   // instruction depending on Before. I.e., there is nothing to do
88855650754SQuentin Colombet   // here.
88955650754SQuentin Colombet }
89055650754SQuentin Colombet 
isSplit() const89155650754SQuentin Colombet bool RegBankSelect::InstrInsertPoint::isSplit() const {
89255650754SQuentin Colombet   // If the insertion point is after a terminator, we need to split.
89355650754SQuentin Colombet   if (!Before)
89455650754SQuentin Colombet     return Instr.isTerminator();
89555650754SQuentin Colombet   // If we insert before an instruction that is after a terminator,
89655650754SQuentin Colombet   // we are still after a terminator.
89755650754SQuentin Colombet   return Instr.getPrevNode() && Instr.getPrevNode()->isTerminator();
89855650754SQuentin Colombet }
89955650754SQuentin Colombet 
frequency(const Pass & P) const90055650754SQuentin Colombet uint64_t RegBankSelect::InstrInsertPoint::frequency(const Pass &P) const {
90155650754SQuentin Colombet   // Even if we need to split, because we insert between terminators,
90255650754SQuentin Colombet   // this split has actually the same frequency as the instruction.
90355650754SQuentin Colombet   const MachineBlockFrequencyInfo *MBFI =
90455650754SQuentin Colombet       P.getAnalysisIfAvailable<MachineBlockFrequencyInfo>();
90555650754SQuentin Colombet   if (!MBFI)
90655650754SQuentin Colombet     return 1;
90755650754SQuentin Colombet   return MBFI->getBlockFreq(Instr.getParent()).getFrequency();
90855650754SQuentin Colombet }
90955650754SQuentin Colombet 
frequency(const Pass & P) const91055650754SQuentin Colombet uint64_t RegBankSelect::MBBInsertPoint::frequency(const Pass &P) const {
91155650754SQuentin Colombet   const MachineBlockFrequencyInfo *MBFI =
91255650754SQuentin Colombet       P.getAnalysisIfAvailable<MachineBlockFrequencyInfo>();
91355650754SQuentin Colombet   if (!MBFI)
91455650754SQuentin Colombet     return 1;
91555650754SQuentin Colombet   return MBFI->getBlockFreq(&MBB).getFrequency();
91655650754SQuentin Colombet }
91755650754SQuentin Colombet 
materialize()91855650754SQuentin Colombet void RegBankSelect::EdgeInsertPoint::materialize() {
91955650754SQuentin Colombet   // If we end up repairing twice at the same place before materializing the
92055650754SQuentin Colombet   // insertion point, we may think we have to split an edge twice.
92155650754SQuentin Colombet   // We should have a factory for the insert point such that identical points
92255650754SQuentin Colombet   // are the same instance.
92355650754SQuentin Colombet   assert(Src.isSuccessor(DstOrSplit) && DstOrSplit->isPredecessor(&Src) &&
92455650754SQuentin Colombet          "This point has already been split");
92555650754SQuentin Colombet   MachineBasicBlock *NewBB = Src.SplitCriticalEdge(DstOrSplit, P);
92655650754SQuentin Colombet   assert(NewBB && "Invalid call to materialize");
92755650754SQuentin Colombet   // We reuse the destination block to hold the information of the new block.
92855650754SQuentin Colombet   DstOrSplit = NewBB;
92955650754SQuentin Colombet }
93055650754SQuentin Colombet 
frequency(const Pass & P) const93155650754SQuentin Colombet uint64_t RegBankSelect::EdgeInsertPoint::frequency(const Pass &P) const {
93255650754SQuentin Colombet   const MachineBlockFrequencyInfo *MBFI =
93355650754SQuentin Colombet       P.getAnalysisIfAvailable<MachineBlockFrequencyInfo>();
93455650754SQuentin Colombet   if (!MBFI)
93555650754SQuentin Colombet     return 1;
93655650754SQuentin Colombet   if (WasMaterialized)
93755650754SQuentin Colombet     return MBFI->getBlockFreq(DstOrSplit).getFrequency();
93855650754SQuentin Colombet 
93955650754SQuentin Colombet   const MachineBranchProbabilityInfo *MBPI =
94055650754SQuentin Colombet       P.getAnalysisIfAvailable<MachineBranchProbabilityInfo>();
94155650754SQuentin Colombet   if (!MBPI)
94255650754SQuentin Colombet     return 1;
94355650754SQuentin Colombet   // The basic block will be on the edge.
94455650754SQuentin Colombet   return (MBFI->getBlockFreq(&Src) * MBPI->getEdgeProbability(&Src, DstOrSplit))
94555650754SQuentin Colombet       .getFrequency();
94655650754SQuentin Colombet }
94755650754SQuentin Colombet 
canMaterialize() const94855650754SQuentin Colombet bool RegBankSelect::EdgeInsertPoint::canMaterialize() const {
94955650754SQuentin Colombet   // If this is not a critical edge, we should not have used this insert
95055650754SQuentin Colombet   // point. Indeed, either the successor or the predecessor should
95155650754SQuentin Colombet   // have do.
95255650754SQuentin Colombet   assert(Src.succ_size() > 1 && DstOrSplit->pred_size() > 1 &&
95355650754SQuentin Colombet          "Edge is not critical");
95455650754SQuentin Colombet   return Src.canSplitCriticalEdge(DstOrSplit);
95555650754SQuentin Colombet }
95655650754SQuentin Colombet 
MappingCost(const BlockFrequency & LocalFreq)957cfd97b93SQuentin Colombet RegBankSelect::MappingCost::MappingCost(const BlockFrequency &LocalFreq)
95876bf48d9SEugene Zelenko     : LocalFreq(LocalFreq.getFrequency()) {}
959cfd97b93SQuentin Colombet 
addLocalCost(uint64_t Cost)960cfd97b93SQuentin Colombet bool RegBankSelect::MappingCost::addLocalCost(uint64_t Cost) {
961cfd97b93SQuentin Colombet   // Check if this overflows.
962cfd97b93SQuentin Colombet   if (LocalCost + Cost < LocalCost) {
963cfd97b93SQuentin Colombet     saturate();
964cfd97b93SQuentin Colombet     return true;
965cfd97b93SQuentin Colombet   }
966cfd97b93SQuentin Colombet   LocalCost += Cost;
967cfd97b93SQuentin Colombet   return isSaturated();
968cfd97b93SQuentin Colombet }
969cfd97b93SQuentin Colombet 
addNonLocalCost(uint64_t Cost)970cfd97b93SQuentin Colombet bool RegBankSelect::MappingCost::addNonLocalCost(uint64_t Cost) {
971cfd97b93SQuentin Colombet   // Check if this overflows.
972cfd97b93SQuentin Colombet   if (NonLocalCost + Cost < NonLocalCost) {
973cfd97b93SQuentin Colombet     saturate();
974cfd97b93SQuentin Colombet     return true;
975cfd97b93SQuentin Colombet   }
976cfd97b93SQuentin Colombet   NonLocalCost += Cost;
977cfd97b93SQuentin Colombet   return isSaturated();
978cfd97b93SQuentin Colombet }
979cfd97b93SQuentin Colombet 
isSaturated() const980cfd97b93SQuentin Colombet bool RegBankSelect::MappingCost::isSaturated() const {
981cfd97b93SQuentin Colombet   return LocalCost == UINT64_MAX - 1 && NonLocalCost == UINT64_MAX &&
982cfd97b93SQuentin Colombet          LocalFreq == UINT64_MAX;
983cfd97b93SQuentin Colombet }
984cfd97b93SQuentin Colombet 
saturate()985cfd97b93SQuentin Colombet void RegBankSelect::MappingCost::saturate() {
986cfd97b93SQuentin Colombet   *this = ImpossibleCost();
987cfd97b93SQuentin Colombet   --LocalCost;
988cfd97b93SQuentin Colombet }
989cfd97b93SQuentin Colombet 
ImpossibleCost()990cfd97b93SQuentin Colombet RegBankSelect::MappingCost RegBankSelect::MappingCost::ImpossibleCost() {
991cfd97b93SQuentin Colombet   return MappingCost(UINT64_MAX, UINT64_MAX, UINT64_MAX);
992cfd97b93SQuentin Colombet }
993cfd97b93SQuentin Colombet 
operator <(const MappingCost & Cost) const994cfd97b93SQuentin Colombet bool RegBankSelect::MappingCost::operator<(const MappingCost &Cost) const {
995cfd97b93SQuentin Colombet   // Sort out the easy cases.
996cfd97b93SQuentin Colombet   if (*this == Cost)
997cfd97b93SQuentin Colombet     return false;
998cfd97b93SQuentin Colombet   // If one is impossible to realize the other is cheaper unless it is
999cfd97b93SQuentin Colombet   // impossible as well.
1000cfd97b93SQuentin Colombet   if ((*this == ImpossibleCost()) || (Cost == ImpossibleCost()))
1001cfd97b93SQuentin Colombet     return (*this == ImpossibleCost()) < (Cost == ImpossibleCost());
1002cfd97b93SQuentin Colombet   // If one is saturated the other is cheaper, unless it is saturated
1003cfd97b93SQuentin Colombet   // as well.
1004cfd97b93SQuentin Colombet   if (isSaturated() || Cost.isSaturated())
1005cfd97b93SQuentin Colombet     return isSaturated() < Cost.isSaturated();
1006cfd97b93SQuentin Colombet   // At this point we know both costs hold sensible values.
1007cfd97b93SQuentin Colombet 
1008cfd97b93SQuentin Colombet   // If both values have a different base frequency, there is no much
1009cfd97b93SQuentin Colombet   // we can do but to scale everything.
1010cfd97b93SQuentin Colombet   // However, if they have the same base frequency we can avoid making
1011cfd97b93SQuentin Colombet   // complicated computation.
1012cfd97b93SQuentin Colombet   uint64_t ThisLocalAdjust;
1013cfd97b93SQuentin Colombet   uint64_t OtherLocalAdjust;
1014cfd97b93SQuentin Colombet   if (LLVM_LIKELY(LocalFreq == Cost.LocalFreq)) {
1015cfd97b93SQuentin Colombet 
1016cfd97b93SQuentin Colombet     // At this point, we know the local costs are comparable.
1017cfd97b93SQuentin Colombet     // Do the case that do not involve potential overflow first.
1018cfd97b93SQuentin Colombet     if (NonLocalCost == Cost.NonLocalCost)
1019cfd97b93SQuentin Colombet       // Since the non-local costs do not discriminate on the result,
1020cfd97b93SQuentin Colombet       // just compare the local costs.
1021cfd97b93SQuentin Colombet       return LocalCost < Cost.LocalCost;
1022cfd97b93SQuentin Colombet 
1023cfd97b93SQuentin Colombet     // The base costs are comparable so we may only keep the relative
1024cfd97b93SQuentin Colombet     // value to increase our chances of avoiding overflows.
1025cfd97b93SQuentin Colombet     ThisLocalAdjust = 0;
1026cfd97b93SQuentin Colombet     OtherLocalAdjust = 0;
1027cfd97b93SQuentin Colombet     if (LocalCost < Cost.LocalCost)
1028cfd97b93SQuentin Colombet       OtherLocalAdjust = Cost.LocalCost - LocalCost;
1029cfd97b93SQuentin Colombet     else
1030cfd97b93SQuentin Colombet       ThisLocalAdjust = LocalCost - Cost.LocalCost;
1031cfd97b93SQuentin Colombet   } else {
1032cfd97b93SQuentin Colombet     ThisLocalAdjust = LocalCost;
1033cfd97b93SQuentin Colombet     OtherLocalAdjust = Cost.LocalCost;
1034cfd97b93SQuentin Colombet   }
1035cfd97b93SQuentin Colombet 
1036cfd97b93SQuentin Colombet   // The non-local costs are comparable, just keep the relative value.
1037cfd97b93SQuentin Colombet   uint64_t ThisNonLocalAdjust = 0;
1038cfd97b93SQuentin Colombet   uint64_t OtherNonLocalAdjust = 0;
1039cfd97b93SQuentin Colombet   if (NonLocalCost < Cost.NonLocalCost)
1040cfd97b93SQuentin Colombet     OtherNonLocalAdjust = Cost.NonLocalCost - NonLocalCost;
1041cfd97b93SQuentin Colombet   else
1042cfd97b93SQuentin Colombet     ThisNonLocalAdjust = NonLocalCost - Cost.NonLocalCost;
1043cfd97b93SQuentin Colombet   // Scale everything to make them comparable.
1044cfd97b93SQuentin Colombet   uint64_t ThisScaledCost = ThisLocalAdjust * LocalFreq;
1045cfd97b93SQuentin Colombet   // Check for overflow on that operation.
1046cfd97b93SQuentin Colombet   bool ThisOverflows = ThisLocalAdjust && (ThisScaledCost < ThisLocalAdjust ||
1047cfd97b93SQuentin Colombet                                            ThisScaledCost < LocalFreq);
1048cfd97b93SQuentin Colombet   uint64_t OtherScaledCost = OtherLocalAdjust * Cost.LocalFreq;
1049cfd97b93SQuentin Colombet   // Check for overflow on the last operation.
1050cfd97b93SQuentin Colombet   bool OtherOverflows =
1051cfd97b93SQuentin Colombet       OtherLocalAdjust &&
1052cfd97b93SQuentin Colombet       (OtherScaledCost < OtherLocalAdjust || OtherScaledCost < Cost.LocalFreq);
1053cfd97b93SQuentin Colombet   // Add the non-local costs.
1054cfd97b93SQuentin Colombet   ThisOverflows |= ThisNonLocalAdjust &&
1055cfd97b93SQuentin Colombet                    ThisScaledCost + ThisNonLocalAdjust < ThisNonLocalAdjust;
1056cfd97b93SQuentin Colombet   ThisScaledCost += ThisNonLocalAdjust;
1057cfd97b93SQuentin Colombet   OtherOverflows |= OtherNonLocalAdjust &&
1058cfd97b93SQuentin Colombet                     OtherScaledCost + OtherNonLocalAdjust < OtherNonLocalAdjust;
1059cfd97b93SQuentin Colombet   OtherScaledCost += OtherNonLocalAdjust;
1060cfd97b93SQuentin Colombet   // If both overflows, we cannot compare without additional
1061cfd97b93SQuentin Colombet   // precision, e.g., APInt. Just give up on that case.
1062cfd97b93SQuentin Colombet   if (ThisOverflows && OtherOverflows)
1063cfd97b93SQuentin Colombet     return false;
1064cfd97b93SQuentin Colombet   // If one overflows but not the other, we can still compare.
1065cfd97b93SQuentin Colombet   if (ThisOverflows || OtherOverflows)
1066cfd97b93SQuentin Colombet     return ThisOverflows < OtherOverflows;
1067cfd97b93SQuentin Colombet   // Otherwise, just compare the values.
1068cfd97b93SQuentin Colombet   return ThisScaledCost < OtherScaledCost;
1069cfd97b93SQuentin Colombet }
1070cfd97b93SQuentin Colombet 
operator ==(const MappingCost & Cost) const1071cfd97b93SQuentin Colombet bool RegBankSelect::MappingCost::operator==(const MappingCost &Cost) const {
1072cfd97b93SQuentin Colombet   return LocalCost == Cost.LocalCost && NonLocalCost == Cost.NonLocalCost &&
1073cfd97b93SQuentin Colombet          LocalFreq == Cost.LocalFreq;
1074cfd97b93SQuentin Colombet }
10750b63b31bSQuentin Colombet 
1076615eb470SAaron Ballman #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
dump() const10778c209aa8SMatthias Braun LLVM_DUMP_METHOD void RegBankSelect::MappingCost::dump() const {
10780b63b31bSQuentin Colombet   print(dbgs());
10790b63b31bSQuentin Colombet   dbgs() << '\n';
10800b63b31bSQuentin Colombet }
10818c209aa8SMatthias Braun #endif
10820b63b31bSQuentin Colombet 
print(raw_ostream & OS) const10830b63b31bSQuentin Colombet void RegBankSelect::MappingCost::print(raw_ostream &OS) const {
10840b63b31bSQuentin Colombet   if (*this == ImpossibleCost()) {
10850b63b31bSQuentin Colombet     OS << "impossible";
10860b63b31bSQuentin Colombet     return;
10870b63b31bSQuentin Colombet   }
10880b63b31bSQuentin Colombet   if (isSaturated()) {
10890b63b31bSQuentin Colombet     OS << "saturated";
10900b63b31bSQuentin Colombet     return;
10910b63b31bSQuentin Colombet   }
10920b63b31bSQuentin Colombet   OS << LocalFreq << " * " << LocalCost << " + " << NonLocalCost;
10930b63b31bSQuentin Colombet }
1094