1 //===- CodeGenRegisters.h - Register and RegisterClass Info -----*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines structures to encapsulate information gleaned from the
11 // target register and register class definitions.
13 //===----------------------------------------------------------------------===//
15 #ifndef CODEGEN_REGISTERS_H
16 #define CODEGEN_REGISTERS_H
18 #include "SetTheory.h"
19 #include "llvm/ADT/ArrayRef.h"
20 #include "llvm/ADT/BitVector.h"
21 #include "llvm/ADT/DenseMap.h"
22 #include "llvm/ADT/SetVector.h"
23 #include "llvm/CodeGen/ValueTypes.h"
24 #include "llvm/Support/ErrorHandling.h"
25 #include "llvm/TableGen/Record.h"
35 /// CodeGenSubRegIndex - Represents a sub-register index.
36 class CodeGenSubRegIndex {
39 std::string Namespace;
42 const unsigned EnumValue;
45 // Are all super-registers containing this SubRegIndex covered by their
47 bool AllSuperRegsCovered;
49 CodeGenSubRegIndex(Record *R, unsigned Enum);
50 CodeGenSubRegIndex(StringRef N, StringRef Nspace, unsigned Enum);
52 const std::string &getName() const { return Name; }
53 const std::string &getNamespace() const { return Namespace; }
54 std::string getQualifiedName() const;
56 // Order CodeGenSubRegIndex pointers by EnumValue.
58 bool operator()(const CodeGenSubRegIndex *A,
59 const CodeGenSubRegIndex *B) const {
61 return A->EnumValue < B->EnumValue;
65 // Map of composite subreg indices.
66 typedef std::map<CodeGenSubRegIndex*, CodeGenSubRegIndex*, Less> CompMap;
68 // Returns the subreg index that results from composing this with Idx.
69 // Returns NULL if this and Idx don't compose.
70 CodeGenSubRegIndex *compose(CodeGenSubRegIndex *Idx) const {
71 CompMap::const_iterator I = Composed.find(Idx);
72 return I == Composed.end() ? 0 : I->second;
75 // Add a composite subreg index: this+A = B.
76 // Return a conflicting composite, or NULL
77 CodeGenSubRegIndex *addComposite(CodeGenSubRegIndex *A,
78 CodeGenSubRegIndex *B) {
80 std::pair<CompMap::iterator, bool> Ins =
81 Composed.insert(std::make_pair(A, B));
82 return (Ins.second || Ins.first->second == B) ? 0 : Ins.first->second;
85 // Update the composite maps of components specified in 'ComposedOf'.
86 void updateComponents(CodeGenRegBank&);
88 // Return the map of composites.
89 const CompMap &getComposites() const { return Composed; }
91 // Compute LaneMask from Composed. Return LaneMask.
92 unsigned computeLaneMask();
98 /// CodeGenRegister - Represents a register definition.
99 struct CodeGenRegister {
103 bool CoveredBySubRegs;
105 // Map SubRegIndex -> Register.
106 typedef std::map<CodeGenSubRegIndex*, CodeGenRegister*,
107 CodeGenSubRegIndex::Less> SubRegMap;
109 CodeGenRegister(Record *R, unsigned Enum);
111 const std::string &getName() const;
113 // Extract more information from TheDef. This is used to build an object
114 // graph after all CodeGenRegister objects have been created.
115 void buildObjectGraph(CodeGenRegBank&);
117 // Lazily compute a map of all sub-registers.
118 // This includes unique entries for all sub-sub-registers.
119 const SubRegMap &computeSubRegs(CodeGenRegBank&);
121 // Compute extra sub-registers by combining the existing sub-registers.
122 void computeSecondarySubRegs(CodeGenRegBank&);
124 // Add this as a super-register to all sub-registers after the sub-register
125 // graph has been built.
126 void computeSuperRegs(CodeGenRegBank&);
128 const SubRegMap &getSubRegs() const {
129 assert(SubRegsComplete && "Must precompute sub-registers");
133 // Add sub-registers to OSet following a pre-order defined by the .td file.
134 void addSubRegsPreOrder(SetVector<const CodeGenRegister*> &OSet,
135 CodeGenRegBank&) const;
137 // Return the sub-register index naming Reg as a sub-register of this
138 // register. Returns NULL if Reg is not a sub-register.
139 CodeGenSubRegIndex *getSubRegIndex(const CodeGenRegister *Reg) const {
140 return SubReg2Idx.lookup(Reg);
143 typedef std::vector<const CodeGenRegister*> SuperRegList;
145 // Get the list of super-registers in topological order, small to large.
146 // This is valid after computeSubRegs visits all registers during RegBank
148 const SuperRegList &getSuperRegs() const {
149 assert(SubRegsComplete && "Must precompute sub-registers");
153 // Get the list of ad hoc aliases. The graph is symmetric, so the list
154 // contains all registers in 'Aliases', and all registers that mention this
155 // register in 'Aliases'.
156 ArrayRef<CodeGenRegister*> getExplicitAliases() const {
157 return ExplicitAliases;
160 // Get the topological signature of this register. This is a small integer
161 // less than RegBank.getNumTopoSigs(). Registers with the same TopoSig have
162 // identical sub-register structure. That is, they support the same set of
163 // sub-register indices mapping to the same kind of sub-registers
165 unsigned getTopoSig() const {
166 assert(SuperRegsComplete && "TopoSigs haven't been computed yet.");
170 // List of register units in ascending order.
171 typedef SmallVector<unsigned, 16> RegUnitList;
173 // How many entries in RegUnitList are native?
174 unsigned NumNativeRegUnits;
176 // Get the list of register units.
177 // This is only valid after computeSubRegs() completes.
178 const RegUnitList &getRegUnits() const { return RegUnits; }
180 // Get the native register units. This is a prefix of getRegUnits().
181 ArrayRef<unsigned> getNativeRegUnits() const {
182 return makeArrayRef(RegUnits).slice(0, NumNativeRegUnits);
185 // Inherit register units from subregisters.
186 // Return true if the RegUnits changed.
187 bool inheritRegUnits(CodeGenRegBank &RegBank);
189 // Adopt a register unit for pressure tracking.
190 // A unit is adopted iff its unit number is >= NumNativeRegUnits.
191 void adoptRegUnit(unsigned RUID) { RegUnits.push_back(RUID); }
193 // Get the sum of this register's register unit weights.
194 unsigned getWeight(const CodeGenRegBank &RegBank) const;
196 // Order CodeGenRegister pointers by EnumValue.
198 bool operator()(const CodeGenRegister *A,
199 const CodeGenRegister *B) const {
201 return A->EnumValue < B->EnumValue;
205 // Canonically ordered set.
206 typedef std::set<const CodeGenRegister*, Less> Set;
209 bool SubRegsComplete;
210 bool SuperRegsComplete;
213 // The sub-registers explicit in the .td file form a tree.
214 SmallVector<CodeGenSubRegIndex*, 8> ExplicitSubRegIndices;
215 SmallVector<CodeGenRegister*, 8> ExplicitSubRegs;
217 // Explicit ad hoc aliases, symmetrized to form an undirected graph.
218 SmallVector<CodeGenRegister*, 8> ExplicitAliases;
220 // Super-registers where this is the first explicit sub-register.
221 SuperRegList LeadingSuperRegs;
224 SuperRegList SuperRegs;
225 DenseMap<const CodeGenRegister*, CodeGenSubRegIndex*> SubReg2Idx;
226 RegUnitList RegUnits;
230 class CodeGenRegisterClass {
231 CodeGenRegister::Set Members;
232 // Allocation orders. Order[0] always contains all registers in Members.
233 std::vector<SmallVector<Record*, 16> > Orders;
234 // Bit mask of sub-classes including this, indexed by their EnumValue.
235 BitVector SubClasses;
236 // List of super-classes, topologocally ordered to have the larger classes
237 // first. This is the same as sorting by EnumValue.
238 SmallVector<CodeGenRegisterClass*, 4> SuperClasses;
242 // For a synthesized class, inherit missing properties from the nearest
244 void inheritProperties(CodeGenRegBank&);
246 // Map SubRegIndex -> sub-class. This is the largest sub-class where all
247 // registers have a SubRegIndex sub-register.
248 DenseMap<CodeGenSubRegIndex*, CodeGenRegisterClass*> SubClassWithSubReg;
250 // Map SubRegIndex -> set of super-reg classes. This is all register
251 // classes SuperRC such that:
253 // R:SubRegIndex in this RC for all R in SuperRC.
255 DenseMap<CodeGenSubRegIndex*,
256 SmallPtrSet<CodeGenRegisterClass*, 8> > SuperRegClasses;
258 // Bit vector of TopoSigs for the registers in this class. This will be
259 // very sparse on regular architectures.
264 std::string Namespace;
265 SmallVector<MVT::SimpleValueType, 4> VTs;
267 unsigned SpillAlignment;
270 std::string AltOrderSelect;
272 // Return the Record that defined this class, or NULL if the class was
273 // created by TableGen.
274 Record *getDef() const { return TheDef; }
276 const std::string &getName() const { return Name; }
277 std::string getQualifiedName() const;
278 ArrayRef<MVT::SimpleValueType> getValueTypes() const {return VTs;}
279 unsigned getNumValueTypes() const { return VTs.size(); }
281 MVT::SimpleValueType getValueTypeNum(unsigned VTNum) const {
282 if (VTNum < VTs.size())
284 llvm_unreachable("VTNum greater than number of ValueTypes in RegClass!");
287 // Return true if this this class contains the register.
288 bool contains(const CodeGenRegister*) const;
290 // Returns true if RC is a subclass.
291 // RC is a sub-class of this class if it is a valid replacement for any
292 // instruction operand where a register of this classis required. It must
293 // satisfy these conditions:
295 // 1. All RC registers are also in this.
296 // 2. The RC spill size must not be smaller than our spill size.
297 // 3. RC spill alignment must be compatible with ours.
299 bool hasSubClass(const CodeGenRegisterClass *RC) const {
300 return SubClasses.test(RC->EnumValue);
303 // getSubClassWithSubReg - Returns the largest sub-class where all
304 // registers have a SubIdx sub-register.
305 CodeGenRegisterClass*
306 getSubClassWithSubReg(CodeGenSubRegIndex *SubIdx) const {
307 return SubClassWithSubReg.lookup(SubIdx);
310 void setSubClassWithSubReg(CodeGenSubRegIndex *SubIdx,
311 CodeGenRegisterClass *SubRC) {
312 SubClassWithSubReg[SubIdx] = SubRC;
315 // getSuperRegClasses - Returns a bit vector of all register classes
316 // containing only SubIdx super-registers of this class.
317 void getSuperRegClasses(CodeGenSubRegIndex *SubIdx, BitVector &Out) const;
319 // addSuperRegClass - Add a class containing only SudIdx super-registers.
320 void addSuperRegClass(CodeGenSubRegIndex *SubIdx,
321 CodeGenRegisterClass *SuperRC) {
322 SuperRegClasses[SubIdx].insert(SuperRC);
325 // getSubClasses - Returns a constant BitVector of subclasses indexed by
327 // The SubClasses vector includs an entry for this class.
328 const BitVector &getSubClasses() const { return SubClasses; }
330 // getSuperClasses - Returns a list of super classes ordered by EnumValue.
331 // The array does not include an entry for this class.
332 ArrayRef<CodeGenRegisterClass*> getSuperClasses() const {
336 // Returns an ordered list of class members.
337 // The order of registers is the same as in the .td file.
338 // No = 0 is the default allocation order, No = 1 is the first alternative.
339 ArrayRef<Record*> getOrder(unsigned No = 0) const {
343 // Return the total number of allocation orders available.
344 unsigned getNumOrders() const { return Orders.size(); }
346 // Get the set of registers. This set contains the same registers as
348 const CodeGenRegister::Set &getMembers() const { return Members; }
350 // Get a bit vector of TopoSigs present in this register class.
351 const BitVector &getTopoSigs() const { return TopoSigs; }
353 // Populate a unique sorted list of units from a register set.
354 void buildRegUnitSet(std::vector<unsigned> &RegUnits) const;
356 CodeGenRegisterClass(CodeGenRegBank&, Record *R);
358 // A key representing the parts of a register class used for forming
359 // sub-classes. Note the ordering provided by this key is not the same as
360 // the topological order used for the EnumValues.
362 const CodeGenRegister::Set *Members;
364 unsigned SpillAlignment;
367 : Members(O.Members),
368 SpillSize(O.SpillSize),
369 SpillAlignment(O.SpillAlignment) {}
371 Key(const CodeGenRegister::Set *M, unsigned S = 0, unsigned A = 0)
372 : Members(M), SpillSize(S), SpillAlignment(A) {}
374 Key(const CodeGenRegisterClass &RC)
375 : Members(&RC.getMembers()),
376 SpillSize(RC.SpillSize),
377 SpillAlignment(RC.SpillAlignment) {}
379 // Lexicographical order of (Members, SpillSize, SpillAlignment).
380 bool operator<(const Key&) const;
383 // Create a non-user defined register class.
384 CodeGenRegisterClass(CodeGenRegBank&, StringRef Name, Key Props);
386 // Called by CodeGenRegBank::CodeGenRegBank().
387 static void computeSubClasses(CodeGenRegBank&);
390 // Register units are used to model interference and register pressure.
391 // Every register is assigned one or more register units such that two
392 // registers overlap if and only if they have a register unit in common.
394 // Normally, one register unit is created per leaf register. Non-leaf
395 // registers inherit the units of their sub-registers.
397 // Weight assigned to this RegUnit for estimating register pressure.
398 // This is useful when equalizing weights in register classes with mixed
399 // register topologies.
402 // Each native RegUnit corresponds to one or two root registers. The full
403 // set of registers containing this unit can be computed as the union of
404 // these two registers and their super-registers.
405 const CodeGenRegister *Roots[2];
407 // Index into RegClassUnitSets where we can find the list of UnitSets that
408 // contain this unit.
409 unsigned RegClassUnitSetsIdx;
411 RegUnit() : Weight(0), RegClassUnitSetsIdx(0) { Roots[0] = Roots[1] = 0; }
413 ArrayRef<const CodeGenRegister*> getRoots() const {
414 assert(!(Roots[1] && !Roots[0]) && "Invalid roots array");
415 return makeArrayRef(Roots, !!Roots[0] + !!Roots[1]);
419 // Each RegUnitSet is a sorted vector with a name.
421 typedef std::vector<unsigned>::const_iterator iterator;
424 std::vector<unsigned> Units;
427 // Base vector for identifying TopoSigs. The contents uniquely identify a
428 // TopoSig, only computeSuperRegs needs to know how.
429 typedef SmallVector<unsigned, 16> TopoSigId;
431 // CodeGenRegBank - Represent a target's registers and the relations between
433 class CodeGenRegBank {
437 std::vector<CodeGenSubRegIndex*> SubRegIndices;
438 DenseMap<Record*, CodeGenSubRegIndex*> Def2SubRegIdx;
440 CodeGenSubRegIndex *createSubRegIndex(StringRef Name, StringRef NameSpace);
442 typedef std::map<SmallVector<CodeGenSubRegIndex*, 8>,
443 CodeGenSubRegIndex*> ConcatIdxMap;
444 ConcatIdxMap ConcatIdx;
447 std::vector<CodeGenRegister*> Registers;
448 StringMap<CodeGenRegister*> RegistersByName;
449 DenseMap<Record*, CodeGenRegister*> Def2Reg;
450 unsigned NumNativeRegUnits;
452 std::map<TopoSigId, unsigned> TopoSigs;
454 // Includes native (0..NumNativeRegUnits-1) and adopted register units.
455 SmallVector<RegUnit, 8> RegUnits;
458 std::vector<CodeGenRegisterClass*> RegClasses;
459 DenseMap<Record*, CodeGenRegisterClass*> Def2RC;
460 typedef std::map<CodeGenRegisterClass::Key, CodeGenRegisterClass*> RCKeyMap;
463 // Remember each unique set of register units. Initially, this contains a
464 // unique set for each register class. Simliar sets are coalesced with
465 // pruneUnitSets and new supersets are inferred during computeRegUnitSets.
466 std::vector<RegUnitSet> RegUnitSets;
468 // Map RegisterClass index to the index of the RegUnitSet that contains the
469 // class's units and any inferred RegUnit supersets.
471 // NOTE: This could grow beyond the number of register classes when we map
472 // register units to lists of unit sets. If the list of unit sets does not
473 // already exist for a register class, we create a new entry in this vector.
474 std::vector<std::vector<unsigned> > RegClassUnitSets;
476 // Add RC to *2RC maps.
477 void addToMaps(CodeGenRegisterClass*);
479 // Create a synthetic sub-class if it is missing.
480 CodeGenRegisterClass *getOrCreateSubClass(const CodeGenRegisterClass *RC,
481 const CodeGenRegister::Set *Membs,
484 // Infer missing register classes.
485 void computeInferredRegisterClasses();
486 void inferCommonSubClass(CodeGenRegisterClass *RC);
487 void inferSubClassWithSubReg(CodeGenRegisterClass *RC);
488 void inferMatchingSuperRegClass(CodeGenRegisterClass *RC,
489 unsigned FirstSubRegRC = 0);
491 // Iteratively prune unit sets.
492 void pruneUnitSets();
494 // Compute a weight for each register unit created during getSubRegs.
495 void computeRegUnitWeights();
497 // Create a RegUnitSet for each RegClass and infer superclasses.
498 void computeRegUnitSets();
500 // Populate the Composite map from sub-register relationships.
501 void computeComposites();
503 // Compute a lane mask for each sub-register index.
504 void computeSubRegIndexLaneMasks();
507 CodeGenRegBank(RecordKeeper&);
509 SetTheory &getSets() { return Sets; }
511 // Sub-register indices. The first NumNamedIndices are defined by the user
512 // in the .td files. The rest are synthesized such that all sub-registers
513 // have a unique name.
514 ArrayRef<CodeGenSubRegIndex*> getSubRegIndices() { return SubRegIndices; }
516 // Find a SubRegIndex form its Record def.
517 CodeGenSubRegIndex *getSubRegIdx(Record*);
519 // Find or create a sub-register index representing the A+B composition.
520 CodeGenSubRegIndex *getCompositeSubRegIndex(CodeGenSubRegIndex *A,
521 CodeGenSubRegIndex *B);
523 // Find or create a sub-register index representing the concatenation of
524 // non-overlapping sibling indices.
526 getConcatSubRegIndex(const SmallVector<CodeGenSubRegIndex*, 8>&);
529 addConcatSubRegIndex(const SmallVector<CodeGenSubRegIndex*, 8> &Parts,
530 CodeGenSubRegIndex *Idx) {
531 ConcatIdx.insert(std::make_pair(Parts, Idx));
534 const std::vector<CodeGenRegister*> &getRegisters() { return Registers; }
535 const StringMap<CodeGenRegister*> &getRegistersByName() {
536 return RegistersByName;
539 // Find a register from its Record def.
540 CodeGenRegister *getReg(Record*);
542 // Get a Register's index into the Registers array.
543 unsigned getRegIndex(const CodeGenRegister *Reg) const {
544 return Reg->EnumValue - 1;
547 // Return the number of allocated TopoSigs. The first TopoSig representing
548 // leaf registers is allocated number 0.
549 unsigned getNumTopoSigs() const {
550 return TopoSigs.size();
553 // Find or create a TopoSig for the given TopoSigId.
554 // This function is only for use by CodeGenRegister::computeSuperRegs().
555 // Others should simply use Reg->getTopoSig().
556 unsigned getTopoSig(const TopoSigId &Id) {
557 return TopoSigs.insert(std::make_pair(Id, TopoSigs.size())).first->second;
560 // Create a native register unit that is associated with one or two root
562 unsigned newRegUnit(CodeGenRegister *R0, CodeGenRegister *R1 = 0) {
563 RegUnits.resize(RegUnits.size() + 1);
564 RegUnits.back().Roots[0] = R0;
565 RegUnits.back().Roots[1] = R1;
566 return RegUnits.size() - 1;
569 // Create a new non-native register unit that can be adopted by a register
570 // to increase its pressure. Note that NumNativeRegUnits is not increased.
571 unsigned newRegUnit(unsigned Weight) {
572 RegUnits.resize(RegUnits.size() + 1);
573 RegUnits.back().Weight = Weight;
574 return RegUnits.size() - 1;
577 // Native units are the singular unit of a leaf register. Register aliasing
578 // is completely characterized by native units. Adopted units exist to give
579 // register additional weight but don't affect aliasing.
580 bool isNativeUnit(unsigned RUID) {
581 return RUID < NumNativeRegUnits;
584 unsigned getNumNativeRegUnits() const {
585 return NumNativeRegUnits;
588 RegUnit &getRegUnit(unsigned RUID) { return RegUnits[RUID]; }
589 const RegUnit &getRegUnit(unsigned RUID) const { return RegUnits[RUID]; }
591 ArrayRef<CodeGenRegisterClass*> getRegClasses() const {
595 // Find a register class from its def.
596 CodeGenRegisterClass *getRegClass(Record*);
598 /// getRegisterClassForRegister - Find the register class that contains the
599 /// specified physical register. If the register is not in a register
600 /// class, return null. If the register is in multiple classes, and the
601 /// classes have a superset-subset relationship and the same set of types,
602 /// return the superclass. Otherwise return null.
603 const CodeGenRegisterClass* getRegClassForRegister(Record *R);
605 // Get the sum of unit weights.
606 unsigned getRegUnitSetWeight(const std::vector<unsigned> &Units) const {
608 for (std::vector<unsigned>::const_iterator
609 I = Units.begin(), E = Units.end(); I != E; ++I)
610 Weight += getRegUnit(*I).Weight;
614 // Increase a RegUnitWeight.
615 void increaseRegUnitWeight(unsigned RUID, unsigned Inc) {
616 getRegUnit(RUID).Weight += Inc;
619 // Get the number of register pressure dimensions.
620 unsigned getNumRegPressureSets() const { return RegUnitSets.size(); }
622 // Get a set of register unit IDs for a given dimension of pressure.
623 RegUnitSet getRegPressureSet(unsigned Idx) const {
624 return RegUnitSets[Idx];
627 // The number of pressure set lists may be larget than the number of
628 // register classes if some register units appeared in a list of sets that
629 // did not correspond to an existing register class.
630 unsigned getNumRegClassPressureSetLists() const {
631 return RegClassUnitSets.size();
634 // Get a list of pressure set IDs for a register class. Liveness of a
635 // register in this class impacts each pressure set in this list by the
636 // weight of the register. An exact solution requires all registers in a
637 // class to have the same class, but it is not strictly guaranteed.
638 ArrayRef<unsigned> getRCPressureSetIDs(unsigned RCIdx) const {
639 return RegClassUnitSets[RCIdx];
642 // Computed derived records such as missing sub-register indices.
643 void computeDerivedInfo();
645 // Compute the set of registers completely covered by the registers in Regs.
646 // The returned BitVector will have a bit set for each register in Regs,
647 // all sub-registers, and all super-registers that are covered by the
648 // registers in Regs.
650 // This is used to compute the mask of call-preserved registers from a list
652 BitVector computeCoveredRegisters(ArrayRef<Record*> Regs);
654 // Bit mask of lanes that cover their registers. A sub-register index whose
655 // LaneMask is contained in CoveringLanes will be completely covered by
656 // another sub-register with the same or larger lane mask.
657 unsigned CoveringLanes;