blob: 5b3b705541c6463b8f03aa32f5cb60c7d4b3dc1b [file] [log] [blame]
Quentin Colombet8e8e85c2016-04-05 19:06:01 +00001//===- llvm/CodeGen/GlobalISel/RegBankSelect.cpp - RegBankSelect -*- C++ -*-==//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9/// \file
10/// This file implements the RegBankSelect class.
11//===----------------------------------------------------------------------===//
12
13#include "llvm/CodeGen/GlobalISel/RegBankSelect.h"
Quentin Colombetcfd97b92016-05-20 00:35:26 +000014#include "llvm/ADT/PostOrderIterator.h"
Ahmed Bougacha24d0d4d2016-08-02 15:10:32 +000015#include "llvm/CodeGen/GlobalISel/MachineLegalizer.h"
Quentin Colombet40ad5732016-04-07 18:19:27 +000016#include "llvm/CodeGen/GlobalISel/RegisterBank.h"
Quentin Colombet55650752016-05-20 00:49:10 +000017#include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
18#include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
Quentin Colombet40ad5732016-04-07 18:19:27 +000019#include "llvm/CodeGen/MachineRegisterInfo.h"
Quentin Colombetacb857b2016-08-27 02:38:27 +000020#include "llvm/CodeGen/TargetPassConfig.h"
Quentin Colombeta5530122016-05-20 17:36:54 +000021#include "llvm/IR/Function.h"
Quentin Colombetcfd97b92016-05-20 00:35:26 +000022#include "llvm/Support/BlockFrequency.h"
Quentin Colombeta41272f2016-06-08 15:49:23 +000023#include "llvm/Support/CommandLine.h"
Quentin Colombete16f5612016-04-07 23:53:55 +000024#include "llvm/Support/Debug.h"
Quentin Colombet40ad5732016-04-07 18:19:27 +000025#include "llvm/Target/TargetSubtargetInfo.h"
Quentin Colombet8e8e85c2016-04-05 19:06:01 +000026
27#define DEBUG_TYPE "regbankselect"
28
29using namespace llvm;
30
Quentin Colombeta41272f2016-06-08 15:49:23 +000031static cl::opt<RegBankSelect::Mode> RegBankSelectMode(
32 cl::desc("Mode of the RegBankSelect pass"), cl::Hidden, cl::Optional,
33 cl::values(clEnumValN(RegBankSelect::Mode::Fast, "regbankselect-fast",
34 "Run the Fast mode (default mapping)"),
35 clEnumValN(RegBankSelect::Mode::Greedy, "regbankselect-greedy",
Mehdi Amini732afdd2016-10-08 19:41:06 +000036 "Use the Greedy mode (best local mapping)")));
Quentin Colombeta41272f2016-06-08 15:49:23 +000037
Quentin Colombet8e8e85c2016-04-05 19:06:01 +000038char RegBankSelect::ID = 0;
Quentin Colombetc13ea882016-09-23 17:50:06 +000039INITIALIZE_PASS_BEGIN(RegBankSelect, DEBUG_TYPE,
Quentin Colombet25fcef72016-05-20 17:54:09 +000040 "Assign register bank of generic virtual registers",
41 false, false);
42INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo)
43INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
Quentin Colombetacb857b2016-08-27 02:38:27 +000044INITIALIZE_PASS_DEPENDENCY(TargetPassConfig)
Quentin Colombetc13ea882016-09-23 17:50:06 +000045INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE,
Quentin Colombet25fcef72016-05-20 17:54:09 +000046 "Assign register bank of generic virtual registers", false,
Tim Northover884b47e2016-07-26 03:29:18 +000047 false)
Quentin Colombet8e8e85c2016-04-05 19:06:01 +000048
Quentin Colombet46df7222016-05-20 16:55:35 +000049RegBankSelect::RegBankSelect(Mode RunningMode)
Quentin Colombet25fcef72016-05-20 17:54:09 +000050 : MachineFunctionPass(ID), RBI(nullptr), MRI(nullptr), TRI(nullptr),
51 MBFI(nullptr), MBPI(nullptr), OptMode(RunningMode) {
Quentin Colombet8e8e85c2016-04-05 19:06:01 +000052 initializeRegBankSelectPass(*PassRegistry::getPassRegistry());
Quentin Colombeta41272f2016-06-08 15:49:23 +000053 if (RegBankSelectMode.getNumOccurrences() != 0) {
54 OptMode = RegBankSelectMode;
55 if (RegBankSelectMode != RunningMode)
56 DEBUG(dbgs() << "RegBankSelect mode overrided by command line\n");
57 }
Quentin Colombet8e8e85c2016-04-05 19:06:01 +000058}
59
Quentin Colombet40ad5732016-04-07 18:19:27 +000060void RegBankSelect::init(MachineFunction &MF) {
61 RBI = MF.getSubtarget().getRegBankInfo();
62 assert(RBI && "Cannot work without RegisterBankInfo");
63 MRI = &MF.getRegInfo();
Quentin Colombetaac71a42016-04-07 21:32:23 +000064 TRI = MF.getSubtarget().getRegisterInfo();
Quentin Colombetacb857b2016-08-27 02:38:27 +000065 TPC = &getAnalysis<TargetPassConfig>();
Quentin Colombet25fcef72016-05-20 17:54:09 +000066 if (OptMode != Mode::Fast) {
67 MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
68 MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
69 } else {
70 MBFI = nullptr;
71 MBPI = nullptr;
72 }
Quentin Colombet40ad5732016-04-07 18:19:27 +000073 MIRBuilder.setMF(MF);
74}
75
Quentin Colombet25fcef72016-05-20 17:54:09 +000076void RegBankSelect::getAnalysisUsage(AnalysisUsage &AU) const {
77 if (OptMode != Mode::Fast) {
78 // We could preserve the information from these two analysis but
79 // the APIs do not allow to do so yet.
80 AU.addRequired<MachineBlockFrequencyInfo>();
81 AU.addRequired<MachineBranchProbabilityInfo>();
82 }
Quentin Colombetacb857b2016-08-27 02:38:27 +000083 AU.addRequired<TargetPassConfig>();
Quentin Colombet25fcef72016-05-20 17:54:09 +000084 MachineFunctionPass::getAnalysisUsage(AU);
85}
86
Quentin Colombet40ad5732016-04-07 18:19:27 +000087bool RegBankSelect::assignmentMatch(
Quentin Colombet0d77da42016-05-20 00:42:57 +000088 unsigned Reg, const RegisterBankInfo::ValueMapping &ValMapping,
89 bool &OnlyAssign) const {
90 // By default we assume we will have to repair something.
91 OnlyAssign = false;
Quentin Colombet40ad5732016-04-07 18:19:27 +000092 // Each part of a break down needs to end up in a different register.
93 // In other word, Reg assignement does not match.
Quentin Colombet0afa7d62016-09-23 00:14:30 +000094 if (ValMapping.NumBreakDowns > 1)
Quentin Colombet40ad5732016-04-07 18:19:27 +000095 return false;
96
Quentin Colombet6d6d6af2016-04-08 16:48:16 +000097 const RegisterBank *CurRegBank = RBI->getRegBank(Reg, *MRI, *TRI);
98 const RegisterBank *DesiredRegBrank = ValMapping.BreakDown[0].RegBank;
Quentin Colombet0d77da42016-05-20 00:42:57 +000099 // Reg is free of assignment, a simple assignment will make the
100 // register bank to match.
101 OnlyAssign = CurRegBank == nullptr;
Quentin Colombet6d6d6af2016-04-08 16:48:16 +0000102 DEBUG(dbgs() << "Does assignment already match: ";
103 if (CurRegBank) dbgs() << *CurRegBank; else dbgs() << "none";
104 dbgs() << " against ";
105 assert(DesiredRegBrank && "The mapping must be valid");
106 dbgs() << *DesiredRegBrank << '\n';);
107 return CurRegBank == DesiredRegBrank;
Quentin Colombet40ad5732016-04-07 18:19:27 +0000108}
109
Quentin Colombetacb857b2016-08-27 02:38:27 +0000110bool RegBankSelect::repairReg(
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000111 MachineOperand &MO, const RegisterBankInfo::ValueMapping &ValMapping,
112 RegBankSelect::RepairingPlacement &RepairPt,
Quentin Colombet06ef4e22016-06-08 16:24:55 +0000113 const iterator_range<SmallVectorImpl<unsigned>::const_iterator> &NewVRegs) {
Quentin Colombet0afa7d62016-09-23 00:14:30 +0000114 if (ValMapping.NumBreakDowns != 1 && !TPC->isGlobalISelAbortEnabled())
Quentin Colombetacb857b2016-08-27 02:38:27 +0000115 return false;
Quentin Colombet0afa7d62016-09-23 00:14:30 +0000116 assert(ValMapping.NumBreakDowns == 1 && "Not yet implemented");
Quentin Colombetf33e3652016-06-08 16:30:55 +0000117 // An empty range of new register means no repairing.
118 assert(NewVRegs.begin() != NewVRegs.end() && "We should not have to repair");
119
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000120 // Assume we are repairing a use and thus, the original reg will be
121 // the source of the repairing.
122 unsigned Src = MO.getReg();
123 unsigned Dst = *NewVRegs.begin();
Quentin Colombet904a2c72016-04-12 00:12:59 +0000124
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000125 // If we repair a definition, swap the source and destination for
126 // the repairing.
127 if (MO.isDef())
Quentin Colombet904a2c72016-04-12 00:12:59 +0000128 std::swap(Src, Dst);
Quentin Colombet904a2c72016-04-12 00:12:59 +0000129
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000130 assert((RepairPt.getNumInsertPoints() == 1 ||
131 TargetRegisterInfo::isPhysicalRegister(Dst)) &&
132 "We are about to create several defs for Dst");
Quentin Colombet904a2c72016-04-12 00:12:59 +0000133
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000134 // Build the instruction used to repair, then clone it at the right places.
Tim Northover756eca32016-07-26 16:45:30 +0000135 MachineInstr *MI = MIRBuilder.buildCopy(Dst, Src);
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000136 MI->removeFromParent();
137 DEBUG(dbgs() << "Copy: " << PrintReg(Src) << " to: " << PrintReg(Dst)
138 << '\n');
139 // TODO:
140 // Check if MI is legal. if not, we need to legalize all the
141 // instructions we are going to insert.
142 std::unique_ptr<MachineInstr *[]> NewInstrs(
143 new MachineInstr *[RepairPt.getNumInsertPoints()]);
144 bool IsFirst = true;
145 unsigned Idx = 0;
146 for (const std::unique_ptr<InsertPoint> &InsertPt : RepairPt) {
147 MachineInstr *CurMI;
148 if (IsFirst)
149 CurMI = MI;
150 else
151 CurMI = MIRBuilder.getMF().CloneMachineInstr(MI);
152 InsertPt->insert(*CurMI);
153 NewInstrs[Idx++] = CurMI;
154 IsFirst = false;
155 }
156 // TODO:
157 // Legalize NewInstrs if need be.
Quentin Colombetacb857b2016-08-27 02:38:27 +0000158 return true;
Quentin Colombet40ad5732016-04-07 18:19:27 +0000159}
160
Quentin Colombetf2723a22016-05-21 01:43:25 +0000161uint64_t RegBankSelect::getRepairCost(
162 const MachineOperand &MO,
163 const RegisterBankInfo::ValueMapping &ValMapping) const {
164 assert(MO.isReg() && "We should only repair register operand");
Quentin Colombet0afa7d62016-09-23 00:14:30 +0000165 assert(ValMapping.NumBreakDowns && "Nothing to map??");
Quentin Colombetf2723a22016-05-21 01:43:25 +0000166
Quentin Colombet0afa7d62016-09-23 00:14:30 +0000167 bool IsSameNumOfValues = ValMapping.NumBreakDowns == 1;
Quentin Colombetf2723a22016-05-21 01:43:25 +0000168 const RegisterBank *CurRegBank = RBI->getRegBank(MO.getReg(), *MRI, *TRI);
169 // If MO does not have a register bank, we should have just been
170 // able to set one unless we have to break the value down.
171 assert((!IsSameNumOfValues || CurRegBank) && "We should not have to repair");
172 // Def: Val <- NewDefs
173 // Same number of values: copy
174 // Different number: Val = build_sequence Defs1, Defs2, ...
175 // Use: NewSources <- Val.
176 // Same number of values: copy.
177 // Different number: Src1, Src2, ... =
178 // extract_value Val, Src1Begin, Src1Len, Src2Begin, Src2Len, ...
179 // We should remember that this value is available somewhere else to
180 // coalesce the value.
181
182 if (IsSameNumOfValues) {
183 const RegisterBank *DesiredRegBrank = ValMapping.BreakDown[0].RegBank;
184 // If we repair a definition, swap the source and destination for
185 // the repairing.
186 if (MO.isDef())
187 std::swap(CurRegBank, DesiredRegBrank);
Quentin Colombetd6886bd2016-06-08 17:39:43 +0000188 // TODO: It may be possible to actually avoid the copy.
189 // If we repair something where the source is defined by a copy
190 // and the source of that copy is on the right bank, we can reuse
191 // it for free.
192 // E.g.,
193 // RegToRepair<BankA> = copy AlternativeSrc<BankB>
194 // = op RegToRepair<BankA>
195 // We can simply propagate AlternativeSrc instead of copying RegToRepair
196 // into a new virtual register.
197 // We would also need to propagate this information in the
198 // repairing placement.
Quentin Colombetcfbdee22016-06-08 01:11:03 +0000199 unsigned Cost =
200 RBI->copyCost(*DesiredRegBrank, *CurRegBank,
201 RegisterBankInfo::getSizeInBits(MO.getReg(), *MRI, *TRI));
Quentin Colombetf2723a22016-05-21 01:43:25 +0000202 // TODO: use a dedicated constant for ImpossibleCost.
203 if (Cost != UINT_MAX)
204 return Cost;
Quentin Colombetacb857b2016-08-27 02:38:27 +0000205 assert(!TPC->isGlobalISelAbortEnabled() &&
206 "Legalization not available yet");
Quentin Colombetf2723a22016-05-21 01:43:25 +0000207 // Return the legalization cost of that repairing.
208 }
Quentin Colombetacb857b2016-08-27 02:38:27 +0000209 assert(!TPC->isGlobalISelAbortEnabled() &&
210 "Complex repairing not implemented yet");
211 return UINT_MAX;
Quentin Colombetf2723a22016-05-21 01:43:25 +0000212}
213
Quentin Colombet79fe1be2016-05-20 18:37:33 +0000214RegisterBankInfo::InstructionMapping &RegBankSelect::findBestMapping(
215 MachineInstr &MI, RegisterBankInfo::InstructionMappings &PossibleMappings,
216 SmallVectorImpl<RepairingPlacement> &RepairPts) {
Quentin Colombetacb857b2016-08-27 02:38:27 +0000217 assert(!PossibleMappings.empty() &&
218 "Do not know how to map this instruction");
Quentin Colombet79fe1be2016-05-20 18:37:33 +0000219
220 RegisterBankInfo::InstructionMapping *BestMapping = nullptr;
221 MappingCost Cost = MappingCost::ImpossibleCost();
222 SmallVector<RepairingPlacement, 4> LocalRepairPts;
223 for (RegisterBankInfo::InstructionMapping &CurMapping : PossibleMappings) {
224 MappingCost CurCost = computeMapping(MI, CurMapping, LocalRepairPts, &Cost);
225 if (CurCost < Cost) {
226 Cost = CurCost;
227 BestMapping = &CurMapping;
228 RepairPts.clear();
229 for (RepairingPlacement &RepairPt : LocalRepairPts)
230 RepairPts.emplace_back(std::move(RepairPt));
231 }
232 }
Quentin Colombetacb857b2016-08-27 02:38:27 +0000233 if (!BestMapping && !TPC->isGlobalISelAbortEnabled()) {
234 // If none of the mapping worked that means they are all impossible.
235 // Thus, pick the first one and set an impossible repairing point.
236 // It will trigger the failed isel mode.
237 BestMapping = &(*PossibleMappings.begin());
238 RepairPts.emplace_back(
239 RepairingPlacement(MI, 0, *TRI, *this, RepairingPlacement::Impossible));
240 } else
241 assert(BestMapping && "No suitable mapping for instruction");
Quentin Colombet79fe1be2016-05-20 18:37:33 +0000242 return *BestMapping;
243}
244
Quentin Colombetf75c2bf2016-05-20 16:36:12 +0000245void RegBankSelect::tryAvoidingSplit(
246 RegBankSelect::RepairingPlacement &RepairPt, const MachineOperand &MO,
247 const RegisterBankInfo::ValueMapping &ValMapping) const {
248 const MachineInstr &MI = *MO.getParent();
249 assert(RepairPt.hasSplit() && "We should not have to adjust for split");
250 // Splitting should only occur for PHIs or between terminators,
251 // because we only do local repairing.
252 assert((MI.isPHI() || MI.isTerminator()) && "Why do we split?");
253
254 assert(&MI.getOperand(RepairPt.getOpIdx()) == &MO &&
255 "Repairing placement does not match operand");
256
257 // If we need splitting for phis, that means it is because we
258 // could not find an insertion point before the terminators of
259 // the predecessor block for this argument. In other words,
260 // the input value is defined by one of the terminators.
261 assert((!MI.isPHI() || !MO.isDef()) && "Need split for phi def?");
262
263 // We split to repair the use of a phi or a terminator.
264 if (!MO.isDef()) {
265 if (MI.isTerminator()) {
266 assert(&MI != &(*MI.getParent()->getFirstTerminator()) &&
267 "Need to split for the first terminator?!");
268 } else {
269 // For the PHI case, the split may not be actually required.
270 // In the copy case, a phi is already a copy on the incoming edge,
271 // therefore there is no need to split.
Quentin Colombet0afa7d62016-09-23 00:14:30 +0000272 if (ValMapping.NumBreakDowns == 1)
Quentin Colombetf75c2bf2016-05-20 16:36:12 +0000273 // This is a already a copy, there is nothing to do.
274 RepairPt.switchTo(RepairingPlacement::RepairingKind::Reassign);
275 }
276 return;
277 }
278
279 // At this point, we need to repair a defintion of a terminator.
280
281 // Technically we need to fix the def of MI on all outgoing
282 // edges of MI to keep the repairing local. In other words, we
283 // will create several definitions of the same register. This
284 // does not work for SSA unless that definition is a physical
285 // register.
286 // However, there are other cases where we can get away with
287 // that while still keeping the repairing local.
288 assert(MI.isTerminator() && MO.isDef() &&
289 "This code is for the def of a terminator");
290
291 // Since we use RPO traversal, if we need to repair a definition
292 // this means this definition could be:
293 // 1. Used by PHIs (i.e., this VReg has been visited as part of the
294 // uses of a phi.), or
295 // 2. Part of a target specific instruction (i.e., the target applied
296 // some register class constraints when creating the instruction.)
297 // If the constraints come for #2, the target said that another mapping
298 // is supported so we may just drop them. Indeed, if we do not change
299 // the number of registers holding that value, the uses will get fixed
300 // when we get to them.
301 // Uses in PHIs may have already been proceeded though.
302 // If the constraints come for #1, then, those are weak constraints and
303 // no actual uses may rely on them. However, the problem remains mainly
304 // the same as for #2. If the value stays in one register, we could
305 // just switch the register bank of the definition, but we would need to
306 // account for a repairing cost for each phi we silently change.
307 //
308 // In any case, if the value needs to be broken down into several
309 // registers, the repairing is not local anymore as we need to patch
310 // every uses to rebuild the value in just one register.
311 //
312 // To summarize:
313 // - If the value is in a physical register, we can do the split and
314 // fix locally.
315 // Otherwise if the value is in a virtual register:
316 // - If the value remains in one register, we do not have to split
317 // just switching the register bank would do, but we need to account
318 // in the repairing cost all the phi we changed.
319 // - If the value spans several registers, then we cannot do a local
320 // repairing.
321
322 // Check if this is a physical or virtual register.
323 unsigned Reg = MO.getReg();
324 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
325 // We are going to split every outgoing edges.
326 // Check that this is possible.
327 // FIXME: The machine representation is currently broken
328 // since it also several terminators in one basic block.
329 // Because of that we would technically need a way to get
330 // the targets of just one terminator to know which edges
331 // we have to split.
332 // Assert that we do not hit the ill-formed representation.
333
334 // If there are other terminators before that one, some of
335 // the outgoing edges may not be dominated by this definition.
336 assert(&MI == &(*MI.getParent()->getFirstTerminator()) &&
337 "Do not know which outgoing edges are relevant");
338 const MachineInstr *Next = MI.getNextNode();
339 assert((!Next || Next->isUnconditionalBranch()) &&
340 "Do not know where each terminator ends up");
341 if (Next)
342 // If the next terminator uses Reg, this means we have
343 // to split right after MI and thus we need a way to ask
344 // which outgoing edges are affected.
345 assert(!Next->readsRegister(Reg) && "Need to split between terminators");
346 // We will split all the edges and repair there.
347 } else {
348 // This is a virtual register defined by a terminator.
Quentin Colombet0afa7d62016-09-23 00:14:30 +0000349 if (ValMapping.NumBreakDowns == 1) {
Quentin Colombetf75c2bf2016-05-20 16:36:12 +0000350 // There is nothing to repair, but we may actually lie on
351 // the repairing cost because of the PHIs already proceeded
352 // as already stated.
353 // Though the code will be correct.
354 assert(0 && "Repairing cost may not be accurate");
355 } else {
356 // We need to do non-local repairing. Basically, patch all
357 // the uses (i.e., phis) that we already proceeded.
358 // For now, just say this mapping is not possible.
359 RepairPt.switchTo(RepairingPlacement::RepairingKind::Impossible);
360 }
361 }
362}
363
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000364RegBankSelect::MappingCost RegBankSelect::computeMapping(
365 MachineInstr &MI, const RegisterBankInfo::InstructionMapping &InstrMapping,
Quentin Colombet6e80dbc2016-05-20 18:00:46 +0000366 SmallVectorImpl<RepairingPlacement> &RepairPts,
367 const RegBankSelect::MappingCost *BestCost) {
368 assert((MBFI || !BestCost) && "Costs comparison require MBFI");
Quentin Colombete16f5612016-04-07 23:53:55 +0000369
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000370 // If mapped with InstrMapping, MI will have the recorded cost.
Quentin Colombet25fcef72016-05-20 17:54:09 +0000371 MappingCost Cost(MBFI ? MBFI->getBlockFreq(MI.getParent()) : 1);
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000372 bool Saturated = Cost.addLocalCost(InstrMapping.getCost());
373 assert(!Saturated && "Possible mapping saturated the cost");
374 DEBUG(dbgs() << "Evaluating mapping cost for: " << MI);
375 DEBUG(dbgs() << "With: " << InstrMapping << '\n');
376 RepairPts.clear();
Quentin Colombet6e80dbc2016-05-20 18:00:46 +0000377 if (BestCost && Cost > *BestCost)
378 return Cost;
379
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000380 // Moreover, to realize this mapping, the register bank of each operand must
381 // match this mapping. In other words, we may need to locally reassign the
382 // register banks. Account for that repairing cost as well.
383 // In this context, local means in the surrounding of MI.
Quentin Colombet1b016772016-09-29 19:51:46 +0000384 for (unsigned OpIdx = 0, EndOpIdx = InstrMapping.getNumOperands();
385 OpIdx != EndOpIdx; ++OpIdx) {
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000386 const MachineOperand &MO = MI.getOperand(OpIdx);
Quentin Colombet40ad5732016-04-07 18:19:27 +0000387 if (!MO.isReg())
388 continue;
389 unsigned Reg = MO.getReg();
390 if (!Reg)
391 continue;
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000392 DEBUG(dbgs() << "Opd" << OpIdx);
Quentin Colombet40ad5732016-04-07 18:19:27 +0000393 const RegisterBankInfo::ValueMapping &ValMapping =
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000394 InstrMapping.getOperandMapping(OpIdx);
395 // If Reg is already properly mapped, this is free.
396 bool Assign;
397 if (assignmentMatch(Reg, ValMapping, Assign)) {
398 DEBUG(dbgs() << " is free (match).\n");
Quentin Colombet40ad5732016-04-07 18:19:27 +0000399 continue;
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000400 }
401 if (Assign) {
402 DEBUG(dbgs() << " is free (simple assignment).\n");
403 RepairPts.emplace_back(RepairingPlacement(MI, OpIdx, *TRI, *this,
404 RepairingPlacement::Reassign));
405 continue;
Quentin Colombet40ad5732016-04-07 18:19:27 +0000406 }
Quentin Colombet904a2c72016-04-12 00:12:59 +0000407
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000408 // Find the insertion point for the repairing code.
409 RepairPts.emplace_back(
410 RepairingPlacement(MI, OpIdx, *TRI, *this, RepairingPlacement::Insert));
411 RepairingPlacement &RepairPt = RepairPts.back();
412
Quentin Colombetf75c2bf2016-05-20 16:36:12 +0000413 // If we need to split a basic block to materialize this insertion point,
414 // we may give a higher cost to this mapping.
415 // Nevertheless, we may get away with the split, so try that first.
416 if (RepairPt.hasSplit())
417 tryAvoidingSplit(RepairPt, MO, ValMapping);
418
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000419 // Check that the materialization of the repairing is possible.
420 if (!RepairPt.canMaterialize())
421 return MappingCost::ImpossibleCost();
422
423 // Account for the split cost and repair cost.
Quentin Colombet6e80dbc2016-05-20 18:00:46 +0000424 // Unless the cost is already saturated or we do not care about the cost.
425 if (!BestCost || Saturated)
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000426 continue;
427
Quentin Colombet6e80dbc2016-05-20 18:00:46 +0000428 // To get accurate information we need MBFI and MBPI.
429 // Thus, if we end up here this information should be here.
430 assert(MBFI && MBPI && "Cost computation requires MBFI and MBPI");
431
Quentin Colombet6feaf8202016-06-08 15:40:32 +0000432 // FIXME: We will have to rework the repairing cost model.
433 // The repairing cost depends on the register bank that MO has.
434 // However, when we break down the value into different values,
435 // MO may not have a register bank while still needing repairing.
436 // For the fast mode, we don't compute the cost so that is fine,
437 // but still for the repairing code, we will have to make a choice.
438 // For the greedy mode, we should choose greedily what is the best
439 // choice based on the next use of MO.
440
Quentin Colombetf2723a22016-05-21 01:43:25 +0000441 // Sums up the repairing cost of MO at each insertion point.
442 uint64_t RepairCost = getRepairCost(MO, ValMapping);
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000443 // Bias used for splitting: 5%.
444 const uint64_t PercentageForBias = 5;
445 uint64_t Bias = (RepairCost * PercentageForBias + 99) / 100;
446 // We should not need more than a couple of instructions to repair
447 // an assignment. In other words, the computation should not
448 // overflow because the repairing cost is free of basic block
449 // frequency.
450 assert(((RepairCost < RepairCost * PercentageForBias) &&
451 (RepairCost * PercentageForBias <
452 RepairCost * PercentageForBias + 99)) &&
453 "Repairing involves more than a billion of instructions?!");
454 for (const std::unique_ptr<InsertPoint> &InsertPt : RepairPt) {
455 assert(InsertPt->canMaterialize() && "We should not have made it here");
456 // We will applied some basic block frequency and those uses uint64_t.
457 if (!InsertPt->isSplit())
458 Saturated = Cost.addLocalCost(RepairCost);
459 else {
460 uint64_t CostForInsertPt = RepairCost;
461 // Again we shouldn't overflow here givent that
462 // CostForInsertPt is frequency free at this point.
463 assert(CostForInsertPt + Bias > CostForInsertPt &&
464 "Repairing + split bias overflows");
465 CostForInsertPt += Bias;
466 uint64_t PtCost = InsertPt->frequency(*this) * CostForInsertPt;
467 // Check if we just overflowed.
468 if ((Saturated = PtCost < CostForInsertPt))
469 Cost.saturate();
470 else
471 Saturated = Cost.addNonLocalCost(PtCost);
472 }
Quentin Colombet6e80dbc2016-05-20 18:00:46 +0000473
474 // Stop looking into what it takes to repair, this is already
475 // too expensive.
476 if (BestCost && Cost > *BestCost)
477 return Cost;
478
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000479 // No need to accumulate more cost information.
480 // We need to still gather the repairing information though.
481 if (Saturated)
482 break;
483 }
Quentin Colombet40ad5732016-04-07 18:19:27 +0000484 }
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000485 return Cost;
486}
487
Quentin Colombetacb857b2016-08-27 02:38:27 +0000488bool RegBankSelect::applyMapping(
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000489 MachineInstr &MI, const RegisterBankInfo::InstructionMapping &InstrMapping,
490 SmallVectorImpl<RegBankSelect::RepairingPlacement> &RepairPts) {
Quentin Colombetf33e3652016-06-08 16:30:55 +0000491 // OpdMapper will hold all the information needed for the rewritting.
492 RegisterBankInfo::OperandsMapper OpdMapper(MI, InstrMapping, *MRI);
493
Quentin Colombetec5c93d2016-06-08 16:45:04 +0000494 // First, place the repairing code.
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000495 for (RepairingPlacement &RepairPt : RepairPts) {
Quentin Colombetacb857b2016-08-27 02:38:27 +0000496 if (!RepairPt.canMaterialize() ||
497 RepairPt.getKind() == RepairingPlacement::Impossible)
498 return false;
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000499 assert(RepairPt.getKind() != RepairingPlacement::None &&
500 "This should not make its way in the list");
501 unsigned OpIdx = RepairPt.getOpIdx();
502 MachineOperand &MO = MI.getOperand(OpIdx);
503 const RegisterBankInfo::ValueMapping &ValMapping =
504 InstrMapping.getOperandMapping(OpIdx);
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000505 unsigned Reg = MO.getReg();
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000506
507 switch (RepairPt.getKind()) {
508 case RepairingPlacement::Reassign:
Quentin Colombet0afa7d62016-09-23 00:14:30 +0000509 assert(ValMapping.NumBreakDowns == 1 &&
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000510 "Reassignment should only be for simple mapping");
511 MRI->setRegBank(Reg, *ValMapping.BreakDown[0].RegBank);
512 break;
513 case RepairingPlacement::Insert:
Quentin Colombetf33e3652016-06-08 16:30:55 +0000514 OpdMapper.createVRegs(OpIdx);
Quentin Colombetacb857b2016-08-27 02:38:27 +0000515 if (!repairReg(MO, ValMapping, RepairPt, OpdMapper.getVRegs(OpIdx)))
516 return false;
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000517 break;
518 default:
519 llvm_unreachable("Other kind should not happen");
520 }
521 }
522 // Second, rewrite the instruction.
Quentin Colombet33406452016-06-08 21:55:30 +0000523 DEBUG(dbgs() << "Actual mapping of the operands: " << OpdMapper << '\n');
Quentin Colombetec5c93d2016-06-08 16:45:04 +0000524 RBI->applyMapping(OpdMapper);
Quentin Colombetacb857b2016-08-27 02:38:27 +0000525 return true;
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000526}
527
Quentin Colombetacb857b2016-08-27 02:38:27 +0000528bool RegBankSelect::assignInstr(MachineInstr &MI) {
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000529 DEBUG(dbgs() << "Assign: " << MI);
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000530 // Remember the repairing placement for all the operands.
531 SmallVector<RepairingPlacement, 4> RepairPts;
532
Quentin Colombet79fe1be2016-05-20 18:37:33 +0000533 RegisterBankInfo::InstructionMapping BestMapping;
534 if (OptMode == RegBankSelect::Mode::Fast) {
535 BestMapping = RBI->getInstrMapping(MI);
536 MappingCost DefaultCost = computeMapping(MI, BestMapping, RepairPts);
537 (void)DefaultCost;
Quentin Colombetacb857b2016-08-27 02:38:27 +0000538 if (DefaultCost == MappingCost::ImpossibleCost())
539 return false;
Quentin Colombet79fe1be2016-05-20 18:37:33 +0000540 } else {
541 RegisterBankInfo::InstructionMappings PossibleMappings =
542 RBI->getInstrPossibleMappings(MI);
Quentin Colombetacb857b2016-08-27 02:38:27 +0000543 if (PossibleMappings.empty())
544 return false;
Quentin Colombet79fe1be2016-05-20 18:37:33 +0000545 BestMapping = std::move(findBestMapping(MI, PossibleMappings, RepairPts));
546 }
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000547 // Make sure the mapping is valid for MI.
Quentin Colombet79fe1be2016-05-20 18:37:33 +0000548 assert(BestMapping.verify(MI) && "Invalid instruction mapping");
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000549
Quentin Colombet79fe1be2016-05-20 18:37:33 +0000550 DEBUG(dbgs() << "Mapping: " << BestMapping << '\n');
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000551
Quentin Colombet9400bfb2016-06-08 21:55:29 +0000552 // After this call, MI may not be valid anymore.
553 // Do not use it.
Quentin Colombetacb857b2016-08-27 02:38:27 +0000554 return applyMapping(MI, BestMapping, RepairPts);
Quentin Colombet40ad5732016-04-07 18:19:27 +0000555}
556
Quentin Colombet8e8e85c2016-04-05 19:06:01 +0000557bool RegBankSelect::runOnMachineFunction(MachineFunction &MF) {
Quentin Colombet60495242016-08-27 00:18:24 +0000558 // If the ISel pipeline failed, do not bother running that pass.
559 if (MF.getProperties().hasProperty(
560 MachineFunctionProperties::Property::FailedISel))
561 return false;
562
Quentin Colombete16f5612016-04-07 23:53:55 +0000563 DEBUG(dbgs() << "Assign register banks for: " << MF.getName() << '\n');
Quentin Colombeta5530122016-05-20 17:36:54 +0000564 const Function *F = MF.getFunction();
565 Mode SaveOptMode = OptMode;
566 if (F->hasFnAttribute(Attribute::OptimizeNone))
567 OptMode = Mode::Fast;
Quentin Colombet40ad5732016-04-07 18:19:27 +0000568 init(MF);
Ahmed Bougacha24d0d4d2016-08-02 15:10:32 +0000569
570#ifndef NDEBUG
571 // Check that our input is fully legal: we require the function to have the
572 // Legalized property, so it should be.
573 // FIXME: This should be in the MachineVerifier, but it can't use the
574 // MachineLegalizer as it's currently in the separate GlobalISel library.
Tim Northover0f140c72016-09-09 11:46:34 +0000575 const MachineRegisterInfo &MRI = MF.getRegInfo();
Ahmed Bougacha24d0d4d2016-08-02 15:10:32 +0000576 if (const MachineLegalizer *MLI = MF.getSubtarget().getMachineLegalizer()) {
577 for (const MachineBasicBlock &MBB : MF) {
578 for (const MachineInstr &MI : MBB) {
Tim Northover0f140c72016-09-09 11:46:34 +0000579 if (isPreISelGenericOpcode(MI.getOpcode()) && !MLI->isLegal(MI, MRI)) {
Quentin Colombetacb857b2016-08-27 02:38:27 +0000580 if (!TPC->isGlobalISelAbortEnabled()) {
581 MF.getProperties().set(
582 MachineFunctionProperties::Property::FailedISel);
583 return false;
584 }
Ahmed Bougacha24d0d4d2016-08-02 15:10:32 +0000585 std::string ErrStorage;
586 raw_string_ostream Err(ErrStorage);
587 Err << "Instruction is not legal: " << MI << '\n';
588 report_fatal_error(Err.str());
589 }
590 }
591 }
592 }
593#endif
594
Quentin Colombet40ad5732016-04-07 18:19:27 +0000595 // Walk the function and assign register banks to all operands.
Quentin Colombetab8c21f2016-04-08 17:19:10 +0000596 // Use a RPOT to make sure all registers are assigned before we choose
597 // the best mapping of the current instruction.
598 ReversePostOrderTraversal<MachineFunction*> RPOT(&MF);
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000599 for (MachineBasicBlock *MBB : RPOT) {
600 // Set a sensible insertion point so that subsequent calls to
601 // MIRBuilder.
602 MIRBuilder.setMBB(*MBB);
Quentin Colombetec5c93d2016-06-08 16:45:04 +0000603 for (MachineBasicBlock::iterator MII = MBB->begin(), End = MBB->end();
604 MII != End;) {
605 // MI might be invalidated by the assignment, so move the
606 // iterator before hand.
Ahmed Bougacha45eb3b92016-08-02 11:41:16 +0000607 MachineInstr &MI = *MII++;
608
609 // Ignore target-specific instructions: they should use proper regclasses.
610 if (isTargetSpecificOpcode(MI.getOpcode()))
611 continue;
612
Quentin Colombetacb857b2016-08-27 02:38:27 +0000613 if (!assignInstr(MI)) {
614 if (TPC->isGlobalISelAbortEnabled())
615 report_fatal_error("Unable to map instruction");
616 MF.getProperties().set(MachineFunctionProperties::Property::FailedISel);
617 return false;
618 }
Quentin Colombetec5c93d2016-06-08 16:45:04 +0000619 }
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000620 }
Quentin Colombeta5530122016-05-20 17:36:54 +0000621 OptMode = SaveOptMode;
Quentin Colombet8e8e85c2016-04-05 19:06:01 +0000622 return false;
623}
Quentin Colombetcfd97b92016-05-20 00:35:26 +0000624
625//------------------------------------------------------------------------------
Quentin Colombet55650752016-05-20 00:49:10 +0000626// Helper Classes Implementation
Quentin Colombetcfd97b92016-05-20 00:35:26 +0000627//------------------------------------------------------------------------------
Quentin Colombet55650752016-05-20 00:49:10 +0000628RegBankSelect::RepairingPlacement::RepairingPlacement(
629 MachineInstr &MI, unsigned OpIdx, const TargetRegisterInfo &TRI, Pass &P,
630 RepairingPlacement::RepairingKind Kind)
631 // Default is, we are going to insert code to repair OpIdx.
632 : Kind(Kind),
633 OpIdx(OpIdx),
634 CanMaterialize(Kind != RepairingKind::Impossible),
635 HasSplit(false),
636 P(P) {
637 const MachineOperand &MO = MI.getOperand(OpIdx);
638 assert(MO.isReg() && "Trying to repair a non-reg operand");
639
640 if (Kind != RepairingKind::Insert)
641 return;
642
643 // Repairings for definitions happen after MI, uses happen before.
644 bool Before = !MO.isDef();
645
646 // Check if we are done with MI.
647 if (!MI.isPHI() && !MI.isTerminator()) {
648 addInsertPoint(MI, Before);
649 // We are done with the initialization.
650 return;
651 }
652
653 // Now, look for the special cases.
654 if (MI.isPHI()) {
655 // - PHI must be the first instructions:
656 // * Before, we have to split the related incoming edge.
657 // * After, move the insertion point past the last phi.
658 if (!Before) {
659 MachineBasicBlock::iterator It = MI.getParent()->getFirstNonPHI();
660 if (It != MI.getParent()->end())
661 addInsertPoint(*It, /*Before*/ true);
662 else
663 addInsertPoint(*(--It), /*Before*/ false);
664 return;
665 }
666 // We repair a use of a phi, we may need to split the related edge.
667 MachineBasicBlock &Pred = *MI.getOperand(OpIdx + 1).getMBB();
668 // Check if we can move the insertion point prior to the
669 // terminators of the predecessor.
670 unsigned Reg = MO.getReg();
671 MachineBasicBlock::iterator It = Pred.getLastNonDebugInstr();
672 for (auto Begin = Pred.begin(); It != Begin && It->isTerminator(); --It)
673 if (It->modifiesRegister(Reg, &TRI)) {
674 // We cannot hoist the repairing code in the predecessor.
675 // Split the edge.
676 addInsertPoint(Pred, *MI.getParent());
677 return;
678 }
679 // At this point, we can insert in Pred.
680
681 // - If It is invalid, Pred is empty and we can insert in Pred
682 // wherever we want.
683 // - If It is valid, It is the first non-terminator, insert after It.
684 if (It == Pred.end())
685 addInsertPoint(Pred, /*Beginning*/ false);
686 else
687 addInsertPoint(*It, /*Before*/ false);
688 } else {
689 // - Terminators must be the last instructions:
690 // * Before, move the insert point before the first terminator.
691 // * After, we have to split the outcoming edges.
692 unsigned Reg = MO.getReg();
693 if (Before) {
694 // Check whether Reg is defined by any terminator.
695 MachineBasicBlock::iterator It = MI;
696 for (auto Begin = MI.getParent()->begin();
697 --It != Begin && It->isTerminator();)
698 if (It->modifiesRegister(Reg, &TRI)) {
699 // Insert the repairing code right after the definition.
700 addInsertPoint(*It, /*Before*/ false);
701 return;
702 }
703 addInsertPoint(*It, /*Before*/ true);
704 return;
705 }
706 // Make sure Reg is not redefined by other terminators, otherwise
707 // we do not know how to split.
708 for (MachineBasicBlock::iterator It = MI, End = MI.getParent()->end();
709 ++It != End;)
710 // The machine verifier should reject this kind of code.
711 assert(It->modifiesRegister(Reg, &TRI) && "Do not know where to split");
712 // Split each outcoming edges.
713 MachineBasicBlock &Src = *MI.getParent();
714 for (auto &Succ : Src.successors())
715 addInsertPoint(Src, Succ);
716 }
717}
718
719void RegBankSelect::RepairingPlacement::addInsertPoint(MachineInstr &MI,
720 bool Before) {
721 addInsertPoint(*new InstrInsertPoint(MI, Before));
722}
723
724void RegBankSelect::RepairingPlacement::addInsertPoint(MachineBasicBlock &MBB,
725 bool Beginning) {
726 addInsertPoint(*new MBBInsertPoint(MBB, Beginning));
727}
728
729void RegBankSelect::RepairingPlacement::addInsertPoint(MachineBasicBlock &Src,
730 MachineBasicBlock &Dst) {
731 addInsertPoint(*new EdgeInsertPoint(Src, Dst, P));
732}
733
734void RegBankSelect::RepairingPlacement::addInsertPoint(
735 RegBankSelect::InsertPoint &Point) {
736 CanMaterialize &= Point.canMaterialize();
737 HasSplit |= Point.isSplit();
738 InsertPoints.emplace_back(&Point);
739}
740
741RegBankSelect::InstrInsertPoint::InstrInsertPoint(MachineInstr &Instr,
742 bool Before)
743 : InsertPoint(), Instr(Instr), Before(Before) {
744 // Since we do not support splitting, we do not need to update
745 // liveness and such, so do not do anything with P.
746 assert((!Before || !Instr.isPHI()) &&
747 "Splitting before phis requires more points");
748 assert((!Before || !Instr.getNextNode() || !Instr.getNextNode()->isPHI()) &&
749 "Splitting between phis does not make sense");
750}
751
752void RegBankSelect::InstrInsertPoint::materialize() {
753 if (isSplit()) {
754 // Slice and return the beginning of the new block.
755 // If we need to split between the terminators, we theoritically
756 // need to know where the first and second set of terminators end
757 // to update the successors properly.
758 // Now, in pratice, we should have a maximum of 2 branch
759 // instructions; one conditional and one unconditional. Therefore
760 // we know how to update the successor by looking at the target of
761 // the unconditional branch.
762 // If we end up splitting at some point, then, we should update
763 // the liveness information and such. I.e., we would need to
764 // access P here.
765 // The machine verifier should actually make sure such cases
766 // cannot happen.
767 llvm_unreachable("Not yet implemented");
768 }
769 // Otherwise the insertion point is just the current or next
770 // instruction depending on Before. I.e., there is nothing to do
771 // here.
772}
773
774bool RegBankSelect::InstrInsertPoint::isSplit() const {
775 // If the insertion point is after a terminator, we need to split.
776 if (!Before)
777 return Instr.isTerminator();
778 // If we insert before an instruction that is after a terminator,
779 // we are still after a terminator.
780 return Instr.getPrevNode() && Instr.getPrevNode()->isTerminator();
781}
782
783uint64_t RegBankSelect::InstrInsertPoint::frequency(const Pass &P) const {
784 // Even if we need to split, because we insert between terminators,
785 // this split has actually the same frequency as the instruction.
786 const MachineBlockFrequencyInfo *MBFI =
787 P.getAnalysisIfAvailable<MachineBlockFrequencyInfo>();
788 if (!MBFI)
789 return 1;
790 return MBFI->getBlockFreq(Instr.getParent()).getFrequency();
791}
792
793uint64_t RegBankSelect::MBBInsertPoint::frequency(const Pass &P) const {
794 const MachineBlockFrequencyInfo *MBFI =
795 P.getAnalysisIfAvailable<MachineBlockFrequencyInfo>();
796 if (!MBFI)
797 return 1;
798 return MBFI->getBlockFreq(&MBB).getFrequency();
799}
800
801void RegBankSelect::EdgeInsertPoint::materialize() {
802 // If we end up repairing twice at the same place before materializing the
803 // insertion point, we may think we have to split an edge twice.
804 // We should have a factory for the insert point such that identical points
805 // are the same instance.
806 assert(Src.isSuccessor(DstOrSplit) && DstOrSplit->isPredecessor(&Src) &&
807 "This point has already been split");
808 MachineBasicBlock *NewBB = Src.SplitCriticalEdge(DstOrSplit, P);
809 assert(NewBB && "Invalid call to materialize");
810 // We reuse the destination block to hold the information of the new block.
811 DstOrSplit = NewBB;
812}
813
814uint64_t RegBankSelect::EdgeInsertPoint::frequency(const Pass &P) const {
815 const MachineBlockFrequencyInfo *MBFI =
816 P.getAnalysisIfAvailable<MachineBlockFrequencyInfo>();
817 if (!MBFI)
818 return 1;
819 if (WasMaterialized)
820 return MBFI->getBlockFreq(DstOrSplit).getFrequency();
821
822 const MachineBranchProbabilityInfo *MBPI =
823 P.getAnalysisIfAvailable<MachineBranchProbabilityInfo>();
824 if (!MBPI)
825 return 1;
826 // The basic block will be on the edge.
827 return (MBFI->getBlockFreq(&Src) * MBPI->getEdgeProbability(&Src, DstOrSplit))
828 .getFrequency();
829}
830
831bool RegBankSelect::EdgeInsertPoint::canMaterialize() const {
832 // If this is not a critical edge, we should not have used this insert
833 // point. Indeed, either the successor or the predecessor should
834 // have do.
835 assert(Src.succ_size() > 1 && DstOrSplit->pred_size() > 1 &&
836 "Edge is not critical");
837 return Src.canSplitCriticalEdge(DstOrSplit);
838}
839
Quentin Colombetcfd97b92016-05-20 00:35:26 +0000840RegBankSelect::MappingCost::MappingCost(const BlockFrequency &LocalFreq)
841 : LocalCost(0), NonLocalCost(0), LocalFreq(LocalFreq.getFrequency()) {}
842
843bool RegBankSelect::MappingCost::addLocalCost(uint64_t Cost) {
844 // Check if this overflows.
845 if (LocalCost + Cost < LocalCost) {
846 saturate();
847 return true;
848 }
849 LocalCost += Cost;
850 return isSaturated();
851}
852
853bool RegBankSelect::MappingCost::addNonLocalCost(uint64_t Cost) {
854 // Check if this overflows.
855 if (NonLocalCost + Cost < NonLocalCost) {
856 saturate();
857 return true;
858 }
859 NonLocalCost += Cost;
860 return isSaturated();
861}
862
863bool RegBankSelect::MappingCost::isSaturated() const {
864 return LocalCost == UINT64_MAX - 1 && NonLocalCost == UINT64_MAX &&
865 LocalFreq == UINT64_MAX;
866}
867
868void RegBankSelect::MappingCost::saturate() {
869 *this = ImpossibleCost();
870 --LocalCost;
871}
872
873RegBankSelect::MappingCost RegBankSelect::MappingCost::ImpossibleCost() {
874 return MappingCost(UINT64_MAX, UINT64_MAX, UINT64_MAX);
875}
876
877bool RegBankSelect::MappingCost::operator<(const MappingCost &Cost) const {
878 // Sort out the easy cases.
879 if (*this == Cost)
880 return false;
881 // If one is impossible to realize the other is cheaper unless it is
882 // impossible as well.
883 if ((*this == ImpossibleCost()) || (Cost == ImpossibleCost()))
884 return (*this == ImpossibleCost()) < (Cost == ImpossibleCost());
885 // If one is saturated the other is cheaper, unless it is saturated
886 // as well.
887 if (isSaturated() || Cost.isSaturated())
888 return isSaturated() < Cost.isSaturated();
889 // At this point we know both costs hold sensible values.
890
891 // If both values have a different base frequency, there is no much
892 // we can do but to scale everything.
893 // However, if they have the same base frequency we can avoid making
894 // complicated computation.
895 uint64_t ThisLocalAdjust;
896 uint64_t OtherLocalAdjust;
897 if (LLVM_LIKELY(LocalFreq == Cost.LocalFreq)) {
898
899 // At this point, we know the local costs are comparable.
900 // Do the case that do not involve potential overflow first.
901 if (NonLocalCost == Cost.NonLocalCost)
902 // Since the non-local costs do not discriminate on the result,
903 // just compare the local costs.
904 return LocalCost < Cost.LocalCost;
905
906 // The base costs are comparable so we may only keep the relative
907 // value to increase our chances of avoiding overflows.
908 ThisLocalAdjust = 0;
909 OtherLocalAdjust = 0;
910 if (LocalCost < Cost.LocalCost)
911 OtherLocalAdjust = Cost.LocalCost - LocalCost;
912 else
913 ThisLocalAdjust = LocalCost - Cost.LocalCost;
914
915 } else {
916 ThisLocalAdjust = LocalCost;
917 OtherLocalAdjust = Cost.LocalCost;
918 }
919
920 // The non-local costs are comparable, just keep the relative value.
921 uint64_t ThisNonLocalAdjust = 0;
922 uint64_t OtherNonLocalAdjust = 0;
923 if (NonLocalCost < Cost.NonLocalCost)
924 OtherNonLocalAdjust = Cost.NonLocalCost - NonLocalCost;
925 else
926 ThisNonLocalAdjust = NonLocalCost - Cost.NonLocalCost;
927 // Scale everything to make them comparable.
928 uint64_t ThisScaledCost = ThisLocalAdjust * LocalFreq;
929 // Check for overflow on that operation.
930 bool ThisOverflows = ThisLocalAdjust && (ThisScaledCost < ThisLocalAdjust ||
931 ThisScaledCost < LocalFreq);
932 uint64_t OtherScaledCost = OtherLocalAdjust * Cost.LocalFreq;
933 // Check for overflow on the last operation.
934 bool OtherOverflows =
935 OtherLocalAdjust &&
936 (OtherScaledCost < OtherLocalAdjust || OtherScaledCost < Cost.LocalFreq);
937 // Add the non-local costs.
938 ThisOverflows |= ThisNonLocalAdjust &&
939 ThisScaledCost + ThisNonLocalAdjust < ThisNonLocalAdjust;
940 ThisScaledCost += ThisNonLocalAdjust;
941 OtherOverflows |= OtherNonLocalAdjust &&
942 OtherScaledCost + OtherNonLocalAdjust < OtherNonLocalAdjust;
943 OtherScaledCost += OtherNonLocalAdjust;
944 // If both overflows, we cannot compare without additional
945 // precision, e.g., APInt. Just give up on that case.
946 if (ThisOverflows && OtherOverflows)
947 return false;
948 // If one overflows but not the other, we can still compare.
949 if (ThisOverflows || OtherOverflows)
950 return ThisOverflows < OtherOverflows;
951 // Otherwise, just compare the values.
952 return ThisScaledCost < OtherScaledCost;
953}
954
955bool RegBankSelect::MappingCost::operator==(const MappingCost &Cost) const {
956 return LocalCost == Cost.LocalCost && NonLocalCost == Cost.NonLocalCost &&
957 LocalFreq == Cost.LocalFreq;
958}