1//===- Record.cpp - Record implementation ---------------------------------===//
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// Implement the tablegen record classes.
11//
12//===----------------------------------------------------------------------===//
13
14#include "llvm/TableGen/Record.h"
15#include "llvm/TableGen/Error.h"
16#include "llvm/Support/DataTypes.h"
17#include "llvm/Support/ErrorHandling.h"
18#include "llvm/Support/Format.h"
19#include "llvm/ADT/DenseMap.h"
20#include "llvm/ADT/FoldingSet.h"
21#include "llvm/ADT/Hashing.h"
22#include "llvm/ADT/SmallVector.h"
23#include "llvm/ADT/STLExtras.h"
24#include "llvm/ADT/StringExtras.h"
25#include "llvm/ADT/StringMap.h"
26
27using namespace llvm;
28
29//===----------------------------------------------------------------------===//
30//    std::string wrapper for DenseMap purposes
31//===----------------------------------------------------------------------===//
32
33namespace llvm {
34
35/// TableGenStringKey - This is a wrapper for std::string suitable for
36/// using as a key to a DenseMap.  Because there isn't a particularly
37/// good way to indicate tombstone or empty keys for strings, we want
38/// to wrap std::string to indicate that this is a "special" string
39/// not expected to take on certain values (those of the tombstone and
40/// empty keys).  This makes things a little safer as it clarifies
41/// that DenseMap is really not appropriate for general strings.
42
43class TableGenStringKey {
44public:
45  TableGenStringKey(const std::string &str) : data(str) {}
46  TableGenStringKey(const char *str) : data(str) {}
47
48  const std::string &str() const { return data; }
49
50  friend hash_code hash_value(const TableGenStringKey &Value) {
51    using llvm::hash_value;
52    return hash_value(Value.str());
53  }
54private:
55  std::string data;
56};
57
58/// Specialize DenseMapInfo for TableGenStringKey.
59template<> struct DenseMapInfo<TableGenStringKey> {
60  static inline TableGenStringKey getEmptyKey() {
61    TableGenStringKey Empty("<<<EMPTY KEY>>>");
62    return Empty;
63  }
64  static inline TableGenStringKey getTombstoneKey() {
65    TableGenStringKey Tombstone("<<<TOMBSTONE KEY>>>");
66    return Tombstone;
67  }
68  static unsigned getHashValue(const TableGenStringKey& Val) {
69    using llvm::hash_value;
70    return hash_value(Val);
71  }
72  static bool isEqual(const TableGenStringKey& LHS,
73                      const TableGenStringKey& RHS) {
74    return LHS.str() == RHS.str();
75  }
76};
77
78} // namespace llvm
79
80//===----------------------------------------------------------------------===//
81//    Type implementations
82//===----------------------------------------------------------------------===//
83
84BitRecTy BitRecTy::Shared;
85IntRecTy IntRecTy::Shared;
86StringRecTy StringRecTy::Shared;
87DagRecTy DagRecTy::Shared;
88
89void RecTy::anchor() { }
90void RecTy::dump() const { print(errs()); }
91
92ListRecTy *RecTy::getListTy() {
93  if (!ListTy)
94    ListTy = new ListRecTy(this);
95  return ListTy;
96}
97
98Init *BitRecTy::convertValue(BitsInit *BI) {
99  if (BI->getNumBits() != 1) return 0; // Only accept if just one bit!
100  return BI->getBit(0);
101}
102
103bool BitRecTy::baseClassOf(const BitsRecTy *RHS) const {
104  return RHS->getNumBits() == 1;
105}
106
107Init *BitRecTy::convertValue(IntInit *II) {
108  int64_t Val = II->getValue();
109  if (Val != 0 && Val != 1) return 0;  // Only accept 0 or 1 for a bit!
110
111  return BitInit::get(Val != 0);
112}
113
114Init *BitRecTy::convertValue(TypedInit *VI) {
115  RecTy *Ty = VI->getType();
116  if (dynamic_cast<BitRecTy*>(Ty) ||
117      dynamic_cast<BitsRecTy*>(Ty) ||
118      dynamic_cast<IntRecTy*>(Ty))
119    return VI;  // Accept variable if it is already of bit type!
120  return 0;
121}
122
123BitsRecTy *BitsRecTy::get(unsigned Sz) {
124  static std::vector<BitsRecTy*> Shared;
125  if (Sz >= Shared.size())
126    Shared.resize(Sz + 1);
127  BitsRecTy *&Ty = Shared[Sz];
128  if (!Ty)
129    Ty = new BitsRecTy(Sz);
130  return Ty;
131}
132
133std::string BitsRecTy::getAsString() const {
134  return "bits<" + utostr(Size) + ">";
135}
136
137Init *BitsRecTy::convertValue(UnsetInit *UI) {
138  SmallVector<Init *, 16> NewBits(Size);
139
140  for (unsigned i = 0; i != Size; ++i)
141    NewBits[i] = UnsetInit::get();
142
143  return BitsInit::get(NewBits);
144}
145
146Init *BitsRecTy::convertValue(BitInit *UI) {
147  if (Size != 1) return 0;  // Can only convert single bit.
148          return BitsInit::get(UI);
149}
150
151/// canFitInBitfield - Return true if the number of bits is large enough to hold
152/// the integer value.
153static bool canFitInBitfield(int64_t Value, unsigned NumBits) {
154  // For example, with NumBits == 4, we permit Values from [-7 .. 15].
155  return (NumBits >= sizeof(Value) * 8) ||
156         (Value >> NumBits == 0) || (Value >> (NumBits-1) == -1);
157}
158
159/// convertValue from Int initializer to bits type: Split the integer up into the
160/// appropriate bits.
161///
162Init *BitsRecTy::convertValue(IntInit *II) {
163  int64_t Value = II->getValue();
164  // Make sure this bitfield is large enough to hold the integer value.
165  if (!canFitInBitfield(Value, Size))
166    return 0;
167
168  SmallVector<Init *, 16> NewBits(Size);
169
170  for (unsigned i = 0; i != Size; ++i)
171    NewBits[i] = BitInit::get(Value & (1LL << i));
172
173  return BitsInit::get(NewBits);
174}
175
176Init *BitsRecTy::convertValue(BitsInit *BI) {
177  // If the number of bits is right, return it.  Otherwise we need to expand or
178  // truncate.
179  if (BI->getNumBits() == Size) return BI;
180  return 0;
181}
182
183Init *BitsRecTy::convertValue(TypedInit *VI) {
184  if (Size == 1 && dynamic_cast<BitRecTy*>(VI->getType()))
185    return BitsInit::get(VI);
186
187  if (VI->getType()->typeIsConvertibleTo(this)) {
188    SmallVector<Init *, 16> NewBits(Size);
189
190    for (unsigned i = 0; i != Size; ++i)
191      NewBits[i] = VarBitInit::get(VI, i);
192    return BitsInit::get(NewBits);
193  }
194
195  return 0;
196}
197
198Init *IntRecTy::convertValue(BitInit *BI) {
199  return IntInit::get(BI->getValue());
200}
201
202Init *IntRecTy::convertValue(BitsInit *BI) {
203  int64_t Result = 0;
204  for (unsigned i = 0, e = BI->getNumBits(); i != e; ++i)
205    if (BitInit *Bit = dynamic_cast<BitInit*>(BI->getBit(i))) {
206      Result |= Bit->getValue() << i;
207    } else {
208      return 0;
209    }
210  return IntInit::get(Result);
211}
212
213Init *IntRecTy::convertValue(TypedInit *TI) {
214  if (TI->getType()->typeIsConvertibleTo(this))
215    return TI;  // Accept variable if already of the right type!
216  return 0;
217}
218
219Init *StringRecTy::convertValue(UnOpInit *BO) {
220  if (BO->getOpcode() == UnOpInit::CAST) {
221    Init *L = BO->getOperand()->convertInitializerTo(this);
222    if (L == 0) return 0;
223    if (L != BO->getOperand())
224      return UnOpInit::get(UnOpInit::CAST, L, new StringRecTy);
225    return BO;
226  }
227
228  return convertValue((TypedInit*)BO);
229}
230
231Init *StringRecTy::convertValue(BinOpInit *BO) {
232  if (BO->getOpcode() == BinOpInit::STRCONCAT) {
233    Init *L = BO->getLHS()->convertInitializerTo(this);
234    Init *R = BO->getRHS()->convertInitializerTo(this);
235    if (L == 0 || R == 0) return 0;
236    if (L != BO->getLHS() || R != BO->getRHS())
237      return BinOpInit::get(BinOpInit::STRCONCAT, L, R, new StringRecTy);
238    return BO;
239  }
240
241  return convertValue((TypedInit*)BO);
242}
243
244
245Init *StringRecTy::convertValue(TypedInit *TI) {
246  if (dynamic_cast<StringRecTy*>(TI->getType()))
247    return TI;  // Accept variable if already of the right type!
248  return 0;
249}
250
251std::string ListRecTy::getAsString() const {
252  return "list<" + Ty->getAsString() + ">";
253}
254
255Init *ListRecTy::convertValue(ListInit *LI) {
256  std::vector<Init*> Elements;
257
258  // Verify that all of the elements of the list are subclasses of the
259  // appropriate class!
260  for (unsigned i = 0, e = LI->getSize(); i != e; ++i)
261    if (Init *CI = LI->getElement(i)->convertInitializerTo(Ty))
262      Elements.push_back(CI);
263    else
264      return 0;
265
266  ListRecTy *LType = dynamic_cast<ListRecTy*>(LI->getType());
267  if (LType == 0) {
268    return 0;
269  }
270
271  return ListInit::get(Elements, this);
272}
273
274Init *ListRecTy::convertValue(TypedInit *TI) {
275  // Ensure that TI is compatible with our class.
276  if (ListRecTy *LRT = dynamic_cast<ListRecTy*>(TI->getType()))
277    if (LRT->getElementType()->typeIsConvertibleTo(getElementType()))
278      return TI;
279  return 0;
280}
281
282Init *DagRecTy::convertValue(TypedInit *TI) {
283  if (TI->getType()->typeIsConvertibleTo(this))
284    return TI;
285  return 0;
286}
287
288Init *DagRecTy::convertValue(UnOpInit *BO) {
289  if (BO->getOpcode() == UnOpInit::CAST) {
290    Init *L = BO->getOperand()->convertInitializerTo(this);
291    if (L == 0) return 0;
292    if (L != BO->getOperand())
293      return UnOpInit::get(UnOpInit::CAST, L, new DagRecTy);
294    return BO;
295  }
296  return 0;
297}
298
299Init *DagRecTy::convertValue(BinOpInit *BO) {
300  if (BO->getOpcode() == BinOpInit::CONCAT) {
301    Init *L = BO->getLHS()->convertInitializerTo(this);
302    Init *R = BO->getRHS()->convertInitializerTo(this);
303    if (L == 0 || R == 0) return 0;
304    if (L != BO->getLHS() || R != BO->getRHS())
305      return BinOpInit::get(BinOpInit::CONCAT, L, R, new DagRecTy);
306    return BO;
307  }
308  return 0;
309}
310
311RecordRecTy *RecordRecTy::get(Record *R) {
312  return &dynamic_cast<RecordRecTy&>(*R->getDefInit()->getType());
313}
314
315std::string RecordRecTy::getAsString() const {
316  return Rec->getName();
317}
318
319Init *RecordRecTy::convertValue(DefInit *DI) {
320  // Ensure that DI is a subclass of Rec.
321  if (!DI->getDef()->isSubClassOf(Rec))
322    return 0;
323  return DI;
324}
325
326Init *RecordRecTy::convertValue(TypedInit *TI) {
327  // Ensure that TI is compatible with Rec.
328  if (RecordRecTy *RRT = dynamic_cast<RecordRecTy*>(TI->getType()))
329    if (RRT->getRecord()->isSubClassOf(getRecord()) ||
330        RRT->getRecord() == getRecord())
331      return TI;
332  return 0;
333}
334
335bool RecordRecTy::baseClassOf(const RecordRecTy *RHS) const {
336  if (Rec == RHS->getRecord() || RHS->getRecord()->isSubClassOf(Rec))
337    return true;
338
339  const std::vector<Record*> &SC = Rec->getSuperClasses();
340  for (unsigned i = 0, e = SC.size(); i != e; ++i)
341    if (RHS->getRecord()->isSubClassOf(SC[i]))
342      return true;
343
344  return false;
345}
346
347
348/// resolveTypes - Find a common type that T1 and T2 convert to.
349/// Return 0 if no such type exists.
350///
351RecTy *llvm::resolveTypes(RecTy *T1, RecTy *T2) {
352  if (!T1->typeIsConvertibleTo(T2)) {
353    if (!T2->typeIsConvertibleTo(T1)) {
354      // If one is a Record type, check superclasses
355      RecordRecTy *RecTy1 = dynamic_cast<RecordRecTy*>(T1);
356      if (RecTy1) {
357        // See if T2 inherits from a type T1 also inherits from
358        const std::vector<Record *> &T1SuperClasses =
359          RecTy1->getRecord()->getSuperClasses();
360        for(std::vector<Record *>::const_iterator i = T1SuperClasses.begin(),
361              iend = T1SuperClasses.end();
362            i != iend;
363            ++i) {
364          RecordRecTy *SuperRecTy1 = RecordRecTy::get(*i);
365          RecTy *NewType1 = resolveTypes(SuperRecTy1, T2);
366          if (NewType1 != 0) {
367            if (NewType1 != SuperRecTy1) {
368              delete SuperRecTy1;
369            }
370            return NewType1;
371          }
372        }
373      }
374      RecordRecTy *RecTy2 = dynamic_cast<RecordRecTy*>(T2);
375      if (RecTy2) {
376        // See if T1 inherits from a type T2 also inherits from
377        const std::vector<Record *> &T2SuperClasses =
378          RecTy2->getRecord()->getSuperClasses();
379        for (std::vector<Record *>::const_iterator i = T2SuperClasses.begin(),
380              iend = T2SuperClasses.end();
381            i != iend;
382            ++i) {
383          RecordRecTy *SuperRecTy2 = RecordRecTy::get(*i);
384          RecTy *NewType2 = resolveTypes(T1, SuperRecTy2);
385          if (NewType2 != 0) {
386            if (NewType2 != SuperRecTy2) {
387              delete SuperRecTy2;
388            }
389            return NewType2;
390          }
391        }
392      }
393      return 0;
394    }
395    return T2;
396  }
397  return T1;
398}
399
400
401//===----------------------------------------------------------------------===//
402//    Initializer implementations
403//===----------------------------------------------------------------------===//
404
405void Init::anchor() { }
406void Init::dump() const { return print(errs()); }
407
408void UnsetInit::anchor() { }
409
410UnsetInit *UnsetInit::get() {
411  static UnsetInit TheInit;
412  return &TheInit;
413}
414
415void BitInit::anchor() { }
416
417BitInit *BitInit::get(bool V) {
418  static BitInit True(true);
419  static BitInit False(false);
420
421  return V ? &True : &False;
422}
423
424static void
425ProfileBitsInit(FoldingSetNodeID &ID, ArrayRef<Init *> Range) {
426  ID.AddInteger(Range.size());
427
428  for (ArrayRef<Init *>::iterator i = Range.begin(),
429         iend = Range.end();
430       i != iend;
431       ++i)
432    ID.AddPointer(*i);
433}
434
435BitsInit *BitsInit::get(ArrayRef<Init *> Range) {
436  typedef FoldingSet<BitsInit> Pool;
437  static Pool ThePool;
438
439  FoldingSetNodeID ID;
440  ProfileBitsInit(ID, Range);
441
442  void *IP = 0;
443  if (BitsInit *I = ThePool.FindNodeOrInsertPos(ID, IP))
444    return I;
445
446  BitsInit *I = new BitsInit(Range);
447  ThePool.InsertNode(I, IP);
448
449  return I;
450}
451
452void BitsInit::Profile(FoldingSetNodeID &ID) const {
453  ProfileBitsInit(ID, Bits);
454}
455
456Init *
457BitsInit::convertInitializerBitRange(const std::vector<unsigned> &Bits) const {
458  SmallVector<Init *, 16> NewBits(Bits.size());
459
460  for (unsigned i = 0, e = Bits.size(); i != e; ++i) {
461    if (Bits[i] >= getNumBits())
462      return 0;
463    NewBits[i] = getBit(Bits[i]);
464  }
465  return BitsInit::get(NewBits);
466}
467
468std::string BitsInit::getAsString() const {
469  std::string Result = "{ ";
470  for (unsigned i = 0, e = getNumBits(); i != e; ++i) {
471    if (i) Result += ", ";
472    if (Init *Bit = getBit(e-i-1))
473      Result += Bit->getAsString();
474    else
475      Result += "*";
476  }
477  return Result + " }";
478}
479
480// Fix bit initializer to preserve the behavior that bit reference from a unset
481// bits initializer will resolve into VarBitInit to keep the field name and bit
482// number used in targets with fixed insn length.
483static Init *fixBitInit(const RecordVal *RV, Init *Before, Init *After) {
484  if (RV || After != UnsetInit::get())
485    return After;
486  return Before;
487}
488
489// resolveReferences - If there are any field references that refer to fields
490// that have been filled in, we can propagate the values now.
491//
492Init *BitsInit::resolveReferences(Record &R, const RecordVal *RV) const {
493  bool Changed = false;
494  SmallVector<Init *, 16> NewBits(getNumBits());
495
496  Init *CachedInit = 0;
497  Init *CachedBitVar = 0;
498  bool CachedBitVarChanged = false;
499
500  for (unsigned i = 0, e = getNumBits(); i != e; ++i) {
501    Init *CurBit = Bits[i];
502    Init *CurBitVar = CurBit->getBitVar();
503
504    NewBits[i] = CurBit;
505
506    if (CurBitVar == CachedBitVar) {
507      if (CachedBitVarChanged) {
508        Init *Bit = CachedInit->getBit(CurBit->getBitNum());
509        NewBits[i] = fixBitInit(RV, CurBit, Bit);
510      }
511      continue;
512    }
513    CachedBitVar = CurBitVar;
514    CachedBitVarChanged = false;
515
516    Init *B;
517    do {
518      B = CurBitVar;
519      CurBitVar = CurBitVar->resolveReferences(R, RV);
520      CachedBitVarChanged |= B != CurBitVar;
521      Changed |= B != CurBitVar;
522    } while (B != CurBitVar);
523    CachedInit = CurBitVar;
524
525    if (CachedBitVarChanged) {
526      Init *Bit = CurBitVar->getBit(CurBit->getBitNum());
527      NewBits[i] = fixBitInit(RV, CurBit, Bit);
528    }
529  }
530
531  if (Changed)
532    return BitsInit::get(NewBits);
533
534  return const_cast<BitsInit *>(this);
535}
536
537IntInit *IntInit::get(int64_t V) {
538  typedef DenseMap<int64_t, IntInit *> Pool;
539  static Pool ThePool;
540
541  IntInit *&I = ThePool[V];
542  if (!I) I = new IntInit(V);
543  return I;
544}
545
546std::string IntInit::getAsString() const {
547  return itostr(Value);
548}
549
550Init *
551IntInit::convertInitializerBitRange(const std::vector<unsigned> &Bits) const {
552  SmallVector<Init *, 16> NewBits(Bits.size());
553
554  for (unsigned i = 0, e = Bits.size(); i != e; ++i) {
555    if (Bits[i] >= 64)
556      return 0;
557
558    NewBits[i] = BitInit::get(Value & (INT64_C(1) << Bits[i]));
559  }
560  return BitsInit::get(NewBits);
561}
562
563void StringInit::anchor() { }
564
565StringInit *StringInit::get(StringRef V) {
566  typedef StringMap<StringInit *> Pool;
567  static Pool ThePool;
568
569  StringInit *&I = ThePool[V];
570  if (!I) I = new StringInit(V);
571  return I;
572}
573
574static void ProfileListInit(FoldingSetNodeID &ID,
575                            ArrayRef<Init *> Range,
576                            RecTy *EltTy) {
577  ID.AddInteger(Range.size());
578  ID.AddPointer(EltTy);
579
580  for (ArrayRef<Init *>::iterator i = Range.begin(),
581         iend = Range.end();
582       i != iend;
583       ++i)
584    ID.AddPointer(*i);
585}
586
587ListInit *ListInit::get(ArrayRef<Init *> Range, RecTy *EltTy) {
588  typedef FoldingSet<ListInit> Pool;
589  static Pool ThePool;
590
591  // Just use the FoldingSetNodeID to compute a hash.  Use a DenseMap
592  // for actual storage.
593  FoldingSetNodeID ID;
594  ProfileListInit(ID, Range, EltTy);
595
596  void *IP = 0;
597  if (ListInit *I = ThePool.FindNodeOrInsertPos(ID, IP))
598    return I;
599
600  ListInit *I = new ListInit(Range, EltTy);
601  ThePool.InsertNode(I, IP);
602  return I;
603}
604
605void ListInit::Profile(FoldingSetNodeID &ID) const {
606  ListRecTy *ListType = dynamic_cast<ListRecTy *>(getType());
607  assert(ListType && "Bad type for ListInit!");
608  RecTy *EltTy = ListType->getElementType();
609
610  ProfileListInit(ID, Values, EltTy);
611}
612
613Init *
614ListInit::convertInitListSlice(const std::vector<unsigned> &Elements) const {
615  std::vector<Init*> Vals;
616  for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
617    if (Elements[i] >= getSize())
618      return 0;
619    Vals.push_back(getElement(Elements[i]));
620  }
621  return ListInit::get(Vals, getType());
622}
623
624Record *ListInit::getElementAsRecord(unsigned i) const {
625  assert(i < Values.size() && "List element index out of range!");
626  DefInit *DI = dynamic_cast<DefInit*>(Values[i]);
627  if (DI == 0) throw "Expected record in list!";
628  return DI->getDef();
629}
630
631Init *ListInit::resolveReferences(Record &R, const RecordVal *RV) const {
632  std::vector<Init*> Resolved;
633  Resolved.reserve(getSize());
634  bool Changed = false;
635
636  for (unsigned i = 0, e = getSize(); i != e; ++i) {
637    Init *E;
638    Init *CurElt = getElement(i);
639
640    do {
641      E = CurElt;
642      CurElt = CurElt->resolveReferences(R, RV);
643      Changed |= E != CurElt;
644    } while (E != CurElt);
645    Resolved.push_back(E);
646  }
647
648  if (Changed)
649    return ListInit::get(Resolved, getType());
650  return const_cast<ListInit *>(this);
651}
652
653Init *ListInit::resolveListElementReference(Record &R, const RecordVal *IRV,
654                                            unsigned Elt) const {
655  if (Elt >= getSize())
656    return 0;  // Out of range reference.
657  Init *E = getElement(Elt);
658  // If the element is set to some value, or if we are resolving a reference
659  // to a specific variable and that variable is explicitly unset, then
660  // replace the VarListElementInit with it.
661  if (IRV || !dynamic_cast<UnsetInit*>(E))
662    return E;
663  return 0;
664}
665
666std::string ListInit::getAsString() const {
667  std::string Result = "[";
668  for (unsigned i = 0, e = Values.size(); i != e; ++i) {
669    if (i) Result += ", ";
670    Result += Values[i]->getAsString();
671  }
672  return Result + "]";
673}
674
675Init *OpInit::resolveListElementReference(Record &R, const RecordVal *IRV,
676                                          unsigned Elt) const {
677  Init *Resolved = resolveReferences(R, IRV);
678  OpInit *OResolved = dynamic_cast<OpInit *>(Resolved);
679  if (OResolved) {
680    Resolved = OResolved->Fold(&R, 0);
681  }
682
683  if (Resolved != this) {
684    TypedInit *Typed = dynamic_cast<TypedInit *>(Resolved);
685    assert(Typed && "Expected typed init for list reference");
686    if (Typed) {
687      Init *New = Typed->resolveListElementReference(R, IRV, Elt);
688      if (New)
689        return New;
690      return VarListElementInit::get(Typed, Elt);
691    }
692  }
693
694  return 0;
695}
696
697Init *OpInit::getBit(unsigned Bit) const {
698  if (getType() == BitRecTy::get())
699    return const_cast<OpInit*>(this);
700  return VarBitInit::get(const_cast<OpInit*>(this), Bit);
701}
702
703UnOpInit *UnOpInit::get(UnaryOp opc, Init *lhs, RecTy *Type) {
704  typedef std::pair<std::pair<unsigned, Init *>, RecTy *> Key;
705
706  typedef DenseMap<Key, UnOpInit *> Pool;
707  static Pool ThePool;
708
709  Key TheKey(std::make_pair(std::make_pair(opc, lhs), Type));
710
711  UnOpInit *&I = ThePool[TheKey];
712  if (!I) I = new UnOpInit(opc, lhs, Type);
713  return I;
714}
715
716Init *UnOpInit::Fold(Record *CurRec, MultiClass *CurMultiClass) const {
717  switch (getOpcode()) {
718  case CAST: {
719    if (getType()->getAsString() == "string") {
720      StringInit *LHSs = dynamic_cast<StringInit*>(LHS);
721      if (LHSs) {
722        return LHSs;
723      }
724
725      DefInit *LHSd = dynamic_cast<DefInit*>(LHS);
726      if (LHSd) {
727        return StringInit::get(LHSd->getDef()->getName());
728      }
729
730      IntInit *LHSi = dynamic_cast<IntInit*>(LHS);
731      if (LHSi) {
732        return StringInit::get(LHSi->getAsString());
733      }
734    } else {
735      StringInit *LHSs = dynamic_cast<StringInit*>(LHS);
736      if (LHSs) {
737        std::string Name = LHSs->getValue();
738
739        // From TGParser::ParseIDValue
740        if (CurRec) {
741          if (const RecordVal *RV = CurRec->getValue(Name)) {
742            if (RV->getType() != getType())
743              throw "type mismatch in cast";
744            return VarInit::get(Name, RV->getType());
745          }
746
747          Init *TemplateArgName = QualifyName(*CurRec, CurMultiClass, Name,
748                                              ":");
749
750          if (CurRec->isTemplateArg(TemplateArgName)) {
751            const RecordVal *RV = CurRec->getValue(TemplateArgName);
752            assert(RV && "Template arg doesn't exist??");
753
754            if (RV->getType() != getType())
755              throw "type mismatch in cast";
756
757            return VarInit::get(TemplateArgName, RV->getType());
758          }
759        }
760
761        if (CurMultiClass) {
762          Init *MCName = QualifyName(CurMultiClass->Rec, CurMultiClass, Name, "::");
763
764          if (CurMultiClass->Rec.isTemplateArg(MCName)) {
765            const RecordVal *RV = CurMultiClass->Rec.getValue(MCName);
766            assert(RV && "Template arg doesn't exist??");
767
768            if (RV->getType() != getType())
769              throw "type mismatch in cast";
770
771            return VarInit::get(MCName, RV->getType());
772          }
773        }
774
775        if (Record *D = (CurRec->getRecords()).getDef(Name))
776          return DefInit::get(D);
777
778        throw TGError(CurRec->getLoc(), "Undefined reference:'" + Name + "'\n");
779      }
780    }
781    break;
782  }
783  case HEAD: {
784    ListInit *LHSl = dynamic_cast<ListInit*>(LHS);
785    if (LHSl) {
786      if (LHSl->getSize() == 0) {
787        assert(0 && "Empty list in car");
788        return 0;
789      }
790      return LHSl->getElement(0);
791    }
792    break;
793  }
794  case TAIL: {
795    ListInit *LHSl = dynamic_cast<ListInit*>(LHS);
796    if (LHSl) {
797      if (LHSl->getSize() == 0) {
798        assert(0 && "Empty list in cdr");
799        return 0;
800      }
801      // Note the +1.  We can't just pass the result of getValues()
802      // directly.
803      ArrayRef<Init *>::iterator begin = LHSl->getValues().begin()+1;
804      ArrayRef<Init *>::iterator end   = LHSl->getValues().end();
805      ListInit *Result =
806        ListInit::get(ArrayRef<Init *>(begin, end - begin),
807                      LHSl->getType());
808      return Result;
809    }
810    break;
811  }
812  case EMPTY: {
813    ListInit *LHSl = dynamic_cast<ListInit*>(LHS);
814    if (LHSl) {
815      if (LHSl->getSize() == 0) {
816        return IntInit::get(1);
817      } else {
818        return IntInit::get(0);
819      }
820    }
821    StringInit *LHSs = dynamic_cast<StringInit*>(LHS);
822    if (LHSs) {
823      if (LHSs->getValue().empty()) {
824        return IntInit::get(1);
825      } else {
826        return IntInit::get(0);
827      }
828    }
829
830    break;
831  }
832  }
833  return const_cast<UnOpInit *>(this);
834}
835
836Init *UnOpInit::resolveReferences(Record &R, const RecordVal *RV) const {
837  Init *lhs = LHS->resolveReferences(R, RV);
838
839  if (LHS != lhs)
840    return (UnOpInit::get(getOpcode(), lhs, getType()))->Fold(&R, 0);
841  return Fold(&R, 0);
842}
843
844std::string UnOpInit::getAsString() const {
845  std::string Result;
846  switch (Opc) {
847  case CAST: Result = "!cast<" + getType()->getAsString() + ">"; break;
848  case HEAD: Result = "!head"; break;
849  case TAIL: Result = "!tail"; break;
850  case EMPTY: Result = "!empty"; break;
851  }
852  return Result + "(" + LHS->getAsString() + ")";
853}
854
855BinOpInit *BinOpInit::get(BinaryOp opc, Init *lhs,
856                          Init *rhs, RecTy *Type) {
857  typedef std::pair<
858    std::pair<std::pair<unsigned, Init *>, Init *>,
859    RecTy *
860    > Key;
861
862  typedef DenseMap<Key, BinOpInit *> Pool;
863  static Pool ThePool;
864
865  Key TheKey(std::make_pair(std::make_pair(std::make_pair(opc, lhs), rhs),
866                            Type));
867
868  BinOpInit *&I = ThePool[TheKey];
869  if (!I) I = new BinOpInit(opc, lhs, rhs, Type);
870  return I;
871}
872
873Init *BinOpInit::Fold(Record *CurRec, MultiClass *CurMultiClass) const {
874  switch (getOpcode()) {
875  case CONCAT: {
876    DagInit *LHSs = dynamic_cast<DagInit*>(LHS);
877    DagInit *RHSs = dynamic_cast<DagInit*>(RHS);
878    if (LHSs && RHSs) {
879      DefInit *LOp = dynamic_cast<DefInit*>(LHSs->getOperator());
880      DefInit *ROp = dynamic_cast<DefInit*>(RHSs->getOperator());
881      if (LOp == 0 || ROp == 0 || LOp->getDef() != ROp->getDef())
882        throw "Concated Dag operators do not match!";
883      std::vector<Init*> Args;
884      std::vector<std::string> ArgNames;
885      for (unsigned i = 0, e = LHSs->getNumArgs(); i != e; ++i) {
886        Args.push_back(LHSs->getArg(i));
887        ArgNames.push_back(LHSs->getArgName(i));
888      }
889      for (unsigned i = 0, e = RHSs->getNumArgs(); i != e; ++i) {
890        Args.push_back(RHSs->getArg(i));
891        ArgNames.push_back(RHSs->getArgName(i));
892      }
893      return DagInit::get(LHSs->getOperator(), "", Args, ArgNames);
894    }
895    break;
896  }
897  case STRCONCAT: {
898    StringInit *LHSs = dynamic_cast<StringInit*>(LHS);
899    StringInit *RHSs = dynamic_cast<StringInit*>(RHS);
900    if (LHSs && RHSs)
901      return StringInit::get(LHSs->getValue() + RHSs->getValue());
902    break;
903  }
904  case EQ: {
905    // try to fold eq comparison for 'bit' and 'int', otherwise fallback
906    // to string objects.
907    IntInit *L =
908      dynamic_cast<IntInit*>(LHS->convertInitializerTo(IntRecTy::get()));
909    IntInit *R =
910      dynamic_cast<IntInit*>(RHS->convertInitializerTo(IntRecTy::get()));
911
912    if (L && R)
913      return IntInit::get(L->getValue() == R->getValue());
914
915    StringInit *LHSs = dynamic_cast<StringInit*>(LHS);
916    StringInit *RHSs = dynamic_cast<StringInit*>(RHS);
917
918    // Make sure we've resolved
919    if (LHSs && RHSs)
920      return IntInit::get(LHSs->getValue() == RHSs->getValue());
921
922    break;
923  }
924  case SHL:
925  case SRA:
926  case SRL: {
927    IntInit *LHSi = dynamic_cast<IntInit*>(LHS);
928    IntInit *RHSi = dynamic_cast<IntInit*>(RHS);
929    if (LHSi && RHSi) {
930      int64_t LHSv = LHSi->getValue(), RHSv = RHSi->getValue();
931      int64_t Result;
932      switch (getOpcode()) {
933      default: llvm_unreachable("Bad opcode!");
934      case SHL: Result = LHSv << RHSv; break;
935      case SRA: Result = LHSv >> RHSv; break;
936      case SRL: Result = (uint64_t)LHSv >> (uint64_t)RHSv; break;
937      }
938      return IntInit::get(Result);
939    }
940    break;
941  }
942  }
943  return const_cast<BinOpInit *>(this);
944}
945
946Init *BinOpInit::resolveReferences(Record &R, const RecordVal *RV) const {
947  Init *lhs = LHS->resolveReferences(R, RV);
948  Init *rhs = RHS->resolveReferences(R, RV);
949
950  if (LHS != lhs || RHS != rhs)
951    return (BinOpInit::get(getOpcode(), lhs, rhs, getType()))->Fold(&R, 0);
952  return Fold(&R, 0);
953}
954
955std::string BinOpInit::getAsString() const {
956  std::string Result;
957  switch (Opc) {
958  case CONCAT: Result = "!con"; break;
959  case SHL: Result = "!shl"; break;
960  case SRA: Result = "!sra"; break;
961  case SRL: Result = "!srl"; break;
962  case EQ: Result = "!eq"; break;
963  case STRCONCAT: Result = "!strconcat"; break;
964  }
965  return Result + "(" + LHS->getAsString() + ", " + RHS->getAsString() + ")";
966}
967
968TernOpInit *TernOpInit::get(TernaryOp opc, Init *lhs,
969                                  Init *mhs, Init *rhs,
970                                  RecTy *Type) {
971  typedef std::pair<
972    std::pair<
973      std::pair<std::pair<unsigned, RecTy *>, Init *>,
974      Init *
975      >,
976    Init *
977    > Key;
978
979  typedef DenseMap<Key, TernOpInit *> Pool;
980  static Pool ThePool;
981
982  Key TheKey(std::make_pair(std::make_pair(std::make_pair(std::make_pair(opc,
983                                                                         Type),
984                                                          lhs),
985                                           mhs),
986                            rhs));
987
988  TernOpInit *&I = ThePool[TheKey];
989  if (!I) I = new TernOpInit(opc, lhs, mhs, rhs, Type);
990  return I;
991}
992
993static Init *ForeachHelper(Init *LHS, Init *MHS, Init *RHS, RecTy *Type,
994                           Record *CurRec, MultiClass *CurMultiClass);
995
996static Init *EvaluateOperation(OpInit *RHSo, Init *LHS, Init *Arg,
997                               RecTy *Type, Record *CurRec,
998                               MultiClass *CurMultiClass) {
999  std::vector<Init *> NewOperands;
1000
1001  TypedInit *TArg = dynamic_cast<TypedInit*>(Arg);
1002
1003  // If this is a dag, recurse
1004  if (TArg && TArg->getType()->getAsString() == "dag") {
1005    Init *Result = ForeachHelper(LHS, Arg, RHSo, Type,
1006                                 CurRec, CurMultiClass);
1007    if (Result != 0) {
1008      return Result;
1009    } else {
1010      return 0;
1011    }
1012  }
1013
1014  for (int i = 0; i < RHSo->getNumOperands(); ++i) {
1015    OpInit *RHSoo = dynamic_cast<OpInit*>(RHSo->getOperand(i));
1016
1017    if (RHSoo) {
1018      Init *Result = EvaluateOperation(RHSoo, LHS, Arg,
1019                                       Type, CurRec, CurMultiClass);
1020      if (Result != 0) {
1021        NewOperands.push_back(Result);
1022      } else {
1023        NewOperands.push_back(Arg);
1024      }
1025    } else if (LHS->getAsString() == RHSo->getOperand(i)->getAsString()) {
1026      NewOperands.push_back(Arg);
1027    } else {
1028      NewOperands.push_back(RHSo->getOperand(i));
1029    }
1030  }
1031
1032  // Now run the operator and use its result as the new leaf
1033  const OpInit *NewOp = RHSo->clone(NewOperands);
1034  Init *NewVal = NewOp->Fold(CurRec, CurMultiClass);
1035  if (NewVal != NewOp)
1036    return NewVal;
1037
1038  return 0;
1039}
1040
1041static Init *ForeachHelper(Init *LHS, Init *MHS, Init *RHS, RecTy *Type,
1042                           Record *CurRec, MultiClass *CurMultiClass) {
1043  DagInit *MHSd = dynamic_cast<DagInit*>(MHS);
1044  ListInit *MHSl = dynamic_cast<ListInit*>(MHS);
1045
1046  DagRecTy *DagType = dynamic_cast<DagRecTy*>(Type);
1047  ListRecTy *ListType = dynamic_cast<ListRecTy*>(Type);
1048
1049  OpInit *RHSo = dynamic_cast<OpInit*>(RHS);
1050
1051  if (!RHSo) {
1052    throw TGError(CurRec->getLoc(), "!foreach requires an operator\n");
1053  }
1054
1055  TypedInit *LHSt = dynamic_cast<TypedInit*>(LHS);
1056
1057  if (!LHSt) {
1058    throw TGError(CurRec->getLoc(), "!foreach requires typed variable\n");
1059  }
1060
1061  if ((MHSd && DagType) || (MHSl && ListType)) {
1062    if (MHSd) {
1063      Init *Val = MHSd->getOperator();
1064      Init *Result = EvaluateOperation(RHSo, LHS, Val,
1065                                       Type, CurRec, CurMultiClass);
1066      if (Result != 0) {
1067        Val = Result;
1068      }
1069
1070      std::vector<std::pair<Init *, std::string> > args;
1071      for (unsigned int i = 0; i < MHSd->getNumArgs(); ++i) {
1072        Init *Arg;
1073        std::string ArgName;
1074        Arg = MHSd->getArg(i);
1075        ArgName = MHSd->getArgName(i);
1076
1077        // Process args
1078        Init *Result = EvaluateOperation(RHSo, LHS, Arg, Type,
1079                                         CurRec, CurMultiClass);
1080        if (Result != 0) {
1081          Arg = Result;
1082        }
1083
1084        // TODO: Process arg names
1085        args.push_back(std::make_pair(Arg, ArgName));
1086      }
1087
1088      return DagInit::get(Val, "", args);
1089    }
1090    if (MHSl) {
1091      std::vector<Init *> NewOperands;
1092      std::vector<Init *> NewList(MHSl->begin(), MHSl->end());
1093
1094      for (std::vector<Init *>::iterator li = NewList.begin(),
1095             liend = NewList.end();
1096           li != liend;
1097           ++li) {
1098        Init *Item = *li;
1099        NewOperands.clear();
1100        for(int i = 0; i < RHSo->getNumOperands(); ++i) {
1101          // First, replace the foreach variable with the list item
1102          if (LHS->getAsString() == RHSo->getOperand(i)->getAsString()) {
1103            NewOperands.push_back(Item);
1104          } else {
1105            NewOperands.push_back(RHSo->getOperand(i));
1106          }
1107        }
1108
1109        // Now run the operator and use its result as the new list item
1110        const OpInit *NewOp = RHSo->clone(NewOperands);
1111        Init *NewItem = NewOp->Fold(CurRec, CurMultiClass);
1112        if (NewItem != NewOp)
1113          *li = NewItem;
1114      }
1115      return ListInit::get(NewList, MHSl->getType());
1116    }
1117  }
1118  return 0;
1119}
1120
1121Init *TernOpInit::Fold(Record *CurRec, MultiClass *CurMultiClass) const {
1122  switch (getOpcode()) {
1123  case SUBST: {
1124    DefInit *LHSd = dynamic_cast<DefInit*>(LHS);
1125    VarInit *LHSv = dynamic_cast<VarInit*>(LHS);
1126    StringInit *LHSs = dynamic_cast<StringInit*>(LHS);
1127
1128    DefInit *MHSd = dynamic_cast<DefInit*>(MHS);
1129    VarInit *MHSv = dynamic_cast<VarInit*>(MHS);
1130    StringInit *MHSs = dynamic_cast<StringInit*>(MHS);
1131
1132    DefInit *RHSd = dynamic_cast<DefInit*>(RHS);
1133    VarInit *RHSv = dynamic_cast<VarInit*>(RHS);
1134    StringInit *RHSs = dynamic_cast<StringInit*>(RHS);
1135
1136    if ((LHSd && MHSd && RHSd)
1137        || (LHSv && MHSv && RHSv)
1138        || (LHSs && MHSs && RHSs)) {
1139      if (RHSd) {
1140        Record *Val = RHSd->getDef();
1141        if (LHSd->getAsString() == RHSd->getAsString()) {
1142          Val = MHSd->getDef();
1143        }
1144        return DefInit::get(Val);
1145      }
1146      if (RHSv) {
1147        std::string Val = RHSv->getName();
1148        if (LHSv->getAsString() == RHSv->getAsString()) {
1149          Val = MHSv->getName();
1150        }
1151        return VarInit::get(Val, getType());
1152      }
1153      if (RHSs) {
1154        std::string Val = RHSs->getValue();
1155
1156        std::string::size_type found;
1157        std::string::size_type idx = 0;
1158        do {
1159          found = Val.find(LHSs->getValue(), idx);
1160          if (found != std::string::npos) {
1161            Val.replace(found, LHSs->getValue().size(), MHSs->getValue());
1162          }
1163          idx = found +  MHSs->getValue().size();
1164        } while (found != std::string::npos);
1165
1166        return StringInit::get(Val);
1167      }
1168    }
1169    break;
1170  }
1171
1172  case FOREACH: {
1173    Init *Result = ForeachHelper(LHS, MHS, RHS, getType(),
1174                                 CurRec, CurMultiClass);
1175    if (Result != 0) {
1176      return Result;
1177    }
1178    break;
1179  }
1180
1181  case IF: {
1182    IntInit *LHSi = dynamic_cast<IntInit*>(LHS);
1183    if (Init *I = LHS->convertInitializerTo(IntRecTy::get()))
1184      LHSi = dynamic_cast<IntInit*>(I);
1185    if (LHSi) {
1186      if (LHSi->getValue()) {
1187        return MHS;
1188      } else {
1189        return RHS;
1190      }
1191    }
1192    break;
1193  }
1194  }
1195
1196  return const_cast<TernOpInit *>(this);
1197}
1198
1199Init *TernOpInit::resolveReferences(Record &R,
1200                                    const RecordVal *RV) const {
1201  Init *lhs = LHS->resolveReferences(R, RV);
1202
1203  if (Opc == IF && lhs != LHS) {
1204    IntInit *Value = dynamic_cast<IntInit*>(lhs);
1205    if (Init *I = lhs->convertInitializerTo(IntRecTy::get()))
1206      Value = dynamic_cast<IntInit*>(I);
1207    if (Value != 0) {
1208      // Short-circuit
1209      if (Value->getValue()) {
1210        Init *mhs = MHS->resolveReferences(R, RV);
1211        return (TernOpInit::get(getOpcode(), lhs, mhs,
1212                                RHS, getType()))->Fold(&R, 0);
1213      } else {
1214        Init *rhs = RHS->resolveReferences(R, RV);
1215        return (TernOpInit::get(getOpcode(), lhs, MHS,
1216                                rhs, getType()))->Fold(&R, 0);
1217      }
1218    }
1219  }
1220
1221  Init *mhs = MHS->resolveReferences(R, RV);
1222  Init *rhs = RHS->resolveReferences(R, RV);
1223
1224  if (LHS != lhs || MHS != mhs || RHS != rhs)
1225    return (TernOpInit::get(getOpcode(), lhs, mhs, rhs,
1226                            getType()))->Fold(&R, 0);
1227  return Fold(&R, 0);
1228}
1229
1230std::string TernOpInit::getAsString() const {
1231  std::string Result;
1232  switch (Opc) {
1233  case SUBST: Result = "!subst"; break;
1234  case FOREACH: Result = "!foreach"; break;
1235  case IF: Result = "!if"; break;
1236 }
1237  return Result + "(" + LHS->getAsString() + ", " + MHS->getAsString() + ", "
1238    + RHS->getAsString() + ")";
1239}
1240
1241RecTy *TypedInit::getFieldType(const std::string &FieldName) const {
1242  RecordRecTy *RecordType = dynamic_cast<RecordRecTy *>(getType());
1243  if (RecordType) {
1244    RecordVal *Field = RecordType->getRecord()->getValue(FieldName);
1245    if (Field) {
1246      return Field->getType();
1247    }
1248  }
1249  return 0;
1250}
1251
1252Init *
1253TypedInit::convertInitializerBitRange(const std::vector<unsigned> &Bits) const {
1254  BitsRecTy *T = dynamic_cast<BitsRecTy*>(getType());
1255  if (T == 0) return 0;  // Cannot subscript a non-bits variable.
1256  unsigned NumBits = T->getNumBits();
1257
1258  SmallVector<Init *, 16> NewBits(Bits.size());
1259  for (unsigned i = 0, e = Bits.size(); i != e; ++i) {
1260    if (Bits[i] >= NumBits)
1261      return 0;
1262
1263    NewBits[i] = VarBitInit::get(const_cast<TypedInit *>(this), Bits[i]);
1264  }
1265  return BitsInit::get(NewBits);
1266}
1267
1268Init *
1269TypedInit::convertInitListSlice(const std::vector<unsigned> &Elements) const {
1270  ListRecTy *T = dynamic_cast<ListRecTy*>(getType());
1271  if (T == 0) return 0;  // Cannot subscript a non-list variable.
1272
1273  if (Elements.size() == 1)
1274    return VarListElementInit::get(const_cast<TypedInit *>(this), Elements[0]);
1275
1276  std::vector<Init*> ListInits;
1277  ListInits.reserve(Elements.size());
1278  for (unsigned i = 0, e = Elements.size(); i != e; ++i)
1279    ListInits.push_back(VarListElementInit::get(const_cast<TypedInit *>(this),
1280                                                Elements[i]));
1281  return ListInit::get(ListInits, T);
1282}
1283
1284
1285VarInit *VarInit::get(const std::string &VN, RecTy *T) {
1286  Init *Value = StringInit::get(VN);
1287  return VarInit::get(Value, T);
1288}
1289
1290VarInit *VarInit::get(Init *VN, RecTy *T) {
1291  typedef std::pair<RecTy *, Init *> Key;
1292  typedef DenseMap<Key, VarInit *> Pool;
1293  static Pool ThePool;
1294
1295  Key TheKey(std::make_pair(T, VN));
1296
1297  VarInit *&I = ThePool[TheKey];
1298  if (!I) I = new VarInit(VN, T);
1299  return I;
1300}
1301
1302const std::string &VarInit::getName() const {
1303  StringInit *NameString =
1304    dynamic_cast<StringInit *>(getNameInit());
1305  assert(NameString && "VarInit name is not a string!");
1306  return NameString->getValue();
1307}
1308
1309Init *VarInit::getBit(unsigned Bit) const {
1310  if (getType() == BitRecTy::get())
1311    return const_cast<VarInit*>(this);
1312  return VarBitInit::get(const_cast<VarInit*>(this), Bit);
1313}
1314
1315Init *VarInit::resolveListElementReference(Record &R,
1316                                           const RecordVal *IRV,
1317                                           unsigned Elt) const {
1318  if (R.isTemplateArg(getNameInit())) return 0;
1319  if (IRV && IRV->getNameInit() != getNameInit()) return 0;
1320
1321  RecordVal *RV = R.getValue(getNameInit());
1322  assert(RV && "Reference to a non-existent variable?");
1323  ListInit *LI = dynamic_cast<ListInit*>(RV->getValue());
1324  if (!LI) {
1325    TypedInit *VI = dynamic_cast<TypedInit*>(RV->getValue());
1326    assert(VI && "Invalid list element!");
1327    return VarListElementInit::get(VI, Elt);
1328  }
1329
1330  if (Elt >= LI->getSize())
1331    return 0;  // Out of range reference.
1332  Init *E = LI->getElement(Elt);
1333  // If the element is set to some value, or if we are resolving a reference
1334  // to a specific variable and that variable is explicitly unset, then
1335  // replace the VarListElementInit with it.
1336  if (IRV || !dynamic_cast<UnsetInit*>(E))
1337    return E;
1338  return 0;
1339}
1340
1341
1342RecTy *VarInit::getFieldType(const std::string &FieldName) const {
1343  if (RecordRecTy *RTy = dynamic_cast<RecordRecTy*>(getType()))
1344    if (const RecordVal *RV = RTy->getRecord()->getValue(FieldName))
1345      return RV->getType();
1346  return 0;
1347}
1348
1349Init *VarInit::getFieldInit(Record &R, const RecordVal *RV,
1350                            const std::string &FieldName) const {
1351  if (dynamic_cast<RecordRecTy*>(getType()))
1352    if (const RecordVal *Val = R.getValue(VarName)) {
1353      if (RV != Val && (RV || dynamic_cast<UnsetInit*>(Val->getValue())))
1354        return 0;
1355      Init *TheInit = Val->getValue();
1356      assert(TheInit != this && "Infinite loop detected!");
1357      if (Init *I = TheInit->getFieldInit(R, RV, FieldName))
1358        return I;
1359      else
1360        return 0;
1361    }
1362  return 0;
1363}
1364
1365/// resolveReferences - This method is used by classes that refer to other
1366/// variables which may not be defined at the time the expression is formed.
1367/// If a value is set for the variable later, this method will be called on
1368/// users of the value to allow the value to propagate out.
1369///
1370Init *VarInit::resolveReferences(Record &R, const RecordVal *RV) const {
1371  if (RecordVal *Val = R.getValue(VarName))
1372    if (RV == Val || (RV == 0 && !dynamic_cast<UnsetInit*>(Val->getValue())))
1373      return Val->getValue();
1374  return const_cast<VarInit *>(this);
1375}
1376
1377VarBitInit *VarBitInit::get(TypedInit *T, unsigned B) {
1378  typedef std::pair<TypedInit *, unsigned> Key;
1379  typedef DenseMap<Key, VarBitInit *> Pool;
1380
1381  static Pool ThePool;
1382
1383  Key TheKey(std::make_pair(T, B));
1384
1385  VarBitInit *&I = ThePool[TheKey];
1386  if (!I) I = new VarBitInit(T, B);
1387  return I;
1388}
1389
1390std::string VarBitInit::getAsString() const {
1391   return TI->getAsString() + "{" + utostr(Bit) + "}";
1392}
1393
1394Init *VarBitInit::resolveReferences(Record &R, const RecordVal *RV) const {
1395  Init *I = TI->resolveReferences(R, RV);
1396  if (TI != I)
1397    return I->getBit(getBitNum());
1398
1399  return const_cast<VarBitInit*>(this);
1400}
1401
1402VarListElementInit *VarListElementInit::get(TypedInit *T,
1403                                            unsigned E) {
1404  typedef std::pair<TypedInit *, unsigned> Key;
1405  typedef DenseMap<Key, VarListElementInit *> Pool;
1406
1407  static Pool ThePool;
1408
1409  Key TheKey(std::make_pair(T, E));
1410
1411  VarListElementInit *&I = ThePool[TheKey];
1412  if (!I) I = new VarListElementInit(T, E);
1413  return I;
1414}
1415
1416std::string VarListElementInit::getAsString() const {
1417  return TI->getAsString() + "[" + utostr(Element) + "]";
1418}
1419
1420Init *
1421VarListElementInit::resolveReferences(Record &R, const RecordVal *RV) const {
1422  if (Init *I = getVariable()->resolveListElementReference(R, RV,
1423                                                           getElementNum()))
1424    return I;
1425  return const_cast<VarListElementInit *>(this);
1426}
1427
1428Init *VarListElementInit::getBit(unsigned Bit) const {
1429  if (getType() == BitRecTy::get())
1430    return const_cast<VarListElementInit*>(this);
1431  return VarBitInit::get(const_cast<VarListElementInit*>(this), Bit);
1432}
1433
1434Init *VarListElementInit:: resolveListElementReference(Record &R,
1435                                                       const RecordVal *RV,
1436                                                       unsigned Elt) const {
1437  Init *Result = TI->resolveListElementReference(R, RV, Element);
1438
1439  if (Result) {
1440    TypedInit *TInit = dynamic_cast<TypedInit *>(Result);
1441    if (TInit) {
1442      Init *Result2 = TInit->resolveListElementReference(R, RV, Elt);
1443      if (Result2) return Result2;
1444      return new VarListElementInit(TInit, Elt);
1445    }
1446    return Result;
1447  }
1448
1449  return 0;
1450}
1451
1452DefInit *DefInit::get(Record *R) {
1453  return R->getDefInit();
1454}
1455
1456RecTy *DefInit::getFieldType(const std::string &FieldName) const {
1457  if (const RecordVal *RV = Def->getValue(FieldName))
1458    return RV->getType();
1459  return 0;
1460}
1461
1462Init *DefInit::getFieldInit(Record &R, const RecordVal *RV,
1463                            const std::string &FieldName) const {
1464  return Def->getValue(FieldName)->getValue();
1465}
1466
1467
1468std::string DefInit::getAsString() const {
1469  return Def->getName();
1470}
1471
1472FieldInit *FieldInit::get(Init *R, const std::string &FN) {
1473  typedef std::pair<Init *, TableGenStringKey> Key;
1474  typedef DenseMap<Key, FieldInit *> Pool;
1475  static Pool ThePool;
1476
1477  Key TheKey(std::make_pair(R, FN));
1478
1479  FieldInit *&I = ThePool[TheKey];
1480  if (!I) I = new FieldInit(R, FN);
1481  return I;
1482}
1483
1484Init *FieldInit::getBit(unsigned Bit) const {
1485  if (getType() == BitRecTy::get())
1486    return const_cast<FieldInit*>(this);
1487  return VarBitInit::get(const_cast<FieldInit*>(this), Bit);
1488}
1489
1490Init *FieldInit::resolveListElementReference(Record &R, const RecordVal *RV,
1491                                             unsigned Elt) const {
1492  if (Init *ListVal = Rec->getFieldInit(R, RV, FieldName))
1493    if (ListInit *LI = dynamic_cast<ListInit*>(ListVal)) {
1494      if (Elt >= LI->getSize()) return 0;
1495      Init *E = LI->getElement(Elt);
1496
1497      // If the element is set to some value, or if we are resolving a
1498      // reference to a specific variable and that variable is explicitly
1499      // unset, then replace the VarListElementInit with it.
1500      if (RV || !dynamic_cast<UnsetInit*>(E))
1501        return E;
1502    }
1503  return 0;
1504}
1505
1506Init *FieldInit::resolveReferences(Record &R, const RecordVal *RV) const {
1507  Init *NewRec = RV ? Rec->resolveReferences(R, RV) : Rec;
1508
1509  Init *BitsVal = NewRec->getFieldInit(R, RV, FieldName);
1510  if (BitsVal) {
1511    Init *BVR = BitsVal->resolveReferences(R, RV);
1512    return BVR->isComplete() ? BVR : const_cast<FieldInit *>(this);
1513  }
1514
1515  if (NewRec != Rec) {
1516    return FieldInit::get(NewRec, FieldName);
1517  }
1518  return const_cast<FieldInit *>(this);
1519}
1520
1521void ProfileDagInit(FoldingSetNodeID &ID,
1522                    Init *V,
1523                    const std::string &VN,
1524                    ArrayRef<Init *> ArgRange,
1525                    ArrayRef<std::string> NameRange) {
1526  ID.AddPointer(V);
1527  ID.AddString(VN);
1528
1529  ArrayRef<Init *>::iterator Arg  = ArgRange.begin();
1530  ArrayRef<std::string>::iterator  Name = NameRange.begin();
1531  while (Arg != ArgRange.end()) {
1532    assert(Name != NameRange.end() && "Arg name underflow!");
1533    ID.AddPointer(*Arg++);
1534    ID.AddString(*Name++);
1535  }
1536  assert(Name == NameRange.end() && "Arg name overflow!");
1537}
1538
1539DagInit *
1540DagInit::get(Init *V, const std::string &VN,
1541             ArrayRef<Init *> ArgRange,
1542             ArrayRef<std::string> NameRange) {
1543  typedef FoldingSet<DagInit> Pool;
1544  static Pool ThePool;
1545
1546  FoldingSetNodeID ID;
1547  ProfileDagInit(ID, V, VN, ArgRange, NameRange);
1548
1549  void *IP = 0;
1550  if (DagInit *I = ThePool.FindNodeOrInsertPos(ID, IP))
1551    return I;
1552
1553  DagInit *I = new DagInit(V, VN, ArgRange, NameRange);
1554  ThePool.InsertNode(I, IP);
1555
1556  return I;
1557}
1558
1559DagInit *
1560DagInit::get(Init *V, const std::string &VN,
1561             const std::vector<std::pair<Init*, std::string> > &args) {
1562  typedef std::pair<Init*, std::string> PairType;
1563
1564  std::vector<Init *> Args;
1565  std::vector<std::string> Names;
1566
1567  for (std::vector<PairType>::const_iterator i = args.begin(),
1568         iend = args.end();
1569       i != iend;
1570       ++i) {
1571    Args.push_back(i->first);
1572    Names.push_back(i->second);
1573  }
1574
1575  return DagInit::get(V, VN, Args, Names);
1576}
1577
1578void DagInit::Profile(FoldingSetNodeID &ID) const {
1579  ProfileDagInit(ID, Val, ValName, Args, ArgNames);
1580}
1581
1582Init *DagInit::resolveReferences(Record &R, const RecordVal *RV) const {
1583  std::vector<Init*> NewArgs;
1584  for (unsigned i = 0, e = Args.size(); i != e; ++i)
1585    NewArgs.push_back(Args[i]->resolveReferences(R, RV));
1586
1587  Init *Op = Val->resolveReferences(R, RV);
1588
1589  if (Args != NewArgs || Op != Val)
1590    return DagInit::get(Op, ValName, NewArgs, ArgNames);
1591
1592  return const_cast<DagInit *>(this);
1593}
1594
1595
1596std::string DagInit::getAsString() const {
1597  std::string Result = "(" + Val->getAsString();
1598  if (!ValName.empty())
1599    Result += ":" + ValName;
1600  if (Args.size()) {
1601    Result += " " + Args[0]->getAsString();
1602    if (!ArgNames[0].empty()) Result += ":$" + ArgNames[0];
1603    for (unsigned i = 1, e = Args.size(); i != e; ++i) {
1604      Result += ", " + Args[i]->getAsString();
1605      if (!ArgNames[i].empty()) Result += ":$" + ArgNames[i];
1606    }
1607  }
1608  return Result + ")";
1609}
1610
1611
1612//===----------------------------------------------------------------------===//
1613//    Other implementations
1614//===----------------------------------------------------------------------===//
1615
1616RecordVal::RecordVal(Init *N, RecTy *T, unsigned P)
1617  : Name(N), Ty(T), Prefix(P) {
1618  Value = Ty->convertValue(UnsetInit::get());
1619  assert(Value && "Cannot create unset value for current type!");
1620}
1621
1622RecordVal::RecordVal(const std::string &N, RecTy *T, unsigned P)
1623  : Name(StringInit::get(N)), Ty(T), Prefix(P) {
1624  Value = Ty->convertValue(UnsetInit::get());
1625  assert(Value && "Cannot create unset value for current type!");
1626}
1627
1628const std::string &RecordVal::getName() const {
1629  StringInit *NameString = dynamic_cast<StringInit *>(Name);
1630  assert(NameString && "RecordVal name is not a string!");
1631  return NameString->getValue();
1632}
1633
1634void RecordVal::dump() const { errs() << *this; }
1635
1636void RecordVal::print(raw_ostream &OS, bool PrintSem) const {
1637  if (getPrefix()) OS << "field ";
1638  OS << *getType() << " " << getNameInitAsString();
1639
1640  if (getValue())
1641    OS << " = " << *getValue();
1642
1643  if (PrintSem) OS << ";\n";
1644}
1645
1646unsigned Record::LastID = 0;
1647
1648void Record::init() {
1649  checkName();
1650
1651  // Every record potentially has a def at the top.  This value is
1652  // replaced with the top-level def name at instantiation time.
1653  RecordVal DN("NAME", StringRecTy::get(), 0);
1654  addValue(DN);
1655}
1656
1657void Record::checkName() {
1658  // Ensure the record name has string type.
1659  const TypedInit *TypedName = dynamic_cast<const TypedInit *>(Name);
1660  assert(TypedName && "Record name is not typed!");
1661  RecTy *Type = TypedName->getType();
1662  if (dynamic_cast<StringRecTy *>(Type) == 0) {
1663    throw TGError(getLoc(), "Record name is not a string!");
1664  }
1665}
1666
1667DefInit *Record::getDefInit() {
1668  if (!TheInit)
1669    TheInit = new DefInit(this, new RecordRecTy(this));
1670  return TheInit;
1671}
1672
1673const std::string &Record::getName() const {
1674  const StringInit *NameString =
1675    dynamic_cast<const StringInit *>(Name);
1676  assert(NameString && "Record name is not a string!");
1677  return NameString->getValue();
1678}
1679
1680void Record::setName(Init *NewName) {
1681  if (TrackedRecords.getDef(Name->getAsUnquotedString()) == this) {
1682    TrackedRecords.removeDef(Name->getAsUnquotedString());
1683    TrackedRecords.addDef(this);
1684  } else if (TrackedRecords.getClass(Name->getAsUnquotedString()) == this) {
1685    TrackedRecords.removeClass(Name->getAsUnquotedString());
1686    TrackedRecords.addClass(this);
1687  }  // Otherwise this isn't yet registered.
1688  Name = NewName;
1689  checkName();
1690  // DO NOT resolve record values to the name at this point because
1691  // there might be default values for arguments of this def.  Those
1692  // arguments might not have been resolved yet so we don't want to
1693  // prematurely assume values for those arguments were not passed to
1694  // this def.
1695  //
1696  // Nonetheless, it may be that some of this Record's values
1697  // reference the record name.  Indeed, the reason for having the
1698  // record name be an Init is to provide this flexibility.  The extra
1699  // resolve steps after completely instantiating defs takes care of
1700  // this.  See TGParser::ParseDef and TGParser::ParseDefm.
1701}
1702
1703void Record::setName(const std::string &Name) {
1704  setName(StringInit::get(Name));
1705}
1706
1707/// resolveReferencesTo - If anything in this record refers to RV, replace the
1708/// reference to RV with the RHS of RV.  If RV is null, we resolve all possible
1709/// references.
1710void Record::resolveReferencesTo(const RecordVal *RV) {
1711  for (unsigned i = 0, e = Values.size(); i != e; ++i) {
1712    if (RV == &Values[i]) // Skip resolve the same field as the given one
1713      continue;
1714    if (Init *V = Values[i].getValue())
1715      if (Values[i].setValue(V->resolveReferences(*this, RV)))
1716        throw TGError(getLoc(), "Invalid value is found when setting '"
1717                      + Values[i].getNameInitAsString()
1718                      + "' after resolving references"
1719                      + (RV ? " against '" + RV->getNameInitAsString()
1720                              + "' of ("
1721                              + RV->getValue()->getAsUnquotedString() + ")"
1722                            : "")
1723                      + "\n");
1724  }
1725  Init *OldName = getNameInit();
1726  Init *NewName = Name->resolveReferences(*this, RV);
1727  if (NewName != OldName) {
1728    // Re-register with RecordKeeper.
1729    setName(NewName);
1730  }
1731}
1732
1733void Record::dump() const { errs() << *this; }
1734
1735raw_ostream &llvm::operator<<(raw_ostream &OS, const Record &R) {
1736  OS << R.getNameInitAsString();
1737
1738  const std::vector<Init *> &TArgs = R.getTemplateArgs();
1739  if (!TArgs.empty()) {
1740    OS << "<";
1741    for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
1742      if (i) OS << ", ";
1743      const RecordVal *RV = R.getValue(TArgs[i]);
1744      assert(RV && "Template argument record not found??");
1745      RV->print(OS, false);
1746    }
1747    OS << ">";
1748  }
1749
1750  OS << " {";
1751  const std::vector<Record*> &SC = R.getSuperClasses();
1752  if (!SC.empty()) {
1753    OS << "\t//";
1754    for (unsigned i = 0, e = SC.size(); i != e; ++i)
1755      OS << " " << SC[i]->getNameInitAsString();
1756  }
1757  OS << "\n";
1758
1759  const std::vector<RecordVal> &Vals = R.getValues();
1760  for (unsigned i = 0, e = Vals.size(); i != e; ++i)
1761    if (Vals[i].getPrefix() && !R.isTemplateArg(Vals[i].getName()))
1762      OS << Vals[i];
1763  for (unsigned i = 0, e = Vals.size(); i != e; ++i)
1764    if (!Vals[i].getPrefix() && !R.isTemplateArg(Vals[i].getName()))
1765      OS << Vals[i];
1766
1767  return OS << "}\n";
1768}
1769
1770/// getValueInit - Return the initializer for a value with the specified name,
1771/// or throw an exception if the field does not exist.
1772///
1773Init *Record::getValueInit(StringRef FieldName) const {
1774  const RecordVal *R = getValue(FieldName);
1775  if (R == 0 || R->getValue() == 0)
1776    throw "Record `" + getName() + "' does not have a field named `" +
1777      FieldName.str() + "'!\n";
1778  return R->getValue();
1779}
1780
1781
1782/// getValueAsString - This method looks up the specified field and returns its
1783/// value as a string, throwing an exception if the field does not exist or if
1784/// the value is not a string.
1785///
1786std::string Record::getValueAsString(StringRef FieldName) const {
1787  const RecordVal *R = getValue(FieldName);
1788  if (R == 0 || R->getValue() == 0)
1789    throw "Record `" + getName() + "' does not have a field named `" +
1790          FieldName.str() + "'!\n";
1791
1792  if (StringInit *SI = dynamic_cast<StringInit*>(R->getValue()))
1793    return SI->getValue();
1794  throw "Record `" + getName() + "', field `" + FieldName.str() +
1795        "' does not have a string initializer!";
1796}
1797
1798/// getValueAsBitsInit - This method looks up the specified field and returns
1799/// its value as a BitsInit, throwing an exception if the field does not exist
1800/// or if the value is not the right type.
1801///
1802BitsInit *Record::getValueAsBitsInit(StringRef FieldName) const {
1803  const RecordVal *R = getValue(FieldName);
1804  if (R == 0 || R->getValue() == 0)
1805    throw "Record `" + getName() + "' does not have a field named `" +
1806          FieldName.str() + "'!\n";
1807
1808  if (BitsInit *BI = dynamic_cast<BitsInit*>(R->getValue()))
1809    return BI;
1810  throw "Record `" + getName() + "', field `" + FieldName.str() +
1811        "' does not have a BitsInit initializer!";
1812}
1813
1814/// getValueAsListInit - This method looks up the specified field and returns
1815/// its value as a ListInit, throwing an exception if the field does not exist
1816/// or if the value is not the right type.
1817///
1818ListInit *Record::getValueAsListInit(StringRef FieldName) const {
1819  const RecordVal *R = getValue(FieldName);
1820  if (R == 0 || R->getValue() == 0)
1821    throw "Record `" + getName() + "' does not have a field named `" +
1822          FieldName.str() + "'!\n";
1823
1824  if (ListInit *LI = dynamic_cast<ListInit*>(R->getValue()))
1825    return LI;
1826  throw "Record `" + getName() + "', field `" + FieldName.str() +
1827        "' does not have a list initializer!";
1828}
1829
1830/// getValueAsListOfDefs - This method looks up the specified field and returns
1831/// its value as a vector of records, throwing an exception if the field does
1832/// not exist or if the value is not the right type.
1833///
1834std::vector<Record*>
1835Record::getValueAsListOfDefs(StringRef FieldName) const {
1836  ListInit *List = getValueAsListInit(FieldName);
1837  std::vector<Record*> Defs;
1838  for (unsigned i = 0; i < List->getSize(); i++) {
1839    if (DefInit *DI = dynamic_cast<DefInit*>(List->getElement(i))) {
1840      Defs.push_back(DI->getDef());
1841    } else {
1842      throw "Record `" + getName() + "', field `" + FieldName.str() +
1843            "' list is not entirely DefInit!";
1844    }
1845  }
1846  return Defs;
1847}
1848
1849/// getValueAsInt - This method looks up the specified field and returns its
1850/// value as an int64_t, throwing an exception if the field does not exist or if
1851/// the value is not the right type.
1852///
1853int64_t Record::getValueAsInt(StringRef FieldName) const {
1854  const RecordVal *R = getValue(FieldName);
1855  if (R == 0 || R->getValue() == 0)
1856    throw "Record `" + getName() + "' does not have a field named `" +
1857          FieldName.str() + "'!\n";
1858
1859  if (IntInit *II = dynamic_cast<IntInit*>(R->getValue()))
1860    return II->getValue();
1861  throw "Record `" + getName() + "', field `" + FieldName.str() +
1862        "' does not have an int initializer!";
1863}
1864
1865/// getValueAsListOfInts - This method looks up the specified field and returns
1866/// its value as a vector of integers, throwing an exception if the field does
1867/// not exist or if the value is not the right type.
1868///
1869std::vector<int64_t>
1870Record::getValueAsListOfInts(StringRef FieldName) const {
1871  ListInit *List = getValueAsListInit(FieldName);
1872  std::vector<int64_t> Ints;
1873  for (unsigned i = 0; i < List->getSize(); i++) {
1874    if (IntInit *II = dynamic_cast<IntInit*>(List->getElement(i))) {
1875      Ints.push_back(II->getValue());
1876    } else {
1877      throw "Record `" + getName() + "', field `" + FieldName.str() +
1878            "' does not have a list of ints initializer!";
1879    }
1880  }
1881  return Ints;
1882}
1883
1884/// getValueAsListOfStrings - This method looks up the specified field and
1885/// returns its value as a vector of strings, throwing an exception if the
1886/// field does not exist or if the value is not the right type.
1887///
1888std::vector<std::string>
1889Record::getValueAsListOfStrings(StringRef FieldName) const {
1890  ListInit *List = getValueAsListInit(FieldName);
1891  std::vector<std::string> Strings;
1892  for (unsigned i = 0; i < List->getSize(); i++) {
1893    if (StringInit *II = dynamic_cast<StringInit*>(List->getElement(i))) {
1894      Strings.push_back(II->getValue());
1895    } else {
1896      throw "Record `" + getName() + "', field `" + FieldName.str() +
1897            "' does not have a list of strings initializer!";
1898    }
1899  }
1900  return Strings;
1901}
1902
1903/// getValueAsDef - This method looks up the specified field and returns its
1904/// value as a Record, throwing an exception if the field does not exist or if
1905/// the value is not the right type.
1906///
1907Record *Record::getValueAsDef(StringRef FieldName) const {
1908  const RecordVal *R = getValue(FieldName);
1909  if (R == 0 || R->getValue() == 0)
1910    throw "Record `" + getName() + "' does not have a field named `" +
1911      FieldName.str() + "'!\n";
1912
1913  if (DefInit *DI = dynamic_cast<DefInit*>(R->getValue()))
1914    return DI->getDef();
1915  throw "Record `" + getName() + "', field `" + FieldName.str() +
1916        "' does not have a def initializer!";
1917}
1918
1919/// getValueAsBit - This method looks up the specified field and returns its
1920/// value as a bit, throwing an exception if the field does not exist or if
1921/// the value is not the right type.
1922///
1923bool Record::getValueAsBit(StringRef FieldName) const {
1924  const RecordVal *R = getValue(FieldName);
1925  if (R == 0 || R->getValue() == 0)
1926    throw "Record `" + getName() + "' does not have a field named `" +
1927      FieldName.str() + "'!\n";
1928
1929  if (BitInit *BI = dynamic_cast<BitInit*>(R->getValue()))
1930    return BI->getValue();
1931  throw "Record `" + getName() + "', field `" + FieldName.str() +
1932        "' does not have a bit initializer!";
1933}
1934
1935bool Record::getValueAsBitOrUnset(StringRef FieldName, bool &Unset) const {
1936  const RecordVal *R = getValue(FieldName);
1937  if (R == 0 || R->getValue() == 0)
1938    throw "Record `" + getName() + "' does not have a field named `" +
1939      FieldName.str() + "'!\n";
1940
1941  if (R->getValue() == UnsetInit::get()) {
1942    Unset = true;
1943    return false;
1944  }
1945  Unset = false;
1946  if (BitInit *BI = dynamic_cast<BitInit*>(R->getValue()))
1947    return BI->getValue();
1948  throw "Record `" + getName() + "', field `" + FieldName.str() +
1949        "' does not have a bit initializer!";
1950}
1951
1952/// getValueAsDag - This method looks up the specified field and returns its
1953/// value as an Dag, throwing an exception if the field does not exist or if
1954/// the value is not the right type.
1955///
1956DagInit *Record::getValueAsDag(StringRef FieldName) const {
1957  const RecordVal *R = getValue(FieldName);
1958  if (R == 0 || R->getValue() == 0)
1959    throw "Record `" + getName() + "' does not have a field named `" +
1960      FieldName.str() + "'!\n";
1961
1962  if (DagInit *DI = dynamic_cast<DagInit*>(R->getValue()))
1963    return DI;
1964  throw "Record `" + getName() + "', field `" + FieldName.str() +
1965        "' does not have a dag initializer!";
1966}
1967
1968
1969void MultiClass::dump() const {
1970  errs() << "Record:\n";
1971  Rec.dump();
1972
1973  errs() << "Defs:\n";
1974  for (RecordVector::const_iterator r = DefPrototypes.begin(),
1975         rend = DefPrototypes.end();
1976       r != rend;
1977       ++r) {
1978    (*r)->dump();
1979  }
1980}
1981
1982
1983void RecordKeeper::dump() const { errs() << *this; }
1984
1985raw_ostream &llvm::operator<<(raw_ostream &OS, const RecordKeeper &RK) {
1986  OS << "------------- Classes -----------------\n";
1987  const std::map<std::string, Record*> &Classes = RK.getClasses();
1988  for (std::map<std::string, Record*>::const_iterator I = Classes.begin(),
1989         E = Classes.end(); I != E; ++I)
1990    OS << "class " << *I->second;
1991
1992  OS << "------------- Defs -----------------\n";
1993  const std::map<std::string, Record*> &Defs = RK.getDefs();
1994  for (std::map<std::string, Record*>::const_iterator I = Defs.begin(),
1995         E = Defs.end(); I != E; ++I)
1996    OS << "def " << *I->second;
1997  return OS;
1998}
1999
2000
2001/// getAllDerivedDefinitions - This method returns all concrete definitions
2002/// that derive from the specified class name.  If a class with the specified
2003/// name does not exist, an error is printed and true is returned.
2004std::vector<Record*>
2005RecordKeeper::getAllDerivedDefinitions(const std::string &ClassName) const {
2006  Record *Class = getClass(ClassName);
2007  if (!Class)
2008    throw "ERROR: Couldn't find the `" + ClassName + "' class!\n";
2009
2010  std::vector<Record*> Defs;
2011  for (std::map<std::string, Record*>::const_iterator I = getDefs().begin(),
2012         E = getDefs().end(); I != E; ++I)
2013    if (I->second->isSubClassOf(Class))
2014      Defs.push_back(I->second);
2015
2016  return Defs;
2017}
2018
2019/// QualifyName - Return an Init with a qualifier prefix referring
2020/// to CurRec's name.
2021Init *llvm::QualifyName(Record &CurRec, MultiClass *CurMultiClass,
2022                        Init *Name, const std::string &Scoper) {
2023  RecTy *Type = dynamic_cast<TypedInit *>(Name)->getType();
2024
2025  BinOpInit *NewName =
2026    BinOpInit::get(BinOpInit::STRCONCAT,
2027                      BinOpInit::get(BinOpInit::STRCONCAT,
2028                                        CurRec.getNameInit(),
2029                                        StringInit::get(Scoper),
2030                                        Type)->Fold(&CurRec, CurMultiClass),
2031                      Name,
2032                      Type);
2033
2034  if (CurMultiClass && Scoper != "::") {
2035    NewName =
2036      BinOpInit::get(BinOpInit::STRCONCAT,
2037                        BinOpInit::get(BinOpInit::STRCONCAT,
2038                                          CurMultiClass->Rec.getNameInit(),
2039                                          StringInit::get("::"),
2040                                          Type)->Fold(&CurRec, CurMultiClass),
2041                        NewName->Fold(&CurRec, CurMultiClass),
2042                        Type);
2043  }
2044
2045  return NewName->Fold(&CurRec, CurMultiClass);
2046}
2047
2048/// QualifyName - Return an Init with a qualifier prefix referring
2049/// to CurRec's name.
2050Init *llvm::QualifyName(Record &CurRec, MultiClass *CurMultiClass,
2051                        const std::string &Name,
2052                        const std::string &Scoper) {
2053  return QualifyName(CurRec, CurMultiClass, StringInit::get(Name), Scoper);
2054}
2055