b3bd81e8a6ff89e15b745b55fe5df7f68e64add3
[oota-llvm.git] / utils / TableGen / CodeGenRegisters.cpp
1 //===- CodeGenRegisters.cpp - Register and RegisterClass Info -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines structures to encapsulate information gleaned from the
11 // target register and register class definitions.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "CodeGenRegisters.h"
16 #include "CodeGenTarget.h"
17 #include "llvm/TableGen/Error.h"
18 #include "llvm/ADT/SmallVector.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/ADT/StringExtras.h"
21
22 using namespace llvm;
23
24 //===----------------------------------------------------------------------===//
25 //                              CodeGenRegister
26 //===----------------------------------------------------------------------===//
27
28 CodeGenRegister::CodeGenRegister(Record *R, unsigned Enum)
29   : TheDef(R),
30     EnumValue(Enum),
31     CostPerUse(R->getValueAsInt("CostPerUse")),
32     SubRegsComplete(false)
33 {}
34
35 const std::string &CodeGenRegister::getName() const {
36   return TheDef->getName();
37 }
38
39 namespace {
40   struct Orphan {
41     CodeGenRegister *SubReg;
42     Record *First, *Second;
43     Orphan(CodeGenRegister *r, Record *a, Record *b)
44       : SubReg(r), First(a), Second(b) {}
45   };
46 }
47
48 const CodeGenRegister::SubRegMap &
49 CodeGenRegister::getSubRegs(CodeGenRegBank &RegBank) {
50   // Only compute this map once.
51   if (SubRegsComplete)
52     return SubRegs;
53   SubRegsComplete = true;
54
55   std::vector<Record*> SubList = TheDef->getValueAsListOfDefs("SubRegs");
56   std::vector<Record*> Indices = TheDef->getValueAsListOfDefs("SubRegIndices");
57   if (SubList.size() != Indices.size())
58     throw TGError(TheDef->getLoc(), "Register " + getName() +
59                   " SubRegIndices doesn't match SubRegs");
60
61   // First insert the direct subregs and make sure they are fully indexed.
62   for (unsigned i = 0, e = SubList.size(); i != e; ++i) {
63     CodeGenRegister *SR = RegBank.getReg(SubList[i]);
64     if (!SubRegs.insert(std::make_pair(Indices[i], SR)).second)
65       throw TGError(TheDef->getLoc(), "SubRegIndex " + Indices[i]->getName() +
66                     " appears twice in Register " + getName());
67   }
68
69   // Keep track of inherited subregs and how they can be reached.
70   SmallVector<Orphan, 8> Orphans;
71
72   // Clone inherited subregs and place duplicate entries on Orphans.
73   // Here the order is important - earlier subregs take precedence.
74   for (unsigned i = 0, e = SubList.size(); i != e; ++i) {
75     CodeGenRegister *SR = RegBank.getReg(SubList[i]);
76     const SubRegMap &Map = SR->getSubRegs(RegBank);
77
78     // Add this as a super-register of SR now all sub-registers are in the list.
79     // This creates a topological ordering, the exact order depends on the
80     // order getSubRegs is called on all registers.
81     SR->SuperRegs.push_back(this);
82
83     for (SubRegMap::const_iterator SI = Map.begin(), SE = Map.end(); SI != SE;
84          ++SI) {
85       if (!SubRegs.insert(*SI).second)
86         Orphans.push_back(Orphan(SI->second, Indices[i], SI->first));
87
88       // Noop sub-register indexes are possible, so avoid duplicates.
89       if (SI->second != SR)
90         SI->second->SuperRegs.push_back(this);
91     }
92   }
93
94   // Process the composites.
95   ListInit *Comps = TheDef->getValueAsListInit("CompositeIndices");
96   for (unsigned i = 0, e = Comps->size(); i != e; ++i) {
97     DagInit *Pat = dynamic_cast<DagInit*>(Comps->getElement(i));
98     if (!Pat)
99       throw TGError(TheDef->getLoc(), "Invalid dag '" +
100                     Comps->getElement(i)->getAsString() +
101                     "' in CompositeIndices");
102     DefInit *BaseIdxInit = dynamic_cast<DefInit*>(Pat->getOperator());
103     if (!BaseIdxInit || !BaseIdxInit->getDef()->isSubClassOf("SubRegIndex"))
104       throw TGError(TheDef->getLoc(), "Invalid SubClassIndex in " +
105                     Pat->getAsString());
106
107     // Resolve list of subreg indices into R2.
108     CodeGenRegister *R2 = this;
109     for (DagInit::const_arg_iterator di = Pat->arg_begin(),
110          de = Pat->arg_end(); di != de; ++di) {
111       DefInit *IdxInit = dynamic_cast<DefInit*>(*di);
112       if (!IdxInit || !IdxInit->getDef()->isSubClassOf("SubRegIndex"))
113         throw TGError(TheDef->getLoc(), "Invalid SubClassIndex in " +
114                       Pat->getAsString());
115       const SubRegMap &R2Subs = R2->getSubRegs(RegBank);
116       SubRegMap::const_iterator ni = R2Subs.find(IdxInit->getDef());
117       if (ni == R2Subs.end())
118         throw TGError(TheDef->getLoc(), "Composite " + Pat->getAsString() +
119                       " refers to bad index in " + R2->getName());
120       R2 = ni->second;
121     }
122
123     // Insert composite index. Allow overriding inherited indices etc.
124     SubRegs[BaseIdxInit->getDef()] = R2;
125
126     // R2 is no longer an orphan.
127     for (unsigned j = 0, je = Orphans.size(); j != je; ++j)
128       if (Orphans[j].SubReg == R2)
129           Orphans[j].SubReg = 0;
130   }
131
132   // Now Orphans contains the inherited subregisters without a direct index.
133   // Create inferred indexes for all missing entries.
134   for (unsigned i = 0, e = Orphans.size(); i != e; ++i) {
135     Orphan &O = Orphans[i];
136     if (!O.SubReg)
137       continue;
138     SubRegs[RegBank.getCompositeSubRegIndex(O.First, O.Second, true)] =
139       O.SubReg;
140   }
141   return SubRegs;
142 }
143
144 void
145 CodeGenRegister::addSubRegsPreOrder(SetVector<CodeGenRegister*> &OSet) const {
146   assert(SubRegsComplete && "Must precompute sub-registers");
147   std::vector<Record*> Indices = TheDef->getValueAsListOfDefs("SubRegIndices");
148   for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
149     CodeGenRegister *SR = SubRegs.find(Indices[i])->second;
150     if (OSet.insert(SR))
151       SR->addSubRegsPreOrder(OSet);
152   }
153 }
154
155 //===----------------------------------------------------------------------===//
156 //                               RegisterTuples
157 //===----------------------------------------------------------------------===//
158
159 // A RegisterTuples def is used to generate pseudo-registers from lists of
160 // sub-registers. We provide a SetTheory expander class that returns the new
161 // registers.
162 namespace {
163 struct TupleExpander : SetTheory::Expander {
164   void expand(SetTheory &ST, Record *Def, SetTheory::RecSet &Elts) {
165     std::vector<Record*> Indices = Def->getValueAsListOfDefs("SubRegIndices");
166     unsigned Dim = Indices.size();
167     ListInit *SubRegs = Def->getValueAsListInit("SubRegs");
168     if (Dim != SubRegs->getSize())
169       throw TGError(Def->getLoc(), "SubRegIndices and SubRegs size mismatch");
170     if (Dim < 2)
171       throw TGError(Def->getLoc(), "Tuples must have at least 2 sub-registers");
172
173     // Evaluate the sub-register lists to be zipped.
174     unsigned Length = ~0u;
175     SmallVector<SetTheory::RecSet, 4> Lists(Dim);
176     for (unsigned i = 0; i != Dim; ++i) {
177       ST.evaluate(SubRegs->getElement(i), Lists[i]);
178       Length = std::min(Length, unsigned(Lists[i].size()));
179     }
180
181     if (Length == 0)
182       return;
183
184     // Precompute some types.
185     Record *RegisterCl = Def->getRecords().getClass("Register");
186     RecTy *RegisterRecTy = RecordRecTy::get(RegisterCl);
187     StringInit *BlankName = StringInit::get("");
188
189     // Zip them up.
190     for (unsigned n = 0; n != Length; ++n) {
191       std::string Name;
192       Record *Proto = Lists[0][n];
193       std::vector<Init*> Tuple;
194       unsigned CostPerUse = 0;
195       for (unsigned i = 0; i != Dim; ++i) {
196         Record *Reg = Lists[i][n];
197         if (i) Name += '_';
198         Name += Reg->getName();
199         Tuple.push_back(DefInit::get(Reg));
200         CostPerUse = std::max(CostPerUse,
201                               unsigned(Reg->getValueAsInt("CostPerUse")));
202       }
203
204       // Create a new Record representing the synthesized register. This record
205       // is only for consumption by CodeGenRegister, it is not added to the
206       // RecordKeeper.
207       Record *NewReg = new Record(Name, Def->getLoc(), Def->getRecords());
208       Elts.insert(NewReg);
209
210       // Copy Proto super-classes.
211       for (unsigned i = 0, e = Proto->getSuperClasses().size(); i != e; ++i)
212         NewReg->addSuperClass(Proto->getSuperClasses()[i]);
213
214       // Copy Proto fields.
215       for (unsigned i = 0, e = Proto->getValues().size(); i != e; ++i) {
216         RecordVal RV = Proto->getValues()[i];
217
218         // Replace the sub-register list with Tuple.
219         if (RV.getName() == "SubRegs")
220           RV.setValue(ListInit::get(Tuple, RegisterRecTy));
221
222         // Provide a blank AsmName. MC hacks are required anyway.
223         if (RV.getName() == "AsmName")
224           RV.setValue(BlankName);
225
226         // CostPerUse is aggregated from all Tuple members.
227         if (RV.getName() == "CostPerUse")
228           RV.setValue(IntInit::get(CostPerUse));
229
230         // Copy fields from the RegisterTuples def.
231         if (RV.getName() == "SubRegIndices" ||
232             RV.getName() == "CompositeIndices") {
233           NewReg->addValue(*Def->getValue(RV.getName()));
234           continue;
235         }
236
237         // Some fields get their default uninitialized value.
238         if (RV.getName() == "DwarfNumbers" ||
239             RV.getName() == "DwarfAlias" ||
240             RV.getName() == "Aliases") {
241           if (const RecordVal *DefRV = RegisterCl->getValue(RV.getName()))
242             NewReg->addValue(*DefRV);
243           continue;
244         }
245
246         // Everything else is copied from Proto.
247         NewReg->addValue(RV);
248       }
249     }
250   }
251 };
252 }
253
254 //===----------------------------------------------------------------------===//
255 //                            CodeGenRegisterClass
256 //===----------------------------------------------------------------------===//
257
258 CodeGenRegisterClass::CodeGenRegisterClass(CodeGenRegBank &RegBank, Record *R)
259   : TheDef(R), Name(R->getName()), EnumValue(-1) {
260   // Rename anonymous register classes.
261   if (R->getName().size() > 9 && R->getName()[9] == '.') {
262     static unsigned AnonCounter = 0;
263     R->setName("AnonRegClass_"+utostr(AnonCounter++));
264   }
265
266   std::vector<Record*> TypeList = R->getValueAsListOfDefs("RegTypes");
267   for (unsigned i = 0, e = TypeList.size(); i != e; ++i) {
268     Record *Type = TypeList[i];
269     if (!Type->isSubClassOf("ValueType"))
270       throw "RegTypes list member '" + Type->getName() +
271         "' does not derive from the ValueType class!";
272     VTs.push_back(getValueType(Type));
273   }
274   assert(!VTs.empty() && "RegisterClass must contain at least one ValueType!");
275
276   // Allocation order 0 is the full set. AltOrders provides others.
277   const SetTheory::RecVec *Elements = RegBank.getSets().expand(R);
278   ListInit *AltOrders = R->getValueAsListInit("AltOrders");
279   Orders.resize(1 + AltOrders->size());
280
281   // Default allocation order always contains all registers.
282   for (unsigned i = 0, e = Elements->size(); i != e; ++i) {
283     Orders[0].push_back((*Elements)[i]);
284     Members.insert(RegBank.getReg((*Elements)[i]));
285   }
286
287   // Alternative allocation orders may be subsets.
288   SetTheory::RecSet Order;
289   for (unsigned i = 0, e = AltOrders->size(); i != e; ++i) {
290     RegBank.getSets().evaluate(AltOrders->getElement(i), Order);
291     Orders[1 + i].append(Order.begin(), Order.end());
292     // Verify that all altorder members are regclass members.
293     while (!Order.empty()) {
294       CodeGenRegister *Reg = RegBank.getReg(Order.back());
295       Order.pop_back();
296       if (!contains(Reg))
297         throw TGError(R->getLoc(), " AltOrder register " + Reg->getName() +
298                       " is not a class member");
299     }
300   }
301
302   // SubRegClasses is a list<dag> containing (RC, subregindex, ...) dags.
303   ListInit *SRC = R->getValueAsListInit("SubRegClasses");
304   for (ListInit::const_iterator i = SRC->begin(), e = SRC->end(); i != e; ++i) {
305     DagInit *DAG = dynamic_cast<DagInit*>(*i);
306     if (!DAG) throw "SubRegClasses must contain DAGs";
307     DefInit *DAGOp = dynamic_cast<DefInit*>(DAG->getOperator());
308     Record *RCRec;
309     if (!DAGOp || !(RCRec = DAGOp->getDef())->isSubClassOf("RegisterClass"))
310       throw "Operator '" + DAG->getOperator()->getAsString() +
311         "' in SubRegClasses is not a RegisterClass";
312     // Iterate over args, all SubRegIndex instances.
313     for (DagInit::const_arg_iterator ai = DAG->arg_begin(), ae = DAG->arg_end();
314          ai != ae; ++ai) {
315       DefInit *Idx = dynamic_cast<DefInit*>(*ai);
316       Record *IdxRec;
317       if (!Idx || !(IdxRec = Idx->getDef())->isSubClassOf("SubRegIndex"))
318         throw "Argument '" + (*ai)->getAsString() +
319           "' in SubRegClasses is not a SubRegIndex";
320       if (!SubRegClasses.insert(std::make_pair(IdxRec, RCRec)).second)
321         throw "SubRegIndex '" + IdxRec->getName() + "' mentioned twice";
322     }
323   }
324
325   // Allow targets to override the size in bits of the RegisterClass.
326   unsigned Size = R->getValueAsInt("Size");
327
328   Namespace = R->getValueAsString("Namespace");
329   SpillSize = Size ? Size : EVT(VTs[0]).getSizeInBits();
330   SpillAlignment = R->getValueAsInt("Alignment");
331   CopyCost = R->getValueAsInt("CopyCost");
332   Allocatable = R->getValueAsBit("isAllocatable");
333   AltOrderSelect = R->getValueAsCode("AltOrderSelect");
334 }
335
336 bool CodeGenRegisterClass::contains(const CodeGenRegister *Reg) const {
337   return Members.count(Reg);
338 }
339
340 // Returns true if RC is a strict subclass.
341 // RC is a sub-class of this class if it is a valid replacement for any
342 // instruction operand where a register of this classis required. It must
343 // satisfy these conditions:
344 //
345 // 1. All RC registers are also in this.
346 // 2. The RC spill size must not be smaller than our spill size.
347 // 3. RC spill alignment must be compatible with ours.
348 //
349 static bool testSubClass(const CodeGenRegisterClass *A,
350                          const CodeGenRegisterClass *B) {
351   return A->SpillAlignment && B->SpillAlignment % A->SpillAlignment == 0 &&
352     A->SpillSize <= B->SpillSize &&
353     std::includes(A->getMembers().begin(), A->getMembers().end(),
354                   B->getMembers().begin(), B->getMembers().end(),
355                   CodeGenRegister::Less());
356 }
357
358 /// Sorting predicate for register classes.  This provides a topological
359 /// ordering that arranges all register classes before their sub-classes.
360 ///
361 /// Register classes with the same registers, spill size, and alignment form a
362 /// clique.  They will be ordered alphabetically.
363 ///
364 static int TopoOrderRC(const void *PA, const void *PB) {
365   const CodeGenRegisterClass *A = *(const CodeGenRegisterClass* const*)PA;
366   const CodeGenRegisterClass *B = *(const CodeGenRegisterClass* const*)PB;
367   if (A == B)
368     return 0;
369
370   // Order by descending set size.
371   if (A->getOrder().size() > B->getOrder().size())
372     return -1;
373   if (A->getOrder().size() < B->getOrder().size())
374     return 1;
375
376   // Order by ascending spill size.
377   if (A->SpillSize < B->SpillSize)
378     return -1;
379   if (A->SpillSize > B->SpillSize)
380     return 1;
381
382   // Order by ascending spill alignment.
383   if (A->SpillAlignment < B->SpillAlignment)
384     return -1;
385   if (A->SpillAlignment > B->SpillAlignment)
386     return 1;
387
388   // Finally order by name as a tie breaker.
389   return A->getName() < B->getName();
390 }
391
392 std::string CodeGenRegisterClass::getQualifiedName() const {
393   if (Namespace.empty())
394     return getName();
395   else
396     return Namespace + "::" + getName();
397 }
398
399 // Compute sub-classes of all register classes.
400 // Assume the classes are ordered topologically.
401 void CodeGenRegisterClass::
402 computeSubClasses(ArrayRef<CodeGenRegisterClass*> RegClasses) {
403   // Visit backwards so sub-classes are seen first.
404   for (unsigned rci = RegClasses.size(); rci; --rci) {
405     CodeGenRegisterClass &RC = *RegClasses[rci - 1];
406     RC.SubClasses.resize(RegClasses.size());
407     RC.SubClasses.set(RC.EnumValue);
408
409     // Normally, all subclasses have IDs >= rci, unless RC is part of a clique.
410     for (unsigned s = rci; s != RegClasses.size(); ++s) {
411       if (RC.SubClasses.test(s))
412         continue;
413       CodeGenRegisterClass *SubRC = RegClasses[s];
414       if (!testSubClass(&RC, SubRC))
415         continue;
416       // SubRC is a sub-class. Grap all its sub-classes so we won't have to
417       // check them again.
418       RC.SubClasses |= SubRC->SubClasses;
419     }
420
421     // Sweep up missed clique members.  They will be immediately preceeding RC.
422     for (unsigned s = rci - 1; s && testSubClass(&RC, RegClasses[s - 1]); --s)
423       RC.SubClasses.set(s - 1);
424   }
425
426   // Compute the SuperClasses lists from the SubClasses vectors.
427   for (unsigned rci = 0; rci != RegClasses.size(); ++rci) {
428     const BitVector &SC = RegClasses[rci]->getSubClasses();
429     for (int s = SC.find_first(); s >= 0; s = SC.find_next(s)) {
430       if (unsigned(s) == rci)
431         continue;
432       RegClasses[s]->SuperClasses.push_back(RegClasses[rci]);
433     }
434   }
435 }
436
437 //===----------------------------------------------------------------------===//
438 //                               CodeGenRegBank
439 //===----------------------------------------------------------------------===//
440
441 CodeGenRegBank::CodeGenRegBank(RecordKeeper &Records) : Records(Records) {
442   // Configure register Sets to understand register classes and tuples.
443   Sets.addFieldExpander("RegisterClass", "MemberList");
444   Sets.addExpander("RegisterTuples", new TupleExpander());
445
446   // Read in the user-defined (named) sub-register indices.
447   // More indices will be synthesized later.
448   SubRegIndices = Records.getAllDerivedDefinitions("SubRegIndex");
449   std::sort(SubRegIndices.begin(), SubRegIndices.end(), LessRecord());
450   NumNamedIndices = SubRegIndices.size();
451
452   // Read in the register definitions.
453   std::vector<Record*> Regs = Records.getAllDerivedDefinitions("Register");
454   std::sort(Regs.begin(), Regs.end(), LessRecord());
455   Registers.reserve(Regs.size());
456   // Assign the enumeration values.
457   for (unsigned i = 0, e = Regs.size(); i != e; ++i)
458     getReg(Regs[i]);
459
460   // Expand tuples and number the new registers.
461   std::vector<Record*> Tups =
462     Records.getAllDerivedDefinitions("RegisterTuples");
463   for (unsigned i = 0, e = Tups.size(); i != e; ++i) {
464     const std::vector<Record*> *TupRegs = Sets.expand(Tups[i]);
465     for (unsigned j = 0, je = TupRegs->size(); j != je; ++j)
466       getReg((*TupRegs)[j]);
467   }
468
469   // Read in register class definitions.
470   std::vector<Record*> RCs = Records.getAllDerivedDefinitions("RegisterClass");
471   if (RCs.empty())
472     throw std::string("No 'RegisterClass' subclasses defined!");
473
474   RegClasses.reserve(RCs.size());
475   for (unsigned i = 0, e = RCs.size(); i != e; ++i) {
476     CodeGenRegisterClass *RC = new CodeGenRegisterClass(*this, RCs[i]);
477     RegClasses.push_back(RC);
478     Def2RC[RCs[i]] = RC;
479   }
480   // Order register classes topologically and assign enum values.
481   array_pod_sort(RegClasses.begin(), RegClasses.end(), TopoOrderRC);
482   for (unsigned i = 0, e = RegClasses.size(); i != e; ++i)
483     RegClasses[i]->EnumValue = i;
484   CodeGenRegisterClass::computeSubClasses(RegClasses);
485 }
486
487 CodeGenRegister *CodeGenRegBank::getReg(Record *Def) {
488   CodeGenRegister *&Reg = Def2Reg[Def];
489   if (Reg)
490     return Reg;
491   Reg = new CodeGenRegister(Def, Registers.size() + 1);
492   Registers.push_back(Reg);
493   return Reg;
494 }
495
496 CodeGenRegisterClass *CodeGenRegBank::getRegClass(Record *Def) {
497   if (CodeGenRegisterClass *RC = Def2RC[Def])
498     return RC;
499
500   throw TGError(Def->getLoc(), "Not a known RegisterClass!");
501 }
502
503 Record *CodeGenRegBank::getCompositeSubRegIndex(Record *A, Record *B,
504                                                 bool create) {
505   // Look for an existing entry.
506   Record *&Comp = Composite[std::make_pair(A, B)];
507   if (Comp || !create)
508     return Comp;
509
510   // None exists, synthesize one.
511   std::string Name = A->getName() + "_then_" + B->getName();
512   Comp = new Record(Name, SMLoc(), Records);
513   SubRegIndices.push_back(Comp);
514   return Comp;
515 }
516
517 unsigned CodeGenRegBank::getSubRegIndexNo(Record *idx) {
518   std::vector<Record*>::const_iterator i =
519     std::find(SubRegIndices.begin(), SubRegIndices.end(), idx);
520   assert(i != SubRegIndices.end() && "Not a SubRegIndex");
521   return (i - SubRegIndices.begin()) + 1;
522 }
523
524 void CodeGenRegBank::computeComposites() {
525   // Precompute all sub-register maps. This will create Composite entries for
526   // all inferred sub-register indices.
527   for (unsigned i = 0, e = Registers.size(); i != e; ++i)
528     Registers[i]->getSubRegs(*this);
529
530   for (unsigned i = 0, e = Registers.size(); i != e; ++i) {
531     CodeGenRegister *Reg1 = Registers[i];
532     const CodeGenRegister::SubRegMap &SRM1 = Reg1->getSubRegs();
533     for (CodeGenRegister::SubRegMap::const_iterator i1 = SRM1.begin(),
534          e1 = SRM1.end(); i1 != e1; ++i1) {
535       Record *Idx1 = i1->first;
536       CodeGenRegister *Reg2 = i1->second;
537       // Ignore identity compositions.
538       if (Reg1 == Reg2)
539         continue;
540       const CodeGenRegister::SubRegMap &SRM2 = Reg2->getSubRegs();
541       // Try composing Idx1 with another SubRegIndex.
542       for (CodeGenRegister::SubRegMap::const_iterator i2 = SRM2.begin(),
543            e2 = SRM2.end(); i2 != e2; ++i2) {
544         std::pair<Record*, Record*> IdxPair(Idx1, i2->first);
545         CodeGenRegister *Reg3 = i2->second;
546         // Ignore identity compositions.
547         if (Reg2 == Reg3)
548           continue;
549         // OK Reg1:IdxPair == Reg3. Find the index with Reg:Idx == Reg3.
550         for (CodeGenRegister::SubRegMap::const_iterator i1d = SRM1.begin(),
551              e1d = SRM1.end(); i1d != e1d; ++i1d) {
552           if (i1d->second == Reg3) {
553             std::pair<CompositeMap::iterator, bool> Ins =
554               Composite.insert(std::make_pair(IdxPair, i1d->first));
555             // Conflicting composition? Emit a warning but allow it.
556             if (!Ins.second && Ins.first->second != i1d->first) {
557               errs() << "Warning: SubRegIndex " << getQualifiedName(Idx1)
558                      << " and " << getQualifiedName(IdxPair.second)
559                      << " compose ambiguously as "
560                      << getQualifiedName(Ins.first->second) << " or "
561                      << getQualifiedName(i1d->first) << "\n";
562             }
563           }
564         }
565       }
566     }
567   }
568
569   // We don't care about the difference between (Idx1, Idx2) -> Idx2 and invalid
570   // compositions, so remove any mappings of that form.
571   for (CompositeMap::iterator i = Composite.begin(), e = Composite.end();
572        i != e;) {
573     CompositeMap::iterator j = i;
574     ++i;
575     if (j->first.second == j->second)
576       Composite.erase(j);
577   }
578 }
579
580 // Compute sets of overlapping registers.
581 //
582 // The standard set is all super-registers and all sub-registers, but the
583 // target description can add arbitrary overlapping registers via the 'Aliases'
584 // field. This complicates things, but we can compute overlapping sets using
585 // the following rules:
586 //
587 // 1. The relation overlap(A, B) is reflexive and symmetric but not transitive.
588 //
589 // 2. overlap(A, B) implies overlap(A, S) for all S in supers(B).
590 //
591 // Alternatively:
592 //
593 //    overlap(A, B) iff there exists:
594 //    A' in { A, subregs(A) } and B' in { B, subregs(B) } such that:
595 //    A' = B' or A' in aliases(B') or B' in aliases(A').
596 //
597 // Here subregs(A) is the full flattened sub-register set returned by
598 // A.getSubRegs() while aliases(A) is simply the special 'Aliases' field in the
599 // description of register A.
600 //
601 // This also implies that registers with a common sub-register are considered
602 // overlapping. This can happen when forming register pairs:
603 //
604 //    P0 = (R0, R1)
605 //    P1 = (R1, R2)
606 //    P2 = (R2, R3)
607 //
608 // In this case, we will infer an overlap between P0 and P1 because of the
609 // shared sub-register R1. There is no overlap between P0 and P2.
610 //
611 void CodeGenRegBank::
612 computeOverlaps(std::map<const CodeGenRegister*, CodeGenRegister::Set> &Map) {
613   assert(Map.empty());
614
615   // Collect overlaps that don't follow from rule 2.
616   for (unsigned i = 0, e = Registers.size(); i != e; ++i) {
617     CodeGenRegister *Reg = Registers[i];
618     CodeGenRegister::Set &Overlaps = Map[Reg];
619
620     // Reg overlaps itself.
621     Overlaps.insert(Reg);
622
623     // All super-registers overlap.
624     const CodeGenRegister::SuperRegList &Supers = Reg->getSuperRegs();
625     Overlaps.insert(Supers.begin(), Supers.end());
626
627     // Form symmetrical relations from the special Aliases[] lists.
628     std::vector<Record*> RegList = Reg->TheDef->getValueAsListOfDefs("Aliases");
629     for (unsigned i2 = 0, e2 = RegList.size(); i2 != e2; ++i2) {
630       CodeGenRegister *Reg2 = getReg(RegList[i2]);
631       CodeGenRegister::Set &Overlaps2 = Map[Reg2];
632       const CodeGenRegister::SuperRegList &Supers2 = Reg2->getSuperRegs();
633       // Reg overlaps Reg2 which implies it overlaps supers(Reg2).
634       Overlaps.insert(Reg2);
635       Overlaps.insert(Supers2.begin(), Supers2.end());
636       Overlaps2.insert(Reg);
637       Overlaps2.insert(Supers.begin(), Supers.end());
638     }
639   }
640
641   // Apply rule 2. and inherit all sub-register overlaps.
642   for (unsigned i = 0, e = Registers.size(); i != e; ++i) {
643     CodeGenRegister *Reg = Registers[i];
644     CodeGenRegister::Set &Overlaps = Map[Reg];
645     const CodeGenRegister::SubRegMap &SRM = Reg->getSubRegs();
646     for (CodeGenRegister::SubRegMap::const_iterator i2 = SRM.begin(),
647          e2 = SRM.end(); i2 != e2; ++i2) {
648       CodeGenRegister::Set &Overlaps2 = Map[i2->second];
649       Overlaps.insert(Overlaps2.begin(), Overlaps2.end());
650     }
651   }
652 }
653
654 void CodeGenRegBank::computeDerivedInfo() {
655   computeComposites();
656 }
657
658 /// getRegisterClassForRegister - Find the register class that contains the
659 /// specified physical register.  If the register is not in a register class,
660 /// return null. If the register is in multiple classes, and the classes have a
661 /// superset-subset relationship and the same set of types, return the
662 /// superclass.  Otherwise return null.
663 const CodeGenRegisterClass*
664 CodeGenRegBank::getRegClassForRegister(Record *R) {
665   const CodeGenRegister *Reg = getReg(R);
666   ArrayRef<CodeGenRegisterClass*> RCs = getRegClasses();
667   const CodeGenRegisterClass *FoundRC = 0;
668   for (unsigned i = 0, e = RCs.size(); i != e; ++i) {
669     const CodeGenRegisterClass &RC = *RCs[i];
670     if (!RC.contains(Reg))
671       continue;
672
673     // If this is the first class that contains the register,
674     // make a note of it and go on to the next class.
675     if (!FoundRC) {
676       FoundRC = &RC;
677       continue;
678     }
679
680     // If a register's classes have different types, return null.
681     if (RC.getValueTypes() != FoundRC->getValueTypes())
682       return 0;
683
684     // Check to see if the previously found class that contains
685     // the register is a subclass of the current class. If so,
686     // prefer the superclass.
687     if (RC.hasSubClass(FoundRC)) {
688       FoundRC = &RC;
689       continue;
690     }
691
692     // Check to see if the previously found class that contains
693     // the register is a superclass of the current class. If so,
694     // prefer the superclass.
695     if (FoundRC->hasSubClass(&RC))
696       continue;
697
698     // Multiple classes, and neither is a superclass of the other.
699     // Return null.
700     return 0;
701   }
702   return FoundRC;
703 }