[Alignment][NFC] Convert StoreInst to MaybeAlign
[llvm-complete.git] / lib / CodeGen / GlobalISel / RegisterBankInfo.cpp
blob3fcc55286bebb0654e3efa2ddf6f45301a9f35ef
1 //===- llvm/CodeGen/GlobalISel/RegisterBankInfo.cpp --------------*- C++ -*-==//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 /// \file
9 /// This file implements the RegisterBankInfo class.
10 //===----------------------------------------------------------------------===//
12 #include "llvm/CodeGen/GlobalISel/RegisterBankInfo.h"
13 #include "llvm/ADT/SmallString.h"
14 #include "llvm/ADT/SmallVector.h"
15 #include "llvm/ADT/Statistic.h"
16 #include "llvm/ADT/iterator_range.h"
17 #include "llvm/CodeGen/GlobalISel/RegisterBank.h"
18 #include "llvm/CodeGen/MachineBasicBlock.h"
19 #include "llvm/CodeGen/MachineFunction.h"
20 #include "llvm/CodeGen/MachineRegisterInfo.h"
21 #include "llvm/CodeGen/TargetOpcodes.h"
22 #include "llvm/CodeGen/TargetRegisterInfo.h"
23 #include "llvm/CodeGen/TargetSubtargetInfo.h"
24 #include "llvm/Config/llvm-config.h"
25 #include "llvm/IR/Type.h"
26 #include "llvm/Support/Debug.h"
27 #include "llvm/Support/raw_ostream.h"
29 #include <algorithm> // For std::max.
31 #define DEBUG_TYPE "registerbankinfo"
33 using namespace llvm;
35 STATISTIC(NumPartialMappingsCreated,
36 "Number of partial mappings dynamically created");
37 STATISTIC(NumPartialMappingsAccessed,
38 "Number of partial mappings dynamically accessed");
39 STATISTIC(NumValueMappingsCreated,
40 "Number of value mappings dynamically created");
41 STATISTIC(NumValueMappingsAccessed,
42 "Number of value mappings dynamically accessed");
43 STATISTIC(NumOperandsMappingsCreated,
44 "Number of operands mappings dynamically created");
45 STATISTIC(NumOperandsMappingsAccessed,
46 "Number of operands mappings dynamically accessed");
47 STATISTIC(NumInstructionMappingsCreated,
48 "Number of instruction mappings dynamically created");
49 STATISTIC(NumInstructionMappingsAccessed,
50 "Number of instruction mappings dynamically accessed");
52 const unsigned RegisterBankInfo::DefaultMappingID = UINT_MAX;
53 const unsigned RegisterBankInfo::InvalidMappingID = UINT_MAX - 1;
55 //------------------------------------------------------------------------------
56 // RegisterBankInfo implementation.
57 //------------------------------------------------------------------------------
58 RegisterBankInfo::RegisterBankInfo(RegisterBank **RegBanks,
59 unsigned NumRegBanks)
60 : RegBanks(RegBanks), NumRegBanks(NumRegBanks) {
61 #ifndef NDEBUG
62 for (unsigned Idx = 0, End = getNumRegBanks(); Idx != End; ++Idx) {
63 assert(RegBanks[Idx] != nullptr && "Invalid RegisterBank");
64 assert(RegBanks[Idx]->isValid() && "RegisterBank should be valid");
66 #endif // NDEBUG
69 bool RegisterBankInfo::verify(const TargetRegisterInfo &TRI) const {
70 #ifndef NDEBUG
71 for (unsigned Idx = 0, End = getNumRegBanks(); Idx != End; ++Idx) {
72 const RegisterBank &RegBank = getRegBank(Idx);
73 assert(Idx == RegBank.getID() &&
74 "ID does not match the index in the array");
75 LLVM_DEBUG(dbgs() << "Verify " << RegBank << '\n');
76 assert(RegBank.verify(TRI) && "RegBank is invalid");
78 #endif // NDEBUG
79 return true;
82 const RegisterBank *
83 RegisterBankInfo::getRegBank(Register Reg, const MachineRegisterInfo &MRI,
84 const TargetRegisterInfo &TRI) const {
85 if (Register::isPhysicalRegister(Reg))
86 return &getRegBankFromRegClass(getMinimalPhysRegClass(Reg, TRI));
88 assert(Reg && "NoRegister does not have a register bank");
89 const RegClassOrRegBank &RegClassOrBank = MRI.getRegClassOrRegBank(Reg);
90 if (auto *RB = RegClassOrBank.dyn_cast<const RegisterBank *>())
91 return RB;
92 if (auto *RC = RegClassOrBank.dyn_cast<const TargetRegisterClass *>())
93 return &getRegBankFromRegClass(*RC);
94 return nullptr;
97 const TargetRegisterClass &
98 RegisterBankInfo::getMinimalPhysRegClass(Register Reg,
99 const TargetRegisterInfo &TRI) const {
100 assert(Register::isPhysicalRegister(Reg) && "Reg must be a physreg");
101 const auto &RegRCIt = PhysRegMinimalRCs.find(Reg);
102 if (RegRCIt != PhysRegMinimalRCs.end())
103 return *RegRCIt->second;
104 const TargetRegisterClass *PhysRC = TRI.getMinimalPhysRegClass(Reg);
105 PhysRegMinimalRCs[Reg] = PhysRC;
106 return *PhysRC;
109 const RegisterBank *RegisterBankInfo::getRegBankFromConstraints(
110 const MachineInstr &MI, unsigned OpIdx, const TargetInstrInfo &TII,
111 const TargetRegisterInfo &TRI) const {
112 // The mapping of the registers may be available via the
113 // register class constraints.
114 const TargetRegisterClass *RC = MI.getRegClassConstraint(OpIdx, &TII, &TRI);
116 if (!RC)
117 return nullptr;
119 const RegisterBank &RegBank = getRegBankFromRegClass(*RC);
120 // Sanity check that the target properly implemented getRegBankFromRegClass.
121 assert(RegBank.covers(*RC) &&
122 "The mapping of the register bank does not make sense");
123 return &RegBank;
126 const TargetRegisterClass *RegisterBankInfo::constrainGenericRegister(
127 Register Reg, const TargetRegisterClass &RC, MachineRegisterInfo &MRI) {
129 // If the register already has a class, fallback to MRI::constrainRegClass.
130 auto &RegClassOrBank = MRI.getRegClassOrRegBank(Reg);
131 if (RegClassOrBank.is<const TargetRegisterClass *>())
132 return MRI.constrainRegClass(Reg, &RC);
134 const RegisterBank *RB = RegClassOrBank.get<const RegisterBank *>();
135 // Otherwise, all we can do is ensure the bank covers the class, and set it.
136 if (RB && !RB->covers(RC))
137 return nullptr;
139 // If nothing was set or the class is simply compatible, set it.
140 MRI.setRegClass(Reg, &RC);
141 return &RC;
144 /// Check whether or not \p MI should be treated like a copy
145 /// for the mappings.
146 /// Copy like instruction are special for mapping because
147 /// they don't have actual register constraints. Moreover,
148 /// they sometimes have register classes assigned and we can
149 /// just use that instead of failing to provide a generic mapping.
150 static bool isCopyLike(const MachineInstr &MI) {
151 return MI.isCopy() || MI.isPHI() ||
152 MI.getOpcode() == TargetOpcode::REG_SEQUENCE;
155 const RegisterBankInfo::InstructionMapping &
156 RegisterBankInfo::getInstrMappingImpl(const MachineInstr &MI) const {
157 // For copies we want to walk over the operands and try to find one
158 // that has a register bank since the instruction itself will not get
159 // us any constraint.
160 bool IsCopyLike = isCopyLike(MI);
161 // For copy like instruction, only the mapping of the definition
162 // is important. The rest is not constrained.
163 unsigned NumOperandsForMapping = IsCopyLike ? 1 : MI.getNumOperands();
165 const MachineFunction &MF = *MI.getMF();
166 const TargetSubtargetInfo &STI = MF.getSubtarget();
167 const TargetRegisterInfo &TRI = *STI.getRegisterInfo();
168 const MachineRegisterInfo &MRI = MF.getRegInfo();
169 // We may need to query the instruction encoding to guess the mapping.
170 const TargetInstrInfo &TII = *STI.getInstrInfo();
172 // Before doing anything complicated check if the mapping is not
173 // directly available.
174 bool CompleteMapping = true;
176 SmallVector<const ValueMapping *, 8> OperandsMapping(NumOperandsForMapping);
177 for (unsigned OpIdx = 0, EndIdx = MI.getNumOperands(); OpIdx != EndIdx;
178 ++OpIdx) {
179 const MachineOperand &MO = MI.getOperand(OpIdx);
180 if (!MO.isReg())
181 continue;
182 Register Reg = MO.getReg();
183 if (!Reg)
184 continue;
185 // The register bank of Reg is just a side effect of the current
186 // excution and in particular, there is no reason to believe this
187 // is the best default mapping for the current instruction. Keep
188 // it as an alternative register bank if we cannot figure out
189 // something.
190 const RegisterBank *AltRegBank = getRegBank(Reg, MRI, TRI);
191 // For copy-like instruction, we want to reuse the register bank
192 // that is already set on Reg, if any, since those instructions do
193 // not have any constraints.
194 const RegisterBank *CurRegBank = IsCopyLike ? AltRegBank : nullptr;
195 if (!CurRegBank) {
196 // If this is a target specific instruction, we can deduce
197 // the register bank from the encoding constraints.
198 CurRegBank = getRegBankFromConstraints(MI, OpIdx, TII, TRI);
199 if (!CurRegBank) {
200 // All our attempts failed, give up.
201 CompleteMapping = false;
203 if (!IsCopyLike)
204 // MI does not carry enough information to guess the mapping.
205 return getInvalidInstructionMapping();
206 continue;
210 unsigned Size = getSizeInBits(Reg, MRI, TRI);
211 const ValueMapping *ValMapping = &getValueMapping(0, Size, *CurRegBank);
212 if (IsCopyLike) {
213 if (!OperandsMapping[0]) {
214 if (MI.isRegSequence()) {
215 // For reg_sequence, the result size does not match the input.
216 unsigned ResultSize = getSizeInBits(MI.getOperand(0).getReg(),
217 MRI, TRI);
218 OperandsMapping[0] = &getValueMapping(0, ResultSize, *CurRegBank);
219 } else {
220 OperandsMapping[0] = ValMapping;
224 // The default handling assumes any register bank can be copied to any
225 // other. If this isn't the case, the target should specially deal with
226 // reg_sequence/phi. There may also be unsatisfiable copies.
227 for (; OpIdx != EndIdx; ++OpIdx) {
228 const MachineOperand &MO = MI.getOperand(OpIdx);
229 if (!MO.isReg())
230 continue;
231 Register Reg = MO.getReg();
232 if (!Reg)
233 continue;
235 const RegisterBank *AltRegBank = getRegBank(Reg, MRI, TRI);
236 if (AltRegBank &&
237 cannotCopy(*CurRegBank, *AltRegBank, getSizeInBits(Reg, MRI, TRI)))
238 return getInvalidInstructionMapping();
241 CompleteMapping = true;
242 break;
245 OperandsMapping[OpIdx] = ValMapping;
248 if (IsCopyLike && !CompleteMapping) {
249 // No way to deduce the type from what we have.
250 return getInvalidInstructionMapping();
253 assert(CompleteMapping && "Setting an uncomplete mapping");
254 return getInstructionMapping(
255 DefaultMappingID, /*Cost*/ 1,
256 /*OperandsMapping*/ getOperandsMapping(OperandsMapping),
257 NumOperandsForMapping);
260 /// Hashing function for PartialMapping.
261 static hash_code hashPartialMapping(unsigned StartIdx, unsigned Length,
262 const RegisterBank *RegBank) {
263 return hash_combine(StartIdx, Length, RegBank ? RegBank->getID() : 0);
266 /// Overloaded version of hash_value for a PartialMapping.
267 hash_code
268 llvm::hash_value(const RegisterBankInfo::PartialMapping &PartMapping) {
269 return hashPartialMapping(PartMapping.StartIdx, PartMapping.Length,
270 PartMapping.RegBank);
273 const RegisterBankInfo::PartialMapping &
274 RegisterBankInfo::getPartialMapping(unsigned StartIdx, unsigned Length,
275 const RegisterBank &RegBank) const {
276 ++NumPartialMappingsAccessed;
278 hash_code Hash = hashPartialMapping(StartIdx, Length, &RegBank);
279 const auto &It = MapOfPartialMappings.find(Hash);
280 if (It != MapOfPartialMappings.end())
281 return *It->second;
283 ++NumPartialMappingsCreated;
285 auto &PartMapping = MapOfPartialMappings[Hash];
286 PartMapping = std::make_unique<PartialMapping>(StartIdx, Length, RegBank);
287 return *PartMapping;
290 const RegisterBankInfo::ValueMapping &
291 RegisterBankInfo::getValueMapping(unsigned StartIdx, unsigned Length,
292 const RegisterBank &RegBank) const {
293 return getValueMapping(&getPartialMapping(StartIdx, Length, RegBank), 1);
296 static hash_code
297 hashValueMapping(const RegisterBankInfo::PartialMapping *BreakDown,
298 unsigned NumBreakDowns) {
299 if (LLVM_LIKELY(NumBreakDowns == 1))
300 return hash_value(*BreakDown);
301 SmallVector<size_t, 8> Hashes(NumBreakDowns);
302 for (unsigned Idx = 0; Idx != NumBreakDowns; ++Idx)
303 Hashes.push_back(hash_value(BreakDown[Idx]));
304 return hash_combine_range(Hashes.begin(), Hashes.end());
307 const RegisterBankInfo::ValueMapping &
308 RegisterBankInfo::getValueMapping(const PartialMapping *BreakDown,
309 unsigned NumBreakDowns) const {
310 ++NumValueMappingsAccessed;
312 hash_code Hash = hashValueMapping(BreakDown, NumBreakDowns);
313 const auto &It = MapOfValueMappings.find(Hash);
314 if (It != MapOfValueMappings.end())
315 return *It->second;
317 ++NumValueMappingsCreated;
319 auto &ValMapping = MapOfValueMappings[Hash];
320 ValMapping = std::make_unique<ValueMapping>(BreakDown, NumBreakDowns);
321 return *ValMapping;
324 template <typename Iterator>
325 const RegisterBankInfo::ValueMapping *
326 RegisterBankInfo::getOperandsMapping(Iterator Begin, Iterator End) const {
328 ++NumOperandsMappingsAccessed;
330 // The addresses of the value mapping are unique.
331 // Therefore, we can use them directly to hash the operand mapping.
332 hash_code Hash = hash_combine_range(Begin, End);
333 auto &Res = MapOfOperandsMappings[Hash];
334 if (Res)
335 return Res.get();
337 ++NumOperandsMappingsCreated;
339 // Create the array of ValueMapping.
340 // Note: this array will not hash to this instance of operands
341 // mapping, because we use the pointer of the ValueMapping
342 // to hash and we expect them to uniquely identify an instance
343 // of value mapping.
344 Res = std::make_unique<ValueMapping[]>(std::distance(Begin, End));
345 unsigned Idx = 0;
346 for (Iterator It = Begin; It != End; ++It, ++Idx) {
347 const ValueMapping *ValMap = *It;
348 if (!ValMap)
349 continue;
350 Res[Idx] = *ValMap;
352 return Res.get();
355 const RegisterBankInfo::ValueMapping *RegisterBankInfo::getOperandsMapping(
356 const SmallVectorImpl<const RegisterBankInfo::ValueMapping *> &OpdsMapping)
357 const {
358 return getOperandsMapping(OpdsMapping.begin(), OpdsMapping.end());
361 const RegisterBankInfo::ValueMapping *RegisterBankInfo::getOperandsMapping(
362 std::initializer_list<const RegisterBankInfo::ValueMapping *> OpdsMapping)
363 const {
364 return getOperandsMapping(OpdsMapping.begin(), OpdsMapping.end());
367 static hash_code
368 hashInstructionMapping(unsigned ID, unsigned Cost,
369 const RegisterBankInfo::ValueMapping *OperandsMapping,
370 unsigned NumOperands) {
371 return hash_combine(ID, Cost, OperandsMapping, NumOperands);
374 const RegisterBankInfo::InstructionMapping &
375 RegisterBankInfo::getInstructionMappingImpl(
376 bool IsInvalid, unsigned ID, unsigned Cost,
377 const RegisterBankInfo::ValueMapping *OperandsMapping,
378 unsigned NumOperands) const {
379 assert(((IsInvalid && ID == InvalidMappingID && Cost == 0 &&
380 OperandsMapping == nullptr && NumOperands == 0) ||
381 !IsInvalid) &&
382 "Mismatch argument for invalid input");
383 ++NumInstructionMappingsAccessed;
385 hash_code Hash =
386 hashInstructionMapping(ID, Cost, OperandsMapping, NumOperands);
387 const auto &It = MapOfInstructionMappings.find(Hash);
388 if (It != MapOfInstructionMappings.end())
389 return *It->second;
391 ++NumInstructionMappingsCreated;
393 auto &InstrMapping = MapOfInstructionMappings[Hash];
394 InstrMapping = std::make_unique<InstructionMapping>(
395 ID, Cost, OperandsMapping, NumOperands);
396 return *InstrMapping;
399 const RegisterBankInfo::InstructionMapping &
400 RegisterBankInfo::getInstrMapping(const MachineInstr &MI) const {
401 const RegisterBankInfo::InstructionMapping &Mapping = getInstrMappingImpl(MI);
402 if (Mapping.isValid())
403 return Mapping;
404 llvm_unreachable("The target must implement this");
407 RegisterBankInfo::InstructionMappings
408 RegisterBankInfo::getInstrPossibleMappings(const MachineInstr &MI) const {
409 InstructionMappings PossibleMappings;
410 const auto &Mapping = getInstrMapping(MI);
411 if (Mapping.isValid()) {
412 // Put the default mapping first.
413 PossibleMappings.push_back(&Mapping);
416 // Then the alternative mapping, if any.
417 InstructionMappings AltMappings = getInstrAlternativeMappings(MI);
418 for (const InstructionMapping *AltMapping : AltMappings)
419 PossibleMappings.push_back(AltMapping);
420 #ifndef NDEBUG
421 for (const InstructionMapping *Mapping : PossibleMappings)
422 assert(Mapping->verify(MI) && "Mapping is invalid");
423 #endif
424 return PossibleMappings;
427 RegisterBankInfo::InstructionMappings
428 RegisterBankInfo::getInstrAlternativeMappings(const MachineInstr &MI) const {
429 // No alternative for MI.
430 return InstructionMappings();
433 void RegisterBankInfo::applyDefaultMapping(const OperandsMapper &OpdMapper) {
434 MachineInstr &MI = OpdMapper.getMI();
435 MachineRegisterInfo &MRI = OpdMapper.getMRI();
436 LLVM_DEBUG(dbgs() << "Applying default-like mapping\n");
437 for (unsigned OpIdx = 0,
438 EndIdx = OpdMapper.getInstrMapping().getNumOperands();
439 OpIdx != EndIdx; ++OpIdx) {
440 LLVM_DEBUG(dbgs() << "OpIdx " << OpIdx);
441 MachineOperand &MO = MI.getOperand(OpIdx);
442 if (!MO.isReg()) {
443 LLVM_DEBUG(dbgs() << " is not a register, nothing to be done\n");
444 continue;
446 if (!MO.getReg()) {
447 LLVM_DEBUG(dbgs() << " is %%noreg, nothing to be done\n");
448 continue;
450 assert(OpdMapper.getInstrMapping().getOperandMapping(OpIdx).NumBreakDowns !=
451 0 &&
452 "Invalid mapping");
453 assert(OpdMapper.getInstrMapping().getOperandMapping(OpIdx).NumBreakDowns ==
454 1 &&
455 "This mapping is too complex for this function");
456 iterator_range<SmallVectorImpl<Register>::const_iterator> NewRegs =
457 OpdMapper.getVRegs(OpIdx);
458 if (NewRegs.empty()) {
459 LLVM_DEBUG(dbgs() << " has not been repaired, nothing to be done\n");
460 continue;
462 Register OrigReg = MO.getReg();
463 Register NewReg = *NewRegs.begin();
464 LLVM_DEBUG(dbgs() << " changed, replace " << printReg(OrigReg, nullptr));
465 MO.setReg(NewReg);
466 LLVM_DEBUG(dbgs() << " with " << printReg(NewReg, nullptr));
468 // The OperandsMapper creates plain scalar, we may have to fix that.
469 // Check if the types match and if not, fix that.
470 LLT OrigTy = MRI.getType(OrigReg);
471 LLT NewTy = MRI.getType(NewReg);
472 if (OrigTy != NewTy) {
473 // The default mapping is not supposed to change the size of
474 // the storage. However, right now we don't necessarily bump all
475 // the types to storage size. For instance, we can consider
476 // s16 G_AND legal whereas the storage size is going to be 32.
477 assert(OrigTy.getSizeInBits() <= NewTy.getSizeInBits() &&
478 "Types with difference size cannot be handled by the default "
479 "mapping");
480 LLVM_DEBUG(dbgs() << "\nChange type of new opd from " << NewTy << " to "
481 << OrigTy);
482 MRI.setType(NewReg, OrigTy);
484 LLVM_DEBUG(dbgs() << '\n');
488 unsigned RegisterBankInfo::getSizeInBits(Register Reg,
489 const MachineRegisterInfo &MRI,
490 const TargetRegisterInfo &TRI) const {
491 if (Register::isPhysicalRegister(Reg)) {
492 // The size is not directly available for physical registers.
493 // Instead, we need to access a register class that contains Reg and
494 // get the size of that register class.
495 // Because this is expensive, we'll cache the register class by calling
496 auto *RC = &getMinimalPhysRegClass(Reg, TRI);
497 assert(RC && "Expecting Register class");
498 return TRI.getRegSizeInBits(*RC);
500 return TRI.getRegSizeInBits(Reg, MRI);
503 //------------------------------------------------------------------------------
504 // Helper classes implementation.
505 //------------------------------------------------------------------------------
506 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
507 LLVM_DUMP_METHOD void RegisterBankInfo::PartialMapping::dump() const {
508 print(dbgs());
509 dbgs() << '\n';
511 #endif
513 bool RegisterBankInfo::PartialMapping::verify() const {
514 assert(RegBank && "Register bank not set");
515 assert(Length && "Empty mapping");
516 assert((StartIdx <= getHighBitIdx()) && "Overflow, switch to APInt?");
517 // Check if the minimum width fits into RegBank.
518 assert(RegBank->getSize() >= Length && "Register bank too small for Mask");
519 return true;
522 void RegisterBankInfo::PartialMapping::print(raw_ostream &OS) const {
523 OS << "[" << StartIdx << ", " << getHighBitIdx() << "], RegBank = ";
524 if (RegBank)
525 OS << *RegBank;
526 else
527 OS << "nullptr";
530 bool RegisterBankInfo::ValueMapping::partsAllUniform() const {
531 if (NumBreakDowns < 2)
532 return true;
534 const PartialMapping *First = begin();
535 for (const PartialMapping *Part = First + 1; Part != end(); ++Part) {
536 if (Part->Length != First->Length || Part->RegBank != First->RegBank)
537 return false;
540 return true;
543 bool RegisterBankInfo::ValueMapping::verify(unsigned MeaningfulBitWidth) const {
544 assert(NumBreakDowns && "Value mapped nowhere?!");
545 unsigned OrigValueBitWidth = 0;
546 for (const RegisterBankInfo::PartialMapping &PartMap : *this) {
547 // Check that each register bank is big enough to hold the partial value:
548 // this check is done by PartialMapping::verify
549 assert(PartMap.verify() && "Partial mapping is invalid");
550 // The original value should completely be mapped.
551 // Thus the maximum accessed index + 1 is the size of the original value.
552 OrigValueBitWidth =
553 std::max(OrigValueBitWidth, PartMap.getHighBitIdx() + 1);
555 assert(OrigValueBitWidth >= MeaningfulBitWidth &&
556 "Meaningful bits not covered by the mapping");
557 APInt ValueMask(OrigValueBitWidth, 0);
558 for (const RegisterBankInfo::PartialMapping &PartMap : *this) {
559 // Check that the union of the partial mappings covers the whole value,
560 // without overlaps.
561 // The high bit is exclusive in the APInt API, thus getHighBitIdx + 1.
562 APInt PartMapMask = APInt::getBitsSet(OrigValueBitWidth, PartMap.StartIdx,
563 PartMap.getHighBitIdx() + 1);
564 ValueMask ^= PartMapMask;
565 assert((ValueMask & PartMapMask) == PartMapMask &&
566 "Some partial mappings overlap");
568 assert(ValueMask.isAllOnesValue() && "Value is not fully mapped");
569 return true;
572 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
573 LLVM_DUMP_METHOD void RegisterBankInfo::ValueMapping::dump() const {
574 print(dbgs());
575 dbgs() << '\n';
577 #endif
579 void RegisterBankInfo::ValueMapping::print(raw_ostream &OS) const {
580 OS << "#BreakDown: " << NumBreakDowns << " ";
581 bool IsFirst = true;
582 for (const PartialMapping &PartMap : *this) {
583 if (!IsFirst)
584 OS << ", ";
585 OS << '[' << PartMap << ']';
586 IsFirst = false;
590 bool RegisterBankInfo::InstructionMapping::verify(
591 const MachineInstr &MI) const {
592 // Check that all the register operands are properly mapped.
593 // Check the constructor invariant.
594 // For PHI, we only care about mapping the definition.
595 assert(NumOperands == (isCopyLike(MI) ? 1 : MI.getNumOperands()) &&
596 "NumOperands must match, see constructor");
597 assert(MI.getParent() && MI.getMF() &&
598 "MI must be connected to a MachineFunction");
599 const MachineFunction &MF = *MI.getMF();
600 const RegisterBankInfo *RBI = MF.getSubtarget().getRegBankInfo();
601 (void)RBI;
603 for (unsigned Idx = 0; Idx < NumOperands; ++Idx) {
604 const MachineOperand &MO = MI.getOperand(Idx);
605 if (!MO.isReg()) {
606 assert(!getOperandMapping(Idx).isValid() &&
607 "We should not care about non-reg mapping");
608 continue;
610 Register Reg = MO.getReg();
611 if (!Reg)
612 continue;
613 assert(getOperandMapping(Idx).isValid() &&
614 "We must have a mapping for reg operands");
615 const RegisterBankInfo::ValueMapping &MOMapping = getOperandMapping(Idx);
616 (void)MOMapping;
617 // Register size in bits.
618 // This size must match what the mapping expects.
619 assert(MOMapping.verify(RBI->getSizeInBits(
620 Reg, MF.getRegInfo(), *MF.getSubtarget().getRegisterInfo())) &&
621 "Value mapping is invalid");
623 return true;
626 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
627 LLVM_DUMP_METHOD void RegisterBankInfo::InstructionMapping::dump() const {
628 print(dbgs());
629 dbgs() << '\n';
631 #endif
633 void RegisterBankInfo::InstructionMapping::print(raw_ostream &OS) const {
634 OS << "ID: " << getID() << " Cost: " << getCost() << " Mapping: ";
636 for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
637 const ValueMapping &ValMapping = getOperandMapping(OpIdx);
638 if (OpIdx)
639 OS << ", ";
640 OS << "{ Idx: " << OpIdx << " Map: " << ValMapping << '}';
644 const int RegisterBankInfo::OperandsMapper::DontKnowIdx = -1;
646 RegisterBankInfo::OperandsMapper::OperandsMapper(
647 MachineInstr &MI, const InstructionMapping &InstrMapping,
648 MachineRegisterInfo &MRI)
649 : MRI(MRI), MI(MI), InstrMapping(InstrMapping) {
650 unsigned NumOpds = InstrMapping.getNumOperands();
651 OpToNewVRegIdx.resize(NumOpds, OperandsMapper::DontKnowIdx);
652 assert(InstrMapping.verify(MI) && "Invalid mapping for MI");
655 iterator_range<SmallVectorImpl<Register>::iterator>
656 RegisterBankInfo::OperandsMapper::getVRegsMem(unsigned OpIdx) {
657 assert(OpIdx < getInstrMapping().getNumOperands() && "Out-of-bound access");
658 unsigned NumPartialVal =
659 getInstrMapping().getOperandMapping(OpIdx).NumBreakDowns;
660 int StartIdx = OpToNewVRegIdx[OpIdx];
662 if (StartIdx == OperandsMapper::DontKnowIdx) {
663 // This is the first time we try to access OpIdx.
664 // Create the cells that will hold all the partial values at the
665 // end of the list of NewVReg.
666 StartIdx = NewVRegs.size();
667 OpToNewVRegIdx[OpIdx] = StartIdx;
668 for (unsigned i = 0; i < NumPartialVal; ++i)
669 NewVRegs.push_back(0);
671 SmallVectorImpl<Register>::iterator End =
672 getNewVRegsEnd(StartIdx, NumPartialVal);
674 return make_range(&NewVRegs[StartIdx], End);
677 SmallVectorImpl<Register>::const_iterator
678 RegisterBankInfo::OperandsMapper::getNewVRegsEnd(unsigned StartIdx,
679 unsigned NumVal) const {
680 return const_cast<OperandsMapper *>(this)->getNewVRegsEnd(StartIdx, NumVal);
682 SmallVectorImpl<Register>::iterator
683 RegisterBankInfo::OperandsMapper::getNewVRegsEnd(unsigned StartIdx,
684 unsigned NumVal) {
685 assert((NewVRegs.size() == StartIdx + NumVal ||
686 NewVRegs.size() > StartIdx + NumVal) &&
687 "NewVRegs too small to contain all the partial mapping");
688 return NewVRegs.size() <= StartIdx + NumVal ? NewVRegs.end()
689 : &NewVRegs[StartIdx + NumVal];
692 void RegisterBankInfo::OperandsMapper::createVRegs(unsigned OpIdx) {
693 assert(OpIdx < getInstrMapping().getNumOperands() && "Out-of-bound access");
694 iterator_range<SmallVectorImpl<Register>::iterator> NewVRegsForOpIdx =
695 getVRegsMem(OpIdx);
696 const ValueMapping &ValMapping = getInstrMapping().getOperandMapping(OpIdx);
697 const PartialMapping *PartMap = ValMapping.begin();
698 for (Register &NewVReg : NewVRegsForOpIdx) {
699 assert(PartMap != ValMapping.end() && "Out-of-bound access");
700 assert(NewVReg == 0 && "Register has already been created");
701 // The new registers are always bound to scalar with the right size.
702 // The actual type has to be set when the target does the mapping
703 // of the instruction.
704 // The rationale is that this generic code cannot guess how the
705 // target plans to split the input type.
706 NewVReg = MRI.createGenericVirtualRegister(LLT::scalar(PartMap->Length));
707 MRI.setRegBank(NewVReg, *PartMap->RegBank);
708 ++PartMap;
712 void RegisterBankInfo::OperandsMapper::setVRegs(unsigned OpIdx,
713 unsigned PartialMapIdx,
714 Register NewVReg) {
715 assert(OpIdx < getInstrMapping().getNumOperands() && "Out-of-bound access");
716 assert(getInstrMapping().getOperandMapping(OpIdx).NumBreakDowns >
717 PartialMapIdx &&
718 "Out-of-bound access for partial mapping");
719 // Make sure the memory is initialized for that operand.
720 (void)getVRegsMem(OpIdx);
721 assert(NewVRegs[OpToNewVRegIdx[OpIdx] + PartialMapIdx] == 0 &&
722 "This value is already set");
723 NewVRegs[OpToNewVRegIdx[OpIdx] + PartialMapIdx] = NewVReg;
726 iterator_range<SmallVectorImpl<Register>::const_iterator>
727 RegisterBankInfo::OperandsMapper::getVRegs(unsigned OpIdx,
728 bool ForDebug) const {
729 (void)ForDebug;
730 assert(OpIdx < getInstrMapping().getNumOperands() && "Out-of-bound access");
731 int StartIdx = OpToNewVRegIdx[OpIdx];
733 if (StartIdx == OperandsMapper::DontKnowIdx)
734 return make_range(NewVRegs.end(), NewVRegs.end());
736 unsigned PartMapSize =
737 getInstrMapping().getOperandMapping(OpIdx).NumBreakDowns;
738 SmallVectorImpl<Register>::const_iterator End =
739 getNewVRegsEnd(StartIdx, PartMapSize);
740 iterator_range<SmallVectorImpl<Register>::const_iterator> Res =
741 make_range(&NewVRegs[StartIdx], End);
742 #ifndef NDEBUG
743 for (Register VReg : Res)
744 assert((VReg || ForDebug) && "Some registers are uninitialized");
745 #endif
746 return Res;
749 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
750 LLVM_DUMP_METHOD void RegisterBankInfo::OperandsMapper::dump() const {
751 print(dbgs(), true);
752 dbgs() << '\n';
754 #endif
756 void RegisterBankInfo::OperandsMapper::print(raw_ostream &OS,
757 bool ForDebug) const {
758 unsigned NumOpds = getInstrMapping().getNumOperands();
759 if (ForDebug) {
760 OS << "Mapping for " << getMI() << "\nwith " << getInstrMapping() << '\n';
761 // Print out the internal state of the index table.
762 OS << "Populated indices (CellNumber, IndexInNewVRegs): ";
763 bool IsFirst = true;
764 for (unsigned Idx = 0; Idx != NumOpds; ++Idx) {
765 if (OpToNewVRegIdx[Idx] != DontKnowIdx) {
766 if (!IsFirst)
767 OS << ", ";
768 OS << '(' << Idx << ", " << OpToNewVRegIdx[Idx] << ')';
769 IsFirst = false;
772 OS << '\n';
773 } else
774 OS << "Mapping ID: " << getInstrMapping().getID() << ' ';
776 OS << "Operand Mapping: ";
777 // If we have a function, we can pretty print the name of the registers.
778 // Otherwise we will print the raw numbers.
779 const TargetRegisterInfo *TRI =
780 getMI().getParent() && getMI().getMF()
781 ? getMI().getMF()->getSubtarget().getRegisterInfo()
782 : nullptr;
783 bool IsFirst = true;
784 for (unsigned Idx = 0; Idx != NumOpds; ++Idx) {
785 if (OpToNewVRegIdx[Idx] == DontKnowIdx)
786 continue;
787 if (!IsFirst)
788 OS << ", ";
789 IsFirst = false;
790 OS << '(' << printReg(getMI().getOperand(Idx).getReg(), TRI) << ", [";
791 bool IsFirstNewVReg = true;
792 for (Register VReg : getVRegs(Idx)) {
793 if (!IsFirstNewVReg)
794 OS << ", ";
795 IsFirstNewVReg = false;
796 OS << printReg(VReg, TRI);
798 OS << "])";