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