blob: 37af50667689878611c7b4b2f99510d04d3e1256 [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();
118 if (ValMapping.BreakDown.size() == 1)
119 MO.setReg(Dst);
Quentin Colombet904a2c72016-04-12 00:12:59 +0000120
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000121 // If we repair a definition, swap the source and destination for
122 // the repairing.
123 if (MO.isDef())
Quentin Colombet904a2c72016-04-12 00:12:59 +0000124 std::swap(Src, Dst);
Quentin Colombet904a2c72016-04-12 00:12:59 +0000125
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000126 assert((RepairPt.getNumInsertPoints() == 1 ||
127 TargetRegisterInfo::isPhysicalRegister(Dst)) &&
128 "We are about to create several defs for Dst");
Quentin Colombet904a2c72016-04-12 00:12:59 +0000129
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000130 // Build the instruction used to repair, then clone it at the right places.
131 MachineInstr *MI = MIRBuilder.buildInstr(TargetOpcode::COPY, Dst, Src);
132 MI->removeFromParent();
133 DEBUG(dbgs() << "Copy: " << PrintReg(Src) << " to: " << PrintReg(Dst)
134 << '\n');
135 // TODO:
136 // Check if MI is legal. if not, we need to legalize all the
137 // instructions we are going to insert.
138 std::unique_ptr<MachineInstr *[]> NewInstrs(
139 new MachineInstr *[RepairPt.getNumInsertPoints()]);
140 bool IsFirst = true;
141 unsigned Idx = 0;
142 for (const std::unique_ptr<InsertPoint> &InsertPt : RepairPt) {
143 MachineInstr *CurMI;
144 if (IsFirst)
145 CurMI = MI;
146 else
147 CurMI = MIRBuilder.getMF().CloneMachineInstr(MI);
148 InsertPt->insert(*CurMI);
149 NewInstrs[Idx++] = CurMI;
150 IsFirst = false;
151 }
152 // TODO:
153 // Legalize NewInstrs if need be.
Quentin Colombet40ad5732016-04-07 18:19:27 +0000154}
155
Quentin Colombetf2723a22016-05-21 01:43:25 +0000156uint64_t RegBankSelect::getRepairCost(
157 const MachineOperand &MO,
158 const RegisterBankInfo::ValueMapping &ValMapping) const {
159 assert(MO.isReg() && "We should only repair register operand");
160 assert(!ValMapping.BreakDown.empty() && "Nothing to map??");
161
162 bool IsSameNumOfValues = ValMapping.BreakDown.size() == 1;
163 const RegisterBank *CurRegBank = RBI->getRegBank(MO.getReg(), *MRI, *TRI);
164 // If MO does not have a register bank, we should have just been
165 // able to set one unless we have to break the value down.
166 assert((!IsSameNumOfValues || CurRegBank) && "We should not have to repair");
167 // Def: Val <- NewDefs
168 // Same number of values: copy
169 // Different number: Val = build_sequence Defs1, Defs2, ...
170 // Use: NewSources <- Val.
171 // Same number of values: copy.
172 // Different number: Src1, Src2, ... =
173 // extract_value Val, Src1Begin, Src1Len, Src2Begin, Src2Len, ...
174 // We should remember that this value is available somewhere else to
175 // coalesce the value.
176
177 if (IsSameNumOfValues) {
178 const RegisterBank *DesiredRegBrank = ValMapping.BreakDown[0].RegBank;
179 // If we repair a definition, swap the source and destination for
180 // the repairing.
181 if (MO.isDef())
182 std::swap(CurRegBank, DesiredRegBrank);
Quentin Colombetcfbdee22016-06-08 01:11:03 +0000183 unsigned Cost =
184 RBI->copyCost(*DesiredRegBrank, *CurRegBank,
185 RegisterBankInfo::getSizeInBits(MO.getReg(), *MRI, *TRI));
Quentin Colombetf2723a22016-05-21 01:43:25 +0000186 // TODO: use a dedicated constant for ImpossibleCost.
187 if (Cost != UINT_MAX)
188 return Cost;
189 assert(false && "Legalization not available yet");
190 // Return the legalization cost of that repairing.
191 }
192 assert(false && "Complex repairing not implemented yet");
193 return 1;
194}
195
Quentin Colombet79fe1be2016-05-20 18:37:33 +0000196RegisterBankInfo::InstructionMapping &RegBankSelect::findBestMapping(
197 MachineInstr &MI, RegisterBankInfo::InstructionMappings &PossibleMappings,
198 SmallVectorImpl<RepairingPlacement> &RepairPts) {
199
200 RegisterBankInfo::InstructionMapping *BestMapping = nullptr;
201 MappingCost Cost = MappingCost::ImpossibleCost();
202 SmallVector<RepairingPlacement, 4> LocalRepairPts;
203 for (RegisterBankInfo::InstructionMapping &CurMapping : PossibleMappings) {
204 MappingCost CurCost = computeMapping(MI, CurMapping, LocalRepairPts, &Cost);
205 if (CurCost < Cost) {
206 Cost = CurCost;
207 BestMapping = &CurMapping;
208 RepairPts.clear();
209 for (RepairingPlacement &RepairPt : LocalRepairPts)
210 RepairPts.emplace_back(std::move(RepairPt));
211 }
212 }
213 assert(BestMapping && "No suitable mapping for instruction");
214 return *BestMapping;
215}
216
Quentin Colombetf75c2bf2016-05-20 16:36:12 +0000217void RegBankSelect::tryAvoidingSplit(
218 RegBankSelect::RepairingPlacement &RepairPt, const MachineOperand &MO,
219 const RegisterBankInfo::ValueMapping &ValMapping) const {
220 const MachineInstr &MI = *MO.getParent();
221 assert(RepairPt.hasSplit() && "We should not have to adjust for split");
222 // Splitting should only occur for PHIs or between terminators,
223 // because we only do local repairing.
224 assert((MI.isPHI() || MI.isTerminator()) && "Why do we split?");
225
226 assert(&MI.getOperand(RepairPt.getOpIdx()) == &MO &&
227 "Repairing placement does not match operand");
228
229 // If we need splitting for phis, that means it is because we
230 // could not find an insertion point before the terminators of
231 // the predecessor block for this argument. In other words,
232 // the input value is defined by one of the terminators.
233 assert((!MI.isPHI() || !MO.isDef()) && "Need split for phi def?");
234
235 // We split to repair the use of a phi or a terminator.
236 if (!MO.isDef()) {
237 if (MI.isTerminator()) {
238 assert(&MI != &(*MI.getParent()->getFirstTerminator()) &&
239 "Need to split for the first terminator?!");
240 } else {
241 // For the PHI case, the split may not be actually required.
242 // In the copy case, a phi is already a copy on the incoming edge,
243 // therefore there is no need to split.
244 if (ValMapping.BreakDown.size() == 1)
245 // This is a already a copy, there is nothing to do.
246 RepairPt.switchTo(RepairingPlacement::RepairingKind::Reassign);
247 }
248 return;
249 }
250
251 // At this point, we need to repair a defintion of a terminator.
252
253 // Technically we need to fix the def of MI on all outgoing
254 // edges of MI to keep the repairing local. In other words, we
255 // will create several definitions of the same register. This
256 // does not work for SSA unless that definition is a physical
257 // register.
258 // However, there are other cases where we can get away with
259 // that while still keeping the repairing local.
260 assert(MI.isTerminator() && MO.isDef() &&
261 "This code is for the def of a terminator");
262
263 // Since we use RPO traversal, if we need to repair a definition
264 // this means this definition could be:
265 // 1. Used by PHIs (i.e., this VReg has been visited as part of the
266 // uses of a phi.), or
267 // 2. Part of a target specific instruction (i.e., the target applied
268 // some register class constraints when creating the instruction.)
269 // If the constraints come for #2, the target said that another mapping
270 // is supported so we may just drop them. Indeed, if we do not change
271 // the number of registers holding that value, the uses will get fixed
272 // when we get to them.
273 // Uses in PHIs may have already been proceeded though.
274 // If the constraints come for #1, then, those are weak constraints and
275 // no actual uses may rely on them. However, the problem remains mainly
276 // the same as for #2. If the value stays in one register, we could
277 // just switch the register bank of the definition, but we would need to
278 // account for a repairing cost for each phi we silently change.
279 //
280 // In any case, if the value needs to be broken down into several
281 // registers, the repairing is not local anymore as we need to patch
282 // every uses to rebuild the value in just one register.
283 //
284 // To summarize:
285 // - If the value is in a physical register, we can do the split and
286 // fix locally.
287 // Otherwise if the value is in a virtual register:
288 // - If the value remains in one register, we do not have to split
289 // just switching the register bank would do, but we need to account
290 // in the repairing cost all the phi we changed.
291 // - If the value spans several registers, then we cannot do a local
292 // repairing.
293
294 // Check if this is a physical or virtual register.
295 unsigned Reg = MO.getReg();
296 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
297 // We are going to split every outgoing edges.
298 // Check that this is possible.
299 // FIXME: The machine representation is currently broken
300 // since it also several terminators in one basic block.
301 // Because of that we would technically need a way to get
302 // the targets of just one terminator to know which edges
303 // we have to split.
304 // Assert that we do not hit the ill-formed representation.
305
306 // If there are other terminators before that one, some of
307 // the outgoing edges may not be dominated by this definition.
308 assert(&MI == &(*MI.getParent()->getFirstTerminator()) &&
309 "Do not know which outgoing edges are relevant");
310 const MachineInstr *Next = MI.getNextNode();
311 assert((!Next || Next->isUnconditionalBranch()) &&
312 "Do not know where each terminator ends up");
313 if (Next)
314 // If the next terminator uses Reg, this means we have
315 // to split right after MI and thus we need a way to ask
316 // which outgoing edges are affected.
317 assert(!Next->readsRegister(Reg) && "Need to split between terminators");
318 // We will split all the edges and repair there.
319 } else {
320 // This is a virtual register defined by a terminator.
321 if (ValMapping.BreakDown.size() == 1) {
322 // There is nothing to repair, but we may actually lie on
323 // the repairing cost because of the PHIs already proceeded
324 // as already stated.
325 // Though the code will be correct.
326 assert(0 && "Repairing cost may not be accurate");
327 } else {
328 // We need to do non-local repairing. Basically, patch all
329 // the uses (i.e., phis) that we already proceeded.
330 // For now, just say this mapping is not possible.
331 RepairPt.switchTo(RepairingPlacement::RepairingKind::Impossible);
332 }
333 }
334}
335
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000336RegBankSelect::MappingCost RegBankSelect::computeMapping(
337 MachineInstr &MI, const RegisterBankInfo::InstructionMapping &InstrMapping,
Quentin Colombet6e80dbc2016-05-20 18:00:46 +0000338 SmallVectorImpl<RepairingPlacement> &RepairPts,
339 const RegBankSelect::MappingCost *BestCost) {
340 assert((MBFI || !BestCost) && "Costs comparison require MBFI");
Quentin Colombete16f5612016-04-07 23:53:55 +0000341
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000342 // If mapped with InstrMapping, MI will have the recorded cost.
Quentin Colombet25fcef72016-05-20 17:54:09 +0000343 MappingCost Cost(MBFI ? MBFI->getBlockFreq(MI.getParent()) : 1);
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000344 bool Saturated = Cost.addLocalCost(InstrMapping.getCost());
345 assert(!Saturated && "Possible mapping saturated the cost");
346 DEBUG(dbgs() << "Evaluating mapping cost for: " << MI);
347 DEBUG(dbgs() << "With: " << InstrMapping << '\n');
348 RepairPts.clear();
Quentin Colombet6e80dbc2016-05-20 18:00:46 +0000349 if (BestCost && Cost > *BestCost)
350 return Cost;
351
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000352 // Moreover, to realize this mapping, the register bank of each operand must
353 // match this mapping. In other words, we may need to locally reassign the
354 // register banks. Account for that repairing cost as well.
355 // In this context, local means in the surrounding of MI.
356 for (unsigned OpIdx = 0, EndOpIdx = MI.getNumOperands(); OpIdx != EndOpIdx;
Quentin Colombet40ad5732016-04-07 18:19:27 +0000357 ++OpIdx) {
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000358 const MachineOperand &MO = MI.getOperand(OpIdx);
Quentin Colombet40ad5732016-04-07 18:19:27 +0000359 if (!MO.isReg())
360 continue;
361 unsigned Reg = MO.getReg();
362 if (!Reg)
363 continue;
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000364 DEBUG(dbgs() << "Opd" << OpIdx);
Quentin Colombet40ad5732016-04-07 18:19:27 +0000365 const RegisterBankInfo::ValueMapping &ValMapping =
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000366 InstrMapping.getOperandMapping(OpIdx);
367 // If Reg is already properly mapped, this is free.
368 bool Assign;
369 if (assignmentMatch(Reg, ValMapping, Assign)) {
370 DEBUG(dbgs() << " is free (match).\n");
Quentin Colombet40ad5732016-04-07 18:19:27 +0000371 continue;
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000372 }
373 if (Assign) {
374 DEBUG(dbgs() << " is free (simple assignment).\n");
375 RepairPts.emplace_back(RepairingPlacement(MI, OpIdx, *TRI, *this,
376 RepairingPlacement::Reassign));
377 continue;
Quentin Colombet40ad5732016-04-07 18:19:27 +0000378 }
Quentin Colombet904a2c72016-04-12 00:12:59 +0000379
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000380 // Find the insertion point for the repairing code.
381 RepairPts.emplace_back(
382 RepairingPlacement(MI, OpIdx, *TRI, *this, RepairingPlacement::Insert));
383 RepairingPlacement &RepairPt = RepairPts.back();
384
Quentin Colombetf75c2bf2016-05-20 16:36:12 +0000385 // If we need to split a basic block to materialize this insertion point,
386 // we may give a higher cost to this mapping.
387 // Nevertheless, we may get away with the split, so try that first.
388 if (RepairPt.hasSplit())
389 tryAvoidingSplit(RepairPt, MO, ValMapping);
390
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000391 // Check that the materialization of the repairing is possible.
392 if (!RepairPt.canMaterialize())
393 return MappingCost::ImpossibleCost();
394
395 // Account for the split cost and repair cost.
Quentin Colombet6e80dbc2016-05-20 18:00:46 +0000396 // Unless the cost is already saturated or we do not care about the cost.
397 if (!BestCost || Saturated)
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000398 continue;
399
Quentin Colombet6e80dbc2016-05-20 18:00:46 +0000400 // To get accurate information we need MBFI and MBPI.
401 // Thus, if we end up here this information should be here.
402 assert(MBFI && MBPI && "Cost computation requires MBFI and MBPI");
403
Quentin Colombet6feaf8202016-06-08 15:40:32 +0000404 // FIXME: We will have to rework the repairing cost model.
405 // The repairing cost depends on the register bank that MO has.
406 // However, when we break down the value into different values,
407 // MO may not have a register bank while still needing repairing.
408 // For the fast mode, we don't compute the cost so that is fine,
409 // but still for the repairing code, we will have to make a choice.
410 // For the greedy mode, we should choose greedily what is the best
411 // choice based on the next use of MO.
412
Quentin Colombetf2723a22016-05-21 01:43:25 +0000413 // Sums up the repairing cost of MO at each insertion point.
414 uint64_t RepairCost = getRepairCost(MO, ValMapping);
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000415 // Bias used for splitting: 5%.
416 const uint64_t PercentageForBias = 5;
417 uint64_t Bias = (RepairCost * PercentageForBias + 99) / 100;
418 // We should not need more than a couple of instructions to repair
419 // an assignment. In other words, the computation should not
420 // overflow because the repairing cost is free of basic block
421 // frequency.
422 assert(((RepairCost < RepairCost * PercentageForBias) &&
423 (RepairCost * PercentageForBias <
424 RepairCost * PercentageForBias + 99)) &&
425 "Repairing involves more than a billion of instructions?!");
426 for (const std::unique_ptr<InsertPoint> &InsertPt : RepairPt) {
427 assert(InsertPt->canMaterialize() && "We should not have made it here");
428 // We will applied some basic block frequency and those uses uint64_t.
429 if (!InsertPt->isSplit())
430 Saturated = Cost.addLocalCost(RepairCost);
431 else {
432 uint64_t CostForInsertPt = RepairCost;
433 // Again we shouldn't overflow here givent that
434 // CostForInsertPt is frequency free at this point.
435 assert(CostForInsertPt + Bias > CostForInsertPt &&
436 "Repairing + split bias overflows");
437 CostForInsertPt += Bias;
438 uint64_t PtCost = InsertPt->frequency(*this) * CostForInsertPt;
439 // Check if we just overflowed.
440 if ((Saturated = PtCost < CostForInsertPt))
441 Cost.saturate();
442 else
443 Saturated = Cost.addNonLocalCost(PtCost);
444 }
Quentin Colombet6e80dbc2016-05-20 18:00:46 +0000445
446 // Stop looking into what it takes to repair, this is already
447 // too expensive.
448 if (BestCost && Cost > *BestCost)
449 return Cost;
450
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000451 // No need to accumulate more cost information.
452 // We need to still gather the repairing information though.
453 if (Saturated)
454 break;
455 }
Quentin Colombet40ad5732016-04-07 18:19:27 +0000456 }
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000457 return Cost;
458}
459
460void RegBankSelect::applyMapping(
461 MachineInstr &MI, const RegisterBankInfo::InstructionMapping &InstrMapping,
462 SmallVectorImpl<RegBankSelect::RepairingPlacement> &RepairPts) {
463 assert(InstrMapping.getID() == RegisterBankInfo::DefaultMappingID &&
464 "Rewriting of MI not implemented yet");
465 // First, place the repairing code.
466 bool NeedRewrite = false;
Quentin Colombetf33e3652016-06-08 16:30:55 +0000467 // OpdMapper will hold all the information needed for the rewritting.
468 RegisterBankInfo::OperandsMapper OpdMapper(MI, InstrMapping, *MRI);
469
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000470 for (RepairingPlacement &RepairPt : RepairPts) {
471 assert(RepairPt.canMaterialize() &&
472 RepairPt.getKind() != RepairingPlacement::Impossible &&
473 "This mapping is impossible");
474 assert(RepairPt.getKind() != RepairingPlacement::None &&
475 "This should not make its way in the list");
476 unsigned OpIdx = RepairPt.getOpIdx();
477 MachineOperand &MO = MI.getOperand(OpIdx);
478 const RegisterBankInfo::ValueMapping &ValMapping =
479 InstrMapping.getOperandMapping(OpIdx);
480 unsigned BreakDownSize = ValMapping.BreakDown.size();
481 unsigned Reg = MO.getReg();
482 NeedRewrite = BreakDownSize != 1;
483
484 switch (RepairPt.getKind()) {
485 case RepairingPlacement::Reassign:
486 assert(BreakDownSize == 1 &&
487 "Reassignment should only be for simple mapping");
488 MRI->setRegBank(Reg, *ValMapping.BreakDown[0].RegBank);
489 break;
490 case RepairingPlacement::Insert:
Quentin Colombetf33e3652016-06-08 16:30:55 +0000491 OpdMapper.createVRegs(OpIdx);
492 repairReg(MO, ValMapping, RepairPt, OpdMapper.getVRegs(OpIdx));
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000493 break;
494 default:
495 llvm_unreachable("Other kind should not happen");
496 }
497 }
498 // Second, rewrite the instruction.
499 (void)NeedRewrite;
500 assert(!NeedRewrite && "Not implemented yet");
501}
502
503void RegBankSelect::assignInstr(MachineInstr &MI) {
504 DEBUG(dbgs() << "Assign: " << MI);
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000505 // Remember the repairing placement for all the operands.
506 SmallVector<RepairingPlacement, 4> RepairPts;
507
Quentin Colombet79fe1be2016-05-20 18:37:33 +0000508 RegisterBankInfo::InstructionMapping BestMapping;
509 if (OptMode == RegBankSelect::Mode::Fast) {
510 BestMapping = RBI->getInstrMapping(MI);
511 MappingCost DefaultCost = computeMapping(MI, BestMapping, RepairPts);
512 (void)DefaultCost;
513 assert(DefaultCost != MappingCost::ImpossibleCost() &&
514 "Default mapping is not suited");
515 } else {
516 RegisterBankInfo::InstructionMappings PossibleMappings =
517 RBI->getInstrPossibleMappings(MI);
518 assert(!PossibleMappings.empty() &&
519 "Do not know how to map this instruction");
520 BestMapping = std::move(findBestMapping(MI, PossibleMappings, RepairPts));
521 }
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000522 // Make sure the mapping is valid for MI.
Quentin Colombet79fe1be2016-05-20 18:37:33 +0000523 assert(BestMapping.verify(MI) && "Invalid instruction mapping");
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000524
Quentin Colombet79fe1be2016-05-20 18:37:33 +0000525 DEBUG(dbgs() << "Mapping: " << BestMapping << '\n');
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000526
Quentin Colombet79fe1be2016-05-20 18:37:33 +0000527 applyMapping(MI, BestMapping, RepairPts);
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000528
Quentin Colombete16f5612016-04-07 23:53:55 +0000529 DEBUG(dbgs() << "Assigned: " << MI);
Quentin Colombet40ad5732016-04-07 18:19:27 +0000530}
531
Quentin Colombet8e8e85c2016-04-05 19:06:01 +0000532bool RegBankSelect::runOnMachineFunction(MachineFunction &MF) {
Quentin Colombete16f5612016-04-07 23:53:55 +0000533 DEBUG(dbgs() << "Assign register banks for: " << MF.getName() << '\n');
Quentin Colombeta5530122016-05-20 17:36:54 +0000534 const Function *F = MF.getFunction();
535 Mode SaveOptMode = OptMode;
536 if (F->hasFnAttribute(Attribute::OptimizeNone))
537 OptMode = Mode::Fast;
Quentin Colombet40ad5732016-04-07 18:19:27 +0000538 init(MF);
539 // Walk the function and assign register banks to all operands.
Quentin Colombetab8c21f2016-04-08 17:19:10 +0000540 // Use a RPOT to make sure all registers are assigned before we choose
541 // the best mapping of the current instruction.
542 ReversePostOrderTraversal<MachineFunction*> RPOT(&MF);
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000543 for (MachineBasicBlock *MBB : RPOT) {
544 // Set a sensible insertion point so that subsequent calls to
545 // MIRBuilder.
546 MIRBuilder.setMBB(*MBB);
Quentin Colombetab8c21f2016-04-08 17:19:10 +0000547 for (MachineInstr &MI : *MBB)
Quentin Colombet40ad5732016-04-07 18:19:27 +0000548 assignInstr(MI);
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000549 }
Quentin Colombeta5530122016-05-20 17:36:54 +0000550 OptMode = SaveOptMode;
Quentin Colombet8e8e85c2016-04-05 19:06:01 +0000551 return false;
552}
Quentin Colombetcfd97b92016-05-20 00:35:26 +0000553
554//------------------------------------------------------------------------------
Quentin Colombet55650752016-05-20 00:49:10 +0000555// Helper Classes Implementation
Quentin Colombetcfd97b92016-05-20 00:35:26 +0000556//------------------------------------------------------------------------------
Quentin Colombet55650752016-05-20 00:49:10 +0000557RegBankSelect::RepairingPlacement::RepairingPlacement(
558 MachineInstr &MI, unsigned OpIdx, const TargetRegisterInfo &TRI, Pass &P,
559 RepairingPlacement::RepairingKind Kind)
560 // Default is, we are going to insert code to repair OpIdx.
561 : Kind(Kind),
562 OpIdx(OpIdx),
563 CanMaterialize(Kind != RepairingKind::Impossible),
564 HasSplit(false),
565 P(P) {
566 const MachineOperand &MO = MI.getOperand(OpIdx);
567 assert(MO.isReg() && "Trying to repair a non-reg operand");
568
569 if (Kind != RepairingKind::Insert)
570 return;
571
572 // Repairings for definitions happen after MI, uses happen before.
573 bool Before = !MO.isDef();
574
575 // Check if we are done with MI.
576 if (!MI.isPHI() && !MI.isTerminator()) {
577 addInsertPoint(MI, Before);
578 // We are done with the initialization.
579 return;
580 }
581
582 // Now, look for the special cases.
583 if (MI.isPHI()) {
584 // - PHI must be the first instructions:
585 // * Before, we have to split the related incoming edge.
586 // * After, move the insertion point past the last phi.
587 if (!Before) {
588 MachineBasicBlock::iterator It = MI.getParent()->getFirstNonPHI();
589 if (It != MI.getParent()->end())
590 addInsertPoint(*It, /*Before*/ true);
591 else
592 addInsertPoint(*(--It), /*Before*/ false);
593 return;
594 }
595 // We repair a use of a phi, we may need to split the related edge.
596 MachineBasicBlock &Pred = *MI.getOperand(OpIdx + 1).getMBB();
597 // Check if we can move the insertion point prior to the
598 // terminators of the predecessor.
599 unsigned Reg = MO.getReg();
600 MachineBasicBlock::iterator It = Pred.getLastNonDebugInstr();
601 for (auto Begin = Pred.begin(); It != Begin && It->isTerminator(); --It)
602 if (It->modifiesRegister(Reg, &TRI)) {
603 // We cannot hoist the repairing code in the predecessor.
604 // Split the edge.
605 addInsertPoint(Pred, *MI.getParent());
606 return;
607 }
608 // At this point, we can insert in Pred.
609
610 // - If It is invalid, Pred is empty and we can insert in Pred
611 // wherever we want.
612 // - If It is valid, It is the first non-terminator, insert after It.
613 if (It == Pred.end())
614 addInsertPoint(Pred, /*Beginning*/ false);
615 else
616 addInsertPoint(*It, /*Before*/ false);
617 } else {
618 // - Terminators must be the last instructions:
619 // * Before, move the insert point before the first terminator.
620 // * After, we have to split the outcoming edges.
621 unsigned Reg = MO.getReg();
622 if (Before) {
623 // Check whether Reg is defined by any terminator.
624 MachineBasicBlock::iterator It = MI;
625 for (auto Begin = MI.getParent()->begin();
626 --It != Begin && It->isTerminator();)
627 if (It->modifiesRegister(Reg, &TRI)) {
628 // Insert the repairing code right after the definition.
629 addInsertPoint(*It, /*Before*/ false);
630 return;
631 }
632 addInsertPoint(*It, /*Before*/ true);
633 return;
634 }
635 // Make sure Reg is not redefined by other terminators, otherwise
636 // we do not know how to split.
637 for (MachineBasicBlock::iterator It = MI, End = MI.getParent()->end();
638 ++It != End;)
639 // The machine verifier should reject this kind of code.
640 assert(It->modifiesRegister(Reg, &TRI) && "Do not know where to split");
641 // Split each outcoming edges.
642 MachineBasicBlock &Src = *MI.getParent();
643 for (auto &Succ : Src.successors())
644 addInsertPoint(Src, Succ);
645 }
646}
647
648void RegBankSelect::RepairingPlacement::addInsertPoint(MachineInstr &MI,
649 bool Before) {
650 addInsertPoint(*new InstrInsertPoint(MI, Before));
651}
652
653void RegBankSelect::RepairingPlacement::addInsertPoint(MachineBasicBlock &MBB,
654 bool Beginning) {
655 addInsertPoint(*new MBBInsertPoint(MBB, Beginning));
656}
657
658void RegBankSelect::RepairingPlacement::addInsertPoint(MachineBasicBlock &Src,
659 MachineBasicBlock &Dst) {
660 addInsertPoint(*new EdgeInsertPoint(Src, Dst, P));
661}
662
663void RegBankSelect::RepairingPlacement::addInsertPoint(
664 RegBankSelect::InsertPoint &Point) {
665 CanMaterialize &= Point.canMaterialize();
666 HasSplit |= Point.isSplit();
667 InsertPoints.emplace_back(&Point);
668}
669
670RegBankSelect::InstrInsertPoint::InstrInsertPoint(MachineInstr &Instr,
671 bool Before)
672 : InsertPoint(), Instr(Instr), Before(Before) {
673 // Since we do not support splitting, we do not need to update
674 // liveness and such, so do not do anything with P.
675 assert((!Before || !Instr.isPHI()) &&
676 "Splitting before phis requires more points");
677 assert((!Before || !Instr.getNextNode() || !Instr.getNextNode()->isPHI()) &&
678 "Splitting between phis does not make sense");
679}
680
681void RegBankSelect::InstrInsertPoint::materialize() {
682 if (isSplit()) {
683 // Slice and return the beginning of the new block.
684 // If we need to split between the terminators, we theoritically
685 // need to know where the first and second set of terminators end
686 // to update the successors properly.
687 // Now, in pratice, we should have a maximum of 2 branch
688 // instructions; one conditional and one unconditional. Therefore
689 // we know how to update the successor by looking at the target of
690 // the unconditional branch.
691 // If we end up splitting at some point, then, we should update
692 // the liveness information and such. I.e., we would need to
693 // access P here.
694 // The machine verifier should actually make sure such cases
695 // cannot happen.
696 llvm_unreachable("Not yet implemented");
697 }
698 // Otherwise the insertion point is just the current or next
699 // instruction depending on Before. I.e., there is nothing to do
700 // here.
701}
702
703bool RegBankSelect::InstrInsertPoint::isSplit() const {
704 // If the insertion point is after a terminator, we need to split.
705 if (!Before)
706 return Instr.isTerminator();
707 // If we insert before an instruction that is after a terminator,
708 // we are still after a terminator.
709 return Instr.getPrevNode() && Instr.getPrevNode()->isTerminator();
710}
711
712uint64_t RegBankSelect::InstrInsertPoint::frequency(const Pass &P) const {
713 // Even if we need to split, because we insert between terminators,
714 // this split has actually the same frequency as the instruction.
715 const MachineBlockFrequencyInfo *MBFI =
716 P.getAnalysisIfAvailable<MachineBlockFrequencyInfo>();
717 if (!MBFI)
718 return 1;
719 return MBFI->getBlockFreq(Instr.getParent()).getFrequency();
720}
721
722uint64_t RegBankSelect::MBBInsertPoint::frequency(const Pass &P) const {
723 const MachineBlockFrequencyInfo *MBFI =
724 P.getAnalysisIfAvailable<MachineBlockFrequencyInfo>();
725 if (!MBFI)
726 return 1;
727 return MBFI->getBlockFreq(&MBB).getFrequency();
728}
729
730void RegBankSelect::EdgeInsertPoint::materialize() {
731 // If we end up repairing twice at the same place before materializing the
732 // insertion point, we may think we have to split an edge twice.
733 // We should have a factory for the insert point such that identical points
734 // are the same instance.
735 assert(Src.isSuccessor(DstOrSplit) && DstOrSplit->isPredecessor(&Src) &&
736 "This point has already been split");
737 MachineBasicBlock *NewBB = Src.SplitCriticalEdge(DstOrSplit, P);
738 assert(NewBB && "Invalid call to materialize");
739 // We reuse the destination block to hold the information of the new block.
740 DstOrSplit = NewBB;
741}
742
743uint64_t RegBankSelect::EdgeInsertPoint::frequency(const Pass &P) const {
744 const MachineBlockFrequencyInfo *MBFI =
745 P.getAnalysisIfAvailable<MachineBlockFrequencyInfo>();
746 if (!MBFI)
747 return 1;
748 if (WasMaterialized)
749 return MBFI->getBlockFreq(DstOrSplit).getFrequency();
750
751 const MachineBranchProbabilityInfo *MBPI =
752 P.getAnalysisIfAvailable<MachineBranchProbabilityInfo>();
753 if (!MBPI)
754 return 1;
755 // The basic block will be on the edge.
756 return (MBFI->getBlockFreq(&Src) * MBPI->getEdgeProbability(&Src, DstOrSplit))
757 .getFrequency();
758}
759
760bool RegBankSelect::EdgeInsertPoint::canMaterialize() const {
761 // If this is not a critical edge, we should not have used this insert
762 // point. Indeed, either the successor or the predecessor should
763 // have do.
764 assert(Src.succ_size() > 1 && DstOrSplit->pred_size() > 1 &&
765 "Edge is not critical");
766 return Src.canSplitCriticalEdge(DstOrSplit);
767}
768
Quentin Colombetcfd97b92016-05-20 00:35:26 +0000769RegBankSelect::MappingCost::MappingCost(const BlockFrequency &LocalFreq)
770 : LocalCost(0), NonLocalCost(0), LocalFreq(LocalFreq.getFrequency()) {}
771
772bool RegBankSelect::MappingCost::addLocalCost(uint64_t Cost) {
773 // Check if this overflows.
774 if (LocalCost + Cost < LocalCost) {
775 saturate();
776 return true;
777 }
778 LocalCost += Cost;
779 return isSaturated();
780}
781
782bool RegBankSelect::MappingCost::addNonLocalCost(uint64_t Cost) {
783 // Check if this overflows.
784 if (NonLocalCost + Cost < NonLocalCost) {
785 saturate();
786 return true;
787 }
788 NonLocalCost += Cost;
789 return isSaturated();
790}
791
792bool RegBankSelect::MappingCost::isSaturated() const {
793 return LocalCost == UINT64_MAX - 1 && NonLocalCost == UINT64_MAX &&
794 LocalFreq == UINT64_MAX;
795}
796
797void RegBankSelect::MappingCost::saturate() {
798 *this = ImpossibleCost();
799 --LocalCost;
800}
801
802RegBankSelect::MappingCost RegBankSelect::MappingCost::ImpossibleCost() {
803 return MappingCost(UINT64_MAX, UINT64_MAX, UINT64_MAX);
804}
805
806bool RegBankSelect::MappingCost::operator<(const MappingCost &Cost) const {
807 // Sort out the easy cases.
808 if (*this == Cost)
809 return false;
810 // If one is impossible to realize the other is cheaper unless it is
811 // impossible as well.
812 if ((*this == ImpossibleCost()) || (Cost == ImpossibleCost()))
813 return (*this == ImpossibleCost()) < (Cost == ImpossibleCost());
814 // If one is saturated the other is cheaper, unless it is saturated
815 // as well.
816 if (isSaturated() || Cost.isSaturated())
817 return isSaturated() < Cost.isSaturated();
818 // At this point we know both costs hold sensible values.
819
820 // If both values have a different base frequency, there is no much
821 // we can do but to scale everything.
822 // However, if they have the same base frequency we can avoid making
823 // complicated computation.
824 uint64_t ThisLocalAdjust;
825 uint64_t OtherLocalAdjust;
826 if (LLVM_LIKELY(LocalFreq == Cost.LocalFreq)) {
827
828 // At this point, we know the local costs are comparable.
829 // Do the case that do not involve potential overflow first.
830 if (NonLocalCost == Cost.NonLocalCost)
831 // Since the non-local costs do not discriminate on the result,
832 // just compare the local costs.
833 return LocalCost < Cost.LocalCost;
834
835 // The base costs are comparable so we may only keep the relative
836 // value to increase our chances of avoiding overflows.
837 ThisLocalAdjust = 0;
838 OtherLocalAdjust = 0;
839 if (LocalCost < Cost.LocalCost)
840 OtherLocalAdjust = Cost.LocalCost - LocalCost;
841 else
842 ThisLocalAdjust = LocalCost - Cost.LocalCost;
843
844 } else {
845 ThisLocalAdjust = LocalCost;
846 OtherLocalAdjust = Cost.LocalCost;
847 }
848
849 // The non-local costs are comparable, just keep the relative value.
850 uint64_t ThisNonLocalAdjust = 0;
851 uint64_t OtherNonLocalAdjust = 0;
852 if (NonLocalCost < Cost.NonLocalCost)
853 OtherNonLocalAdjust = Cost.NonLocalCost - NonLocalCost;
854 else
855 ThisNonLocalAdjust = NonLocalCost - Cost.NonLocalCost;
856 // Scale everything to make them comparable.
857 uint64_t ThisScaledCost = ThisLocalAdjust * LocalFreq;
858 // Check for overflow on that operation.
859 bool ThisOverflows = ThisLocalAdjust && (ThisScaledCost < ThisLocalAdjust ||
860 ThisScaledCost < LocalFreq);
861 uint64_t OtherScaledCost = OtherLocalAdjust * Cost.LocalFreq;
862 // Check for overflow on the last operation.
863 bool OtherOverflows =
864 OtherLocalAdjust &&
865 (OtherScaledCost < OtherLocalAdjust || OtherScaledCost < Cost.LocalFreq);
866 // Add the non-local costs.
867 ThisOverflows |= ThisNonLocalAdjust &&
868 ThisScaledCost + ThisNonLocalAdjust < ThisNonLocalAdjust;
869 ThisScaledCost += ThisNonLocalAdjust;
870 OtherOverflows |= OtherNonLocalAdjust &&
871 OtherScaledCost + OtherNonLocalAdjust < OtherNonLocalAdjust;
872 OtherScaledCost += OtherNonLocalAdjust;
873 // If both overflows, we cannot compare without additional
874 // precision, e.g., APInt. Just give up on that case.
875 if (ThisOverflows && OtherOverflows)
876 return false;
877 // If one overflows but not the other, we can still compare.
878 if (ThisOverflows || OtherOverflows)
879 return ThisOverflows < OtherOverflows;
880 // Otherwise, just compare the values.
881 return ThisScaledCost < OtherScaledCost;
882}
883
884bool RegBankSelect::MappingCost::operator==(const MappingCost &Cost) const {
885 return LocalCost == Cost.LocalCost && NonLocalCost == Cost.NonLocalCost &&
886 LocalFreq == Cost.LocalFreq;
887}