blob: 152fc0c306c73e476f541173953cd0ef33ebf79f [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 Colombete16f5612016-04-07 23:53:55 +000021#include "llvm/Support/Debug.h"
Quentin Colombet40ad5732016-04-07 18:19:27 +000022#include "llvm/Target/TargetSubtargetInfo.h"
Quentin Colombet8e8e85c2016-04-05 19:06:01 +000023
24#define DEBUG_TYPE "regbankselect"
25
26using namespace llvm;
27
28char RegBankSelect::ID = 0;
Quentin Colombet25fcef72016-05-20 17:54:09 +000029INITIALIZE_PASS_BEGIN(RegBankSelect, "regbankselect",
30 "Assign register bank of generic virtual registers",
31 false, false);
32INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo)
33INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
34INITIALIZE_PASS_END(RegBankSelect, "regbankselect",
35 "Assign register bank of generic virtual registers", false,
36 false);
Quentin Colombet8e8e85c2016-04-05 19:06:01 +000037
Quentin Colombet46df7222016-05-20 16:55:35 +000038RegBankSelect::RegBankSelect(Mode RunningMode)
Quentin Colombet25fcef72016-05-20 17:54:09 +000039 : MachineFunctionPass(ID), RBI(nullptr), MRI(nullptr), TRI(nullptr),
40 MBFI(nullptr), MBPI(nullptr), OptMode(RunningMode) {
Quentin Colombet8e8e85c2016-04-05 19:06:01 +000041 initializeRegBankSelectPass(*PassRegistry::getPassRegistry());
42}
43
Quentin Colombet40ad5732016-04-07 18:19:27 +000044void RegBankSelect::init(MachineFunction &MF) {
45 RBI = MF.getSubtarget().getRegBankInfo();
46 assert(RBI && "Cannot work without RegisterBankInfo");
47 MRI = &MF.getRegInfo();
Quentin Colombetaac71a42016-04-07 21:32:23 +000048 TRI = MF.getSubtarget().getRegisterInfo();
Quentin Colombet25fcef72016-05-20 17:54:09 +000049 if (OptMode != Mode::Fast) {
50 MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
51 MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
52 } else {
53 MBFI = nullptr;
54 MBPI = nullptr;
55 }
Quentin Colombet40ad5732016-04-07 18:19:27 +000056 MIRBuilder.setMF(MF);
57}
58
Quentin Colombet25fcef72016-05-20 17:54:09 +000059void RegBankSelect::getAnalysisUsage(AnalysisUsage &AU) const {
60 if (OptMode != Mode::Fast) {
61 // We could preserve the information from these two analysis but
62 // the APIs do not allow to do so yet.
63 AU.addRequired<MachineBlockFrequencyInfo>();
64 AU.addRequired<MachineBranchProbabilityInfo>();
65 }
66 MachineFunctionPass::getAnalysisUsage(AU);
67}
68
Quentin Colombet40ad5732016-04-07 18:19:27 +000069bool RegBankSelect::assignmentMatch(
Quentin Colombet0d77da42016-05-20 00:42:57 +000070 unsigned Reg, const RegisterBankInfo::ValueMapping &ValMapping,
71 bool &OnlyAssign) const {
72 // By default we assume we will have to repair something.
73 OnlyAssign = false;
Quentin Colombet40ad5732016-04-07 18:19:27 +000074 // Each part of a break down needs to end up in a different register.
75 // In other word, Reg assignement does not match.
76 if (ValMapping.BreakDown.size() > 1)
77 return false;
78
Quentin Colombet6d6d6af2016-04-08 16:48:16 +000079 const RegisterBank *CurRegBank = RBI->getRegBank(Reg, *MRI, *TRI);
80 const RegisterBank *DesiredRegBrank = ValMapping.BreakDown[0].RegBank;
Quentin Colombet0d77da42016-05-20 00:42:57 +000081 // Reg is free of assignment, a simple assignment will make the
82 // register bank to match.
83 OnlyAssign = CurRegBank == nullptr;
Quentin Colombet6d6d6af2016-04-08 16:48:16 +000084 DEBUG(dbgs() << "Does assignment already match: ";
85 if (CurRegBank) dbgs() << *CurRegBank; else dbgs() << "none";
86 dbgs() << " against ";
87 assert(DesiredRegBrank && "The mapping must be valid");
88 dbgs() << *DesiredRegBrank << '\n';);
89 return CurRegBank == DesiredRegBrank;
Quentin Colombet40ad5732016-04-07 18:19:27 +000090}
91
Quentin Colombetd84d00b2016-05-20 00:55:51 +000092void RegBankSelect::repairReg(
93 MachineOperand &MO, const RegisterBankInfo::ValueMapping &ValMapping,
94 RegBankSelect::RepairingPlacement &RepairPt,
95 const iterator_range<SmallVectorImpl<unsigned>::iterator> &NewVRegs) {
96 assert(ValMapping.BreakDown.size() == 1 && "Not yet implemented");
97 // Assume we are repairing a use and thus, the original reg will be
98 // the source of the repairing.
99 unsigned Src = MO.getReg();
100 unsigned Dst = *NewVRegs.begin();
101 if (ValMapping.BreakDown.size() == 1)
102 MO.setReg(Dst);
Quentin Colombet904a2c72016-04-12 00:12:59 +0000103
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000104 // If we repair a definition, swap the source and destination for
105 // the repairing.
106 if (MO.isDef())
Quentin Colombet904a2c72016-04-12 00:12:59 +0000107 std::swap(Src, Dst);
Quentin Colombet904a2c72016-04-12 00:12:59 +0000108
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000109 assert((RepairPt.getNumInsertPoints() == 1 ||
110 TargetRegisterInfo::isPhysicalRegister(Dst)) &&
111 "We are about to create several defs for Dst");
Quentin Colombet904a2c72016-04-12 00:12:59 +0000112
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000113 // Build the instruction used to repair, then clone it at the right places.
114 MachineInstr *MI = MIRBuilder.buildInstr(TargetOpcode::COPY, Dst, Src);
115 MI->removeFromParent();
116 DEBUG(dbgs() << "Copy: " << PrintReg(Src) << " to: " << PrintReg(Dst)
117 << '\n');
118 // TODO:
119 // Check if MI is legal. if not, we need to legalize all the
120 // instructions we are going to insert.
121 std::unique_ptr<MachineInstr *[]> NewInstrs(
122 new MachineInstr *[RepairPt.getNumInsertPoints()]);
123 bool IsFirst = true;
124 unsigned Idx = 0;
125 for (const std::unique_ptr<InsertPoint> &InsertPt : RepairPt) {
126 MachineInstr *CurMI;
127 if (IsFirst)
128 CurMI = MI;
129 else
130 CurMI = MIRBuilder.getMF().CloneMachineInstr(MI);
131 InsertPt->insert(*CurMI);
132 NewInstrs[Idx++] = CurMI;
133 IsFirst = false;
134 }
135 // TODO:
136 // Legalize NewInstrs if need be.
Quentin Colombet40ad5732016-04-07 18:19:27 +0000137}
138
Quentin Colombetf75c2bf2016-05-20 16:36:12 +0000139void RegBankSelect::tryAvoidingSplit(
140 RegBankSelect::RepairingPlacement &RepairPt, const MachineOperand &MO,
141 const RegisterBankInfo::ValueMapping &ValMapping) const {
142 const MachineInstr &MI = *MO.getParent();
143 assert(RepairPt.hasSplit() && "We should not have to adjust for split");
144 // Splitting should only occur for PHIs or between terminators,
145 // because we only do local repairing.
146 assert((MI.isPHI() || MI.isTerminator()) && "Why do we split?");
147
148 assert(&MI.getOperand(RepairPt.getOpIdx()) == &MO &&
149 "Repairing placement does not match operand");
150
151 // If we need splitting for phis, that means it is because we
152 // could not find an insertion point before the terminators of
153 // the predecessor block for this argument. In other words,
154 // the input value is defined by one of the terminators.
155 assert((!MI.isPHI() || !MO.isDef()) && "Need split for phi def?");
156
157 // We split to repair the use of a phi or a terminator.
158 if (!MO.isDef()) {
159 if (MI.isTerminator()) {
160 assert(&MI != &(*MI.getParent()->getFirstTerminator()) &&
161 "Need to split for the first terminator?!");
162 } else {
163 // For the PHI case, the split may not be actually required.
164 // In the copy case, a phi is already a copy on the incoming edge,
165 // therefore there is no need to split.
166 if (ValMapping.BreakDown.size() == 1)
167 // This is a already a copy, there is nothing to do.
168 RepairPt.switchTo(RepairingPlacement::RepairingKind::Reassign);
169 }
170 return;
171 }
172
173 // At this point, we need to repair a defintion of a terminator.
174
175 // Technically we need to fix the def of MI on all outgoing
176 // edges of MI to keep the repairing local. In other words, we
177 // will create several definitions of the same register. This
178 // does not work for SSA unless that definition is a physical
179 // register.
180 // However, there are other cases where we can get away with
181 // that while still keeping the repairing local.
182 assert(MI.isTerminator() && MO.isDef() &&
183 "This code is for the def of a terminator");
184
185 // Since we use RPO traversal, if we need to repair a definition
186 // this means this definition could be:
187 // 1. Used by PHIs (i.e., this VReg has been visited as part of the
188 // uses of a phi.), or
189 // 2. Part of a target specific instruction (i.e., the target applied
190 // some register class constraints when creating the instruction.)
191 // If the constraints come for #2, the target said that another mapping
192 // is supported so we may just drop them. Indeed, if we do not change
193 // the number of registers holding that value, the uses will get fixed
194 // when we get to them.
195 // Uses in PHIs may have already been proceeded though.
196 // If the constraints come for #1, then, those are weak constraints and
197 // no actual uses may rely on them. However, the problem remains mainly
198 // the same as for #2. If the value stays in one register, we could
199 // just switch the register bank of the definition, but we would need to
200 // account for a repairing cost for each phi we silently change.
201 //
202 // In any case, if the value needs to be broken down into several
203 // registers, the repairing is not local anymore as we need to patch
204 // every uses to rebuild the value in just one register.
205 //
206 // To summarize:
207 // - If the value is in a physical register, we can do the split and
208 // fix locally.
209 // Otherwise if the value is in a virtual register:
210 // - If the value remains in one register, we do not have to split
211 // just switching the register bank would do, but we need to account
212 // in the repairing cost all the phi we changed.
213 // - If the value spans several registers, then we cannot do a local
214 // repairing.
215
216 // Check if this is a physical or virtual register.
217 unsigned Reg = MO.getReg();
218 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
219 // We are going to split every outgoing edges.
220 // Check that this is possible.
221 // FIXME: The machine representation is currently broken
222 // since it also several terminators in one basic block.
223 // Because of that we would technically need a way to get
224 // the targets of just one terminator to know which edges
225 // we have to split.
226 // Assert that we do not hit the ill-formed representation.
227
228 // If there are other terminators before that one, some of
229 // the outgoing edges may not be dominated by this definition.
230 assert(&MI == &(*MI.getParent()->getFirstTerminator()) &&
231 "Do not know which outgoing edges are relevant");
232 const MachineInstr *Next = MI.getNextNode();
233 assert((!Next || Next->isUnconditionalBranch()) &&
234 "Do not know where each terminator ends up");
235 if (Next)
236 // If the next terminator uses Reg, this means we have
237 // to split right after MI and thus we need a way to ask
238 // which outgoing edges are affected.
239 assert(!Next->readsRegister(Reg) && "Need to split between terminators");
240 // We will split all the edges and repair there.
241 } else {
242 // This is a virtual register defined by a terminator.
243 if (ValMapping.BreakDown.size() == 1) {
244 // There is nothing to repair, but we may actually lie on
245 // the repairing cost because of the PHIs already proceeded
246 // as already stated.
247 // Though the code will be correct.
248 assert(0 && "Repairing cost may not be accurate");
249 } else {
250 // We need to do non-local repairing. Basically, patch all
251 // the uses (i.e., phis) that we already proceeded.
252 // For now, just say this mapping is not possible.
253 RepairPt.switchTo(RepairingPlacement::RepairingKind::Impossible);
254 }
255 }
256}
257
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000258RegBankSelect::MappingCost RegBankSelect::computeMapping(
259 MachineInstr &MI, const RegisterBankInfo::InstructionMapping &InstrMapping,
Quentin Colombet6e80dbc2016-05-20 18:00:46 +0000260 SmallVectorImpl<RepairingPlacement> &RepairPts,
261 const RegBankSelect::MappingCost *BestCost) {
262 assert((MBFI || !BestCost) && "Costs comparison require MBFI");
Quentin Colombete16f5612016-04-07 23:53:55 +0000263
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000264 // If mapped with InstrMapping, MI will have the recorded cost.
Quentin Colombet25fcef72016-05-20 17:54:09 +0000265 MappingCost Cost(MBFI ? MBFI->getBlockFreq(MI.getParent()) : 1);
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000266 bool Saturated = Cost.addLocalCost(InstrMapping.getCost());
267 assert(!Saturated && "Possible mapping saturated the cost");
268 DEBUG(dbgs() << "Evaluating mapping cost for: " << MI);
269 DEBUG(dbgs() << "With: " << InstrMapping << '\n');
270 RepairPts.clear();
Quentin Colombet6e80dbc2016-05-20 18:00:46 +0000271 if (BestCost && Cost > *BestCost)
272 return Cost;
273
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000274 // Moreover, to realize this mapping, the register bank of each operand must
275 // match this mapping. In other words, we may need to locally reassign the
276 // register banks. Account for that repairing cost as well.
277 // In this context, local means in the surrounding of MI.
278 for (unsigned OpIdx = 0, EndOpIdx = MI.getNumOperands(); OpIdx != EndOpIdx;
Quentin Colombet40ad5732016-04-07 18:19:27 +0000279 ++OpIdx) {
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000280 const MachineOperand &MO = MI.getOperand(OpIdx);
Quentin Colombet40ad5732016-04-07 18:19:27 +0000281 if (!MO.isReg())
282 continue;
283 unsigned Reg = MO.getReg();
284 if (!Reg)
285 continue;
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000286 DEBUG(dbgs() << "Opd" << OpIdx);
Quentin Colombet40ad5732016-04-07 18:19:27 +0000287 const RegisterBankInfo::ValueMapping &ValMapping =
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000288 InstrMapping.getOperandMapping(OpIdx);
289 // If Reg is already properly mapped, this is free.
290 bool Assign;
291 if (assignmentMatch(Reg, ValMapping, Assign)) {
292 DEBUG(dbgs() << " is free (match).\n");
Quentin Colombet40ad5732016-04-07 18:19:27 +0000293 continue;
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000294 }
295 if (Assign) {
296 DEBUG(dbgs() << " is free (simple assignment).\n");
297 RepairPts.emplace_back(RepairingPlacement(MI, OpIdx, *TRI, *this,
298 RepairingPlacement::Reassign));
299 continue;
Quentin Colombet40ad5732016-04-07 18:19:27 +0000300 }
Quentin Colombet904a2c72016-04-12 00:12:59 +0000301
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000302 // TODO:
303 // Ask the repairing module how much it would cost to get this mapping.
304 // Use: NewSources <- Val.
305 // Same size: copy.
306 // Different size: Src1, Src2, ... =
307 // extract_value Val, Src1Begin, Src1Len, Src2Begin, Src2Len, ...
308 // Def: Val <- NewDefs
309 // Same size: copy
310 // Different size: Val = build_sequence Defs1, Defs2, ...
311 // We should remember that this value is available somewhere else to
312 // coalesce the value.
Quentin Colombet904a2c72016-04-12 00:12:59 +0000313
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000314 // Find the insertion point for the repairing code.
315 RepairPts.emplace_back(
316 RepairingPlacement(MI, OpIdx, *TRI, *this, RepairingPlacement::Insert));
317 RepairingPlacement &RepairPt = RepairPts.back();
318
Quentin Colombetf75c2bf2016-05-20 16:36:12 +0000319 // If we need to split a basic block to materialize this insertion point,
320 // we may give a higher cost to this mapping.
321 // Nevertheless, we may get away with the split, so try that first.
322 if (RepairPt.hasSplit())
323 tryAvoidingSplit(RepairPt, MO, ValMapping);
324
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000325 // Check that the materialization of the repairing is possible.
326 if (!RepairPt.canMaterialize())
327 return MappingCost::ImpossibleCost();
328
329 // Account for the split cost and repair cost.
Quentin Colombet6e80dbc2016-05-20 18:00:46 +0000330 // Unless the cost is already saturated or we do not care about the cost.
331 if (!BestCost || Saturated)
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000332 continue;
333
Quentin Colombet6e80dbc2016-05-20 18:00:46 +0000334 // To get accurate information we need MBFI and MBPI.
335 // Thus, if we end up here this information should be here.
336 assert(MBFI && MBPI && "Cost computation requires MBFI and MBPI");
337
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000338 // Sums up the repairing cost of at each insertion point.
339 // TODO: Get the actual repairing cost.
340 uint64_t RepairCost = 1;
341 // Bias used for splitting: 5%.
342 const uint64_t PercentageForBias = 5;
343 uint64_t Bias = (RepairCost * PercentageForBias + 99) / 100;
344 // We should not need more than a couple of instructions to repair
345 // an assignment. In other words, the computation should not
346 // overflow because the repairing cost is free of basic block
347 // frequency.
348 assert(((RepairCost < RepairCost * PercentageForBias) &&
349 (RepairCost * PercentageForBias <
350 RepairCost * PercentageForBias + 99)) &&
351 "Repairing involves more than a billion of instructions?!");
352 for (const std::unique_ptr<InsertPoint> &InsertPt : RepairPt) {
353 assert(InsertPt->canMaterialize() && "We should not have made it here");
354 // We will applied some basic block frequency and those uses uint64_t.
355 if (!InsertPt->isSplit())
356 Saturated = Cost.addLocalCost(RepairCost);
357 else {
358 uint64_t CostForInsertPt = RepairCost;
359 // Again we shouldn't overflow here givent that
360 // CostForInsertPt is frequency free at this point.
361 assert(CostForInsertPt + Bias > CostForInsertPt &&
362 "Repairing + split bias overflows");
363 CostForInsertPt += Bias;
364 uint64_t PtCost = InsertPt->frequency(*this) * CostForInsertPt;
365 // Check if we just overflowed.
366 if ((Saturated = PtCost < CostForInsertPt))
367 Cost.saturate();
368 else
369 Saturated = Cost.addNonLocalCost(PtCost);
370 }
Quentin Colombet6e80dbc2016-05-20 18:00:46 +0000371
372 // Stop looking into what it takes to repair, this is already
373 // too expensive.
374 if (BestCost && Cost > *BestCost)
375 return Cost;
376
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000377 // No need to accumulate more cost information.
378 // We need to still gather the repairing information though.
379 if (Saturated)
380 break;
381 }
Quentin Colombet40ad5732016-04-07 18:19:27 +0000382 }
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000383 return Cost;
384}
385
386void RegBankSelect::applyMapping(
387 MachineInstr &MI, const RegisterBankInfo::InstructionMapping &InstrMapping,
388 SmallVectorImpl<RegBankSelect::RepairingPlacement> &RepairPts) {
389 assert(InstrMapping.getID() == RegisterBankInfo::DefaultMappingID &&
390 "Rewriting of MI not implemented yet");
391 // First, place the repairing code.
392 bool NeedRewrite = false;
393 SmallVector<unsigned, 8> NewVRegs;
394 for (RepairingPlacement &RepairPt : RepairPts) {
395 assert(RepairPt.canMaterialize() &&
396 RepairPt.getKind() != RepairingPlacement::Impossible &&
397 "This mapping is impossible");
398 assert(RepairPt.getKind() != RepairingPlacement::None &&
399 "This should not make its way in the list");
400 unsigned OpIdx = RepairPt.getOpIdx();
401 MachineOperand &MO = MI.getOperand(OpIdx);
402 const RegisterBankInfo::ValueMapping &ValMapping =
403 InstrMapping.getOperandMapping(OpIdx);
404 unsigned BreakDownSize = ValMapping.BreakDown.size();
405 unsigned Reg = MO.getReg();
406 NeedRewrite = BreakDownSize != 1;
407
408 switch (RepairPt.getKind()) {
409 case RepairingPlacement::Reassign:
410 assert(BreakDownSize == 1 &&
411 "Reassignment should only be for simple mapping");
412 MRI->setRegBank(Reg, *ValMapping.BreakDown[0].RegBank);
413 break;
414 case RepairingPlacement::Insert:
415 // We need as many new virtual registers as the number of partial mapping.
416 for (const RegisterBankInfo::PartialMapping &PartMap :
417 ValMapping.BreakDown) {
418 unsigned Tmp = MRI->createGenericVirtualRegister(PartMap.Length);
419 MRI->setRegBank(Tmp, *PartMap.RegBank);
420 NewVRegs.push_back(Tmp);
421 }
422 repairReg(MO, ValMapping, RepairPt,
423 make_range(NewVRegs.end() - BreakDownSize, NewVRegs.end()));
424 break;
425 default:
426 llvm_unreachable("Other kind should not happen");
427 }
428 }
429 // Second, rewrite the instruction.
430 (void)NeedRewrite;
431 assert(!NeedRewrite && "Not implemented yet");
432}
433
434void RegBankSelect::assignInstr(MachineInstr &MI) {
435 DEBUG(dbgs() << "Assign: " << MI);
436 RegisterBankInfo::InstructionMapping DefaultMapping =
437 RBI->getInstrMapping(MI);
438 // Remember the repairing placement for all the operands.
439 SmallVector<RepairingPlacement, 4> RepairPts;
440
441 MappingCost DefaultCost = computeMapping(MI, DefaultMapping, RepairPts);
442 (void)DefaultCost;
443 assert(DefaultCost != MappingCost::ImpossibleCost() &&
444 "Default mapping is not suited");
445
446 // Make sure the mapping is valid for MI.
447 assert(DefaultMapping.verify(MI) && "Invalid instruction mapping");
448
449 DEBUG(dbgs() << "Mapping: " << DefaultMapping << '\n');
450
451 applyMapping(MI, DefaultMapping, RepairPts);
452
Quentin Colombete16f5612016-04-07 23:53:55 +0000453 DEBUG(dbgs() << "Assigned: " << MI);
Quentin Colombet40ad5732016-04-07 18:19:27 +0000454}
455
Quentin Colombet8e8e85c2016-04-05 19:06:01 +0000456bool RegBankSelect::runOnMachineFunction(MachineFunction &MF) {
Quentin Colombete16f5612016-04-07 23:53:55 +0000457 DEBUG(dbgs() << "Assign register banks for: " << MF.getName() << '\n');
Quentin Colombeta5530122016-05-20 17:36:54 +0000458 const Function *F = MF.getFunction();
459 Mode SaveOptMode = OptMode;
460 if (F->hasFnAttribute(Attribute::OptimizeNone))
461 OptMode = Mode::Fast;
Quentin Colombet40ad5732016-04-07 18:19:27 +0000462 init(MF);
463 // Walk the function and assign register banks to all operands.
Quentin Colombetab8c21f2016-04-08 17:19:10 +0000464 // Use a RPOT to make sure all registers are assigned before we choose
465 // the best mapping of the current instruction.
466 ReversePostOrderTraversal<MachineFunction*> RPOT(&MF);
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000467 for (MachineBasicBlock *MBB : RPOT) {
468 // Set a sensible insertion point so that subsequent calls to
469 // MIRBuilder.
470 MIRBuilder.setMBB(*MBB);
Quentin Colombetab8c21f2016-04-08 17:19:10 +0000471 for (MachineInstr &MI : *MBB)
Quentin Colombet40ad5732016-04-07 18:19:27 +0000472 assignInstr(MI);
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000473 }
Quentin Colombeta5530122016-05-20 17:36:54 +0000474 OptMode = SaveOptMode;
Quentin Colombet8e8e85c2016-04-05 19:06:01 +0000475 return false;
476}
Quentin Colombetcfd97b92016-05-20 00:35:26 +0000477
478//------------------------------------------------------------------------------
Quentin Colombet55650752016-05-20 00:49:10 +0000479// Helper Classes Implementation
Quentin Colombetcfd97b92016-05-20 00:35:26 +0000480//------------------------------------------------------------------------------
Quentin Colombet55650752016-05-20 00:49:10 +0000481RegBankSelect::RepairingPlacement::RepairingPlacement(
482 MachineInstr &MI, unsigned OpIdx, const TargetRegisterInfo &TRI, Pass &P,
483 RepairingPlacement::RepairingKind Kind)
484 // Default is, we are going to insert code to repair OpIdx.
485 : Kind(Kind),
486 OpIdx(OpIdx),
487 CanMaterialize(Kind != RepairingKind::Impossible),
488 HasSplit(false),
489 P(P) {
490 const MachineOperand &MO = MI.getOperand(OpIdx);
491 assert(MO.isReg() && "Trying to repair a non-reg operand");
492
493 if (Kind != RepairingKind::Insert)
494 return;
495
496 // Repairings for definitions happen after MI, uses happen before.
497 bool Before = !MO.isDef();
498
499 // Check if we are done with MI.
500 if (!MI.isPHI() && !MI.isTerminator()) {
501 addInsertPoint(MI, Before);
502 // We are done with the initialization.
503 return;
504 }
505
506 // Now, look for the special cases.
507 if (MI.isPHI()) {
508 // - PHI must be the first instructions:
509 // * Before, we have to split the related incoming edge.
510 // * After, move the insertion point past the last phi.
511 if (!Before) {
512 MachineBasicBlock::iterator It = MI.getParent()->getFirstNonPHI();
513 if (It != MI.getParent()->end())
514 addInsertPoint(*It, /*Before*/ true);
515 else
516 addInsertPoint(*(--It), /*Before*/ false);
517 return;
518 }
519 // We repair a use of a phi, we may need to split the related edge.
520 MachineBasicBlock &Pred = *MI.getOperand(OpIdx + 1).getMBB();
521 // Check if we can move the insertion point prior to the
522 // terminators of the predecessor.
523 unsigned Reg = MO.getReg();
524 MachineBasicBlock::iterator It = Pred.getLastNonDebugInstr();
525 for (auto Begin = Pred.begin(); It != Begin && It->isTerminator(); --It)
526 if (It->modifiesRegister(Reg, &TRI)) {
527 // We cannot hoist the repairing code in the predecessor.
528 // Split the edge.
529 addInsertPoint(Pred, *MI.getParent());
530 return;
531 }
532 // At this point, we can insert in Pred.
533
534 // - If It is invalid, Pred is empty and we can insert in Pred
535 // wherever we want.
536 // - If It is valid, It is the first non-terminator, insert after It.
537 if (It == Pred.end())
538 addInsertPoint(Pred, /*Beginning*/ false);
539 else
540 addInsertPoint(*It, /*Before*/ false);
541 } else {
542 // - Terminators must be the last instructions:
543 // * Before, move the insert point before the first terminator.
544 // * After, we have to split the outcoming edges.
545 unsigned Reg = MO.getReg();
546 if (Before) {
547 // Check whether Reg is defined by any terminator.
548 MachineBasicBlock::iterator It = MI;
549 for (auto Begin = MI.getParent()->begin();
550 --It != Begin && It->isTerminator();)
551 if (It->modifiesRegister(Reg, &TRI)) {
552 // Insert the repairing code right after the definition.
553 addInsertPoint(*It, /*Before*/ false);
554 return;
555 }
556 addInsertPoint(*It, /*Before*/ true);
557 return;
558 }
559 // Make sure Reg is not redefined by other terminators, otherwise
560 // we do not know how to split.
561 for (MachineBasicBlock::iterator It = MI, End = MI.getParent()->end();
562 ++It != End;)
563 // The machine verifier should reject this kind of code.
564 assert(It->modifiesRegister(Reg, &TRI) && "Do not know where to split");
565 // Split each outcoming edges.
566 MachineBasicBlock &Src = *MI.getParent();
567 for (auto &Succ : Src.successors())
568 addInsertPoint(Src, Succ);
569 }
570}
571
572void RegBankSelect::RepairingPlacement::addInsertPoint(MachineInstr &MI,
573 bool Before) {
574 addInsertPoint(*new InstrInsertPoint(MI, Before));
575}
576
577void RegBankSelect::RepairingPlacement::addInsertPoint(MachineBasicBlock &MBB,
578 bool Beginning) {
579 addInsertPoint(*new MBBInsertPoint(MBB, Beginning));
580}
581
582void RegBankSelect::RepairingPlacement::addInsertPoint(MachineBasicBlock &Src,
583 MachineBasicBlock &Dst) {
584 addInsertPoint(*new EdgeInsertPoint(Src, Dst, P));
585}
586
587void RegBankSelect::RepairingPlacement::addInsertPoint(
588 RegBankSelect::InsertPoint &Point) {
589 CanMaterialize &= Point.canMaterialize();
590 HasSplit |= Point.isSplit();
591 InsertPoints.emplace_back(&Point);
592}
593
594RegBankSelect::InstrInsertPoint::InstrInsertPoint(MachineInstr &Instr,
595 bool Before)
596 : InsertPoint(), Instr(Instr), Before(Before) {
597 // Since we do not support splitting, we do not need to update
598 // liveness and such, so do not do anything with P.
599 assert((!Before || !Instr.isPHI()) &&
600 "Splitting before phis requires more points");
601 assert((!Before || !Instr.getNextNode() || !Instr.getNextNode()->isPHI()) &&
602 "Splitting between phis does not make sense");
603}
604
605void RegBankSelect::InstrInsertPoint::materialize() {
606 if (isSplit()) {
607 // Slice and return the beginning of the new block.
608 // If we need to split between the terminators, we theoritically
609 // need to know where the first and second set of terminators end
610 // to update the successors properly.
611 // Now, in pratice, we should have a maximum of 2 branch
612 // instructions; one conditional and one unconditional. Therefore
613 // we know how to update the successor by looking at the target of
614 // the unconditional branch.
615 // If we end up splitting at some point, then, we should update
616 // the liveness information and such. I.e., we would need to
617 // access P here.
618 // The machine verifier should actually make sure such cases
619 // cannot happen.
620 llvm_unreachable("Not yet implemented");
621 }
622 // Otherwise the insertion point is just the current or next
623 // instruction depending on Before. I.e., there is nothing to do
624 // here.
625}
626
627bool RegBankSelect::InstrInsertPoint::isSplit() const {
628 // If the insertion point is after a terminator, we need to split.
629 if (!Before)
630 return Instr.isTerminator();
631 // If we insert before an instruction that is after a terminator,
632 // we are still after a terminator.
633 return Instr.getPrevNode() && Instr.getPrevNode()->isTerminator();
634}
635
636uint64_t RegBankSelect::InstrInsertPoint::frequency(const Pass &P) const {
637 // Even if we need to split, because we insert between terminators,
638 // this split has actually the same frequency as the instruction.
639 const MachineBlockFrequencyInfo *MBFI =
640 P.getAnalysisIfAvailable<MachineBlockFrequencyInfo>();
641 if (!MBFI)
642 return 1;
643 return MBFI->getBlockFreq(Instr.getParent()).getFrequency();
644}
645
646uint64_t RegBankSelect::MBBInsertPoint::frequency(const Pass &P) const {
647 const MachineBlockFrequencyInfo *MBFI =
648 P.getAnalysisIfAvailable<MachineBlockFrequencyInfo>();
649 if (!MBFI)
650 return 1;
651 return MBFI->getBlockFreq(&MBB).getFrequency();
652}
653
654void RegBankSelect::EdgeInsertPoint::materialize() {
655 // If we end up repairing twice at the same place before materializing the
656 // insertion point, we may think we have to split an edge twice.
657 // We should have a factory for the insert point such that identical points
658 // are the same instance.
659 assert(Src.isSuccessor(DstOrSplit) && DstOrSplit->isPredecessor(&Src) &&
660 "This point has already been split");
661 MachineBasicBlock *NewBB = Src.SplitCriticalEdge(DstOrSplit, P);
662 assert(NewBB && "Invalid call to materialize");
663 // We reuse the destination block to hold the information of the new block.
664 DstOrSplit = NewBB;
665}
666
667uint64_t RegBankSelect::EdgeInsertPoint::frequency(const Pass &P) const {
668 const MachineBlockFrequencyInfo *MBFI =
669 P.getAnalysisIfAvailable<MachineBlockFrequencyInfo>();
670 if (!MBFI)
671 return 1;
672 if (WasMaterialized)
673 return MBFI->getBlockFreq(DstOrSplit).getFrequency();
674
675 const MachineBranchProbabilityInfo *MBPI =
676 P.getAnalysisIfAvailable<MachineBranchProbabilityInfo>();
677 if (!MBPI)
678 return 1;
679 // The basic block will be on the edge.
680 return (MBFI->getBlockFreq(&Src) * MBPI->getEdgeProbability(&Src, DstOrSplit))
681 .getFrequency();
682}
683
684bool RegBankSelect::EdgeInsertPoint::canMaterialize() const {
685 // If this is not a critical edge, we should not have used this insert
686 // point. Indeed, either the successor or the predecessor should
687 // have do.
688 assert(Src.succ_size() > 1 && DstOrSplit->pred_size() > 1 &&
689 "Edge is not critical");
690 return Src.canSplitCriticalEdge(DstOrSplit);
691}
692
Quentin Colombetcfd97b92016-05-20 00:35:26 +0000693RegBankSelect::MappingCost::MappingCost(const BlockFrequency &LocalFreq)
694 : LocalCost(0), NonLocalCost(0), LocalFreq(LocalFreq.getFrequency()) {}
695
696bool RegBankSelect::MappingCost::addLocalCost(uint64_t Cost) {
697 // Check if this overflows.
698 if (LocalCost + Cost < LocalCost) {
699 saturate();
700 return true;
701 }
702 LocalCost += Cost;
703 return isSaturated();
704}
705
706bool RegBankSelect::MappingCost::addNonLocalCost(uint64_t Cost) {
707 // Check if this overflows.
708 if (NonLocalCost + Cost < NonLocalCost) {
709 saturate();
710 return true;
711 }
712 NonLocalCost += Cost;
713 return isSaturated();
714}
715
716bool RegBankSelect::MappingCost::isSaturated() const {
717 return LocalCost == UINT64_MAX - 1 && NonLocalCost == UINT64_MAX &&
718 LocalFreq == UINT64_MAX;
719}
720
721void RegBankSelect::MappingCost::saturate() {
722 *this = ImpossibleCost();
723 --LocalCost;
724}
725
726RegBankSelect::MappingCost RegBankSelect::MappingCost::ImpossibleCost() {
727 return MappingCost(UINT64_MAX, UINT64_MAX, UINT64_MAX);
728}
729
730bool RegBankSelect::MappingCost::operator<(const MappingCost &Cost) const {
731 // Sort out the easy cases.
732 if (*this == Cost)
733 return false;
734 // If one is impossible to realize the other is cheaper unless it is
735 // impossible as well.
736 if ((*this == ImpossibleCost()) || (Cost == ImpossibleCost()))
737 return (*this == ImpossibleCost()) < (Cost == ImpossibleCost());
738 // If one is saturated the other is cheaper, unless it is saturated
739 // as well.
740 if (isSaturated() || Cost.isSaturated())
741 return isSaturated() < Cost.isSaturated();
742 // At this point we know both costs hold sensible values.
743
744 // If both values have a different base frequency, there is no much
745 // we can do but to scale everything.
746 // However, if they have the same base frequency we can avoid making
747 // complicated computation.
748 uint64_t ThisLocalAdjust;
749 uint64_t OtherLocalAdjust;
750 if (LLVM_LIKELY(LocalFreq == Cost.LocalFreq)) {
751
752 // At this point, we know the local costs are comparable.
753 // Do the case that do not involve potential overflow first.
754 if (NonLocalCost == Cost.NonLocalCost)
755 // Since the non-local costs do not discriminate on the result,
756 // just compare the local costs.
757 return LocalCost < Cost.LocalCost;
758
759 // The base costs are comparable so we may only keep the relative
760 // value to increase our chances of avoiding overflows.
761 ThisLocalAdjust = 0;
762 OtherLocalAdjust = 0;
763 if (LocalCost < Cost.LocalCost)
764 OtherLocalAdjust = Cost.LocalCost - LocalCost;
765 else
766 ThisLocalAdjust = LocalCost - Cost.LocalCost;
767
768 } else {
769 ThisLocalAdjust = LocalCost;
770 OtherLocalAdjust = Cost.LocalCost;
771 }
772
773 // The non-local costs are comparable, just keep the relative value.
774 uint64_t ThisNonLocalAdjust = 0;
775 uint64_t OtherNonLocalAdjust = 0;
776 if (NonLocalCost < Cost.NonLocalCost)
777 OtherNonLocalAdjust = Cost.NonLocalCost - NonLocalCost;
778 else
779 ThisNonLocalAdjust = NonLocalCost - Cost.NonLocalCost;
780 // Scale everything to make them comparable.
781 uint64_t ThisScaledCost = ThisLocalAdjust * LocalFreq;
782 // Check for overflow on that operation.
783 bool ThisOverflows = ThisLocalAdjust && (ThisScaledCost < ThisLocalAdjust ||
784 ThisScaledCost < LocalFreq);
785 uint64_t OtherScaledCost = OtherLocalAdjust * Cost.LocalFreq;
786 // Check for overflow on the last operation.
787 bool OtherOverflows =
788 OtherLocalAdjust &&
789 (OtherScaledCost < OtherLocalAdjust || OtherScaledCost < Cost.LocalFreq);
790 // Add the non-local costs.
791 ThisOverflows |= ThisNonLocalAdjust &&
792 ThisScaledCost + ThisNonLocalAdjust < ThisNonLocalAdjust;
793 ThisScaledCost += ThisNonLocalAdjust;
794 OtherOverflows |= OtherNonLocalAdjust &&
795 OtherScaledCost + OtherNonLocalAdjust < OtherNonLocalAdjust;
796 OtherScaledCost += OtherNonLocalAdjust;
797 // If both overflows, we cannot compare without additional
798 // precision, e.g., APInt. Just give up on that case.
799 if (ThisOverflows && OtherOverflows)
800 return false;
801 // If one overflows but not the other, we can still compare.
802 if (ThisOverflows || OtherOverflows)
803 return ThisOverflows < OtherOverflows;
804 // Otherwise, just compare the values.
805 return ThisScaledCost < OtherScaledCost;
806}
807
808bool RegBankSelect::MappingCost::operator==(const MappingCost &Cost) const {
809 return LocalCost == Cost.LocalCost && NonLocalCost == Cost.NonLocalCost &&
810 LocalFreq == Cost.LocalFreq;
811}