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 != (uint32_t)-1 && ARange.Offset != (uint32_t)-1 &&
128 BRange.Offset == (uint32_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 != (uint32_t)-1 && ARange.Offset != (uint32_t)-1 &&
139 BRange.Offset == (uint32_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 uint8_t SpillStackID;
378 /// Contains the combination of the lane masks of all subregisters.
379 LaneBitmask LaneMask;
380 /// True if there are at least 2 subregisters which do not interfere.
381 bool HasDisjunctSubRegs;
382 bool CoveredBySubRegs;
383 /// A register class is artificial if all its members are artificial.
384 bool Artificial;
385 /// Generate register pressure set for this register class and any class
386 /// synthesized from it.
387 bool GeneratePressureSet;
388
389 // Return the Record that defined this class, or NULL if the class was
390 // created by TableGen.
391 const Record *getDef() const { return TheDef; }
392
393 std::string getNamespaceQualification() const;
394 const std::string &getName() const { return Name; }
395 std::string getQualifiedName() const;
396 std::string getIdName() const;
397 std::string getQualifiedIdName() const;
398 ArrayRef<ValueTypeByHwMode> getValueTypes() const { return VTs; }
399 unsigned getNumValueTypes() const { return VTs.size(); }
400 bool hasType(const ValueTypeByHwMode &VT) const;
401
402 const ValueTypeByHwMode &getValueTypeNum(unsigned VTNum) const {
403 if (VTNum < VTs.size())
404 return VTs[VTNum];
405 llvm_unreachable("VTNum greater than number of ValueTypes in RegClass!");
406 }
407
408 // Return true if this class contains the register.
409 bool contains(const CodeGenRegister *) const;
410
411 // Returns true if RC is a subclass.
412 // RC is a sub-class of this class if it is a valid replacement for any
413 // instruction operand where a register of this classis required. It must
414 // satisfy these conditions:
415 //
416 // 1. All RC registers are also in this.
417 // 2. The RC spill size must not be smaller than our spill size.
418 // 3. RC spill alignment must be compatible with ours.
419 //
420 bool hasSubClass(const CodeGenRegisterClass *RC) const {
421 return SubClasses.test(Idx: RC->EnumValue);
422 }
423
424 // getSubClassWithSubReg - Returns the largest sub-class where all
425 // registers have a SubIdx sub-register.
426 CodeGenRegisterClass *
427 getSubClassWithSubReg(const CodeGenSubRegIndex *SubIdx) const {
428 return SubClassWithSubReg.lookup(Val: SubIdx);
429 }
430
431 /// Find largest subclass where all registers have SubIdx subregisters in
432 /// SubRegClass and the largest subregister class that contains those
433 /// subregisters without (as far as possible) also containing additional
434 /// registers.
435 ///
436 /// This can be used to find a suitable pair of classes for subregister
437 /// copies. \return std::pair<SubClass, SubRegClass> where SubClass is a
438 /// SubClass is a class where every register has SubIdx and SubRegClass is a
439 /// class where every register is covered by the SubIdx subregister of
440 /// SubClass.
441 std::optional<std::pair<CodeGenRegisterClass *, CodeGenRegisterClass *>>
442 getMatchingSubClassWithSubRegs(CodeGenRegBank &RegBank,
443 const CodeGenSubRegIndex *SubIdx) const;
444
445 void setSubClassWithSubReg(const CodeGenSubRegIndex *SubIdx,
446 CodeGenRegisterClass *SubRC) {
447 SubClassWithSubReg[SubIdx] = SubRC;
448 }
449
450 // getSuperRegClasses - Returns a bit vector of all register classes
451 // containing only SubIdx super-registers of this class.
452 void getSuperRegClasses(const CodeGenSubRegIndex *SubIdx,
453 BitVector &Out) const;
454
455 // addSuperRegClass - Add a class containing only SubIdx super-registers.
456 void addSuperRegClass(CodeGenSubRegIndex *SubIdx,
457 CodeGenRegisterClass *SuperRC) {
458 SuperRegClasses[SubIdx].insert(V: SuperRC);
459 }
460
461 void extendSuperRegClasses(CodeGenSubRegIndex *SubIdx);
462
463 // getSubClasses - Returns a constant BitVector of subclasses indexed by
464 // EnumValue.
465 // The SubClasses vector includes an entry for this class.
466 const BitVector &getSubClasses() const { return SubClasses; }
467
468 // getSuperClasses - Returns a list of super classes ordered by EnumValue.
469 // The array does not include an entry for this class.
470 ArrayRef<CodeGenRegisterClass *> getSuperClasses() const {
471 return SuperClasses;
472 }
473
474 // Returns an ordered list of class members.
475 // The order of registers is the same as in the .td file.
476 // No = 0 is the default allocation order, No = 1 is the first alternative.
477 ArrayRef<const Record *> getOrder(unsigned No = 0) const {
478 return Orders[No];
479 }
480
481 // Return the total number of allocation orders available.
482 unsigned getNumOrders() const { return Orders.size(); }
483
484 // Get the set of registers. This set contains the same registers as
485 // getOrder(0).
486 const CodeGenRegister::Vec &getMembers() const { return Members; }
487
488 // Get a bit vector of TopoSigs of registers with super registers in this
489 // register class.
490 const BitVector &getRegsWithSuperRegsTopoSigs() const {
491 return RegsWithSuperRegsTopoSigs;
492 }
493
494 // Get a weight of this register class.
495 unsigned getWeight(const CodeGenRegBank &) const;
496
497 // Populate a unique sorted list of units from a register set.
498 void buildRegUnitSet(const CodeGenRegBank &RegBank,
499 std::vector<unsigned> &RegUnits) const;
500
501 CodeGenRegisterClass(CodeGenRegBank &, const Record *R);
502 CodeGenRegisterClass(CodeGenRegisterClass &) = delete;
503
504 // A key representing the parts of a register class used for forming
505 // sub-classes. Note the ordering provided by this key is not the same as
506 // the topological order used for the EnumValues.
507 struct Key {
508 const CodeGenRegister::Vec *Members;
509 RegSizeInfoByHwMode RSI;
510
511 // Ignore artificial registers when comparing classes. We use this
512 // to find existing classes that contain the same non-artificial
513 // members, but may differ in presence of artificial ones, thus
514 // avoiding creating extra register classes for codegen needs.
515 bool IgnoreArtificialMembers;
516
517 Key(const CodeGenRegister::Vec *M, const RegSizeInfoByHwMode &I,
518 bool IgnoreArtificialMembers = false)
519 : Members(M), RSI(I), IgnoreArtificialMembers(IgnoreArtificialMembers) {
520 }
521
522 Key(const CodeGenRegisterClass &RC, bool IgnoreArtificialMembers = false)
523 : Members(&RC.getMembers()), RSI(RC.RSI),
524 IgnoreArtificialMembers(IgnoreArtificialMembers) {}
525
526 // Lexicographical order of (Members, RegSizeInfoByHwMode).
527 bool operator<(const Key &) const;
528 };
529
530 // Create a non-user defined register class.
531 CodeGenRegisterClass(CodeGenRegBank &, StringRef Name, Key Props);
532
533 // Called by CodeGenRegBank::CodeGenRegBank().
534 static void computeSubClasses(CodeGenRegBank &);
535
536 // Get ordering value among register base classes.
537 std::optional<int> getBaseClassOrder() const {
538 if (TheDef && !TheDef->isValueUnset(FieldName: "BaseClassOrder"))
539 return TheDef->getValueAsInt(FieldName: "BaseClassOrder");
540 return {};
541 }
542
543 void setInferredFrom(CodeGenSubRegIndex *Idx, CodeGenRegisterClass *RC) {
544 assert(Idx && RC);
545 assert(!InferredFromSubRegIdx);
546
547 InferredFromSubRegIdx = Idx;
548 InferredFromRC = RC;
549 }
550
551 CodeGenSubRegIndex *getInferredFromSubRegIdx() const {
552 return InferredFromSubRegIdx;
553 }
554
555 CodeGenRegisterClass *getInferredFromRC() const { return InferredFromRC; }
556};
557
558// Register categories are used when we need to deterine the category a
559// register falls into (GPR, vector, fixed, etc.) without having to know
560// specific information about the target architecture.
561class CodeGenRegisterCategory {
562 const Record *TheDef;
563 std::string Name;
564 std::list<CodeGenRegisterClass *> Classes;
565
566public:
567 CodeGenRegisterCategory(CodeGenRegBank &, const Record *R);
568 CodeGenRegisterCategory(CodeGenRegisterCategory &) = delete;
569
570 // Return the Record that defined this class, or NULL if the class was
571 // created by TableGen.
572 const Record *getDef() const { return TheDef; }
573
574 std::string getName() const { return Name; }
575 std::list<CodeGenRegisterClass *> getClasses() const { return Classes; }
576};
577
578// Register units are used to model interference and register pressure.
579// Every register is assigned one or more register units such that two
580// registers overlap if and only if they have a register unit in common.
581//
582// Normally, one register unit is created per leaf register. Non-leaf
583// registers inherit the units of their sub-registers.
584struct RegUnit {
585 // Weight assigned to this RegUnit for estimating register pressure.
586 // This is useful when equalizing weights in register classes with mixed
587 // register topologies.
588 unsigned Weight = 0;
589
590 // Each native RegUnit corresponds to one or two root registers. The full
591 // set of registers containing this unit can be computed as the union of
592 // these two registers and their super-registers.
593 const CodeGenRegister *Roots[2];
594
595 // Index into RegClassUnitSets where we can find the list of UnitSets that
596 // contain this unit.
597 unsigned RegClassUnitSetsIdx = 0;
598 // A register unit is artificial if at least one of its roots is
599 // artificial.
600 bool Artificial = false;
601
602 RegUnit() { Roots[0] = Roots[1] = nullptr; }
603
604 ArrayRef<const CodeGenRegister *> getRoots() const {
605 assert(!(Roots[1] && !Roots[0]) && "Invalid roots array");
606 return ArrayRef(Roots, !!Roots[0] + !!Roots[1]);
607 }
608};
609
610// Each RegUnitSet is a sorted vector with a name.
611struct RegUnitSet {
612 using iterator = std::vector<unsigned>::const_iterator;
613
614 std::string Name;
615 std::vector<unsigned> Units;
616 unsigned Weight = 0; // Cache the sum of all unit weights.
617 unsigned Order = 0; // Cache the sort key.
618
619 RegUnitSet(std::string Name) : Name(std::move(Name)) {}
620};
621
622// Base vector for identifying TopoSigs. The contents uniquely identify a
623// TopoSig, only computeSuperRegs needs to know how.
624using TopoSigId = SmallVector<unsigned, 16>;
625
626// CodeGenRegBank - Represent a target's registers and the relations between
627// them.
628class CodeGenRegBank {
629 const RecordKeeper &Records;
630
631 SetTheory Sets;
632
633 const CodeGenHwModes &CGH;
634
635 const bool RegistersAreIntervals;
636
637 std::deque<CodeGenSubRegIndex> SubRegIndices;
638 DenseMap<const Record *, CodeGenSubRegIndex *> Def2SubRegIdx;
639
640 // Subregister indices sorted topologically by composition.
641 std::vector<CodeGenSubRegIndex *> SubRegIndicesRPOT;
642
643 CodeGenSubRegIndex *createSubRegIndex(StringRef Name, StringRef NameSpace);
644
645 using ConcatIdxMap =
646 std::map<SmallVector<CodeGenSubRegIndex *, 8>, CodeGenSubRegIndex *>;
647 ConcatIdxMap ConcatIdx;
648
649 // Registers.
650 std::deque<CodeGenRegister> Registers;
651 StringMap<CodeGenRegister *> RegistersByName;
652 DenseMap<const Record *, CodeGenRegister *> Def2Reg;
653 unsigned NumNativeRegUnits;
654
655 std::map<TopoSigId, unsigned> TopoSigs;
656
657 // Includes native (0..NumNativeRegUnits-1) and adopted register units.
658 SmallVector<RegUnit, 8> RegUnits;
659
660 // Register classes.
661 std::list<CodeGenRegisterClass> RegClasses;
662 DenseMap<const Record *, CodeGenRegisterClass *> Def2RC;
663 using RCKeyMap = std::map<CodeGenRegisterClass::Key, CodeGenRegisterClass *>;
664 RCKeyMap Key2RC;
665
666 // Register categories.
667 std::list<CodeGenRegisterCategory> RegCategories;
668 using RCatKeyMap =
669 std::map<CodeGenRegisterClass::Key, CodeGenRegisterCategory *>;
670 RCatKeyMap Key2RCat;
671
672 // Remember each unique set of register units. Initially, this contains a
673 // unique set for each register class. Simliar sets are coalesced with
674 // pruneUnitSets and new supersets are inferred during computeRegUnitSets.
675 std::vector<RegUnitSet> RegUnitSets;
676
677 // Map RegisterClass index to the index of the RegUnitSet that contains the
678 // class's units and any inferred RegUnit supersets.
679 //
680 // NOTE: This could grow beyond the number of register classes when we map
681 // register units to lists of unit sets. If the list of unit sets does not
682 // already exist for a register class, we create a new entry in this vector.
683 std::vector<std::vector<unsigned>> RegClassUnitSets;
684
685 // Give each register unit set an order based on sorting criteria.
686 std::vector<unsigned> RegUnitSetOrder;
687
688 // Keep track of synthesized definitions generated in TupleExpander.
689 std::vector<std::unique_ptr<Record>> SynthDefs;
690
691 // Add RC to *2RC maps.
692 void addToMaps(CodeGenRegisterClass *);
693
694 // Create a synthetic sub-class if it is missing. Returns (RC, inserted).
695 std::pair<CodeGenRegisterClass *, bool>
696 getOrCreateSubClass(const CodeGenRegisterClass *RC,
697 const CodeGenRegister::Vec *Membs, StringRef Name);
698
699 // Infer missing register classes.
700 void computeInferredRegisterClasses();
701 void inferCommonSubClass(CodeGenRegisterClass *RC);
702 void inferSubClassWithSubReg(CodeGenRegisterClass *RC);
703
704 void inferMatchingSuperRegClass(CodeGenRegisterClass *RC) {
705 inferMatchingSuperRegClass(RC, FirstSubRegRC: RegClasses.begin());
706 }
707
708 void inferMatchingSuperRegClass(
709 CodeGenRegisterClass *RC,
710 std::list<CodeGenRegisterClass>::iterator FirstSubRegRC);
711
712 // Iteratively prune unit sets.
713 void pruneUnitSets();
714
715 // Compute a weight for each register unit created during getSubRegs.
716 void computeRegUnitWeights();
717
718 // Enforce that all registers are intervals of regunits if requested.
719 void enforceRegUnitIntervals();
720
721 // Create a RegUnitSet for each RegClass and infer superclasses.
722 void computeRegUnitSets();
723
724 // Populate the Composite map from sub-register relationships.
725 void computeComposites();
726
727 // Compute a lane mask for each sub-register index.
728 void computeSubRegLaneMasks();
729
730 // Compute RPOT of subregister indices by composition.
731 void computeSubRegIndicesRPOT();
732
733 /// Computes a lane mask for each register unit enumerated by a physical
734 /// register.
735 void computeRegUnitLaneMasks();
736
737 // Helper function for printing debug information. Handles artificial
738 // (non-native) reg units.
739 void printRegUnitNames(ArrayRef<unsigned> Units) const;
740
741public:
742 CodeGenRegBank(const RecordKeeper &, const CodeGenHwModes &,
743 const bool RegistersAreIntervals);
744 CodeGenRegBank(CodeGenRegBank &) = delete;
745
746 SetTheory &getSets() { return Sets; }
747
748 const CodeGenHwModes &getHwModes() const { return CGH; }
749
750 // Sub-register indices. The first NumNamedIndices are defined by the user
751 // in the .td files. The rest are synthesized such that all sub-registers
752 // have a unique name.
753 const std::deque<CodeGenSubRegIndex> &getSubRegIndices() const {
754 return SubRegIndices;
755 }
756
757 // Find a SubRegIndex from its Record def or add to the list if it does
758 // not exist there yet.
759 CodeGenSubRegIndex *getSubRegIdx(const Record *);
760
761 // Find a SubRegIndex from its Record def.
762 const CodeGenSubRegIndex *findSubRegIdx(const Record *Def) const;
763
764 // Find or create a sub-register index representing the A+B composition.
765 CodeGenSubRegIndex *getCompositeSubRegIndex(CodeGenSubRegIndex *A,
766 CodeGenSubRegIndex *B);
767
768 // Find or create a sub-register index representing the concatenation of
769 // non-overlapping sibling indices.
770 CodeGenSubRegIndex *
771 getConcatSubRegIndex(const SmallVector<CodeGenSubRegIndex *, 8> &Parts,
772 const CodeGenHwModes &CGH);
773
774 const std::deque<CodeGenRegister> &getRegisters() const { return Registers; }
775
776 const StringMap<CodeGenRegister *> &getRegistersByName() const {
777 return RegistersByName;
778 }
779
780 // Find a register from its Record def.
781 CodeGenRegister *getReg(const Record *);
782
783 // Get a Register's index into the Registers array.
784 static unsigned getRegIndex(const CodeGenRegister *Reg) {
785 return Reg->EnumValue - 1;
786 }
787
788 // Return the number of allocated TopoSigs. The first TopoSig representing
789 // leaf registers is allocated number 0.
790 unsigned getNumTopoSigs() const { return TopoSigs.size(); }
791
792 // Find or create a TopoSig for the given TopoSigId.
793 // This function is only for use by CodeGenRegister::computeSuperRegs().
794 // Others should simply use Reg->getTopoSig().
795 unsigned getTopoSig(const TopoSigId &Id) {
796 return TopoSigs.try_emplace(k: Id, args: TopoSigs.size()).first->second;
797 }
798
799 // Create a native register unit that is associated with one or two root
800 // registers.
801 unsigned newRegUnit(CodeGenRegister *R0, CodeGenRegister *R1 = nullptr) {
802 RegUnit &RU = RegUnits.emplace_back();
803 RU.Roots[0] = R0;
804 RU.Roots[1] = R1;
805 RU.Artificial = R0->Artificial;
806 if (R1)
807 RU.Artificial |= R1->Artificial;
808 return RegUnits.size() - 1;
809 }
810
811 // Create a new non-native register unit that can be adopted by a register
812 // to increase its pressure. Note that NumNativeRegUnits is not increased.
813 unsigned newRegUnit(unsigned Weight) {
814 RegUnit &RU = RegUnits.emplace_back();
815 RU.Weight = Weight;
816 return RegUnits.size() - 1;
817 }
818
819 // Native units are the singular unit of a leaf register. Register aliasing
820 // is completely characterized by native units. Adopted units exist to give
821 // register additional weight but don't affect aliasing.
822 bool isNativeUnit(unsigned RUID) const { return RUID < NumNativeRegUnits; }
823
824 unsigned getNumNativeRegUnits() const { return NumNativeRegUnits; }
825
826 RegUnit &getRegUnit(unsigned RUID) { return RegUnits[RUID]; }
827 const RegUnit &getRegUnit(unsigned RUID) const { return RegUnits[RUID]; }
828
829 std::list<CodeGenRegisterClass> &getRegClasses() { return RegClasses; }
830
831 const std::list<CodeGenRegisterClass> &getRegClasses() const {
832 return RegClasses;
833 }
834
835 std::list<CodeGenRegisterCategory> &getRegCategories() {
836 return RegCategories;
837 }
838
839 const std::list<CodeGenRegisterCategory> &getRegCategories() const {
840 return RegCategories;
841 }
842
843 // Find a register class from its def.
844 CodeGenRegisterClass *getRegClass(const Record *,
845 ArrayRef<SMLoc> Loc = {}) const;
846
847 /// getRegisterClassForRegister - Find the register class that contains the
848 /// specified physical register. If the register is not in a register
849 /// class, return null. If the register is in multiple classes, and the
850 /// classes have a superset-subset relationship and the same set of types,
851 /// return the superclass. Otherwise return null.
852 const CodeGenRegisterClass *getRegClassForRegister(const Record *R);
853
854 /// Returns whether \p RegClass contains register \p Reg, handling
855 /// RegClassByHwMode and RegisterByHwMode correctly.
856 /// This should be preferred instead of
857 /// `RegBank.getRegClass(RC).contains(RegBank.getReg(R))`.
858 bool regClassContainsReg(const Record *RegClass, const Record *RegDef,
859 ArrayRef<SMLoc> Loc = {});
860
861 // Analog of TargetRegisterInfo::getMinimalPhysRegClass. Unlike
862 // getRegClassForRegister, this tries to find the smallest class containing
863 // the physical register. If \p VT is specified, it will only find classes
864 // with a matching type
865 const CodeGenRegisterClass *
866 getMinimalPhysRegClass(const Record *RegRecord,
867 ValueTypeByHwMode *VT = nullptr);
868
869 /// Return the largest register class which supports \p Ty and covers \p
870 /// SubIdx if it exists.
871 const CodeGenRegisterClass *
872 getSuperRegForSubReg(const ValueTypeByHwMode &Ty,
873 const CodeGenSubRegIndex *SubIdx,
874 bool MustBeAllocatable = false) const;
875
876 // Get the sum of unit weights.
877 unsigned getRegUnitSetWeight(const std::vector<unsigned> &Units) const {
878 unsigned Weight = 0;
879 for (unsigned Unit : Units)
880 Weight += getRegUnit(RUID: Unit).Weight;
881 return Weight;
882 }
883
884 unsigned getRegSetIDAt(unsigned Order) const {
885 return RegUnitSetOrder[Order];
886 }
887
888 const RegUnitSet &getRegSetAt(unsigned Order) const {
889 return RegUnitSets[RegUnitSetOrder[Order]];
890 }
891
892 // Increase a RegUnitWeight.
893 void increaseRegUnitWeight(unsigned RUID, unsigned Inc) {
894 getRegUnit(RUID).Weight += Inc;
895 }
896
897 // Get the number of register pressure dimensions.
898 unsigned getNumRegPressureSets() const { return RegUnitSets.size(); }
899
900 // Get a set of register unit IDs for a given dimension of pressure.
901 const RegUnitSet &getRegPressureSet(unsigned Idx) const {
902 return RegUnitSets[Idx];
903 }
904
905 // The number of pressure set lists may be larget than the number of
906 // register classes if some register units appeared in a list of sets that
907 // did not correspond to an existing register class.
908 unsigned getNumRegClassPressureSetLists() const {
909 return RegClassUnitSets.size();
910 }
911
912 // Get a list of pressure set IDs for a register class. Liveness of a
913 // register in this class impacts each pressure set in this list by the
914 // weight of the register. An exact solution requires all registers in a
915 // class to have the same class, but it is not strictly guaranteed.
916 ArrayRef<unsigned> getRCPressureSetIDs(unsigned RCIdx) const {
917 return RegClassUnitSets[RCIdx];
918 }
919
920 // Computed derived records such as missing sub-register indices.
921 void computeDerivedInfo();
922
923 // Compute the set of registers completely covered by the registers in Regs.
924 // The returned BitVector will have a bit set for each register in Regs,
925 // all sub-registers, and all super-registers that are covered by the
926 // registers in Regs.
927 //
928 // This is used to compute the mask of call-preserved registers from a list
929 // of callee-saves.
930 BitVector computeCoveredRegisters(ArrayRef<const Record *> Regs);
931
932 // Bit mask of lanes that cover their registers. A sub-register index whose
933 // LaneMask is contained in CoveringLanes will be completely covered by
934 // another sub-register with the same or larger lane mask.
935 LaneBitmask CoveringLanes;
936};
937
938} // end namespace llvm
939
940#endif // LLVM_UTILS_TABLEGEN_COMMON_CODEGENREGISTERS_H
941