blob: 6248ab460971455a226ad69c7f56432908e3bfc4 [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,
Tim Northover884b47e2016-07-26 03:29:18 +000045 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.
Tim Northover756eca32016-07-26 16:45:30 +0000129 MachineInstr *MI = MIRBuilder.buildCopy(Dst, Src);
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000130 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 Colombetd6886bd2016-06-08 17:39:43 +0000181 // TODO: It may be possible to actually avoid the copy.
182 // If we repair something where the source is defined by a copy
183 // and the source of that copy is on the right bank, we can reuse
184 // it for free.
185 // E.g.,
186 // RegToRepair<BankA> = copy AlternativeSrc<BankB>
187 // = op RegToRepair<BankA>
188 // We can simply propagate AlternativeSrc instead of copying RegToRepair
189 // into a new virtual register.
190 // We would also need to propagate this information in the
191 // repairing placement.
Quentin Colombetcfbdee22016-06-08 01:11:03 +0000192 unsigned Cost =
193 RBI->copyCost(*DesiredRegBrank, *CurRegBank,
194 RegisterBankInfo::getSizeInBits(MO.getReg(), *MRI, *TRI));
Quentin Colombetf2723a22016-05-21 01:43:25 +0000195 // TODO: use a dedicated constant for ImpossibleCost.
196 if (Cost != UINT_MAX)
197 return Cost;
198 assert(false && "Legalization not available yet");
199 // Return the legalization cost of that repairing.
200 }
201 assert(false && "Complex repairing not implemented yet");
202 return 1;
203}
204
Quentin Colombet79fe1be2016-05-20 18:37:33 +0000205RegisterBankInfo::InstructionMapping &RegBankSelect::findBestMapping(
206 MachineInstr &MI, RegisterBankInfo::InstructionMappings &PossibleMappings,
207 SmallVectorImpl<RepairingPlacement> &RepairPts) {
208
209 RegisterBankInfo::InstructionMapping *BestMapping = nullptr;
210 MappingCost Cost = MappingCost::ImpossibleCost();
211 SmallVector<RepairingPlacement, 4> LocalRepairPts;
212 for (RegisterBankInfo::InstructionMapping &CurMapping : PossibleMappings) {
213 MappingCost CurCost = computeMapping(MI, CurMapping, LocalRepairPts, &Cost);
214 if (CurCost < Cost) {
215 Cost = CurCost;
216 BestMapping = &CurMapping;
217 RepairPts.clear();
218 for (RepairingPlacement &RepairPt : LocalRepairPts)
219 RepairPts.emplace_back(std::move(RepairPt));
220 }
221 }
222 assert(BestMapping && "No suitable mapping for instruction");
223 return *BestMapping;
224}
225
Quentin Colombetf75c2bf2016-05-20 16:36:12 +0000226void RegBankSelect::tryAvoidingSplit(
227 RegBankSelect::RepairingPlacement &RepairPt, const MachineOperand &MO,
228 const RegisterBankInfo::ValueMapping &ValMapping) const {
229 const MachineInstr &MI = *MO.getParent();
230 assert(RepairPt.hasSplit() && "We should not have to adjust for split");
231 // Splitting should only occur for PHIs or between terminators,
232 // because we only do local repairing.
233 assert((MI.isPHI() || MI.isTerminator()) && "Why do we split?");
234
235 assert(&MI.getOperand(RepairPt.getOpIdx()) == &MO &&
236 "Repairing placement does not match operand");
237
238 // If we need splitting for phis, that means it is because we
239 // could not find an insertion point before the terminators of
240 // the predecessor block for this argument. In other words,
241 // the input value is defined by one of the terminators.
242 assert((!MI.isPHI() || !MO.isDef()) && "Need split for phi def?");
243
244 // We split to repair the use of a phi or a terminator.
245 if (!MO.isDef()) {
246 if (MI.isTerminator()) {
247 assert(&MI != &(*MI.getParent()->getFirstTerminator()) &&
248 "Need to split for the first terminator?!");
249 } else {
250 // For the PHI case, the split may not be actually required.
251 // In the copy case, a phi is already a copy on the incoming edge,
252 // therefore there is no need to split.
253 if (ValMapping.BreakDown.size() == 1)
254 // This is a already a copy, there is nothing to do.
255 RepairPt.switchTo(RepairingPlacement::RepairingKind::Reassign);
256 }
257 return;
258 }
259
260 // At this point, we need to repair a defintion of a terminator.
261
262 // Technically we need to fix the def of MI on all outgoing
263 // edges of MI to keep the repairing local. In other words, we
264 // will create several definitions of the same register. This
265 // does not work for SSA unless that definition is a physical
266 // register.
267 // However, there are other cases where we can get away with
268 // that while still keeping the repairing local.
269 assert(MI.isTerminator() && MO.isDef() &&
270 "This code is for the def of a terminator");
271
272 // Since we use RPO traversal, if we need to repair a definition
273 // this means this definition could be:
274 // 1. Used by PHIs (i.e., this VReg has been visited as part of the
275 // uses of a phi.), or
276 // 2. Part of a target specific instruction (i.e., the target applied
277 // some register class constraints when creating the instruction.)
278 // If the constraints come for #2, the target said that another mapping
279 // is supported so we may just drop them. Indeed, if we do not change
280 // the number of registers holding that value, the uses will get fixed
281 // when we get to them.
282 // Uses in PHIs may have already been proceeded though.
283 // If the constraints come for #1, then, those are weak constraints and
284 // no actual uses may rely on them. However, the problem remains mainly
285 // the same as for #2. If the value stays in one register, we could
286 // just switch the register bank of the definition, but we would need to
287 // account for a repairing cost for each phi we silently change.
288 //
289 // In any case, if the value needs to be broken down into several
290 // registers, the repairing is not local anymore as we need to patch
291 // every uses to rebuild the value in just one register.
292 //
293 // To summarize:
294 // - If the value is in a physical register, we can do the split and
295 // fix locally.
296 // Otherwise if the value is in a virtual register:
297 // - If the value remains in one register, we do not have to split
298 // just switching the register bank would do, but we need to account
299 // in the repairing cost all the phi we changed.
300 // - If the value spans several registers, then we cannot do a local
301 // repairing.
302
303 // Check if this is a physical or virtual register.
304 unsigned Reg = MO.getReg();
305 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
306 // We are going to split every outgoing edges.
307 // Check that this is possible.
308 // FIXME: The machine representation is currently broken
309 // since it also several terminators in one basic block.
310 // Because of that we would technically need a way to get
311 // the targets of just one terminator to know which edges
312 // we have to split.
313 // Assert that we do not hit the ill-formed representation.
314
315 // If there are other terminators before that one, some of
316 // the outgoing edges may not be dominated by this definition.
317 assert(&MI == &(*MI.getParent()->getFirstTerminator()) &&
318 "Do not know which outgoing edges are relevant");
319 const MachineInstr *Next = MI.getNextNode();
320 assert((!Next || Next->isUnconditionalBranch()) &&
321 "Do not know where each terminator ends up");
322 if (Next)
323 // If the next terminator uses Reg, this means we have
324 // to split right after MI and thus we need a way to ask
325 // which outgoing edges are affected.
326 assert(!Next->readsRegister(Reg) && "Need to split between terminators");
327 // We will split all the edges and repair there.
328 } else {
329 // This is a virtual register defined by a terminator.
330 if (ValMapping.BreakDown.size() == 1) {
331 // There is nothing to repair, but we may actually lie on
332 // the repairing cost because of the PHIs already proceeded
333 // as already stated.
334 // Though the code will be correct.
335 assert(0 && "Repairing cost may not be accurate");
336 } else {
337 // We need to do non-local repairing. Basically, patch all
338 // the uses (i.e., phis) that we already proceeded.
339 // For now, just say this mapping is not possible.
340 RepairPt.switchTo(RepairingPlacement::RepairingKind::Impossible);
341 }
342 }
343}
344
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000345RegBankSelect::MappingCost RegBankSelect::computeMapping(
346 MachineInstr &MI, const RegisterBankInfo::InstructionMapping &InstrMapping,
Quentin Colombet6e80dbc2016-05-20 18:00:46 +0000347 SmallVectorImpl<RepairingPlacement> &RepairPts,
348 const RegBankSelect::MappingCost *BestCost) {
349 assert((MBFI || !BestCost) && "Costs comparison require MBFI");
Quentin Colombete16f5612016-04-07 23:53:55 +0000350
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000351 // If mapped with InstrMapping, MI will have the recorded cost.
Quentin Colombet25fcef72016-05-20 17:54:09 +0000352 MappingCost Cost(MBFI ? MBFI->getBlockFreq(MI.getParent()) : 1);
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000353 bool Saturated = Cost.addLocalCost(InstrMapping.getCost());
354 assert(!Saturated && "Possible mapping saturated the cost");
355 DEBUG(dbgs() << "Evaluating mapping cost for: " << MI);
356 DEBUG(dbgs() << "With: " << InstrMapping << '\n');
357 RepairPts.clear();
Quentin Colombet6e80dbc2016-05-20 18:00:46 +0000358 if (BestCost && Cost > *BestCost)
359 return Cost;
360
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000361 // Moreover, to realize this mapping, the register bank of each operand must
362 // match this mapping. In other words, we may need to locally reassign the
363 // register banks. Account for that repairing cost as well.
364 // In this context, local means in the surrounding of MI.
365 for (unsigned OpIdx = 0, EndOpIdx = MI.getNumOperands(); OpIdx != EndOpIdx;
Quentin Colombet40ad5732016-04-07 18:19:27 +0000366 ++OpIdx) {
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000367 const MachineOperand &MO = MI.getOperand(OpIdx);
Quentin Colombet40ad5732016-04-07 18:19:27 +0000368 if (!MO.isReg())
369 continue;
370 unsigned Reg = MO.getReg();
371 if (!Reg)
372 continue;
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000373 DEBUG(dbgs() << "Opd" << OpIdx);
Quentin Colombet40ad5732016-04-07 18:19:27 +0000374 const RegisterBankInfo::ValueMapping &ValMapping =
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000375 InstrMapping.getOperandMapping(OpIdx);
376 // If Reg is already properly mapped, this is free.
377 bool Assign;
378 if (assignmentMatch(Reg, ValMapping, Assign)) {
379 DEBUG(dbgs() << " is free (match).\n");
Quentin Colombet40ad5732016-04-07 18:19:27 +0000380 continue;
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000381 }
382 if (Assign) {
383 DEBUG(dbgs() << " is free (simple assignment).\n");
384 RepairPts.emplace_back(RepairingPlacement(MI, OpIdx, *TRI, *this,
385 RepairingPlacement::Reassign));
386 continue;
Quentin Colombet40ad5732016-04-07 18:19:27 +0000387 }
Quentin Colombet904a2c72016-04-12 00:12:59 +0000388
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000389 // Find the insertion point for the repairing code.
390 RepairPts.emplace_back(
391 RepairingPlacement(MI, OpIdx, *TRI, *this, RepairingPlacement::Insert));
392 RepairingPlacement &RepairPt = RepairPts.back();
393
Quentin Colombetf75c2bf2016-05-20 16:36:12 +0000394 // If we need to split a basic block to materialize this insertion point,
395 // we may give a higher cost to this mapping.
396 // Nevertheless, we may get away with the split, so try that first.
397 if (RepairPt.hasSplit())
398 tryAvoidingSplit(RepairPt, MO, ValMapping);
399
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000400 // Check that the materialization of the repairing is possible.
401 if (!RepairPt.canMaterialize())
402 return MappingCost::ImpossibleCost();
403
404 // Account for the split cost and repair cost.
Quentin Colombet6e80dbc2016-05-20 18:00:46 +0000405 // Unless the cost is already saturated or we do not care about the cost.
406 if (!BestCost || Saturated)
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000407 continue;
408
Quentin Colombet6e80dbc2016-05-20 18:00:46 +0000409 // To get accurate information we need MBFI and MBPI.
410 // Thus, if we end up here this information should be here.
411 assert(MBFI && MBPI && "Cost computation requires MBFI and MBPI");
412
Quentin Colombet6feaf8202016-06-08 15:40:32 +0000413 // FIXME: We will have to rework the repairing cost model.
414 // The repairing cost depends on the register bank that MO has.
415 // However, when we break down the value into different values,
416 // MO may not have a register bank while still needing repairing.
417 // For the fast mode, we don't compute the cost so that is fine,
418 // but still for the repairing code, we will have to make a choice.
419 // For the greedy mode, we should choose greedily what is the best
420 // choice based on the next use of MO.
421
Quentin Colombetf2723a22016-05-21 01:43:25 +0000422 // Sums up the repairing cost of MO at each insertion point.
423 uint64_t RepairCost = getRepairCost(MO, ValMapping);
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000424 // Bias used for splitting: 5%.
425 const uint64_t PercentageForBias = 5;
426 uint64_t Bias = (RepairCost * PercentageForBias + 99) / 100;
427 // We should not need more than a couple of instructions to repair
428 // an assignment. In other words, the computation should not
429 // overflow because the repairing cost is free of basic block
430 // frequency.
431 assert(((RepairCost < RepairCost * PercentageForBias) &&
432 (RepairCost * PercentageForBias <
433 RepairCost * PercentageForBias + 99)) &&
434 "Repairing involves more than a billion of instructions?!");
435 for (const std::unique_ptr<InsertPoint> &InsertPt : RepairPt) {
436 assert(InsertPt->canMaterialize() && "We should not have made it here");
437 // We will applied some basic block frequency and those uses uint64_t.
438 if (!InsertPt->isSplit())
439 Saturated = Cost.addLocalCost(RepairCost);
440 else {
441 uint64_t CostForInsertPt = RepairCost;
442 // Again we shouldn't overflow here givent that
443 // CostForInsertPt is frequency free at this point.
444 assert(CostForInsertPt + Bias > CostForInsertPt &&
445 "Repairing + split bias overflows");
446 CostForInsertPt += Bias;
447 uint64_t PtCost = InsertPt->frequency(*this) * CostForInsertPt;
448 // Check if we just overflowed.
449 if ((Saturated = PtCost < CostForInsertPt))
450 Cost.saturate();
451 else
452 Saturated = Cost.addNonLocalCost(PtCost);
453 }
Quentin Colombet6e80dbc2016-05-20 18:00:46 +0000454
455 // Stop looking into what it takes to repair, this is already
456 // too expensive.
457 if (BestCost && Cost > *BestCost)
458 return Cost;
459
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000460 // No need to accumulate more cost information.
461 // We need to still gather the repairing information though.
462 if (Saturated)
463 break;
464 }
Quentin Colombet40ad5732016-04-07 18:19:27 +0000465 }
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000466 return Cost;
467}
468
469void RegBankSelect::applyMapping(
470 MachineInstr &MI, const RegisterBankInfo::InstructionMapping &InstrMapping,
471 SmallVectorImpl<RegBankSelect::RepairingPlacement> &RepairPts) {
Quentin Colombetf33e3652016-06-08 16:30:55 +0000472 // OpdMapper will hold all the information needed for the rewritting.
473 RegisterBankInfo::OperandsMapper OpdMapper(MI, InstrMapping, *MRI);
474
Quentin Colombetec5c93d2016-06-08 16:45:04 +0000475 // First, place the repairing code.
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000476 for (RepairingPlacement &RepairPt : RepairPts) {
477 assert(RepairPt.canMaterialize() &&
478 RepairPt.getKind() != RepairingPlacement::Impossible &&
479 "This mapping is impossible");
480 assert(RepairPt.getKind() != RepairingPlacement::None &&
481 "This should not make its way in the list");
482 unsigned OpIdx = RepairPt.getOpIdx();
483 MachineOperand &MO = MI.getOperand(OpIdx);
484 const RegisterBankInfo::ValueMapping &ValMapping =
485 InstrMapping.getOperandMapping(OpIdx);
486 unsigned BreakDownSize = ValMapping.BreakDown.size();
Quentin Colombet86be3742016-06-08 17:39:47 +0000487 (void)BreakDownSize;
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000488 unsigned Reg = MO.getReg();
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000489
490 switch (RepairPt.getKind()) {
491 case RepairingPlacement::Reassign:
492 assert(BreakDownSize == 1 &&
493 "Reassignment should only be for simple mapping");
494 MRI->setRegBank(Reg, *ValMapping.BreakDown[0].RegBank);
495 break;
496 case RepairingPlacement::Insert:
Quentin Colombetf33e3652016-06-08 16:30:55 +0000497 OpdMapper.createVRegs(OpIdx);
498 repairReg(MO, ValMapping, RepairPt, OpdMapper.getVRegs(OpIdx));
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000499 break;
500 default:
501 llvm_unreachable("Other kind should not happen");
502 }
503 }
504 // Second, rewrite the instruction.
Quentin Colombet33406452016-06-08 21:55:30 +0000505 DEBUG(dbgs() << "Actual mapping of the operands: " << OpdMapper << '\n');
Quentin Colombetec5c93d2016-06-08 16:45:04 +0000506 RBI->applyMapping(OpdMapper);
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000507}
508
509void RegBankSelect::assignInstr(MachineInstr &MI) {
510 DEBUG(dbgs() << "Assign: " << MI);
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000511 // Remember the repairing placement for all the operands.
512 SmallVector<RepairingPlacement, 4> RepairPts;
513
Quentin Colombet79fe1be2016-05-20 18:37:33 +0000514 RegisterBankInfo::InstructionMapping BestMapping;
515 if (OptMode == RegBankSelect::Mode::Fast) {
516 BestMapping = RBI->getInstrMapping(MI);
517 MappingCost DefaultCost = computeMapping(MI, BestMapping, RepairPts);
518 (void)DefaultCost;
519 assert(DefaultCost != MappingCost::ImpossibleCost() &&
520 "Default mapping is not suited");
521 } else {
522 RegisterBankInfo::InstructionMappings PossibleMappings =
523 RBI->getInstrPossibleMappings(MI);
524 assert(!PossibleMappings.empty() &&
525 "Do not know how to map this instruction");
526 BestMapping = std::move(findBestMapping(MI, PossibleMappings, RepairPts));
527 }
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000528 // Make sure the mapping is valid for MI.
Quentin Colombet79fe1be2016-05-20 18:37:33 +0000529 assert(BestMapping.verify(MI) && "Invalid instruction mapping");
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000530
Quentin Colombet79fe1be2016-05-20 18:37:33 +0000531 DEBUG(dbgs() << "Mapping: " << BestMapping << '\n');
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000532
Quentin Colombet9400bfb2016-06-08 21:55:29 +0000533 // After this call, MI may not be valid anymore.
534 // Do not use it.
Quentin Colombet79fe1be2016-05-20 18:37:33 +0000535 applyMapping(MI, BestMapping, RepairPts);
Quentin Colombet40ad5732016-04-07 18:19:27 +0000536}
537
Quentin Colombet8e8e85c2016-04-05 19:06:01 +0000538bool RegBankSelect::runOnMachineFunction(MachineFunction &MF) {
Quentin Colombete16f5612016-04-07 23:53:55 +0000539 DEBUG(dbgs() << "Assign register banks for: " << MF.getName() << '\n');
Quentin Colombeta5530122016-05-20 17:36:54 +0000540 const Function *F = MF.getFunction();
541 Mode SaveOptMode = OptMode;
542 if (F->hasFnAttribute(Attribute::OptimizeNone))
543 OptMode = Mode::Fast;
Quentin Colombet40ad5732016-04-07 18:19:27 +0000544 init(MF);
545 // Walk the function and assign register banks to all operands.
Quentin Colombetab8c21f2016-04-08 17:19:10 +0000546 // Use a RPOT to make sure all registers are assigned before we choose
547 // the best mapping of the current instruction.
548 ReversePostOrderTraversal<MachineFunction*> RPOT(&MF);
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000549 for (MachineBasicBlock *MBB : RPOT) {
550 // Set a sensible insertion point so that subsequent calls to
551 // MIRBuilder.
552 MIRBuilder.setMBB(*MBB);
Quentin Colombetec5c93d2016-06-08 16:45:04 +0000553 for (MachineBasicBlock::iterator MII = MBB->begin(), End = MBB->end();
554 MII != End;) {
555 // MI might be invalidated by the assignment, so move the
556 // iterator before hand.
Ahmed Bougacha45eb3b92016-08-02 11:41:16 +0000557 MachineInstr &MI = *MII++;
558
559 // Ignore target-specific instructions: they should use proper regclasses.
560 if (isTargetSpecificOpcode(MI.getOpcode()))
561 continue;
562
563 assignInstr(MI);
Quentin Colombetec5c93d2016-06-08 16:45:04 +0000564 }
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000565 }
Quentin Colombeta5530122016-05-20 17:36:54 +0000566 OptMode = SaveOptMode;
Quentin Colombet8e8e85c2016-04-05 19:06:01 +0000567 return false;
568}
Quentin Colombetcfd97b92016-05-20 00:35:26 +0000569
570//------------------------------------------------------------------------------
Quentin Colombet55650752016-05-20 00:49:10 +0000571// Helper Classes Implementation
Quentin Colombetcfd97b92016-05-20 00:35:26 +0000572//------------------------------------------------------------------------------
Quentin Colombet55650752016-05-20 00:49:10 +0000573RegBankSelect::RepairingPlacement::RepairingPlacement(
574 MachineInstr &MI, unsigned OpIdx, const TargetRegisterInfo &TRI, Pass &P,
575 RepairingPlacement::RepairingKind Kind)
576 // Default is, we are going to insert code to repair OpIdx.
577 : Kind(Kind),
578 OpIdx(OpIdx),
579 CanMaterialize(Kind != RepairingKind::Impossible),
580 HasSplit(false),
581 P(P) {
582 const MachineOperand &MO = MI.getOperand(OpIdx);
583 assert(MO.isReg() && "Trying to repair a non-reg operand");
584
585 if (Kind != RepairingKind::Insert)
586 return;
587
588 // Repairings for definitions happen after MI, uses happen before.
589 bool Before = !MO.isDef();
590
591 // Check if we are done with MI.
592 if (!MI.isPHI() && !MI.isTerminator()) {
593 addInsertPoint(MI, Before);
594 // We are done with the initialization.
595 return;
596 }
597
598 // Now, look for the special cases.
599 if (MI.isPHI()) {
600 // - PHI must be the first instructions:
601 // * Before, we have to split the related incoming edge.
602 // * After, move the insertion point past the last phi.
603 if (!Before) {
604 MachineBasicBlock::iterator It = MI.getParent()->getFirstNonPHI();
605 if (It != MI.getParent()->end())
606 addInsertPoint(*It, /*Before*/ true);
607 else
608 addInsertPoint(*(--It), /*Before*/ false);
609 return;
610 }
611 // We repair a use of a phi, we may need to split the related edge.
612 MachineBasicBlock &Pred = *MI.getOperand(OpIdx + 1).getMBB();
613 // Check if we can move the insertion point prior to the
614 // terminators of the predecessor.
615 unsigned Reg = MO.getReg();
616 MachineBasicBlock::iterator It = Pred.getLastNonDebugInstr();
617 for (auto Begin = Pred.begin(); It != Begin && It->isTerminator(); --It)
618 if (It->modifiesRegister(Reg, &TRI)) {
619 // We cannot hoist the repairing code in the predecessor.
620 // Split the edge.
621 addInsertPoint(Pred, *MI.getParent());
622 return;
623 }
624 // At this point, we can insert in Pred.
625
626 // - If It is invalid, Pred is empty and we can insert in Pred
627 // wherever we want.
628 // - If It is valid, It is the first non-terminator, insert after It.
629 if (It == Pred.end())
630 addInsertPoint(Pred, /*Beginning*/ false);
631 else
632 addInsertPoint(*It, /*Before*/ false);
633 } else {
634 // - Terminators must be the last instructions:
635 // * Before, move the insert point before the first terminator.
636 // * After, we have to split the outcoming edges.
637 unsigned Reg = MO.getReg();
638 if (Before) {
639 // Check whether Reg is defined by any terminator.
640 MachineBasicBlock::iterator It = MI;
641 for (auto Begin = MI.getParent()->begin();
642 --It != Begin && It->isTerminator();)
643 if (It->modifiesRegister(Reg, &TRI)) {
644 // Insert the repairing code right after the definition.
645 addInsertPoint(*It, /*Before*/ false);
646 return;
647 }
648 addInsertPoint(*It, /*Before*/ true);
649 return;
650 }
651 // Make sure Reg is not redefined by other terminators, otherwise
652 // we do not know how to split.
653 for (MachineBasicBlock::iterator It = MI, End = MI.getParent()->end();
654 ++It != End;)
655 // The machine verifier should reject this kind of code.
656 assert(It->modifiesRegister(Reg, &TRI) && "Do not know where to split");
657 // Split each outcoming edges.
658 MachineBasicBlock &Src = *MI.getParent();
659 for (auto &Succ : Src.successors())
660 addInsertPoint(Src, Succ);
661 }
662}
663
664void RegBankSelect::RepairingPlacement::addInsertPoint(MachineInstr &MI,
665 bool Before) {
666 addInsertPoint(*new InstrInsertPoint(MI, Before));
667}
668
669void RegBankSelect::RepairingPlacement::addInsertPoint(MachineBasicBlock &MBB,
670 bool Beginning) {
671 addInsertPoint(*new MBBInsertPoint(MBB, Beginning));
672}
673
674void RegBankSelect::RepairingPlacement::addInsertPoint(MachineBasicBlock &Src,
675 MachineBasicBlock &Dst) {
676 addInsertPoint(*new EdgeInsertPoint(Src, Dst, P));
677}
678
679void RegBankSelect::RepairingPlacement::addInsertPoint(
680 RegBankSelect::InsertPoint &Point) {
681 CanMaterialize &= Point.canMaterialize();
682 HasSplit |= Point.isSplit();
683 InsertPoints.emplace_back(&Point);
684}
685
686RegBankSelect::InstrInsertPoint::InstrInsertPoint(MachineInstr &Instr,
687 bool Before)
688 : InsertPoint(), Instr(Instr), Before(Before) {
689 // Since we do not support splitting, we do not need to update
690 // liveness and such, so do not do anything with P.
691 assert((!Before || !Instr.isPHI()) &&
692 "Splitting before phis requires more points");
693 assert((!Before || !Instr.getNextNode() || !Instr.getNextNode()->isPHI()) &&
694 "Splitting between phis does not make sense");
695}
696
697void RegBankSelect::InstrInsertPoint::materialize() {
698 if (isSplit()) {
699 // Slice and return the beginning of the new block.
700 // If we need to split between the terminators, we theoritically
701 // need to know where the first and second set of terminators end
702 // to update the successors properly.
703 // Now, in pratice, we should have a maximum of 2 branch
704 // instructions; one conditional and one unconditional. Therefore
705 // we know how to update the successor by looking at the target of
706 // the unconditional branch.
707 // If we end up splitting at some point, then, we should update
708 // the liveness information and such. I.e., we would need to
709 // access P here.
710 // The machine verifier should actually make sure such cases
711 // cannot happen.
712 llvm_unreachable("Not yet implemented");
713 }
714 // Otherwise the insertion point is just the current or next
715 // instruction depending on Before. I.e., there is nothing to do
716 // here.
717}
718
719bool RegBankSelect::InstrInsertPoint::isSplit() const {
720 // If the insertion point is after a terminator, we need to split.
721 if (!Before)
722 return Instr.isTerminator();
723 // If we insert before an instruction that is after a terminator,
724 // we are still after a terminator.
725 return Instr.getPrevNode() && Instr.getPrevNode()->isTerminator();
726}
727
728uint64_t RegBankSelect::InstrInsertPoint::frequency(const Pass &P) const {
729 // Even if we need to split, because we insert between terminators,
730 // this split has actually the same frequency as the instruction.
731 const MachineBlockFrequencyInfo *MBFI =
732 P.getAnalysisIfAvailable<MachineBlockFrequencyInfo>();
733 if (!MBFI)
734 return 1;
735 return MBFI->getBlockFreq(Instr.getParent()).getFrequency();
736}
737
738uint64_t RegBankSelect::MBBInsertPoint::frequency(const Pass &P) const {
739 const MachineBlockFrequencyInfo *MBFI =
740 P.getAnalysisIfAvailable<MachineBlockFrequencyInfo>();
741 if (!MBFI)
742 return 1;
743 return MBFI->getBlockFreq(&MBB).getFrequency();
744}
745
746void RegBankSelect::EdgeInsertPoint::materialize() {
747 // If we end up repairing twice at the same place before materializing the
748 // insertion point, we may think we have to split an edge twice.
749 // We should have a factory for the insert point such that identical points
750 // are the same instance.
751 assert(Src.isSuccessor(DstOrSplit) && DstOrSplit->isPredecessor(&Src) &&
752 "This point has already been split");
753 MachineBasicBlock *NewBB = Src.SplitCriticalEdge(DstOrSplit, P);
754 assert(NewBB && "Invalid call to materialize");
755 // We reuse the destination block to hold the information of the new block.
756 DstOrSplit = NewBB;
757}
758
759uint64_t RegBankSelect::EdgeInsertPoint::frequency(const Pass &P) const {
760 const MachineBlockFrequencyInfo *MBFI =
761 P.getAnalysisIfAvailable<MachineBlockFrequencyInfo>();
762 if (!MBFI)
763 return 1;
764 if (WasMaterialized)
765 return MBFI->getBlockFreq(DstOrSplit).getFrequency();
766
767 const MachineBranchProbabilityInfo *MBPI =
768 P.getAnalysisIfAvailable<MachineBranchProbabilityInfo>();
769 if (!MBPI)
770 return 1;
771 // The basic block will be on the edge.
772 return (MBFI->getBlockFreq(&Src) * MBPI->getEdgeProbability(&Src, DstOrSplit))
773 .getFrequency();
774}
775
776bool RegBankSelect::EdgeInsertPoint::canMaterialize() const {
777 // If this is not a critical edge, we should not have used this insert
778 // point. Indeed, either the successor or the predecessor should
779 // have do.
780 assert(Src.succ_size() > 1 && DstOrSplit->pred_size() > 1 &&
781 "Edge is not critical");
782 return Src.canSplitCriticalEdge(DstOrSplit);
783}
784
Quentin Colombetcfd97b92016-05-20 00:35:26 +0000785RegBankSelect::MappingCost::MappingCost(const BlockFrequency &LocalFreq)
786 : LocalCost(0), NonLocalCost(0), LocalFreq(LocalFreq.getFrequency()) {}
787
788bool RegBankSelect::MappingCost::addLocalCost(uint64_t Cost) {
789 // Check if this overflows.
790 if (LocalCost + Cost < LocalCost) {
791 saturate();
792 return true;
793 }
794 LocalCost += Cost;
795 return isSaturated();
796}
797
798bool RegBankSelect::MappingCost::addNonLocalCost(uint64_t Cost) {
799 // Check if this overflows.
800 if (NonLocalCost + Cost < NonLocalCost) {
801 saturate();
802 return true;
803 }
804 NonLocalCost += Cost;
805 return isSaturated();
806}
807
808bool RegBankSelect::MappingCost::isSaturated() const {
809 return LocalCost == UINT64_MAX - 1 && NonLocalCost == UINT64_MAX &&
810 LocalFreq == UINT64_MAX;
811}
812
813void RegBankSelect::MappingCost::saturate() {
814 *this = ImpossibleCost();
815 --LocalCost;
816}
817
818RegBankSelect::MappingCost RegBankSelect::MappingCost::ImpossibleCost() {
819 return MappingCost(UINT64_MAX, UINT64_MAX, UINT64_MAX);
820}
821
822bool RegBankSelect::MappingCost::operator<(const MappingCost &Cost) const {
823 // Sort out the easy cases.
824 if (*this == Cost)
825 return false;
826 // If one is impossible to realize the other is cheaper unless it is
827 // impossible as well.
828 if ((*this == ImpossibleCost()) || (Cost == ImpossibleCost()))
829 return (*this == ImpossibleCost()) < (Cost == ImpossibleCost());
830 // If one is saturated the other is cheaper, unless it is saturated
831 // as well.
832 if (isSaturated() || Cost.isSaturated())
833 return isSaturated() < Cost.isSaturated();
834 // At this point we know both costs hold sensible values.
835
836 // If both values have a different base frequency, there is no much
837 // we can do but to scale everything.
838 // However, if they have the same base frequency we can avoid making
839 // complicated computation.
840 uint64_t ThisLocalAdjust;
841 uint64_t OtherLocalAdjust;
842 if (LLVM_LIKELY(LocalFreq == Cost.LocalFreq)) {
843
844 // At this point, we know the local costs are comparable.
845 // Do the case that do not involve potential overflow first.
846 if (NonLocalCost == Cost.NonLocalCost)
847 // Since the non-local costs do not discriminate on the result,
848 // just compare the local costs.
849 return LocalCost < Cost.LocalCost;
850
851 // The base costs are comparable so we may only keep the relative
852 // value to increase our chances of avoiding overflows.
853 ThisLocalAdjust = 0;
854 OtherLocalAdjust = 0;
855 if (LocalCost < Cost.LocalCost)
856 OtherLocalAdjust = Cost.LocalCost - LocalCost;
857 else
858 ThisLocalAdjust = LocalCost - Cost.LocalCost;
859
860 } else {
861 ThisLocalAdjust = LocalCost;
862 OtherLocalAdjust = Cost.LocalCost;
863 }
864
865 // The non-local costs are comparable, just keep the relative value.
866 uint64_t ThisNonLocalAdjust = 0;
867 uint64_t OtherNonLocalAdjust = 0;
868 if (NonLocalCost < Cost.NonLocalCost)
869 OtherNonLocalAdjust = Cost.NonLocalCost - NonLocalCost;
870 else
871 ThisNonLocalAdjust = NonLocalCost - Cost.NonLocalCost;
872 // Scale everything to make them comparable.
873 uint64_t ThisScaledCost = ThisLocalAdjust * LocalFreq;
874 // Check for overflow on that operation.
875 bool ThisOverflows = ThisLocalAdjust && (ThisScaledCost < ThisLocalAdjust ||
876 ThisScaledCost < LocalFreq);
877 uint64_t OtherScaledCost = OtherLocalAdjust * Cost.LocalFreq;
878 // Check for overflow on the last operation.
879 bool OtherOverflows =
880 OtherLocalAdjust &&
881 (OtherScaledCost < OtherLocalAdjust || OtherScaledCost < Cost.LocalFreq);
882 // Add the non-local costs.
883 ThisOverflows |= ThisNonLocalAdjust &&
884 ThisScaledCost + ThisNonLocalAdjust < ThisNonLocalAdjust;
885 ThisScaledCost += ThisNonLocalAdjust;
886 OtherOverflows |= OtherNonLocalAdjust &&
887 OtherScaledCost + OtherNonLocalAdjust < OtherNonLocalAdjust;
888 OtherScaledCost += OtherNonLocalAdjust;
889 // If both overflows, we cannot compare without additional
890 // precision, e.g., APInt. Just give up on that case.
891 if (ThisOverflows && OtherOverflows)
892 return false;
893 // If one overflows but not the other, we can still compare.
894 if (ThisOverflows || OtherOverflows)
895 return ThisOverflows < OtherOverflows;
896 // Otherwise, just compare the values.
897 return ThisScaledCost < OtherScaledCost;
898}
899
900bool RegBankSelect::MappingCost::operator==(const MappingCost &Cost) const {
901 return LocalCost == Cost.LocalCost && NonLocalCost == Cost.NonLocalCost &&
902 LocalFreq == Cost.LocalFreq;
903}