1 //===- CodeGenRegisters.cpp - Register and RegisterClass Info -------------===//
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 #include "CodeGenRegisters.h"
16 #include "CodeGenTarget.h"
17 #include "llvm/ADT/SmallVector.h"
18 #include "llvm/ADT/StringExtras.h"
22 //===----------------------------------------------------------------------===//
24 //===----------------------------------------------------------------------===//
26 CodeGenRegister::CodeGenRegister(Record *R, unsigned Enum)
29 CostPerUse(R->getValueAsInt("CostPerUse")),
30 SubRegsComplete(false)
33 const std::string &CodeGenRegister::getName() const {
34 return TheDef->getName();
39 CodeGenRegister *SubReg;
40 Record *First, *Second;
41 Orphan(CodeGenRegister *r, Record *a, Record *b)
42 : SubReg(r), First(a), Second(b) {}
46 const CodeGenRegister::SubRegMap &
47 CodeGenRegister::getSubRegs(CodeGenRegBank &RegBank) {
48 // Only compute this map once.
51 SubRegsComplete = true;
53 std::vector<Record*> SubList = TheDef->getValueAsListOfDefs("SubRegs");
54 std::vector<Record*> Indices = TheDef->getValueAsListOfDefs("SubRegIndices");
55 if (SubList.size() != Indices.size())
56 throw TGError(TheDef->getLoc(), "Register " + getName() +
57 " SubRegIndices doesn't match SubRegs");
59 // First insert the direct subregs and make sure they are fully indexed.
60 for (unsigned i = 0, e = SubList.size(); i != e; ++i) {
61 CodeGenRegister *SR = RegBank.getReg(SubList[i]);
62 if (!SubRegs.insert(std::make_pair(Indices[i], SR)).second)
63 throw TGError(TheDef->getLoc(), "SubRegIndex " + Indices[i]->getName() +
64 " appears twice in Register " + getName());
67 // Keep track of inherited subregs and how they can be reached.
68 SmallVector<Orphan, 8> Orphans;
70 // Clone inherited subregs and place duplicate entries on Orphans.
71 // Here the order is important - earlier subregs take precedence.
72 for (unsigned i = 0, e = SubList.size(); i != e; ++i) {
73 CodeGenRegister *SR = RegBank.getReg(SubList[i]);
74 const SubRegMap &Map = SR->getSubRegs(RegBank);
76 // Add this as a super-register of SR now all sub-registers are in the list.
77 // This creates a topological ordering, the exact order depends on the
78 // order getSubRegs is called on all registers.
79 SR->SuperRegs.push_back(this);
81 for (SubRegMap::const_iterator SI = Map.begin(), SE = Map.end(); SI != SE;
83 if (!SubRegs.insert(*SI).second)
84 Orphans.push_back(Orphan(SI->second, Indices[i], SI->first));
86 // Noop sub-register indexes are possible, so avoid duplicates.
88 SI->second->SuperRegs.push_back(this);
92 // Process the composites.
93 ListInit *Comps = TheDef->getValueAsListInit("CompositeIndices");
94 for (unsigned i = 0, e = Comps->size(); i != e; ++i) {
95 DagInit *Pat = dynamic_cast<DagInit*>(Comps->getElement(i));
97 throw TGError(TheDef->getLoc(), "Invalid dag '" +
98 Comps->getElement(i)->getAsString() +
99 "' in CompositeIndices");
100 DefInit *BaseIdxInit = dynamic_cast<DefInit*>(Pat->getOperator());
101 if (!BaseIdxInit || !BaseIdxInit->getDef()->isSubClassOf("SubRegIndex"))
102 throw TGError(TheDef->getLoc(), "Invalid SubClassIndex in " +
105 // Resolve list of subreg indices into R2.
106 CodeGenRegister *R2 = this;
107 for (DagInit::const_arg_iterator di = Pat->arg_begin(),
108 de = Pat->arg_end(); di != de; ++di) {
109 DefInit *IdxInit = dynamic_cast<DefInit*>(*di);
110 if (!IdxInit || !IdxInit->getDef()->isSubClassOf("SubRegIndex"))
111 throw TGError(TheDef->getLoc(), "Invalid SubClassIndex in " +
113 const SubRegMap &R2Subs = R2->getSubRegs(RegBank);
114 SubRegMap::const_iterator ni = R2Subs.find(IdxInit->getDef());
115 if (ni == R2Subs.end())
116 throw TGError(TheDef->getLoc(), "Composite " + Pat->getAsString() +
117 " refers to bad index in " + R2->getName());
121 // Insert composite index. Allow overriding inherited indices etc.
122 SubRegs[BaseIdxInit->getDef()] = R2;
124 // R2 is no longer an orphan.
125 for (unsigned j = 0, je = Orphans.size(); j != je; ++j)
126 if (Orphans[j].SubReg == R2)
127 Orphans[j].SubReg = 0;
130 // Now Orphans contains the inherited subregisters without a direct index.
131 // Create inferred indexes for all missing entries.
132 for (unsigned i = 0, e = Orphans.size(); i != e; ++i) {
133 Orphan &O = Orphans[i];
136 SubRegs[RegBank.getCompositeSubRegIndex(O.First, O.Second, true)] =
143 CodeGenRegister::addSubRegsPreOrder(SetVector<CodeGenRegister*> &OSet) const {
144 assert(SubRegsComplete && "Must precompute sub-registers");
145 std::vector<Record*> Indices = TheDef->getValueAsListOfDefs("SubRegIndices");
146 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
147 CodeGenRegister *SR = SubRegs.find(Indices[i])->second;
149 SR->addSubRegsPreOrder(OSet);
153 //===----------------------------------------------------------------------===//
154 // CodeGenRegisterClass
155 //===----------------------------------------------------------------------===//
157 CodeGenRegisterClass::CodeGenRegisterClass(CodeGenRegBank &RegBank, Record *R)
159 // Rename anonymous register classes.
160 if (R->getName().size() > 9 && R->getName()[9] == '.') {
161 static unsigned AnonCounter = 0;
162 R->setName("AnonRegClass_"+utostr(AnonCounter++));
165 std::vector<Record*> TypeList = R->getValueAsListOfDefs("RegTypes");
166 for (unsigned i = 0, e = TypeList.size(); i != e; ++i) {
167 Record *Type = TypeList[i];
168 if (!Type->isSubClassOf("ValueType"))
169 throw "RegTypes list member '" + Type->getName() +
170 "' does not derive from the ValueType class!";
171 VTs.push_back(getValueType(Type));
173 assert(!VTs.empty() && "RegisterClass must contain at least one ValueType!");
175 Elements = R->getValueAsListOfDefs("MemberList");
176 for (unsigned i = 0, e = Elements.size(); i != e; ++i)
177 Members.insert(RegBank.getReg(Elements[i]));
179 // SubRegClasses is a list<dag> containing (RC, subregindex, ...) dags.
180 ListInit *SRC = R->getValueAsListInit("SubRegClasses");
181 for (ListInit::const_iterator i = SRC->begin(), e = SRC->end(); i != e; ++i) {
182 DagInit *DAG = dynamic_cast<DagInit*>(*i);
183 if (!DAG) throw "SubRegClasses must contain DAGs";
184 DefInit *DAGOp = dynamic_cast<DefInit*>(DAG->getOperator());
186 if (!DAGOp || !(RCRec = DAGOp->getDef())->isSubClassOf("RegisterClass"))
187 throw "Operator '" + DAG->getOperator()->getAsString() +
188 "' in SubRegClasses is not a RegisterClass";
189 // Iterate over args, all SubRegIndex instances.
190 for (DagInit::const_arg_iterator ai = DAG->arg_begin(), ae = DAG->arg_end();
192 DefInit *Idx = dynamic_cast<DefInit*>(*ai);
194 if (!Idx || !(IdxRec = Idx->getDef())->isSubClassOf("SubRegIndex"))
195 throw "Argument '" + (*ai)->getAsString() +
196 "' in SubRegClasses is not a SubRegIndex";
197 if (!SubRegClasses.insert(std::make_pair(IdxRec, RCRec)).second)
198 throw "SubRegIndex '" + IdxRec->getName() + "' mentioned twice";
202 // Allow targets to override the size in bits of the RegisterClass.
203 unsigned Size = R->getValueAsInt("Size");
205 Namespace = R->getValueAsString("Namespace");
206 SpillSize = Size ? Size : EVT(VTs[0]).getSizeInBits();
207 SpillAlignment = R->getValueAsInt("Alignment");
208 CopyCost = R->getValueAsInt("CopyCost");
209 Allocatable = R->getValueAsBit("isAllocatable");
210 MethodBodies = R->getValueAsCode("MethodBodies");
211 MethodProtos = R->getValueAsCode("MethodProtos");
214 bool CodeGenRegisterClass::contains(const CodeGenRegister *Reg) const {
215 return Members.count(Reg);
218 // Returns true if RC is a strict subclass.
219 // RC is a sub-class of this class if it is a valid replacement for any
220 // instruction operand where a register of this classis required. It must
221 // satisfy these conditions:
223 // 1. All RC registers are also in this.
224 // 2. The RC spill size must not be smaller than our spill size.
225 // 3. RC spill alignment must be compatible with ours.
227 bool CodeGenRegisterClass::hasSubClass(const CodeGenRegisterClass *RC) const {
228 return SpillAlignment && RC->SpillAlignment % SpillAlignment == 0 &&
229 SpillSize <= RC->SpillSize &&
230 std::includes(Members.begin(), Members.end(),
231 RC->Members.begin(), RC->Members.end());
234 const std::string &CodeGenRegisterClass::getName() const {
235 return TheDef->getName();
238 //===----------------------------------------------------------------------===//
240 //===----------------------------------------------------------------------===//
242 CodeGenRegBank::CodeGenRegBank(RecordKeeper &Records) : Records(Records) {
243 // Read in the user-defined (named) sub-register indices.
244 // More indices will be synthesized later.
245 SubRegIndices = Records.getAllDerivedDefinitions("SubRegIndex");
246 std::sort(SubRegIndices.begin(), SubRegIndices.end(), LessRecord());
247 NumNamedIndices = SubRegIndices.size();
249 // Read in the register definitions.
250 std::vector<Record*> Regs = Records.getAllDerivedDefinitions("Register");
251 std::sort(Regs.begin(), Regs.end(), LessRecord());
252 Registers.reserve(Regs.size());
253 // Assign the enumeration values.
254 for (unsigned i = 0, e = Regs.size(); i != e; ++i)
255 Registers.push_back(CodeGenRegister(Regs[i], i + 1));
257 // Read in register class definitions.
258 std::vector<Record*> RCs = Records.getAllDerivedDefinitions("RegisterClass");
260 throw std::string("No 'RegisterClass' subclasses defined!");
262 RegClasses.reserve(RCs.size());
263 for (unsigned i = 0, e = RCs.size(); i != e; ++i)
264 RegClasses.push_back(CodeGenRegisterClass(*this, RCs[i]));
267 CodeGenRegister *CodeGenRegBank::getReg(Record *Def) {
269 for (unsigned i = 0, e = Registers.size(); i != e; ++i)
270 Def2Reg[Registers[i].TheDef] = &Registers[i];
272 if (CodeGenRegister *Reg = Def2Reg[Def])
275 throw TGError(Def->getLoc(), "Not a known Register!");
278 CodeGenRegisterClass *CodeGenRegBank::getRegClass(Record *Def) {
280 for (unsigned i = 0, e = RegClasses.size(); i != e; ++i)
281 Def2RC[RegClasses[i].TheDef] = &RegClasses[i];
283 if (CodeGenRegisterClass *RC = Def2RC[Def])
286 throw TGError(Def->getLoc(), "Not a known RegisterClass!");
289 Record *CodeGenRegBank::getCompositeSubRegIndex(Record *A, Record *B,
291 // Look for an existing entry.
292 Record *&Comp = Composite[std::make_pair(A, B)];
296 // None exists, synthesize one.
297 std::string Name = A->getName() + "_then_" + B->getName();
298 Comp = new Record(Name, SMLoc(), Records);
299 Records.addDef(Comp);
300 SubRegIndices.push_back(Comp);
304 unsigned CodeGenRegBank::getSubRegIndexNo(Record *idx) {
305 std::vector<Record*>::const_iterator i =
306 std::find(SubRegIndices.begin(), SubRegIndices.end(), idx);
307 assert(i != SubRegIndices.end() && "Not a SubRegIndex");
308 return (i - SubRegIndices.begin()) + 1;
311 void CodeGenRegBank::computeComposites() {
312 // Precompute all sub-register maps. This will create Composite entries for
313 // all inferred sub-register indices.
314 for (unsigned i = 0, e = Registers.size(); i != e; ++i)
315 Registers[i].getSubRegs(*this);
317 for (unsigned i = 0, e = Registers.size(); i != e; ++i) {
318 CodeGenRegister *Reg1 = &Registers[i];
319 const CodeGenRegister::SubRegMap &SRM1 = Reg1->getSubRegs();
320 for (CodeGenRegister::SubRegMap::const_iterator i1 = SRM1.begin(),
321 e1 = SRM1.end(); i1 != e1; ++i1) {
322 Record *Idx1 = i1->first;
323 CodeGenRegister *Reg2 = i1->second;
324 // Ignore identity compositions.
327 const CodeGenRegister::SubRegMap &SRM2 = Reg2->getSubRegs();
328 // Try composing Idx1 with another SubRegIndex.
329 for (CodeGenRegister::SubRegMap::const_iterator i2 = SRM2.begin(),
330 e2 = SRM2.end(); i2 != e2; ++i2) {
331 std::pair<Record*, Record*> IdxPair(Idx1, i2->first);
332 CodeGenRegister *Reg3 = i2->second;
333 // Ignore identity compositions.
336 // OK Reg1:IdxPair == Reg3. Find the index with Reg:Idx == Reg3.
337 for (CodeGenRegister::SubRegMap::const_iterator i1d = SRM1.begin(),
338 e1d = SRM1.end(); i1d != e1d; ++i1d) {
339 if (i1d->second == Reg3) {
340 std::pair<CompositeMap::iterator, bool> Ins =
341 Composite.insert(std::make_pair(IdxPair, i1d->first));
342 // Conflicting composition? Emit a warning but allow it.
343 if (!Ins.second && Ins.first->second != i1d->first) {
344 errs() << "Warning: SubRegIndex " << getQualifiedName(Idx1)
345 << " and " << getQualifiedName(IdxPair.second)
346 << " compose ambiguously as "
347 << getQualifiedName(Ins.first->second) << " or "
348 << getQualifiedName(i1d->first) << "\n";
356 // We don't care about the difference between (Idx1, Idx2) -> Idx2 and invalid
357 // compositions, so remove any mappings of that form.
358 for (CompositeMap::iterator i = Composite.begin(), e = Composite.end();
360 CompositeMap::iterator j = i;
362 if (j->first.second == j->second)
367 // Compute sets of overlapping registers.
369 // The standard set is all super-registers and all sub-registers, but the
370 // target description can add arbitrary overlapping registers via the 'Aliases'
371 // field. This complicates things, but we can compute overlapping sets using
372 // the following rules:
374 // 1. The relation overlap(A, B) is reflexive and symmetric but not transitive.
376 // 2. overlap(A, B) implies overlap(A, S) for all S in supers(B).
380 // overlap(A, B) iff there exists:
381 // A' in { A, subregs(A) } and B' in { B, subregs(B) } such that:
382 // A' = B' or A' in aliases(B') or B' in aliases(A').
384 // Here subregs(A) is the full flattened sub-register set returned by
385 // A.getSubRegs() while aliases(A) is simply the special 'Aliases' field in the
386 // description of register A.
388 // This also implies that registers with a common sub-register are considered
389 // overlapping. This can happen when forming register pairs:
395 // In this case, we will infer an overlap between P0 and P1 because of the
396 // shared sub-register R1. There is no overlap between P0 and P2.
398 void CodeGenRegBank::
399 computeOverlaps(std::map<const CodeGenRegister*, CodeGenRegister::Set> &Map) {
402 // Collect overlaps that don't follow from rule 2.
403 for (unsigned i = 0, e = Registers.size(); i != e; ++i) {
404 CodeGenRegister *Reg = &Registers[i];
405 CodeGenRegister::Set &Overlaps = Map[Reg];
407 // Reg overlaps itself.
408 Overlaps.insert(Reg);
410 // All super-registers overlap.
411 const CodeGenRegister::SuperRegList &Supers = Reg->getSuperRegs();
412 Overlaps.insert(Supers.begin(), Supers.end());
414 // Form symmetrical relations from the special Aliases[] lists.
415 std::vector<Record*> RegList = Reg->TheDef->getValueAsListOfDefs("Aliases");
416 for (unsigned i2 = 0, e2 = RegList.size(); i2 != e2; ++i2) {
417 CodeGenRegister *Reg2 = getReg(RegList[i2]);
418 CodeGenRegister::Set &Overlaps2 = Map[Reg2];
419 const CodeGenRegister::SuperRegList &Supers2 = Reg2->getSuperRegs();
420 // Reg overlaps Reg2 which implies it overlaps supers(Reg2).
421 Overlaps.insert(Reg2);
422 Overlaps.insert(Supers2.begin(), Supers2.end());
423 Overlaps2.insert(Reg);
424 Overlaps2.insert(Supers.begin(), Supers.end());
428 // Apply rule 2. and inherit all sub-register overlaps.
429 for (unsigned i = 0, e = Registers.size(); i != e; ++i) {
430 CodeGenRegister *Reg = &Registers[i];
431 CodeGenRegister::Set &Overlaps = Map[Reg];
432 const CodeGenRegister::SubRegMap &SRM = Reg->getSubRegs();
433 for (CodeGenRegister::SubRegMap::const_iterator i2 = SRM.begin(),
434 e2 = SRM.end(); i2 != e2; ++i2) {
435 CodeGenRegister::Set &Overlaps2 = Map[i2->second];
436 Overlaps.insert(Overlaps2.begin(), Overlaps2.end());
441 void CodeGenRegBank::computeDerivedInfo() {
445 /// getRegisterClassForRegister - Find the register class that contains the
446 /// specified physical register. If the register is not in a register class,
447 /// return null. If the register is in multiple classes, and the classes have a
448 /// superset-subset relationship and the same set of types, return the
449 /// superclass. Otherwise return null.
450 const CodeGenRegisterClass*
451 CodeGenRegBank::getRegClassForRegister(Record *R) {
452 const CodeGenRegister *Reg = getReg(R);
453 const std::vector<CodeGenRegisterClass> &RCs = getRegClasses();
454 const CodeGenRegisterClass *FoundRC = 0;
455 for (unsigned i = 0, e = RCs.size(); i != e; ++i) {
456 const CodeGenRegisterClass &RC = RCs[i];
457 if (!RC.contains(Reg))
460 // If this is the first class that contains the register,
461 // make a note of it and go on to the next class.
467 // If a register's classes have different types, return null.
468 if (RC.getValueTypes() != FoundRC->getValueTypes())
471 // Check to see if the previously found class that contains
472 // the register is a subclass of the current class. If so,
473 // prefer the superclass.
474 if (RC.hasSubClass(FoundRC)) {
479 // Check to see if the previously found class that contains
480 // the register is a superclass of the current class. If so,
481 // prefer the superclass.
482 if (FoundRC->hasSubClass(&RC))
485 // Multiple classes, and neither is a superclass of the other.