1//===- CodeGenRegisters.h - Register and RegisterClass Info -----*- 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//
9// This file defines structures to encapsulate information gleaned from the
10// target register and register class definitions.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_UTILS_TABLEGEN_COMMON_CODEGENREGISTERS_H
15#define LLVM_UTILS_TABLEGEN_COMMON_CODEGENREGISTERS_H
16
17#include "CodeGenHwModes.h"
18#include "InfoByHwMode.h"
19#include "llvm/ADT/ArrayRef.h"
20#include "llvm/ADT/BitVector.h"
21#include "llvm/ADT/DenseMap.h"
22#include "llvm/ADT/STLExtras.h"
23#include "llvm/ADT/SetVector.h"
24#include "llvm/ADT/SmallVector.h"
25#include "llvm/ADT/SparseBitVector.h"
26#include "llvm/ADT/StringMap.h"
27#include "llvm/ADT/StringRef.h"
28#include "llvm/MC/LaneBitmask.h"
29#include "llvm/Support/ErrorHandling.h"
30#include "llvm/TableGen/Record.h"
31#include "llvm/TableGen/SetTheory.h"
32#include <cassert>
33#include <cstdint>
34#include <deque>
35#include <functional>
36#include <list>
37#include <map>
38#include <memory>
39#include <optional>
40#include <string>
41#include <utility>
42#include <vector>
43
44namespace llvm {
45
46class CodeGenRegBank;
47
48/// Used to encode a step in a register lane mask transformation.
49/// Mask the bits specified in Mask, then rotate them Rol bits to the left
50/// assuming a wraparound at 32bits.
51struct MaskRolPair {
52 LaneBitmask Mask;
53 uint8_t RotateLeft;
54
55 bool operator==(const MaskRolPair Other) const {
56 return Mask == Other.Mask && RotateLeft == Other.RotateLeft;
57 }
58 bool operator!=(const MaskRolPair Other) const {
59 return Mask != Other.Mask || RotateLeft != Other.RotateLeft;
60 }
61};
62
63/// CodeGenSubRegIndex - Represents a sub-register index.
64class CodeGenSubRegIndex {
65 const Record *const TheDef;
66 std::string Name;
67 std::string Namespace;
68
69public:
70 SubRegRangeByHwMode Range;
71 const unsigned EnumValue;
72 mutable LaneBitmask LaneMask;
73 mutable SmallVector<MaskRolPair, 1> CompositionLaneMaskTransform;
74
75 /// A list of subregister indexes concatenated resulting in this
76 /// subregister index. This is the reverse of CodeGenRegBank::ConcatIdx.
77 SmallVector<CodeGenSubRegIndex *, 4> ConcatenationOf;
78
79 // Are all super-registers containing this SubRegIndex covered by their
80 // sub-registers?
81 bool AllSuperRegsCovered;
82 // A subregister index is "artificial" if every subregister obtained
83 // from applying this index is artificial. Artificial subregister
84 // indexes are not used to create new register classes.
85 bool Artificial;
86
87 CodeGenSubRegIndex(const Record *R, unsigned Enum, const CodeGenHwModes &CGH);
88 CodeGenSubRegIndex(StringRef N, StringRef Nspace, unsigned Enum);
89 CodeGenSubRegIndex(CodeGenSubRegIndex &) = delete;
90
91 const std::string &getName() const { return Name; }
92 const std::string &getNamespace() const { return Namespace; }
93 std::string getQualifiedName() const;
94
95 // Map of composite subreg indices.
96 using CompMap =
97 std::map<CodeGenSubRegIndex *, CodeGenSubRegIndex *, deref<std::less<>>>;
98
99 // Returns the subreg index that results from composing this with Idx.
100 // Returns NULL if this and Idx don't compose.
101 CodeGenSubRegIndex *compose(CodeGenSubRegIndex *Idx) const {
102 CompMap::const_iterator I = Composed.find(x: Idx);
103 return I == Composed.end() ? nullptr : I->second;
104 }
105
106 // Add a composite subreg index: this+A = B.
107 // Return a conflicting composite, or NULL
108 CodeGenSubRegIndex *addComposite(CodeGenSubRegIndex *A, CodeGenSubRegIndex *B,
109 const CodeGenHwModes &CGH) {
110 assert(A && B);
111 std::pair<CompMap::iterator, bool> Ins = Composed.try_emplace(k: A, args&: B);
112
113 // Synthetic subreg indices that aren't contiguous (for instance ARM
114 // register tuples) don't have a bit range, so it's OK to let
115 // B->Offset == -1. For the other cases, accumulate the offset and set
116 // the size here. Only do so if there is no offset yet though.
117 unsigned NumModes = CGH.getNumModeIds();
118 // Skip default mode.
119 for (unsigned M = 0; M < NumModes; ++M) {
120 // Handle DefaultMode last.
121 if (M == DefaultMode)
122 continue;
123 SubRegRange &Range = this->Range.get(Mode: M);
124 SubRegRange &ARange = A->Range.get(Mode: M);
125 SubRegRange &BRange = B->Range.get(Mode: M);
126
127 if (Range.Offset != (uint16_t)-1 && ARange.Offset != (uint16_t)-1 &&
128 BRange.Offset == (uint16_t)-1) {
129 BRange.Offset = Range.Offset + ARange.Offset;
130 BRange.Size = ARange.Size;
131 }
132 }
133
134 // Now handle default.
135 SubRegRange &Range = this->Range.get(Mode: DefaultMode);
136 SubRegRange &ARange = A->Range.get(Mode: DefaultMode);
137 SubRegRange &BRange = B->Range.get(Mode: DefaultMode);
138 if (Range.Offset != (uint16_t)-1 && ARange.Offset != (uint16_t)-1 &&
139 BRange.Offset == (uint16_t)-1) {
140 BRange.Offset = Range.Offset + ARange.Offset;
141 BRange.Size = ARange.Size;
142 }
143
144 return (Ins.second || Ins.first->second == B) ? nullptr : Ins.first->second;
145 }
146
147 // Update the composite maps of components specified in 'ComposedOf'.
148 void updateComponents(CodeGenRegBank &);
149
150 // Return the map of composites.
151 const CompMap &getComposites() const { return Composed; }
152
153 // Compute LaneMask from Composed. Return LaneMask.
154 LaneBitmask computeLaneMask() const;
155
156 void setConcatenationOf(ArrayRef<CodeGenSubRegIndex *> Parts);
157
158 /// Replaces subregister indexes in the `ConcatenationOf` list with
159 /// list of subregisters they are composed of (if any). Do this recursively.
160 void computeConcatTransitiveClosure();
161
162 bool operator<(const CodeGenSubRegIndex &RHS) const {
163 return this->EnumValue < RHS.EnumValue;
164 }
165
166private:
167 CompMap Composed;
168};
169
170/// CodeGenRegister - Represents a register definition.
171class CodeGenRegister {
172 friend class CodeGenRegBank;
173
174public:
175 const Record *TheDef;
176 unsigned EnumValue;
177 std::vector<int64_t> CostPerUse;
178 bool CoveredBySubRegs = true;
179 bool HasDisjunctSubRegs = false;
180 bool Artificial = true;
181 bool Constant = false;
182
183 // Map SubRegIndex -> Register.
184 using SubRegMap =
185 std::map<CodeGenSubRegIndex *, CodeGenRegister *, deref<std::less<>>>;
186
187 CodeGenRegister(const Record *R, unsigned Enum);
188
189 StringRef getName() const {
190 assert(TheDef && "no def");
191 return TheDef->getName();
192 }
193
194 // Extract more information from TheDef. This is used to build an object
195 // graph after all CodeGenRegister objects have been created.
196 void buildObjectGraph(CodeGenRegBank &);
197
198 // Lazily compute a map of all sub-registers.
199 // This includes unique entries for all sub-sub-registers.
200 const SubRegMap &computeSubRegs(CodeGenRegBank &);
201
202 // Compute extra sub-registers by combining the existing sub-registers.
203 void computeSecondarySubRegs(CodeGenRegBank &);
204
205 // Add this as a super-register to all sub-registers after the sub-register
206 // graph has been built.
207 void computeSuperRegs(CodeGenRegBank &);
208
209 const SubRegMap &getSubRegs() const {
210 assert(SubRegsComplete && "Must precompute sub-registers");
211 return SubRegs;
212 }
213
214 // Add sub-registers to OSet following a pre-order defined by the .td file.
215 void addSubRegsPreOrder(SetVector<const CodeGenRegister *> &OSet,
216 CodeGenRegBank &) const;
217
218 // Return the sub-register index naming Reg as a sub-register of this
219 // register. Returns NULL if Reg is not a sub-register.
220 CodeGenSubRegIndex *getSubRegIndex(const CodeGenRegister *Reg) const {
221 return SubReg2Idx.lookup(Val: Reg);
222 }
223
224 using SuperRegList = std::vector<const CodeGenRegister *>;
225
226 // Get the list of super-registers in topological order, small to large.
227 // This is valid after computeSubRegs visits all registers during RegBank
228 // construction.
229 const SuperRegList &getSuperRegs() const {
230 assert(SubRegsComplete && "Must precompute sub-registers");
231 return SuperRegs;
232 }
233
234 // Get the list of ad hoc aliases. The graph is symmetric, so the list
235 // contains all registers in 'Aliases', and all registers that mention this
236 // register in 'Aliases'.
237 ArrayRef<CodeGenRegister *> getExplicitAliases() const {
238 return ExplicitAliases;
239 }
240
241 // Get the topological signature of this register. This is a small integer
242 // less than RegBank.getNumTopoSigs(). Registers with the same TopoSig have
243 // identical sub-register structure. That is, they support the same set of
244 // sub-register indices mapping to the same kind of sub-registers
245 // (TopoSig-wise).
246 unsigned getTopoSig() const {
247 assert(SuperRegsComplete && "TopoSigs haven't been computed yet.");
248 return TopoSig;
249 }
250
251 // List of register units in ascending order.
252 using RegUnitList = SparseBitVector<>;
253 using RegUnitLaneMaskList = SmallVector<LaneBitmask, 16>;
254
255 // How many entries in RegUnitList are native?
256 RegUnitList NativeRegUnits;
257
258 // Get the list of register units.
259 // This is only valid after computeSubRegs() completes.
260 const RegUnitList &getRegUnits() const { return RegUnits; }
261
262 void setNewRegUnits(const RegUnitList &NewRegUnits) {
263 RegUnits = NewRegUnits;
264 }
265
266 ArrayRef<LaneBitmask> getRegUnitLaneMasks() const {
267 return ArrayRef(RegUnitLaneMasks).slice(N: 0, M: NativeRegUnits.count());
268 }
269
270 // Get the native register units. This is a prefix of getRegUnits().
271 RegUnitList getNativeRegUnits() const { return NativeRegUnits; }
272
273 void setRegUnitLaneMasks(const RegUnitLaneMaskList &LaneMasks) {
274 RegUnitLaneMasks = LaneMasks;
275 }
276
277 // Inherit register units from subregisters.
278 // Return true if the RegUnits changed.
279 bool inheritRegUnits(CodeGenRegBank &RegBank);
280
281 // Adopt a register unit for pressure tracking.
282 // A unit is adopted iff its unit number is >= NativeRegUnits.count().
283 void adoptRegUnit(unsigned RUID) { RegUnits.set(RUID); }
284
285 // Get the sum of this register's register unit weights.
286 unsigned getWeight(const CodeGenRegBank &RegBank) const;
287
288 // Canonically ordered set.
289 using Vec = std::vector<const CodeGenRegister *>;
290
291private:
292 bool SubRegsComplete;
293 bool SuperRegsComplete;
294 unsigned TopoSig;
295
296 // The sub-registers explicit in the .td file form a tree.
297 SmallVector<CodeGenSubRegIndex *, 8> ExplicitSubRegIndices;
298 SmallVector<CodeGenRegister *, 8> ExplicitSubRegs;
299
300 // Explicit ad hoc aliases, symmetrized to form an undirected graph.
301 SmallVector<CodeGenRegister *, 8> ExplicitAliases;
302
303 // Super-registers where this is the first explicit sub-register.
304 SuperRegList LeadingSuperRegs;
305
306 SubRegMap SubRegs;
307 SuperRegList SuperRegs;
308 DenseMap<const CodeGenRegister *, CodeGenSubRegIndex *> SubReg2Idx;
309 RegUnitList RegUnits;
310 RegUnitLaneMaskList RegUnitLaneMasks;
311};
312
313inline bool operator<(const CodeGenRegister &A, const CodeGenRegister &B) {
314 return A.EnumValue < B.EnumValue;
315}
316
317inline bool operator==(const CodeGenRegister &A, const CodeGenRegister &B) {
318 return A.EnumValue == B.EnumValue;
319}
320
321inline bool operator!=(const CodeGenRegister &A, const CodeGenRegister &B) {
322 return !(A == B);
323}
324
325class CodeGenRegisterClass {
326 CodeGenRegister::Vec Members;
327 // Bit mask of members, indexed by getRegIndex.
328 BitVector MemberBV;
329 // Allocation orders. Order[0] always contains all registers in Members.
330 std::vector<SmallVector<const Record *, 16>> Orders;
331 // Bit mask of sub-classes including this, indexed by their EnumValue.
332 BitVector SubClasses;
333 // List of super-classes, topologocally ordered to have the larger classes
334 // first. This is the same as sorting by EnumValue.
335 SmallVector<CodeGenRegisterClass *, 4> SuperClasses;
336 const Record *TheDef;
337 std::string Name;
338
339 // For a synthesized class, inherit missing properties from the nearest
340 // super-class.
341 void inheritProperties(CodeGenRegBank &);
342
343 // Map SubRegIndex -> sub-class. This is the largest sub-class where all
344 // registers have a SubRegIndex sub-register.
345 DenseMap<const CodeGenSubRegIndex *, CodeGenRegisterClass *>
346 SubClassWithSubReg;
347
348 // Map SubRegIndex -> set of super-reg classes. This is all register
349 // classes SuperRC such that:
350 //
351 // R:SubRegIndex in this RC for all R in SuperRC.
352 //
353 DenseMap<CodeGenSubRegIndex *, DenseSet<CodeGenRegisterClass *>>
354 SuperRegClasses;
355
356 // Bit vector of TopoSigs for the registers with super registers in this
357 // class. This will be very sparse on regular architectures.
358 BitVector RegsWithSuperRegsTopoSigs;
359
360 // If the register class was inferred for getMatchingSuperRegClass, this
361 // holds the subregister index and subregister class for which the register
362 // class was created.
363 CodeGenSubRegIndex *InferredFromSubRegIdx = nullptr;
364 CodeGenRegisterClass *InferredFromRC = nullptr;
365
366public:
367 unsigned EnumValue;
368 StringRef Namespace;
369 SmallVector<ValueTypeByHwMode, 4> VTs;
370 RegSizeInfoByHwMode RSI;
371 uint8_t CopyCost;
372 bool Allocatable;
373 StringRef AltOrderSelect;
374 uint8_t AllocationPriority;
375 bool GlobalPriority;
376 uint8_t TSFlags;
377 /// Contains the combination of the lane masks of all subregisters.
378 LaneBitmask LaneMask;
379 /// True if there are at least 2 subregisters which do not interfere.
380 bool HasDisjunctSubRegs;
381 bool CoveredBySubRegs;
382 /// A register class is artificial if all its members are artificial.
383 bool Artificial;
384 /// Generate register pressure set for this register class and any class
385 /// synthesized from it.
386 bool GeneratePressureSet;
387
388 // Return the Record that defined this class, or NULL if the class was
389 // created by TableGen.
390 const Record *getDef() const { return TheDef; }
391
392 std::string getNamespaceQualification() const;
393 const std::string &getName() const { return Name; }
394 std::string getQualifiedName() const;
395 std::string getIdName() const;
396 std::string getQualifiedIdName() const;
397 ArrayRef<ValueTypeByHwMode> getValueTypes() const { return VTs; }
398 unsigned getNumValueTypes() const { return VTs.size(); }
399 bool hasType(const ValueTypeByHwMode &VT) const;
400
401 const ValueTypeByHwMode &getValueTypeNum(unsigned VTNum) const {
402 if (VTNum < VTs.size())
403 return VTs[VTNum];
404 llvm_unreachable("VTNum greater than number of ValueTypes in RegClass!");
405 }
406
407 // Return true if this class contains the register.
408 bool contains(const CodeGenRegister *) const;
409
410 // Returns true if RC is a subclass.
411 // RC is a sub-class of this class if it is a valid replacement for any
412 // instruction operand where a register of this classis required. It must
413 // satisfy these conditions:
414 //
415 // 1. All RC registers are also in this.
416 // 2. The RC spill size must not be smaller than our spill size.
417 // 3. RC spill alignment must be compatible with ours.
418 //
419 bool hasSubClass(const CodeGenRegisterClass *RC) const {
420 return SubClasses.test(Idx: RC->EnumValue);
421 }
422
423 // getSubClassWithSubReg - Returns the largest sub-class where all
424 // registers have a SubIdx sub-register.
425 CodeGenRegisterClass *
426 getSubClassWithSubReg(const CodeGenSubRegIndex *SubIdx) const {
427 return SubClassWithSubReg.lookup(Val: SubIdx);
428 }
429
430 /// Find largest subclass where all registers have SubIdx subregisters in
431 /// SubRegClass and the largest subregister class that contains those
432 /// subregisters without (as far as possible) also containing additional
433 /// registers.
434 ///
435 /// This can be used to find a suitable pair of classes for subregister
436 /// copies. \return std::pair<SubClass, SubRegClass> where SubClass is a
437 /// SubClass is a class where every register has SubIdx and SubRegClass is a
438 /// class where every register is covered by the SubIdx subregister of
439 /// SubClass.
440 std::optional<std::pair<CodeGenRegisterClass *, CodeGenRegisterClass *>>
441 getMatchingSubClassWithSubRegs(CodeGenRegBank &RegBank,
442 const CodeGenSubRegIndex *SubIdx) const;
443
444 void setSubClassWithSubReg(const CodeGenSubRegIndex *SubIdx,
445 CodeGenRegisterClass *SubRC) {
446 SubClassWithSubReg[SubIdx] = SubRC;
447 }
448
449 // getSuperRegClasses - Returns a bit vector of all register classes
450 // containing only SubIdx super-registers of this class.
451 void getSuperRegClasses(const CodeGenSubRegIndex *SubIdx,
452 BitVector &Out) const;
453
454 // addSuperRegClass - Add a class containing only SubIdx super-registers.
455 void addSuperRegClass(CodeGenSubRegIndex *SubIdx,
456 CodeGenRegisterClass *SuperRC) {
457 SuperRegClasses[SubIdx].insert(V: SuperRC);
458 }
459
460 void extendSuperRegClasses(CodeGenSubRegIndex *SubIdx);
461
462 // getSubClasses - Returns a constant BitVector of subclasses indexed by
463 // EnumValue.
464 // The SubClasses vector includes an entry for this class.
465 const BitVector &getSubClasses() const { return SubClasses; }
466
467 // getSuperClasses - Returns a list of super classes ordered by EnumValue.
468 // The array does not include an entry for this class.
469 ArrayRef<CodeGenRegisterClass *> getSuperClasses() const {
470 return SuperClasses;
471 }
472
473 // Returns an ordered list of class members.
474 // The order of registers is the same as in the .td file.
475 // No = 0 is the default allocation order, No = 1 is the first alternative.
476 ArrayRef<const Record *> getOrder(unsigned No = 0) const {
477 return Orders[No];
478 }
479
480 // Return the total number of allocation orders available.
481 unsigned getNumOrders() const { return Orders.size(); }
482
483 // Get the set of registers. This set contains the same registers as
484 // getOrder(0).
485 const CodeGenRegister::Vec &getMembers() const { return Members; }
486
487 // Get a bit vector of TopoSigs of registers with super registers in this
488 // register class.
489 const BitVector &getRegsWithSuperRegsTopoSigs() const {
490 return RegsWithSuperRegsTopoSigs;
491 }
492
493 // Get a weight of this register class.
494 unsigned getWeight(const CodeGenRegBank &) const;
495
496 // Populate a unique sorted list of units from a register set.
497 void buildRegUnitSet(const CodeGenRegBank &RegBank,
498 std::vector<unsigned> &RegUnits) const;
499
500 CodeGenRegisterClass(CodeGenRegBank &, const Record *R);
501 CodeGenRegisterClass(CodeGenRegisterClass &) = delete;
502
503 // A key representing the parts of a register class used for forming
504 // sub-classes. Note the ordering provided by this key is not the same as
505 // the topological order used for the EnumValues.
506 struct Key {
507 const CodeGenRegister::Vec *Members;
508 RegSizeInfoByHwMode RSI;
509
510 // Ignore artificial registers when comparing classes. We use this
511 // to find existing classes that contain the same non-artificial
512 // members, but may differ in presence of artificial ones, thus
513 // avoiding creating extra register classes for codegen needs.
514 bool IgnoreArtificialMembers;
515
516 Key(const CodeGenRegister::Vec *M, const RegSizeInfoByHwMode &I,
517 bool IgnoreArtificialMembers = false)
518 : Members(M), RSI(I), IgnoreArtificialMembers(IgnoreArtificialMembers) {
519 }
520
521 Key(const CodeGenRegisterClass &RC, bool IgnoreArtificialMembers = false)
522 : Members(&RC.getMembers()), RSI(RC.RSI),
523 IgnoreArtificialMembers(IgnoreArtificialMembers) {}
524
525 // Lexicographical order of (Members, RegSizeInfoByHwMode).
526 bool operator<(const Key &) const;
527 };
528
529 // Create a non-user defined register class.
530 CodeGenRegisterClass(CodeGenRegBank &, StringRef Name, Key Props);
531
532 // Called by CodeGenRegBank::CodeGenRegBank().
533 static void computeSubClasses(CodeGenRegBank &);
534
535 // Get ordering value among register base classes.
536 std::optional<int> getBaseClassOrder() const {
537 if (TheDef && !TheDef->isValueUnset(FieldName: "BaseClassOrder"))
538 return TheDef->getValueAsInt(FieldName: "BaseClassOrder");
539 return {};
540 }
541
542 void setInferredFrom(CodeGenSubRegIndex *Idx, CodeGenRegisterClass *RC) {
543 assert(Idx && RC);
544 assert(!InferredFromSubRegIdx);
545
546 InferredFromSubRegIdx = Idx;
547 InferredFromRC = RC;
548 }
549
550 CodeGenSubRegIndex *getInferredFromSubRegIdx() const {
551 return InferredFromSubRegIdx;
552 }
553
554 CodeGenRegisterClass *getInferredFromRC() const { return InferredFromRC; }
555};
556
557// Register categories are used when we need to deterine the category a
558// register falls into (GPR, vector, fixed, etc.) without having to know
559// specific information about the target architecture.
560class CodeGenRegisterCategory {
561 const Record *TheDef;
562 std::string Name;
563 std::list<CodeGenRegisterClass *> Classes;
564
565public:
566 CodeGenRegisterCategory(CodeGenRegBank &, const Record *R);
567 CodeGenRegisterCategory(CodeGenRegisterCategory &) = delete;
568
569 // Return the Record that defined this class, or NULL if the class was
570 // created by TableGen.
571 const Record *getDef() const { return TheDef; }
572
573 std::string getName() const { return Name; }
574 std::list<CodeGenRegisterClass *> getClasses() const { return Classes; }
575};
576
577// Register units are used to model interference and register pressure.
578// Every register is assigned one or more register units such that two
579// registers overlap if and only if they have a register unit in common.
580//
581// Normally, one register unit is created per leaf register. Non-leaf
582// registers inherit the units of their sub-registers.
583struct RegUnit {
584 // Weight assigned to this RegUnit for estimating register pressure.
585 // This is useful when equalizing weights in register classes with mixed
586 // register topologies.
587 unsigned Weight = 0;
588
589 // Each native RegUnit corresponds to one or two root registers. The full
590 // set of registers containing this unit can be computed as the union of
591 // these two registers and their super-registers.
592 const CodeGenRegister *Roots[2];
593
594 // Index into RegClassUnitSets where we can find the list of UnitSets that
595 // contain this unit.
596 unsigned RegClassUnitSetsIdx = 0;
597 // A register unit is artificial if at least one of its roots is
598 // artificial.
599 bool Artificial = false;
600
601 RegUnit() { Roots[0] = Roots[1] = nullptr; }
602
603 ArrayRef<const CodeGenRegister *> getRoots() const {
604 assert(!(Roots[1] && !Roots[0]) && "Invalid roots array");
605 return ArrayRef(Roots, !!Roots[0] + !!Roots[1]);
606 }
607};
608
609// Each RegUnitSet is a sorted vector with a name.
610struct RegUnitSet {
611 using iterator = std::vector<unsigned>::const_iterator;
612
613 std::string Name;
614 std::vector<unsigned> Units;
615 unsigned Weight = 0; // Cache the sum of all unit weights.
616 unsigned Order = 0; // Cache the sort key.
617
618 RegUnitSet(std::string Name) : Name(std::move(Name)) {}
619};
620
621// Base vector for identifying TopoSigs. The contents uniquely identify a
622// TopoSig, only computeSuperRegs needs to know how.
623using TopoSigId = SmallVector<unsigned, 16>;
624
625// CodeGenRegBank - Represent a target's registers and the relations between
626// them.
627class CodeGenRegBank {
628 const RecordKeeper &Records;
629
630 SetTheory Sets;
631
632 const CodeGenHwModes &CGH;
633
634 const bool RegistersAreIntervals;
635
636 std::deque<CodeGenSubRegIndex> SubRegIndices;
637 DenseMap<const Record *, CodeGenSubRegIndex *> Def2SubRegIdx;
638
639 // Subregister indices sorted topologically by composition.
640 std::vector<CodeGenSubRegIndex *> SubRegIndicesRPOT;
641
642 CodeGenSubRegIndex *createSubRegIndex(StringRef Name, StringRef NameSpace);
643
644 using ConcatIdxMap =
645 std::map<SmallVector<CodeGenSubRegIndex *, 8>, CodeGenSubRegIndex *>;
646 ConcatIdxMap ConcatIdx;
647
648 // Registers.
649 std::deque<CodeGenRegister> Registers;
650 StringMap<CodeGenRegister *> RegistersByName;
651 DenseMap<const Record *, CodeGenRegister *> Def2Reg;
652 unsigned NumNativeRegUnits;
653
654 std::map<TopoSigId, unsigned> TopoSigs;
655
656 // Includes native (0..NumNativeRegUnits-1) and adopted register units.
657 SmallVector<RegUnit, 8> RegUnits;
658
659 // Register classes.
660 std::list<CodeGenRegisterClass> RegClasses;
661 DenseMap<const Record *, CodeGenRegisterClass *> Def2RC;
662 using RCKeyMap = std::map<CodeGenRegisterClass::Key, CodeGenRegisterClass *>;
663 RCKeyMap Key2RC;
664
665 // Register categories.
666 std::list<CodeGenRegisterCategory> RegCategories;
667 using RCatKeyMap =
668 std::map<CodeGenRegisterClass::Key, CodeGenRegisterCategory *>;
669 RCatKeyMap Key2RCat;
670
671 // Remember each unique set of register units. Initially, this contains a
672 // unique set for each register class. Simliar sets are coalesced with
673 // pruneUnitSets and new supersets are inferred during computeRegUnitSets.
674 std::vector<RegUnitSet> RegUnitSets;
675
676 // Map RegisterClass index to the index of the RegUnitSet that contains the
677 // class's units and any inferred RegUnit supersets.
678 //
679 // NOTE: This could grow beyond the number of register classes when we map
680 // register units to lists of unit sets. If the list of unit sets does not
681 // already exist for a register class, we create a new entry in this vector.
682 std::vector<std::vector<unsigned>> RegClassUnitSets;
683
684 // Give each register unit set an order based on sorting criteria.
685 std::vector<unsigned> RegUnitSetOrder;
686
687 // Keep track of synthesized definitions generated in TupleExpander.
688 std::vector<std::unique_ptr<Record>> SynthDefs;
689
690 // Add RC to *2RC maps.
691 void addToMaps(CodeGenRegisterClass *);
692
693 // Create a synthetic sub-class if it is missing. Returns (RC, inserted).
694 std::pair<CodeGenRegisterClass *, bool>
695 getOrCreateSubClass(const CodeGenRegisterClass *RC,
696 const CodeGenRegister::Vec *Membs, StringRef Name);
697
698 // Infer missing register classes.
699 void computeInferredRegisterClasses();
700 void inferCommonSubClass(CodeGenRegisterClass *RC);
701 void inferSubClassWithSubReg(CodeGenRegisterClass *RC);
702
703 void inferMatchingSuperRegClass(CodeGenRegisterClass *RC) {
704 inferMatchingSuperRegClass(RC, FirstSubRegRC: RegClasses.begin());
705 }
706
707 void inferMatchingSuperRegClass(
708 CodeGenRegisterClass *RC,
709 std::list<CodeGenRegisterClass>::iterator FirstSubRegRC);
710
711 // Iteratively prune unit sets.
712 void pruneUnitSets();
713
714 // Compute a weight for each register unit created during getSubRegs.
715 void computeRegUnitWeights();
716
717 // Enforce that all registers are intervals of regunits if requested.
718 void enforceRegUnitIntervals();
719
720 // Create a RegUnitSet for each RegClass and infer superclasses.
721 void computeRegUnitSets();
722
723 // Populate the Composite map from sub-register relationships.
724 void computeComposites();
725
726 // Compute a lane mask for each sub-register index.
727 void computeSubRegLaneMasks();
728
729 // Compute RPOT of subregister indices by composition.
730 void computeSubRegIndicesRPOT();
731
732 /// Computes a lane mask for each register unit enumerated by a physical
733 /// register.
734 void computeRegUnitLaneMasks();
735
736 // Helper function for printing debug information. Handles artificial
737 // (non-native) reg units.
738 void printRegUnitNames(ArrayRef<unsigned> Units) const;
739
740public:
741 CodeGenRegBank(const RecordKeeper &, const CodeGenHwModes &,
742 const bool RegistersAreIntervals);
743 CodeGenRegBank(CodeGenRegBank &) = delete;
744
745 SetTheory &getSets() { return Sets; }
746
747 const CodeGenHwModes &getHwModes() const { return CGH; }
748
749 // Sub-register indices. The first NumNamedIndices are defined by the user
750 // in the .td files. The rest are synthesized such that all sub-registers
751 // have a unique name.
752 const std::deque<CodeGenSubRegIndex> &getSubRegIndices() const {
753 return SubRegIndices;
754 }
755
756 // Find a SubRegIndex from its Record def or add to the list if it does
757 // not exist there yet.
758 CodeGenSubRegIndex *getSubRegIdx(const Record *);
759
760 // Find a SubRegIndex from its Record def.
761 const CodeGenSubRegIndex *findSubRegIdx(const Record *Def) const;
762
763 // Find or create a sub-register index representing the A+B composition.
764 CodeGenSubRegIndex *getCompositeSubRegIndex(CodeGenSubRegIndex *A,
765 CodeGenSubRegIndex *B);
766
767 // Find or create a sub-register index representing the concatenation of
768 // non-overlapping sibling indices.
769 CodeGenSubRegIndex *
770 getConcatSubRegIndex(const SmallVector<CodeGenSubRegIndex *, 8> &Parts,
771 const CodeGenHwModes &CGH);
772
773 const std::deque<CodeGenRegister> &getRegisters() const { return Registers; }
774
775 const StringMap<CodeGenRegister *> &getRegistersByName() const {
776 return RegistersByName;
777 }
778
779 // Find a register from its Record def.
780 CodeGenRegister *getReg(const Record *);
781
782 // Get a Register's index into the Registers array.
783 static unsigned getRegIndex(const CodeGenRegister *Reg) {
784 return Reg->EnumValue - 1;
785 }
786
787 // Return the number of allocated TopoSigs. The first TopoSig representing
788 // leaf registers is allocated number 0.
789 unsigned getNumTopoSigs() const { return TopoSigs.size(); }
790
791 // Find or create a TopoSig for the given TopoSigId.
792 // This function is only for use by CodeGenRegister::computeSuperRegs().
793 // Others should simply use Reg->getTopoSig().
794 unsigned getTopoSig(const TopoSigId &Id) {
795 return TopoSigs.try_emplace(k: Id, args: TopoSigs.size()).first->second;
796 }
797
798 // Create a native register unit that is associated with one or two root
799 // registers.
800 unsigned newRegUnit(CodeGenRegister *R0, CodeGenRegister *R1 = nullptr) {
801 RegUnit &RU = RegUnits.emplace_back();
802 RU.Roots[0] = R0;
803 RU.Roots[1] = R1;
804 RU.Artificial = R0->Artificial;
805 if (R1)
806 RU.Artificial |= R1->Artificial;
807 return RegUnits.size() - 1;
808 }
809
810 // Create a new non-native register unit that can be adopted by a register
811 // to increase its pressure. Note that NumNativeRegUnits is not increased.
812 unsigned newRegUnit(unsigned Weight) {
813 RegUnit &RU = RegUnits.emplace_back();
814 RU.Weight = Weight;
815 return RegUnits.size() - 1;
816 }
817
818 // Native units are the singular unit of a leaf register. Register aliasing
819 // is completely characterized by native units. Adopted units exist to give
820 // register additional weight but don't affect aliasing.
821 bool isNativeUnit(unsigned RUID) const { return RUID < NumNativeRegUnits; }
822
823 unsigned getNumNativeRegUnits() const { return NumNativeRegUnits; }
824
825 RegUnit &getRegUnit(unsigned RUID) { return RegUnits[RUID]; }
826 const RegUnit &getRegUnit(unsigned RUID) const { return RegUnits[RUID]; }
827
828 std::list<CodeGenRegisterClass> &getRegClasses() { return RegClasses; }
829
830 const std::list<CodeGenRegisterClass> &getRegClasses() const {
831 return RegClasses;
832 }
833
834 std::list<CodeGenRegisterCategory> &getRegCategories() {
835 return RegCategories;
836 }
837
838 const std::list<CodeGenRegisterCategory> &getRegCategories() const {
839 return RegCategories;
840 }
841
842 // Find a register class from its def.
843 CodeGenRegisterClass *getRegClass(const Record *,
844 ArrayRef<SMLoc> Loc = {}) const;
845
846 /// getRegisterClassForRegister - Find the register class that contains the
847 /// specified physical register. If the register is not in a register
848 /// class, return null. If the register is in multiple classes, and the
849 /// classes have a superset-subset relationship and the same set of types,
850 /// return the superclass. Otherwise return null.
851 const CodeGenRegisterClass *getRegClassForRegister(const Record *R);
852
853 /// Returns whether \p RegClass contains register \p Reg, handling
854 /// RegClassByHwMode and RegisterByHwMode correctly.
855 /// This should be preferred instead of
856 /// `RegBank.getRegClass(RC).contains(RegBank.getReg(R))`.
857 bool regClassContainsReg(const Record *RegClass, const Record *RegDef,
858 ArrayRef<SMLoc> Loc = {});
859
860 // Analog of TargetRegisterInfo::getMinimalPhysRegClass. Unlike
861 // getRegClassForRegister, this tries to find the smallest class containing
862 // the physical register. If \p VT is specified, it will only find classes
863 // with a matching type
864 const CodeGenRegisterClass *
865 getMinimalPhysRegClass(const Record *RegRecord,
866 ValueTypeByHwMode *VT = nullptr);
867
868 /// Return the largest register class which supports \p Ty and covers \p
869 /// SubIdx if it exists.
870 const CodeGenRegisterClass *
871 getSuperRegForSubReg(const ValueTypeByHwMode &Ty,
872 const CodeGenSubRegIndex *SubIdx,
873 bool MustBeAllocatable = false) const;
874
875 // Get the sum of unit weights.
876 unsigned getRegUnitSetWeight(const std::vector<unsigned> &Units) const {
877 unsigned Weight = 0;
878 for (unsigned Unit : Units)
879 Weight += getRegUnit(RUID: Unit).Weight;
880 return Weight;
881 }
882
883 unsigned getRegSetIDAt(unsigned Order) const {
884 return RegUnitSetOrder[Order];
885 }
886
887 const RegUnitSet &getRegSetAt(unsigned Order) const {
888 return RegUnitSets[RegUnitSetOrder[Order]];
889 }
890
891 // Increase a RegUnitWeight.
892 void increaseRegUnitWeight(unsigned RUID, unsigned Inc) {
893 getRegUnit(RUID).Weight += Inc;
894 }
895
896 // Get the number of register pressure dimensions.
897 unsigned getNumRegPressureSets() const { return RegUnitSets.size(); }
898
899 // Get a set of register unit IDs for a given dimension of pressure.
900 const RegUnitSet &getRegPressureSet(unsigned Idx) const {
901 return RegUnitSets[Idx];
902 }
903
904 // The number of pressure set lists may be larget than the number of
905 // register classes if some register units appeared in a list of sets that
906 // did not correspond to an existing register class.
907 unsigned getNumRegClassPressureSetLists() const {
908 return RegClassUnitSets.size();
909 }
910
911 // Get a list of pressure set IDs for a register class. Liveness of a
912 // register in this class impacts each pressure set in this list by the
913 // weight of the register. An exact solution requires all registers in a
914 // class to have the same class, but it is not strictly guaranteed.
915 ArrayRef<unsigned> getRCPressureSetIDs(unsigned RCIdx) const {
916 return RegClassUnitSets[RCIdx];
917 }
918
919 // Computed derived records such as missing sub-register indices.
920 void computeDerivedInfo();
921
922 // Compute the set of registers completely covered by the registers in Regs.
923 // The returned BitVector will have a bit set for each register in Regs,
924 // all sub-registers, and all super-registers that are covered by the
925 // registers in Regs.
926 //
927 // This is used to compute the mask of call-preserved registers from a list
928 // of callee-saves.
929 BitVector computeCoveredRegisters(ArrayRef<const Record *> Regs);
930
931 // Bit mask of lanes that cover their registers. A sub-register index whose
932 // LaneMask is contained in CoveringLanes will be completely covered by
933 // another sub-register with the same or larger lane mask.
934 LaneBitmask CoveringLanes;
935};
936
937} // end namespace llvm
938
939#endif // LLVM_UTILS_TABLEGEN_COMMON_CODEGENREGISTERS_H
940