blob: 79b78abe95a78efb81345dd2fea34962b5089abd [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 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();
487 unsigned Reg = MO.getReg();
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000488
489 switch (RepairPt.getKind()) {
490 case RepairingPlacement::Reassign:
491 assert(BreakDownSize == 1 &&
492 "Reassignment should only be for simple mapping");
493 MRI->setRegBank(Reg, *ValMapping.BreakDown[0].RegBank);
494 break;
495 case RepairingPlacement::Insert:
Quentin Colombetf33e3652016-06-08 16:30:55 +0000496 OpdMapper.createVRegs(OpIdx);
497 repairReg(MO, ValMapping, RepairPt, OpdMapper.getVRegs(OpIdx));
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000498 break;
499 default:
500 llvm_unreachable("Other kind should not happen");
501 }
502 }
503 // Second, rewrite the instruction.
Quentin Colombetec5c93d2016-06-08 16:45:04 +0000504 RBI->applyMapping(OpdMapper);
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000505}
506
507void RegBankSelect::assignInstr(MachineInstr &MI) {
508 DEBUG(dbgs() << "Assign: " << MI);
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000509 // Remember the repairing placement for all the operands.
510 SmallVector<RepairingPlacement, 4> RepairPts;
511
Quentin Colombet79fe1be2016-05-20 18:37:33 +0000512 RegisterBankInfo::InstructionMapping BestMapping;
513 if (OptMode == RegBankSelect::Mode::Fast) {
514 BestMapping = RBI->getInstrMapping(MI);
515 MappingCost DefaultCost = computeMapping(MI, BestMapping, RepairPts);
516 (void)DefaultCost;
517 assert(DefaultCost != MappingCost::ImpossibleCost() &&
518 "Default mapping is not suited");
519 } else {
520 RegisterBankInfo::InstructionMappings PossibleMappings =
521 RBI->getInstrPossibleMappings(MI);
522 assert(!PossibleMappings.empty() &&
523 "Do not know how to map this instruction");
524 BestMapping = std::move(findBestMapping(MI, PossibleMappings, RepairPts));
525 }
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000526 // Make sure the mapping is valid for MI.
Quentin Colombet79fe1be2016-05-20 18:37:33 +0000527 assert(BestMapping.verify(MI) && "Invalid instruction mapping");
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000528
Quentin Colombet79fe1be2016-05-20 18:37:33 +0000529 DEBUG(dbgs() << "Mapping: " << BestMapping << '\n');
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000530
Quentin Colombet79fe1be2016-05-20 18:37:33 +0000531 applyMapping(MI, BestMapping, RepairPts);
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000532
Quentin Colombete16f5612016-04-07 23:53:55 +0000533 DEBUG(dbgs() << "Assigned: " << MI);
Quentin Colombet40ad5732016-04-07 18:19:27 +0000534}
535
Quentin Colombet8e8e85c2016-04-05 19:06:01 +0000536bool RegBankSelect::runOnMachineFunction(MachineFunction &MF) {
Quentin Colombete16f5612016-04-07 23:53:55 +0000537 DEBUG(dbgs() << "Assign register banks for: " << MF.getName() << '\n');
Quentin Colombeta5530122016-05-20 17:36:54 +0000538 const Function *F = MF.getFunction();
539 Mode SaveOptMode = OptMode;
540 if (F->hasFnAttribute(Attribute::OptimizeNone))
541 OptMode = Mode::Fast;
Quentin Colombet40ad5732016-04-07 18:19:27 +0000542 init(MF);
543 // Walk the function and assign register banks to all operands.
Quentin Colombetab8c21f2016-04-08 17:19:10 +0000544 // Use a RPOT to make sure all registers are assigned before we choose
545 // the best mapping of the current instruction.
546 ReversePostOrderTraversal<MachineFunction*> RPOT(&MF);
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000547 for (MachineBasicBlock *MBB : RPOT) {
548 // Set a sensible insertion point so that subsequent calls to
549 // MIRBuilder.
550 MIRBuilder.setMBB(*MBB);
Quentin Colombetec5c93d2016-06-08 16:45:04 +0000551 for (MachineBasicBlock::iterator MII = MBB->begin(), End = MBB->end();
552 MII != End;) {
553 // MI might be invalidated by the assignment, so move the
554 // iterator before hand.
555 assignInstr(*MII++);
556 }
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000557 }
Quentin Colombeta5530122016-05-20 17:36:54 +0000558 OptMode = SaveOptMode;
Quentin Colombet8e8e85c2016-04-05 19:06:01 +0000559 return false;
560}
Quentin Colombetcfd97b92016-05-20 00:35:26 +0000561
562//------------------------------------------------------------------------------
Quentin Colombet55650752016-05-20 00:49:10 +0000563// Helper Classes Implementation
Quentin Colombetcfd97b92016-05-20 00:35:26 +0000564//------------------------------------------------------------------------------
Quentin Colombet55650752016-05-20 00:49:10 +0000565RegBankSelect::RepairingPlacement::RepairingPlacement(
566 MachineInstr &MI, unsigned OpIdx, const TargetRegisterInfo &TRI, Pass &P,
567 RepairingPlacement::RepairingKind Kind)
568 // Default is, we are going to insert code to repair OpIdx.
569 : Kind(Kind),
570 OpIdx(OpIdx),
571 CanMaterialize(Kind != RepairingKind::Impossible),
572 HasSplit(false),
573 P(P) {
574 const MachineOperand &MO = MI.getOperand(OpIdx);
575 assert(MO.isReg() && "Trying to repair a non-reg operand");
576
577 if (Kind != RepairingKind::Insert)
578 return;
579
580 // Repairings for definitions happen after MI, uses happen before.
581 bool Before = !MO.isDef();
582
583 // Check if we are done with MI.
584 if (!MI.isPHI() && !MI.isTerminator()) {
585 addInsertPoint(MI, Before);
586 // We are done with the initialization.
587 return;
588 }
589
590 // Now, look for the special cases.
591 if (MI.isPHI()) {
592 // - PHI must be the first instructions:
593 // * Before, we have to split the related incoming edge.
594 // * After, move the insertion point past the last phi.
595 if (!Before) {
596 MachineBasicBlock::iterator It = MI.getParent()->getFirstNonPHI();
597 if (It != MI.getParent()->end())
598 addInsertPoint(*It, /*Before*/ true);
599 else
600 addInsertPoint(*(--It), /*Before*/ false);
601 return;
602 }
603 // We repair a use of a phi, we may need to split the related edge.
604 MachineBasicBlock &Pred = *MI.getOperand(OpIdx + 1).getMBB();
605 // Check if we can move the insertion point prior to the
606 // terminators of the predecessor.
607 unsigned Reg = MO.getReg();
608 MachineBasicBlock::iterator It = Pred.getLastNonDebugInstr();
609 for (auto Begin = Pred.begin(); It != Begin && It->isTerminator(); --It)
610 if (It->modifiesRegister(Reg, &TRI)) {
611 // We cannot hoist the repairing code in the predecessor.
612 // Split the edge.
613 addInsertPoint(Pred, *MI.getParent());
614 return;
615 }
616 // At this point, we can insert in Pred.
617
618 // - If It is invalid, Pred is empty and we can insert in Pred
619 // wherever we want.
620 // - If It is valid, It is the first non-terminator, insert after It.
621 if (It == Pred.end())
622 addInsertPoint(Pred, /*Beginning*/ false);
623 else
624 addInsertPoint(*It, /*Before*/ false);
625 } else {
626 // - Terminators must be the last instructions:
627 // * Before, move the insert point before the first terminator.
628 // * After, we have to split the outcoming edges.
629 unsigned Reg = MO.getReg();
630 if (Before) {
631 // Check whether Reg is defined by any terminator.
632 MachineBasicBlock::iterator It = MI;
633 for (auto Begin = MI.getParent()->begin();
634 --It != Begin && It->isTerminator();)
635 if (It->modifiesRegister(Reg, &TRI)) {
636 // Insert the repairing code right after the definition.
637 addInsertPoint(*It, /*Before*/ false);
638 return;
639 }
640 addInsertPoint(*It, /*Before*/ true);
641 return;
642 }
643 // Make sure Reg is not redefined by other terminators, otherwise
644 // we do not know how to split.
645 for (MachineBasicBlock::iterator It = MI, End = MI.getParent()->end();
646 ++It != End;)
647 // The machine verifier should reject this kind of code.
648 assert(It->modifiesRegister(Reg, &TRI) && "Do not know where to split");
649 // Split each outcoming edges.
650 MachineBasicBlock &Src = *MI.getParent();
651 for (auto &Succ : Src.successors())
652 addInsertPoint(Src, Succ);
653 }
654}
655
656void RegBankSelect::RepairingPlacement::addInsertPoint(MachineInstr &MI,
657 bool Before) {
658 addInsertPoint(*new InstrInsertPoint(MI, Before));
659}
660
661void RegBankSelect::RepairingPlacement::addInsertPoint(MachineBasicBlock &MBB,
662 bool Beginning) {
663 addInsertPoint(*new MBBInsertPoint(MBB, Beginning));
664}
665
666void RegBankSelect::RepairingPlacement::addInsertPoint(MachineBasicBlock &Src,
667 MachineBasicBlock &Dst) {
668 addInsertPoint(*new EdgeInsertPoint(Src, Dst, P));
669}
670
671void RegBankSelect::RepairingPlacement::addInsertPoint(
672 RegBankSelect::InsertPoint &Point) {
673 CanMaterialize &= Point.canMaterialize();
674 HasSplit |= Point.isSplit();
675 InsertPoints.emplace_back(&Point);
676}
677
678RegBankSelect::InstrInsertPoint::InstrInsertPoint(MachineInstr &Instr,
679 bool Before)
680 : InsertPoint(), Instr(Instr), Before(Before) {
681 // Since we do not support splitting, we do not need to update
682 // liveness and such, so do not do anything with P.
683 assert((!Before || !Instr.isPHI()) &&
684 "Splitting before phis requires more points");
685 assert((!Before || !Instr.getNextNode() || !Instr.getNextNode()->isPHI()) &&
686 "Splitting between phis does not make sense");
687}
688
689void RegBankSelect::InstrInsertPoint::materialize() {
690 if (isSplit()) {
691 // Slice and return the beginning of the new block.
692 // If we need to split between the terminators, we theoritically
693 // need to know where the first and second set of terminators end
694 // to update the successors properly.
695 // Now, in pratice, we should have a maximum of 2 branch
696 // instructions; one conditional and one unconditional. Therefore
697 // we know how to update the successor by looking at the target of
698 // the unconditional branch.
699 // If we end up splitting at some point, then, we should update
700 // the liveness information and such. I.e., we would need to
701 // access P here.
702 // The machine verifier should actually make sure such cases
703 // cannot happen.
704 llvm_unreachable("Not yet implemented");
705 }
706 // Otherwise the insertion point is just the current or next
707 // instruction depending on Before. I.e., there is nothing to do
708 // here.
709}
710
711bool RegBankSelect::InstrInsertPoint::isSplit() const {
712 // If the insertion point is after a terminator, we need to split.
713 if (!Before)
714 return Instr.isTerminator();
715 // If we insert before an instruction that is after a terminator,
716 // we are still after a terminator.
717 return Instr.getPrevNode() && Instr.getPrevNode()->isTerminator();
718}
719
720uint64_t RegBankSelect::InstrInsertPoint::frequency(const Pass &P) const {
721 // Even if we need to split, because we insert between terminators,
722 // this split has actually the same frequency as the instruction.
723 const MachineBlockFrequencyInfo *MBFI =
724 P.getAnalysisIfAvailable<MachineBlockFrequencyInfo>();
725 if (!MBFI)
726 return 1;
727 return MBFI->getBlockFreq(Instr.getParent()).getFrequency();
728}
729
730uint64_t RegBankSelect::MBBInsertPoint::frequency(const Pass &P) const {
731 const MachineBlockFrequencyInfo *MBFI =
732 P.getAnalysisIfAvailable<MachineBlockFrequencyInfo>();
733 if (!MBFI)
734 return 1;
735 return MBFI->getBlockFreq(&MBB).getFrequency();
736}
737
738void RegBankSelect::EdgeInsertPoint::materialize() {
739 // If we end up repairing twice at the same place before materializing the
740 // insertion point, we may think we have to split an edge twice.
741 // We should have a factory for the insert point such that identical points
742 // are the same instance.
743 assert(Src.isSuccessor(DstOrSplit) && DstOrSplit->isPredecessor(&Src) &&
744 "This point has already been split");
745 MachineBasicBlock *NewBB = Src.SplitCriticalEdge(DstOrSplit, P);
746 assert(NewBB && "Invalid call to materialize");
747 // We reuse the destination block to hold the information of the new block.
748 DstOrSplit = NewBB;
749}
750
751uint64_t RegBankSelect::EdgeInsertPoint::frequency(const Pass &P) const {
752 const MachineBlockFrequencyInfo *MBFI =
753 P.getAnalysisIfAvailable<MachineBlockFrequencyInfo>();
754 if (!MBFI)
755 return 1;
756 if (WasMaterialized)
757 return MBFI->getBlockFreq(DstOrSplit).getFrequency();
758
759 const MachineBranchProbabilityInfo *MBPI =
760 P.getAnalysisIfAvailable<MachineBranchProbabilityInfo>();
761 if (!MBPI)
762 return 1;
763 // The basic block will be on the edge.
764 return (MBFI->getBlockFreq(&Src) * MBPI->getEdgeProbability(&Src, DstOrSplit))
765 .getFrequency();
766}
767
768bool RegBankSelect::EdgeInsertPoint::canMaterialize() const {
769 // If this is not a critical edge, we should not have used this insert
770 // point. Indeed, either the successor or the predecessor should
771 // have do.
772 assert(Src.succ_size() > 1 && DstOrSplit->pred_size() > 1 &&
773 "Edge is not critical");
774 return Src.canSplitCriticalEdge(DstOrSplit);
775}
776
Quentin Colombetcfd97b92016-05-20 00:35:26 +0000777RegBankSelect::MappingCost::MappingCost(const BlockFrequency &LocalFreq)
778 : LocalCost(0), NonLocalCost(0), LocalFreq(LocalFreq.getFrequency()) {}
779
780bool RegBankSelect::MappingCost::addLocalCost(uint64_t Cost) {
781 // Check if this overflows.
782 if (LocalCost + Cost < LocalCost) {
783 saturate();
784 return true;
785 }
786 LocalCost += Cost;
787 return isSaturated();
788}
789
790bool RegBankSelect::MappingCost::addNonLocalCost(uint64_t Cost) {
791 // Check if this overflows.
792 if (NonLocalCost + Cost < NonLocalCost) {
793 saturate();
794 return true;
795 }
796 NonLocalCost += Cost;
797 return isSaturated();
798}
799
800bool RegBankSelect::MappingCost::isSaturated() const {
801 return LocalCost == UINT64_MAX - 1 && NonLocalCost == UINT64_MAX &&
802 LocalFreq == UINT64_MAX;
803}
804
805void RegBankSelect::MappingCost::saturate() {
806 *this = ImpossibleCost();
807 --LocalCost;
808}
809
810RegBankSelect::MappingCost RegBankSelect::MappingCost::ImpossibleCost() {
811 return MappingCost(UINT64_MAX, UINT64_MAX, UINT64_MAX);
812}
813
814bool RegBankSelect::MappingCost::operator<(const MappingCost &Cost) const {
815 // Sort out the easy cases.
816 if (*this == Cost)
817 return false;
818 // If one is impossible to realize the other is cheaper unless it is
819 // impossible as well.
820 if ((*this == ImpossibleCost()) || (Cost == ImpossibleCost()))
821 return (*this == ImpossibleCost()) < (Cost == ImpossibleCost());
822 // If one is saturated the other is cheaper, unless it is saturated
823 // as well.
824 if (isSaturated() || Cost.isSaturated())
825 return isSaturated() < Cost.isSaturated();
826 // At this point we know both costs hold sensible values.
827
828 // If both values have a different base frequency, there is no much
829 // we can do but to scale everything.
830 // However, if they have the same base frequency we can avoid making
831 // complicated computation.
832 uint64_t ThisLocalAdjust;
833 uint64_t OtherLocalAdjust;
834 if (LLVM_LIKELY(LocalFreq == Cost.LocalFreq)) {
835
836 // At this point, we know the local costs are comparable.
837 // Do the case that do not involve potential overflow first.
838 if (NonLocalCost == Cost.NonLocalCost)
839 // Since the non-local costs do not discriminate on the result,
840 // just compare the local costs.
841 return LocalCost < Cost.LocalCost;
842
843 // The base costs are comparable so we may only keep the relative
844 // value to increase our chances of avoiding overflows.
845 ThisLocalAdjust = 0;
846 OtherLocalAdjust = 0;
847 if (LocalCost < Cost.LocalCost)
848 OtherLocalAdjust = Cost.LocalCost - LocalCost;
849 else
850 ThisLocalAdjust = LocalCost - Cost.LocalCost;
851
852 } else {
853 ThisLocalAdjust = LocalCost;
854 OtherLocalAdjust = Cost.LocalCost;
855 }
856
857 // The non-local costs are comparable, just keep the relative value.
858 uint64_t ThisNonLocalAdjust = 0;
859 uint64_t OtherNonLocalAdjust = 0;
860 if (NonLocalCost < Cost.NonLocalCost)
861 OtherNonLocalAdjust = Cost.NonLocalCost - NonLocalCost;
862 else
863 ThisNonLocalAdjust = NonLocalCost - Cost.NonLocalCost;
864 // Scale everything to make them comparable.
865 uint64_t ThisScaledCost = ThisLocalAdjust * LocalFreq;
866 // Check for overflow on that operation.
867 bool ThisOverflows = ThisLocalAdjust && (ThisScaledCost < ThisLocalAdjust ||
868 ThisScaledCost < LocalFreq);
869 uint64_t OtherScaledCost = OtherLocalAdjust * Cost.LocalFreq;
870 // Check for overflow on the last operation.
871 bool OtherOverflows =
872 OtherLocalAdjust &&
873 (OtherScaledCost < OtherLocalAdjust || OtherScaledCost < Cost.LocalFreq);
874 // Add the non-local costs.
875 ThisOverflows |= ThisNonLocalAdjust &&
876 ThisScaledCost + ThisNonLocalAdjust < ThisNonLocalAdjust;
877 ThisScaledCost += ThisNonLocalAdjust;
878 OtherOverflows |= OtherNonLocalAdjust &&
879 OtherScaledCost + OtherNonLocalAdjust < OtherNonLocalAdjust;
880 OtherScaledCost += OtherNonLocalAdjust;
881 // If both overflows, we cannot compare without additional
882 // precision, e.g., APInt. Just give up on that case.
883 if (ThisOverflows && OtherOverflows)
884 return false;
885 // If one overflows but not the other, we can still compare.
886 if (ThisOverflows || OtherOverflows)
887 return ThisOverflows < OtherOverflows;
888 // Otherwise, just compare the values.
889 return ThisScaledCost < OtherScaledCost;
890}
891
892bool RegBankSelect::MappingCost::operator==(const MappingCost &Cost) const {
893 return LocalCost == Cost.LocalCost && NonLocalCost == Cost.NonLocalCost &&
894 LocalFreq == Cost.LocalFreq;
895}