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