blob: 4dc2bd8c81a4c532da1f61be01ffbb6bde144fc5 [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 Colombet79fe1be2016-05-20 18:37:33 +0000139RegisterBankInfo::InstructionMapping &RegBankSelect::findBestMapping(
140 MachineInstr &MI, RegisterBankInfo::InstructionMappings &PossibleMappings,
141 SmallVectorImpl<RepairingPlacement> &RepairPts) {
142
143 RegisterBankInfo::InstructionMapping *BestMapping = nullptr;
144 MappingCost Cost = MappingCost::ImpossibleCost();
145 SmallVector<RepairingPlacement, 4> LocalRepairPts;
146 for (RegisterBankInfo::InstructionMapping &CurMapping : PossibleMappings) {
147 MappingCost CurCost = computeMapping(MI, CurMapping, LocalRepairPts, &Cost);
148 if (CurCost < Cost) {
149 Cost = CurCost;
150 BestMapping = &CurMapping;
151 RepairPts.clear();
152 for (RepairingPlacement &RepairPt : LocalRepairPts)
153 RepairPts.emplace_back(std::move(RepairPt));
154 }
155 }
156 assert(BestMapping && "No suitable mapping for instruction");
157 return *BestMapping;
158}
159
Quentin Colombetf75c2bf2016-05-20 16:36:12 +0000160void RegBankSelect::tryAvoidingSplit(
161 RegBankSelect::RepairingPlacement &RepairPt, const MachineOperand &MO,
162 const RegisterBankInfo::ValueMapping &ValMapping) const {
163 const MachineInstr &MI = *MO.getParent();
164 assert(RepairPt.hasSplit() && "We should not have to adjust for split");
165 // Splitting should only occur for PHIs or between terminators,
166 // because we only do local repairing.
167 assert((MI.isPHI() || MI.isTerminator()) && "Why do we split?");
168
169 assert(&MI.getOperand(RepairPt.getOpIdx()) == &MO &&
170 "Repairing placement does not match operand");
171
172 // If we need splitting for phis, that means it is because we
173 // could not find an insertion point before the terminators of
174 // the predecessor block for this argument. In other words,
175 // the input value is defined by one of the terminators.
176 assert((!MI.isPHI() || !MO.isDef()) && "Need split for phi def?");
177
178 // We split to repair the use of a phi or a terminator.
179 if (!MO.isDef()) {
180 if (MI.isTerminator()) {
181 assert(&MI != &(*MI.getParent()->getFirstTerminator()) &&
182 "Need to split for the first terminator?!");
183 } else {
184 // For the PHI case, the split may not be actually required.
185 // In the copy case, a phi is already a copy on the incoming edge,
186 // therefore there is no need to split.
187 if (ValMapping.BreakDown.size() == 1)
188 // This is a already a copy, there is nothing to do.
189 RepairPt.switchTo(RepairingPlacement::RepairingKind::Reassign);
190 }
191 return;
192 }
193
194 // At this point, we need to repair a defintion of a terminator.
195
196 // Technically we need to fix the def of MI on all outgoing
197 // edges of MI to keep the repairing local. In other words, we
198 // will create several definitions of the same register. This
199 // does not work for SSA unless that definition is a physical
200 // register.
201 // However, there are other cases where we can get away with
202 // that while still keeping the repairing local.
203 assert(MI.isTerminator() && MO.isDef() &&
204 "This code is for the def of a terminator");
205
206 // Since we use RPO traversal, if we need to repair a definition
207 // this means this definition could be:
208 // 1. Used by PHIs (i.e., this VReg has been visited as part of the
209 // uses of a phi.), or
210 // 2. Part of a target specific instruction (i.e., the target applied
211 // some register class constraints when creating the instruction.)
212 // If the constraints come for #2, the target said that another mapping
213 // is supported so we may just drop them. Indeed, if we do not change
214 // the number of registers holding that value, the uses will get fixed
215 // when we get to them.
216 // Uses in PHIs may have already been proceeded though.
217 // If the constraints come for #1, then, those are weak constraints and
218 // no actual uses may rely on them. However, the problem remains mainly
219 // the same as for #2. If the value stays in one register, we could
220 // just switch the register bank of the definition, but we would need to
221 // account for a repairing cost for each phi we silently change.
222 //
223 // In any case, if the value needs to be broken down into several
224 // registers, the repairing is not local anymore as we need to patch
225 // every uses to rebuild the value in just one register.
226 //
227 // To summarize:
228 // - If the value is in a physical register, we can do the split and
229 // fix locally.
230 // Otherwise if the value is in a virtual register:
231 // - If the value remains in one register, we do not have to split
232 // just switching the register bank would do, but we need to account
233 // in the repairing cost all the phi we changed.
234 // - If the value spans several registers, then we cannot do a local
235 // repairing.
236
237 // Check if this is a physical or virtual register.
238 unsigned Reg = MO.getReg();
239 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
240 // We are going to split every outgoing edges.
241 // Check that this is possible.
242 // FIXME: The machine representation is currently broken
243 // since it also several terminators in one basic block.
244 // Because of that we would technically need a way to get
245 // the targets of just one terminator to know which edges
246 // we have to split.
247 // Assert that we do not hit the ill-formed representation.
248
249 // If there are other terminators before that one, some of
250 // the outgoing edges may not be dominated by this definition.
251 assert(&MI == &(*MI.getParent()->getFirstTerminator()) &&
252 "Do not know which outgoing edges are relevant");
253 const MachineInstr *Next = MI.getNextNode();
254 assert((!Next || Next->isUnconditionalBranch()) &&
255 "Do not know where each terminator ends up");
256 if (Next)
257 // If the next terminator uses Reg, this means we have
258 // to split right after MI and thus we need a way to ask
259 // which outgoing edges are affected.
260 assert(!Next->readsRegister(Reg) && "Need to split between terminators");
261 // We will split all the edges and repair there.
262 } else {
263 // This is a virtual register defined by a terminator.
264 if (ValMapping.BreakDown.size() == 1) {
265 // There is nothing to repair, but we may actually lie on
266 // the repairing cost because of the PHIs already proceeded
267 // as already stated.
268 // Though the code will be correct.
269 assert(0 && "Repairing cost may not be accurate");
270 } else {
271 // We need to do non-local repairing. Basically, patch all
272 // the uses (i.e., phis) that we already proceeded.
273 // For now, just say this mapping is not possible.
274 RepairPt.switchTo(RepairingPlacement::RepairingKind::Impossible);
275 }
276 }
277}
278
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000279RegBankSelect::MappingCost RegBankSelect::computeMapping(
280 MachineInstr &MI, const RegisterBankInfo::InstructionMapping &InstrMapping,
Quentin Colombet6e80dbc2016-05-20 18:00:46 +0000281 SmallVectorImpl<RepairingPlacement> &RepairPts,
282 const RegBankSelect::MappingCost *BestCost) {
283 assert((MBFI || !BestCost) && "Costs comparison require MBFI");
Quentin Colombete16f5612016-04-07 23:53:55 +0000284
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000285 // If mapped with InstrMapping, MI will have the recorded cost.
Quentin Colombet25fcef72016-05-20 17:54:09 +0000286 MappingCost Cost(MBFI ? MBFI->getBlockFreq(MI.getParent()) : 1);
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000287 bool Saturated = Cost.addLocalCost(InstrMapping.getCost());
288 assert(!Saturated && "Possible mapping saturated the cost");
289 DEBUG(dbgs() << "Evaluating mapping cost for: " << MI);
290 DEBUG(dbgs() << "With: " << InstrMapping << '\n');
291 RepairPts.clear();
Quentin Colombet6e80dbc2016-05-20 18:00:46 +0000292 if (BestCost && Cost > *BestCost)
293 return Cost;
294
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000295 // Moreover, to realize this mapping, the register bank of each operand must
296 // match this mapping. In other words, we may need to locally reassign the
297 // register banks. Account for that repairing cost as well.
298 // In this context, local means in the surrounding of MI.
299 for (unsigned OpIdx = 0, EndOpIdx = MI.getNumOperands(); OpIdx != EndOpIdx;
Quentin Colombet40ad5732016-04-07 18:19:27 +0000300 ++OpIdx) {
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000301 const MachineOperand &MO = MI.getOperand(OpIdx);
Quentin Colombet40ad5732016-04-07 18:19:27 +0000302 if (!MO.isReg())
303 continue;
304 unsigned Reg = MO.getReg();
305 if (!Reg)
306 continue;
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000307 DEBUG(dbgs() << "Opd" << OpIdx);
Quentin Colombet40ad5732016-04-07 18:19:27 +0000308 const RegisterBankInfo::ValueMapping &ValMapping =
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000309 InstrMapping.getOperandMapping(OpIdx);
310 // If Reg is already properly mapped, this is free.
311 bool Assign;
312 if (assignmentMatch(Reg, ValMapping, Assign)) {
313 DEBUG(dbgs() << " is free (match).\n");
Quentin Colombet40ad5732016-04-07 18:19:27 +0000314 continue;
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000315 }
316 if (Assign) {
317 DEBUG(dbgs() << " is free (simple assignment).\n");
318 RepairPts.emplace_back(RepairingPlacement(MI, OpIdx, *TRI, *this,
319 RepairingPlacement::Reassign));
320 continue;
Quentin Colombet40ad5732016-04-07 18:19:27 +0000321 }
Quentin Colombet904a2c72016-04-12 00:12:59 +0000322
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000323 // TODO:
324 // Ask the repairing module how much it would cost to get this mapping.
325 // Use: NewSources <- Val.
326 // Same size: copy.
327 // Different size: Src1, Src2, ... =
328 // extract_value Val, Src1Begin, Src1Len, Src2Begin, Src2Len, ...
329 // Def: Val <- NewDefs
330 // Same size: copy
331 // Different size: Val = build_sequence Defs1, Defs2, ...
332 // We should remember that this value is available somewhere else to
333 // coalesce the value.
Quentin Colombet904a2c72016-04-12 00:12:59 +0000334
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000335 // Find the insertion point for the repairing code.
336 RepairPts.emplace_back(
337 RepairingPlacement(MI, OpIdx, *TRI, *this, RepairingPlacement::Insert));
338 RepairingPlacement &RepairPt = RepairPts.back();
339
Quentin Colombetf75c2bf2016-05-20 16:36:12 +0000340 // If we need to split a basic block to materialize this insertion point,
341 // we may give a higher cost to this mapping.
342 // Nevertheless, we may get away with the split, so try that first.
343 if (RepairPt.hasSplit())
344 tryAvoidingSplit(RepairPt, MO, ValMapping);
345
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000346 // Check that the materialization of the repairing is possible.
347 if (!RepairPt.canMaterialize())
348 return MappingCost::ImpossibleCost();
349
350 // Account for the split cost and repair cost.
Quentin Colombet6e80dbc2016-05-20 18:00:46 +0000351 // Unless the cost is already saturated or we do not care about the cost.
352 if (!BestCost || Saturated)
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000353 continue;
354
Quentin Colombet6e80dbc2016-05-20 18:00:46 +0000355 // To get accurate information we need MBFI and MBPI.
356 // Thus, if we end up here this information should be here.
357 assert(MBFI && MBPI && "Cost computation requires MBFI and MBPI");
358
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000359 // Sums up the repairing cost of at each insertion point.
360 // TODO: Get the actual repairing cost.
361 uint64_t RepairCost = 1;
362 // Bias used for splitting: 5%.
363 const uint64_t PercentageForBias = 5;
364 uint64_t Bias = (RepairCost * PercentageForBias + 99) / 100;
365 // We should not need more than a couple of instructions to repair
366 // an assignment. In other words, the computation should not
367 // overflow because the repairing cost is free of basic block
368 // frequency.
369 assert(((RepairCost < RepairCost * PercentageForBias) &&
370 (RepairCost * PercentageForBias <
371 RepairCost * PercentageForBias + 99)) &&
372 "Repairing involves more than a billion of instructions?!");
373 for (const std::unique_ptr<InsertPoint> &InsertPt : RepairPt) {
374 assert(InsertPt->canMaterialize() && "We should not have made it here");
375 // We will applied some basic block frequency and those uses uint64_t.
376 if (!InsertPt->isSplit())
377 Saturated = Cost.addLocalCost(RepairCost);
378 else {
379 uint64_t CostForInsertPt = RepairCost;
380 // Again we shouldn't overflow here givent that
381 // CostForInsertPt is frequency free at this point.
382 assert(CostForInsertPt + Bias > CostForInsertPt &&
383 "Repairing + split bias overflows");
384 CostForInsertPt += Bias;
385 uint64_t PtCost = InsertPt->frequency(*this) * CostForInsertPt;
386 // Check if we just overflowed.
387 if ((Saturated = PtCost < CostForInsertPt))
388 Cost.saturate();
389 else
390 Saturated = Cost.addNonLocalCost(PtCost);
391 }
Quentin Colombet6e80dbc2016-05-20 18:00:46 +0000392
393 // Stop looking into what it takes to repair, this is already
394 // too expensive.
395 if (BestCost && Cost > *BestCost)
396 return Cost;
397
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000398 // No need to accumulate more cost information.
399 // We need to still gather the repairing information though.
400 if (Saturated)
401 break;
402 }
Quentin Colombet40ad5732016-04-07 18:19:27 +0000403 }
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000404 return Cost;
405}
406
407void RegBankSelect::applyMapping(
408 MachineInstr &MI, const RegisterBankInfo::InstructionMapping &InstrMapping,
409 SmallVectorImpl<RegBankSelect::RepairingPlacement> &RepairPts) {
410 assert(InstrMapping.getID() == RegisterBankInfo::DefaultMappingID &&
411 "Rewriting of MI not implemented yet");
412 // First, place the repairing code.
413 bool NeedRewrite = false;
414 SmallVector<unsigned, 8> NewVRegs;
415 for (RepairingPlacement &RepairPt : RepairPts) {
416 assert(RepairPt.canMaterialize() &&
417 RepairPt.getKind() != RepairingPlacement::Impossible &&
418 "This mapping is impossible");
419 assert(RepairPt.getKind() != RepairingPlacement::None &&
420 "This should not make its way in the list");
421 unsigned OpIdx = RepairPt.getOpIdx();
422 MachineOperand &MO = MI.getOperand(OpIdx);
423 const RegisterBankInfo::ValueMapping &ValMapping =
424 InstrMapping.getOperandMapping(OpIdx);
425 unsigned BreakDownSize = ValMapping.BreakDown.size();
426 unsigned Reg = MO.getReg();
427 NeedRewrite = BreakDownSize != 1;
428
429 switch (RepairPt.getKind()) {
430 case RepairingPlacement::Reassign:
431 assert(BreakDownSize == 1 &&
432 "Reassignment should only be for simple mapping");
433 MRI->setRegBank(Reg, *ValMapping.BreakDown[0].RegBank);
434 break;
435 case RepairingPlacement::Insert:
436 // We need as many new virtual registers as the number of partial mapping.
437 for (const RegisterBankInfo::PartialMapping &PartMap :
438 ValMapping.BreakDown) {
439 unsigned Tmp = MRI->createGenericVirtualRegister(PartMap.Length);
440 MRI->setRegBank(Tmp, *PartMap.RegBank);
441 NewVRegs.push_back(Tmp);
442 }
443 repairReg(MO, ValMapping, RepairPt,
444 make_range(NewVRegs.end() - BreakDownSize, NewVRegs.end()));
445 break;
446 default:
447 llvm_unreachable("Other kind should not happen");
448 }
449 }
450 // Second, rewrite the instruction.
451 (void)NeedRewrite;
452 assert(!NeedRewrite && "Not implemented yet");
453}
454
455void RegBankSelect::assignInstr(MachineInstr &MI) {
456 DEBUG(dbgs() << "Assign: " << MI);
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000457 // Remember the repairing placement for all the operands.
458 SmallVector<RepairingPlacement, 4> RepairPts;
459
Quentin Colombet79fe1be2016-05-20 18:37:33 +0000460 RegisterBankInfo::InstructionMapping BestMapping;
461 if (OptMode == RegBankSelect::Mode::Fast) {
462 BestMapping = RBI->getInstrMapping(MI);
463 MappingCost DefaultCost = computeMapping(MI, BestMapping, RepairPts);
464 (void)DefaultCost;
465 assert(DefaultCost != MappingCost::ImpossibleCost() &&
466 "Default mapping is not suited");
467 } else {
468 RegisterBankInfo::InstructionMappings PossibleMappings =
469 RBI->getInstrPossibleMappings(MI);
470 assert(!PossibleMappings.empty() &&
471 "Do not know how to map this instruction");
472 BestMapping = std::move(findBestMapping(MI, PossibleMappings, RepairPts));
473 }
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000474 // Make sure the mapping is valid for MI.
Quentin Colombet79fe1be2016-05-20 18:37:33 +0000475 assert(BestMapping.verify(MI) && "Invalid instruction mapping");
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000476
Quentin Colombet79fe1be2016-05-20 18:37:33 +0000477 DEBUG(dbgs() << "Mapping: " << BestMapping << '\n');
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000478
Quentin Colombet79fe1be2016-05-20 18:37:33 +0000479 applyMapping(MI, BestMapping, RepairPts);
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000480
Quentin Colombete16f5612016-04-07 23:53:55 +0000481 DEBUG(dbgs() << "Assigned: " << MI);
Quentin Colombet40ad5732016-04-07 18:19:27 +0000482}
483
Quentin Colombet8e8e85c2016-04-05 19:06:01 +0000484bool RegBankSelect::runOnMachineFunction(MachineFunction &MF) {
Quentin Colombete16f5612016-04-07 23:53:55 +0000485 DEBUG(dbgs() << "Assign register banks for: " << MF.getName() << '\n');
Quentin Colombeta5530122016-05-20 17:36:54 +0000486 const Function *F = MF.getFunction();
487 Mode SaveOptMode = OptMode;
488 if (F->hasFnAttribute(Attribute::OptimizeNone))
489 OptMode = Mode::Fast;
Quentin Colombet40ad5732016-04-07 18:19:27 +0000490 init(MF);
491 // Walk the function and assign register banks to all operands.
Quentin Colombetab8c21f2016-04-08 17:19:10 +0000492 // Use a RPOT to make sure all registers are assigned before we choose
493 // the best mapping of the current instruction.
494 ReversePostOrderTraversal<MachineFunction*> RPOT(&MF);
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000495 for (MachineBasicBlock *MBB : RPOT) {
496 // Set a sensible insertion point so that subsequent calls to
497 // MIRBuilder.
498 MIRBuilder.setMBB(*MBB);
Quentin Colombetab8c21f2016-04-08 17:19:10 +0000499 for (MachineInstr &MI : *MBB)
Quentin Colombet40ad5732016-04-07 18:19:27 +0000500 assignInstr(MI);
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000501 }
Quentin Colombeta5530122016-05-20 17:36:54 +0000502 OptMode = SaveOptMode;
Quentin Colombet8e8e85c2016-04-05 19:06:01 +0000503 return false;
504}
Quentin Colombetcfd97b92016-05-20 00:35:26 +0000505
506//------------------------------------------------------------------------------
Quentin Colombet55650752016-05-20 00:49:10 +0000507// Helper Classes Implementation
Quentin Colombetcfd97b92016-05-20 00:35:26 +0000508//------------------------------------------------------------------------------
Quentin Colombet55650752016-05-20 00:49:10 +0000509RegBankSelect::RepairingPlacement::RepairingPlacement(
510 MachineInstr &MI, unsigned OpIdx, const TargetRegisterInfo &TRI, Pass &P,
511 RepairingPlacement::RepairingKind Kind)
512 // Default is, we are going to insert code to repair OpIdx.
513 : Kind(Kind),
514 OpIdx(OpIdx),
515 CanMaterialize(Kind != RepairingKind::Impossible),
516 HasSplit(false),
517 P(P) {
518 const MachineOperand &MO = MI.getOperand(OpIdx);
519 assert(MO.isReg() && "Trying to repair a non-reg operand");
520
521 if (Kind != RepairingKind::Insert)
522 return;
523
524 // Repairings for definitions happen after MI, uses happen before.
525 bool Before = !MO.isDef();
526
527 // Check if we are done with MI.
528 if (!MI.isPHI() && !MI.isTerminator()) {
529 addInsertPoint(MI, Before);
530 // We are done with the initialization.
531 return;
532 }
533
534 // Now, look for the special cases.
535 if (MI.isPHI()) {
536 // - PHI must be the first instructions:
537 // * Before, we have to split the related incoming edge.
538 // * After, move the insertion point past the last phi.
539 if (!Before) {
540 MachineBasicBlock::iterator It = MI.getParent()->getFirstNonPHI();
541 if (It != MI.getParent()->end())
542 addInsertPoint(*It, /*Before*/ true);
543 else
544 addInsertPoint(*(--It), /*Before*/ false);
545 return;
546 }
547 // We repair a use of a phi, we may need to split the related edge.
548 MachineBasicBlock &Pred = *MI.getOperand(OpIdx + 1).getMBB();
549 // Check if we can move the insertion point prior to the
550 // terminators of the predecessor.
551 unsigned Reg = MO.getReg();
552 MachineBasicBlock::iterator It = Pred.getLastNonDebugInstr();
553 for (auto Begin = Pred.begin(); It != Begin && It->isTerminator(); --It)
554 if (It->modifiesRegister(Reg, &TRI)) {
555 // We cannot hoist the repairing code in the predecessor.
556 // Split the edge.
557 addInsertPoint(Pred, *MI.getParent());
558 return;
559 }
560 // At this point, we can insert in Pred.
561
562 // - If It is invalid, Pred is empty and we can insert in Pred
563 // wherever we want.
564 // - If It is valid, It is the first non-terminator, insert after It.
565 if (It == Pred.end())
566 addInsertPoint(Pred, /*Beginning*/ false);
567 else
568 addInsertPoint(*It, /*Before*/ false);
569 } else {
570 // - Terminators must be the last instructions:
571 // * Before, move the insert point before the first terminator.
572 // * After, we have to split the outcoming edges.
573 unsigned Reg = MO.getReg();
574 if (Before) {
575 // Check whether Reg is defined by any terminator.
576 MachineBasicBlock::iterator It = MI;
577 for (auto Begin = MI.getParent()->begin();
578 --It != Begin && It->isTerminator();)
579 if (It->modifiesRegister(Reg, &TRI)) {
580 // Insert the repairing code right after the definition.
581 addInsertPoint(*It, /*Before*/ false);
582 return;
583 }
584 addInsertPoint(*It, /*Before*/ true);
585 return;
586 }
587 // Make sure Reg is not redefined by other terminators, otherwise
588 // we do not know how to split.
589 for (MachineBasicBlock::iterator It = MI, End = MI.getParent()->end();
590 ++It != End;)
591 // The machine verifier should reject this kind of code.
592 assert(It->modifiesRegister(Reg, &TRI) && "Do not know where to split");
593 // Split each outcoming edges.
594 MachineBasicBlock &Src = *MI.getParent();
595 for (auto &Succ : Src.successors())
596 addInsertPoint(Src, Succ);
597 }
598}
599
600void RegBankSelect::RepairingPlacement::addInsertPoint(MachineInstr &MI,
601 bool Before) {
602 addInsertPoint(*new InstrInsertPoint(MI, Before));
603}
604
605void RegBankSelect::RepairingPlacement::addInsertPoint(MachineBasicBlock &MBB,
606 bool Beginning) {
607 addInsertPoint(*new MBBInsertPoint(MBB, Beginning));
608}
609
610void RegBankSelect::RepairingPlacement::addInsertPoint(MachineBasicBlock &Src,
611 MachineBasicBlock &Dst) {
612 addInsertPoint(*new EdgeInsertPoint(Src, Dst, P));
613}
614
615void RegBankSelect::RepairingPlacement::addInsertPoint(
616 RegBankSelect::InsertPoint &Point) {
617 CanMaterialize &= Point.canMaterialize();
618 HasSplit |= Point.isSplit();
619 InsertPoints.emplace_back(&Point);
620}
621
622RegBankSelect::InstrInsertPoint::InstrInsertPoint(MachineInstr &Instr,
623 bool Before)
624 : InsertPoint(), Instr(Instr), Before(Before) {
625 // Since we do not support splitting, we do not need to update
626 // liveness and such, so do not do anything with P.
627 assert((!Before || !Instr.isPHI()) &&
628 "Splitting before phis requires more points");
629 assert((!Before || !Instr.getNextNode() || !Instr.getNextNode()->isPHI()) &&
630 "Splitting between phis does not make sense");
631}
632
633void RegBankSelect::InstrInsertPoint::materialize() {
634 if (isSplit()) {
635 // Slice and return the beginning of the new block.
636 // If we need to split between the terminators, we theoritically
637 // need to know where the first and second set of terminators end
638 // to update the successors properly.
639 // Now, in pratice, we should have a maximum of 2 branch
640 // instructions; one conditional and one unconditional. Therefore
641 // we know how to update the successor by looking at the target of
642 // the unconditional branch.
643 // If we end up splitting at some point, then, we should update
644 // the liveness information and such. I.e., we would need to
645 // access P here.
646 // The machine verifier should actually make sure such cases
647 // cannot happen.
648 llvm_unreachable("Not yet implemented");
649 }
650 // Otherwise the insertion point is just the current or next
651 // instruction depending on Before. I.e., there is nothing to do
652 // here.
653}
654
655bool RegBankSelect::InstrInsertPoint::isSplit() const {
656 // If the insertion point is after a terminator, we need to split.
657 if (!Before)
658 return Instr.isTerminator();
659 // If we insert before an instruction that is after a terminator,
660 // we are still after a terminator.
661 return Instr.getPrevNode() && Instr.getPrevNode()->isTerminator();
662}
663
664uint64_t RegBankSelect::InstrInsertPoint::frequency(const Pass &P) const {
665 // Even if we need to split, because we insert between terminators,
666 // this split has actually the same frequency as the instruction.
667 const MachineBlockFrequencyInfo *MBFI =
668 P.getAnalysisIfAvailable<MachineBlockFrequencyInfo>();
669 if (!MBFI)
670 return 1;
671 return MBFI->getBlockFreq(Instr.getParent()).getFrequency();
672}
673
674uint64_t RegBankSelect::MBBInsertPoint::frequency(const Pass &P) const {
675 const MachineBlockFrequencyInfo *MBFI =
676 P.getAnalysisIfAvailable<MachineBlockFrequencyInfo>();
677 if (!MBFI)
678 return 1;
679 return MBFI->getBlockFreq(&MBB).getFrequency();
680}
681
682void RegBankSelect::EdgeInsertPoint::materialize() {
683 // If we end up repairing twice at the same place before materializing the
684 // insertion point, we may think we have to split an edge twice.
685 // We should have a factory for the insert point such that identical points
686 // are the same instance.
687 assert(Src.isSuccessor(DstOrSplit) && DstOrSplit->isPredecessor(&Src) &&
688 "This point has already been split");
689 MachineBasicBlock *NewBB = Src.SplitCriticalEdge(DstOrSplit, P);
690 assert(NewBB && "Invalid call to materialize");
691 // We reuse the destination block to hold the information of the new block.
692 DstOrSplit = NewBB;
693}
694
695uint64_t RegBankSelect::EdgeInsertPoint::frequency(const Pass &P) const {
696 const MachineBlockFrequencyInfo *MBFI =
697 P.getAnalysisIfAvailable<MachineBlockFrequencyInfo>();
698 if (!MBFI)
699 return 1;
700 if (WasMaterialized)
701 return MBFI->getBlockFreq(DstOrSplit).getFrequency();
702
703 const MachineBranchProbabilityInfo *MBPI =
704 P.getAnalysisIfAvailable<MachineBranchProbabilityInfo>();
705 if (!MBPI)
706 return 1;
707 // The basic block will be on the edge.
708 return (MBFI->getBlockFreq(&Src) * MBPI->getEdgeProbability(&Src, DstOrSplit))
709 .getFrequency();
710}
711
712bool RegBankSelect::EdgeInsertPoint::canMaterialize() const {
713 // If this is not a critical edge, we should not have used this insert
714 // point. Indeed, either the successor or the predecessor should
715 // have do.
716 assert(Src.succ_size() > 1 && DstOrSplit->pred_size() > 1 &&
717 "Edge is not critical");
718 return Src.canSplitCriticalEdge(DstOrSplit);
719}
720
Quentin Colombetcfd97b92016-05-20 00:35:26 +0000721RegBankSelect::MappingCost::MappingCost(const BlockFrequency &LocalFreq)
722 : LocalCost(0), NonLocalCost(0), LocalFreq(LocalFreq.getFrequency()) {}
723
724bool RegBankSelect::MappingCost::addLocalCost(uint64_t Cost) {
725 // Check if this overflows.
726 if (LocalCost + Cost < LocalCost) {
727 saturate();
728 return true;
729 }
730 LocalCost += Cost;
731 return isSaturated();
732}
733
734bool RegBankSelect::MappingCost::addNonLocalCost(uint64_t Cost) {
735 // Check if this overflows.
736 if (NonLocalCost + Cost < NonLocalCost) {
737 saturate();
738 return true;
739 }
740 NonLocalCost += Cost;
741 return isSaturated();
742}
743
744bool RegBankSelect::MappingCost::isSaturated() const {
745 return LocalCost == UINT64_MAX - 1 && NonLocalCost == UINT64_MAX &&
746 LocalFreq == UINT64_MAX;
747}
748
749void RegBankSelect::MappingCost::saturate() {
750 *this = ImpossibleCost();
751 --LocalCost;
752}
753
754RegBankSelect::MappingCost RegBankSelect::MappingCost::ImpossibleCost() {
755 return MappingCost(UINT64_MAX, UINT64_MAX, UINT64_MAX);
756}
757
758bool RegBankSelect::MappingCost::operator<(const MappingCost &Cost) const {
759 // Sort out the easy cases.
760 if (*this == Cost)
761 return false;
762 // If one is impossible to realize the other is cheaper unless it is
763 // impossible as well.
764 if ((*this == ImpossibleCost()) || (Cost == ImpossibleCost()))
765 return (*this == ImpossibleCost()) < (Cost == ImpossibleCost());
766 // If one is saturated the other is cheaper, unless it is saturated
767 // as well.
768 if (isSaturated() || Cost.isSaturated())
769 return isSaturated() < Cost.isSaturated();
770 // At this point we know both costs hold sensible values.
771
772 // If both values have a different base frequency, there is no much
773 // we can do but to scale everything.
774 // However, if they have the same base frequency we can avoid making
775 // complicated computation.
776 uint64_t ThisLocalAdjust;
777 uint64_t OtherLocalAdjust;
778 if (LLVM_LIKELY(LocalFreq == Cost.LocalFreq)) {
779
780 // At this point, we know the local costs are comparable.
781 // Do the case that do not involve potential overflow first.
782 if (NonLocalCost == Cost.NonLocalCost)
783 // Since the non-local costs do not discriminate on the result,
784 // just compare the local costs.
785 return LocalCost < Cost.LocalCost;
786
787 // The base costs are comparable so we may only keep the relative
788 // value to increase our chances of avoiding overflows.
789 ThisLocalAdjust = 0;
790 OtherLocalAdjust = 0;
791 if (LocalCost < Cost.LocalCost)
792 OtherLocalAdjust = Cost.LocalCost - LocalCost;
793 else
794 ThisLocalAdjust = LocalCost - Cost.LocalCost;
795
796 } else {
797 ThisLocalAdjust = LocalCost;
798 OtherLocalAdjust = Cost.LocalCost;
799 }
800
801 // The non-local costs are comparable, just keep the relative value.
802 uint64_t ThisNonLocalAdjust = 0;
803 uint64_t OtherNonLocalAdjust = 0;
804 if (NonLocalCost < Cost.NonLocalCost)
805 OtherNonLocalAdjust = Cost.NonLocalCost - NonLocalCost;
806 else
807 ThisNonLocalAdjust = NonLocalCost - Cost.NonLocalCost;
808 // Scale everything to make them comparable.
809 uint64_t ThisScaledCost = ThisLocalAdjust * LocalFreq;
810 // Check for overflow on that operation.
811 bool ThisOverflows = ThisLocalAdjust && (ThisScaledCost < ThisLocalAdjust ||
812 ThisScaledCost < LocalFreq);
813 uint64_t OtherScaledCost = OtherLocalAdjust * Cost.LocalFreq;
814 // Check for overflow on the last operation.
815 bool OtherOverflows =
816 OtherLocalAdjust &&
817 (OtherScaledCost < OtherLocalAdjust || OtherScaledCost < Cost.LocalFreq);
818 // Add the non-local costs.
819 ThisOverflows |= ThisNonLocalAdjust &&
820 ThisScaledCost + ThisNonLocalAdjust < ThisNonLocalAdjust;
821 ThisScaledCost += ThisNonLocalAdjust;
822 OtherOverflows |= OtherNonLocalAdjust &&
823 OtherScaledCost + OtherNonLocalAdjust < OtherNonLocalAdjust;
824 OtherScaledCost += OtherNonLocalAdjust;
825 // If both overflows, we cannot compare without additional
826 // precision, e.g., APInt. Just give up on that case.
827 if (ThisOverflows && OtherOverflows)
828 return false;
829 // If one overflows but not the other, we can still compare.
830 if (ThisOverflows || OtherOverflows)
831 return ThisOverflows < OtherOverflows;
832 // Otherwise, just compare the values.
833 return ThisScaledCost < OtherScaledCost;
834}
835
836bool RegBankSelect::MappingCost::operator==(const MappingCost &Cost) const {
837 return LocalCost == Cost.LocalCost && NonLocalCost == Cost.NonLocalCost &&
838 LocalFreq == Cost.LocalFreq;
839}