1 //===- Record.cpp - Record implementation ---------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // Implement the tablegen record classes.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "llvm/ADT/ArrayRef.h"
14 #include "llvm/ADT/DenseMap.h"
15 #include "llvm/ADT/FoldingSet.h"
16 #include "llvm/ADT/SmallString.h"
17 #include "llvm/ADT/SmallVector.h"
18 #include "llvm/ADT/Statistic.h"
19 #include "llvm/ADT/StringExtras.h"
20 #include "llvm/ADT/StringMap.h"
21 #include "llvm/ADT/StringRef.h"
22 #include "llvm/ADT/StringSet.h"
23 #include "llvm/Config/llvm-config.h"
24 #include "llvm/Support/Allocator.h"
25 #include "llvm/Support/Casting.h"
26 #include "llvm/Support/Compiler.h"
27 #include "llvm/Support/ErrorHandling.h"
28 #include "llvm/Support/SMLoc.h"
29 #include "llvm/Support/raw_ostream.h"
30 #include "llvm/TableGen/Error.h"
31 #include "llvm/TableGen/Record.h"
32 #include <cassert>
33 #include <cstdint>
34 #include <memory>
35 #include <map>
36 #include <string>
37 #include <utility>
38 #include <vector>
39 
40 using namespace llvm;
41 
42 #define DEBUG_TYPE "tblgen-records"
43 
44 static BumpPtrAllocator Allocator;
45 
46 STATISTIC(CodeInitsConstructed,
47           "The total number of unique CodeInits constructed");
48 
49 //===----------------------------------------------------------------------===//
50 //    Type implementations
51 //===----------------------------------------------------------------------===//
52 
53 BitRecTy BitRecTy::Shared;
54 CodeRecTy CodeRecTy::Shared;
55 IntRecTy IntRecTy::Shared;
56 StringRecTy StringRecTy::Shared;
57 DagRecTy DagRecTy::Shared;
58 
59 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
60 LLVM_DUMP_METHOD void RecTy::dump() const { print(errs()); }
61 #endif
62 
63 ListRecTy *RecTy::getListTy() {
64   if (!ListTy)
65     ListTy = new(Allocator) ListRecTy(this);
66   return ListTy;
67 }
68 
69 bool RecTy::typeIsConvertibleTo(const RecTy *RHS) const {
70   assert(RHS && "NULL pointer");
71   return Kind == RHS->getRecTyKind();
72 }
73 
74 bool RecTy::typeIsA(const RecTy *RHS) const { return this == RHS; }
75 
76 bool BitRecTy::typeIsConvertibleTo(const RecTy *RHS) const{
77   if (RecTy::typeIsConvertibleTo(RHS) || RHS->getRecTyKind() == IntRecTyKind)
78     return true;
79   if (const BitsRecTy *BitsTy = dyn_cast<BitsRecTy>(RHS))
80     return BitsTy->getNumBits() == 1;
81   return false;
82 }
83 
84 BitsRecTy *BitsRecTy::get(unsigned Sz) {
85   static std::vector<BitsRecTy*> Shared;
86   if (Sz >= Shared.size())
87     Shared.resize(Sz + 1);
88   BitsRecTy *&Ty = Shared[Sz];
89   if (!Ty)
90     Ty = new(Allocator) BitsRecTy(Sz);
91   return Ty;
92 }
93 
94 std::string BitsRecTy::getAsString() const {
95   return "bits<" + utostr(Size) + ">";
96 }
97 
98 bool BitsRecTy::typeIsConvertibleTo(const RecTy *RHS) const {
99   if (RecTy::typeIsConvertibleTo(RHS)) //argument and the sender are same type
100     return cast<BitsRecTy>(RHS)->Size == Size;
101   RecTyKind kind = RHS->getRecTyKind();
102   return (kind == BitRecTyKind && Size == 1) || (kind == IntRecTyKind);
103 }
104 
105 bool BitsRecTy::typeIsA(const RecTy *RHS) const {
106   if (const BitsRecTy *RHSb = dyn_cast<BitsRecTy>(RHS))
107     return RHSb->Size == Size;
108   return false;
109 }
110 
111 bool IntRecTy::typeIsConvertibleTo(const RecTy *RHS) const {
112   RecTyKind kind = RHS->getRecTyKind();
113   return kind==BitRecTyKind || kind==BitsRecTyKind || kind==IntRecTyKind;
114 }
115 
116 bool CodeRecTy::typeIsConvertibleTo(const RecTy *RHS) const {
117   RecTyKind Kind = RHS->getRecTyKind();
118   return Kind == CodeRecTyKind || Kind == StringRecTyKind;
119 }
120 
121 std::string StringRecTy::getAsString() const {
122   return "string";
123 }
124 
125 bool StringRecTy::typeIsConvertibleTo(const RecTy *RHS) const {
126   RecTyKind Kind = RHS->getRecTyKind();
127   return Kind == StringRecTyKind || Kind == CodeRecTyKind;
128 }
129 
130 std::string ListRecTy::getAsString() const {
131   return "list<" + ElementTy->getAsString() + ">";
132 }
133 
134 bool ListRecTy::typeIsConvertibleTo(const RecTy *RHS) const {
135   if (const auto *ListTy = dyn_cast<ListRecTy>(RHS))
136     return ElementTy->typeIsConvertibleTo(ListTy->getElementType());
137   return false;
138 }
139 
140 bool ListRecTy::typeIsA(const RecTy *RHS) const {
141   if (const ListRecTy *RHSl = dyn_cast<ListRecTy>(RHS))
142     return getElementType()->typeIsA(RHSl->getElementType());
143   return false;
144 }
145 
146 std::string DagRecTy::getAsString() const {
147   return "dag";
148 }
149 
150 static void ProfileRecordRecTy(FoldingSetNodeID &ID,
151                                ArrayRef<Record *> Classes) {
152   ID.AddInteger(Classes.size());
153   for (Record *R : Classes)
154     ID.AddPointer(R);
155 }
156 
157 RecordRecTy *RecordRecTy::get(ArrayRef<Record *> UnsortedClasses) {
158   if (UnsortedClasses.empty()) {
159     static RecordRecTy AnyRecord(0);
160     return &AnyRecord;
161   }
162 
163   FoldingSet<RecordRecTy> &ThePool =
164       UnsortedClasses[0]->getRecords().RecordTypePool;
165 
166   SmallVector<Record *, 4> Classes(UnsortedClasses.begin(),
167                                    UnsortedClasses.end());
168   llvm::sort(Classes, [](Record *LHS, Record *RHS) {
169     return LHS->getNameInitAsString() < RHS->getNameInitAsString();
170   });
171 
172   FoldingSetNodeID ID;
173   ProfileRecordRecTy(ID, Classes);
174 
175   void *IP = nullptr;
176   if (RecordRecTy *Ty = ThePool.FindNodeOrInsertPos(ID, IP))
177     return Ty;
178 
179 #ifndef NDEBUG
180   // Check for redundancy.
181   for (unsigned i = 0; i < Classes.size(); ++i) {
182     for (unsigned j = 0; j < Classes.size(); ++j) {
183       assert(i == j || !Classes[i]->isSubClassOf(Classes[j]));
184     }
185     assert(&Classes[0]->getRecords() == &Classes[i]->getRecords());
186   }
187 #endif
188 
189   void *Mem = Allocator.Allocate(totalSizeToAlloc<Record *>(Classes.size()),
190                                  alignof(RecordRecTy));
191   RecordRecTy *Ty = new(Mem) RecordRecTy(Classes.size());
192   std::uninitialized_copy(Classes.begin(), Classes.end(),
193                           Ty->getTrailingObjects<Record *>());
194   ThePool.InsertNode(Ty, IP);
195   return Ty;
196 }
197 
198 void RecordRecTy::Profile(FoldingSetNodeID &ID) const {
199   ProfileRecordRecTy(ID, getClasses());
200 }
201 
202 std::string RecordRecTy::getAsString() const {
203   if (NumClasses == 1)
204     return getClasses()[0]->getNameInitAsString();
205 
206   std::string Str = "{";
207   bool First = true;
208   for (Record *R : getClasses()) {
209     if (!First)
210       Str += ", ";
211     First = false;
212     Str += R->getNameInitAsString();
213   }
214   Str += "}";
215   return Str;
216 }
217 
218 bool RecordRecTy::isSubClassOf(Record *Class) const {
219   return llvm::any_of(getClasses(), [Class](Record *MySuperClass) {
220                                       return MySuperClass == Class ||
221                                              MySuperClass->isSubClassOf(Class);
222                                     });
223 }
224 
225 bool RecordRecTy::typeIsConvertibleTo(const RecTy *RHS) const {
226   if (this == RHS)
227     return true;
228 
229   const RecordRecTy *RTy = dyn_cast<RecordRecTy>(RHS);
230   if (!RTy)
231     return false;
232 
233   return llvm::all_of(RTy->getClasses(), [this](Record *TargetClass) {
234                                            return isSubClassOf(TargetClass);
235                                          });
236 }
237 
238 bool RecordRecTy::typeIsA(const RecTy *RHS) const {
239   return typeIsConvertibleTo(RHS);
240 }
241 
242 static RecordRecTy *resolveRecordTypes(RecordRecTy *T1, RecordRecTy *T2) {
243   SmallVector<Record *, 4> CommonSuperClasses;
244   SmallVector<Record *, 4> Stack;
245 
246   Stack.insert(Stack.end(), T1->classes_begin(), T1->classes_end());
247 
248   while (!Stack.empty()) {
249     Record *R = Stack.back();
250     Stack.pop_back();
251 
252     if (T2->isSubClassOf(R)) {
253       CommonSuperClasses.push_back(R);
254     } else {
255       R->getDirectSuperClasses(Stack);
256     }
257   }
258 
259   return RecordRecTy::get(CommonSuperClasses);
260 }
261 
262 RecTy *llvm::resolveTypes(RecTy *T1, RecTy *T2) {
263   if (T1 == T2)
264     return T1;
265 
266   if (RecordRecTy *RecTy1 = dyn_cast<RecordRecTy>(T1)) {
267     if (RecordRecTy *RecTy2 = dyn_cast<RecordRecTy>(T2))
268       return resolveRecordTypes(RecTy1, RecTy2);
269   }
270 
271   if (T1->typeIsConvertibleTo(T2))
272     return T2;
273   if (T2->typeIsConvertibleTo(T1))
274     return T1;
275 
276   if (ListRecTy *ListTy1 = dyn_cast<ListRecTy>(T1)) {
277     if (ListRecTy *ListTy2 = dyn_cast<ListRecTy>(T2)) {
278       RecTy* NewType = resolveTypes(ListTy1->getElementType(),
279                                     ListTy2->getElementType());
280       if (NewType)
281         return NewType->getListTy();
282     }
283   }
284 
285   return nullptr;
286 }
287 
288 //===----------------------------------------------------------------------===//
289 //    Initializer implementations
290 //===----------------------------------------------------------------------===//
291 
292 void Init::anchor() {}
293 
294 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
295 LLVM_DUMP_METHOD void Init::dump() const { return print(errs()); }
296 #endif
297 
298 UnsetInit *UnsetInit::get() {
299   static UnsetInit TheInit;
300   return &TheInit;
301 }
302 
303 Init *UnsetInit::getCastTo(RecTy *Ty) const {
304   return const_cast<UnsetInit *>(this);
305 }
306 
307 Init *UnsetInit::convertInitializerTo(RecTy *Ty) const {
308   return const_cast<UnsetInit *>(this);
309 }
310 
311 BitInit *BitInit::get(bool V) {
312   static BitInit True(true);
313   static BitInit False(false);
314 
315   return V ? &True : &False;
316 }
317 
318 Init *BitInit::convertInitializerTo(RecTy *Ty) const {
319   if (isa<BitRecTy>(Ty))
320     return const_cast<BitInit *>(this);
321 
322   if (isa<IntRecTy>(Ty))
323     return IntInit::get(getValue());
324 
325   if (auto *BRT = dyn_cast<BitsRecTy>(Ty)) {
326     // Can only convert single bit.
327     if (BRT->getNumBits() == 1)
328       return BitsInit::get(const_cast<BitInit *>(this));
329   }
330 
331   return nullptr;
332 }
333 
334 static void
335 ProfileBitsInit(FoldingSetNodeID &ID, ArrayRef<Init *> Range) {
336   ID.AddInteger(Range.size());
337 
338   for (Init *I : Range)
339     ID.AddPointer(I);
340 }
341 
342 BitsInit *BitsInit::get(ArrayRef<Init *> Range) {
343   static FoldingSet<BitsInit> ThePool;
344 
345   FoldingSetNodeID ID;
346   ProfileBitsInit(ID, Range);
347 
348   void *IP = nullptr;
349   if (BitsInit *I = ThePool.FindNodeOrInsertPos(ID, IP))
350     return I;
351 
352   void *Mem = Allocator.Allocate(totalSizeToAlloc<Init *>(Range.size()),
353                                  alignof(BitsInit));
354   BitsInit *I = new(Mem) BitsInit(Range.size());
355   std::uninitialized_copy(Range.begin(), Range.end(),
356                           I->getTrailingObjects<Init *>());
357   ThePool.InsertNode(I, IP);
358   return I;
359 }
360 
361 void BitsInit::Profile(FoldingSetNodeID &ID) const {
362   ProfileBitsInit(ID, makeArrayRef(getTrailingObjects<Init *>(), NumBits));
363 }
364 
365 Init *BitsInit::convertInitializerTo(RecTy *Ty) const {
366   if (isa<BitRecTy>(Ty)) {
367     if (getNumBits() != 1) return nullptr; // Only accept if just one bit!
368     return getBit(0);
369   }
370 
371   if (auto *BRT = dyn_cast<BitsRecTy>(Ty)) {
372     // If the number of bits is right, return it.  Otherwise we need to expand
373     // or truncate.
374     if (getNumBits() != BRT->getNumBits()) return nullptr;
375     return const_cast<BitsInit *>(this);
376   }
377 
378   if (isa<IntRecTy>(Ty)) {
379     int64_t Result = 0;
380     for (unsigned i = 0, e = getNumBits(); i != e; ++i)
381       if (auto *Bit = dyn_cast<BitInit>(getBit(i)))
382         Result |= static_cast<int64_t>(Bit->getValue()) << i;
383       else
384         return nullptr;
385     return IntInit::get(Result);
386   }
387 
388   return nullptr;
389 }
390 
391 Init *
392 BitsInit::convertInitializerBitRange(ArrayRef<unsigned> Bits) const {
393   SmallVector<Init *, 16> NewBits(Bits.size());
394 
395   for (unsigned i = 0, e = Bits.size(); i != e; ++i) {
396     if (Bits[i] >= getNumBits())
397       return nullptr;
398     NewBits[i] = getBit(Bits[i]);
399   }
400   return BitsInit::get(NewBits);
401 }
402 
403 bool BitsInit::isConcrete() const {
404   for (unsigned i = 0, e = getNumBits(); i != e; ++i) {
405     if (!getBit(i)->isConcrete())
406       return false;
407   }
408   return true;
409 }
410 
411 std::string BitsInit::getAsString() const {
412   std::string Result = "{ ";
413   for (unsigned i = 0, e = getNumBits(); i != e; ++i) {
414     if (i) Result += ", ";
415     if (Init *Bit = getBit(e-i-1))
416       Result += Bit->getAsString();
417     else
418       Result += "*";
419   }
420   return Result + " }";
421 }
422 
423 // resolveReferences - If there are any field references that refer to fields
424 // that have been filled in, we can propagate the values now.
425 Init *BitsInit::resolveReferences(Resolver &R) const {
426   bool Changed = false;
427   SmallVector<Init *, 16> NewBits(getNumBits());
428 
429   Init *CachedBitVarRef = nullptr;
430   Init *CachedBitVarResolved = nullptr;
431 
432   for (unsigned i = 0, e = getNumBits(); i != e; ++i) {
433     Init *CurBit = getBit(i);
434     Init *NewBit = CurBit;
435 
436     if (VarBitInit *CurBitVar = dyn_cast<VarBitInit>(CurBit)) {
437       if (CurBitVar->getBitVar() != CachedBitVarRef) {
438         CachedBitVarRef = CurBitVar->getBitVar();
439         CachedBitVarResolved = CachedBitVarRef->resolveReferences(R);
440       }
441       assert(CachedBitVarResolved && "Unresolved bitvar reference");
442       NewBit = CachedBitVarResolved->getBit(CurBitVar->getBitNum());
443     } else {
444       // getBit(0) implicitly converts int and bits<1> values to bit.
445       NewBit = CurBit->resolveReferences(R)->getBit(0);
446     }
447 
448     if (isa<UnsetInit>(NewBit) && R.keepUnsetBits())
449       NewBit = CurBit;
450     NewBits[i] = NewBit;
451     Changed |= CurBit != NewBit;
452   }
453 
454   if (Changed)
455     return BitsInit::get(NewBits);
456 
457   return const_cast<BitsInit *>(this);
458 }
459 
460 IntInit *IntInit::get(int64_t V) {
461   static std::map<int64_t, IntInit*> ThePool;
462 
463   IntInit *&I = ThePool[V];
464   if (!I) I = new(Allocator) IntInit(V);
465   return I;
466 }
467 
468 std::string IntInit::getAsString() const {
469   return itostr(Value);
470 }
471 
472 static bool canFitInBitfield(int64_t Value, unsigned NumBits) {
473   // For example, with NumBits == 4, we permit Values from [-7 .. 15].
474   return (NumBits >= sizeof(Value) * 8) ||
475          (Value >> NumBits == 0) || (Value >> (NumBits-1) == -1);
476 }
477 
478 Init *IntInit::convertInitializerTo(RecTy *Ty) const {
479   if (isa<IntRecTy>(Ty))
480     return const_cast<IntInit *>(this);
481 
482   if (isa<BitRecTy>(Ty)) {
483     int64_t Val = getValue();
484     if (Val != 0 && Val != 1) return nullptr;  // Only accept 0 or 1 for a bit!
485     return BitInit::get(Val != 0);
486   }
487 
488   if (auto *BRT = dyn_cast<BitsRecTy>(Ty)) {
489     int64_t Value = getValue();
490     // Make sure this bitfield is large enough to hold the integer value.
491     if (!canFitInBitfield(Value, BRT->getNumBits()))
492       return nullptr;
493 
494     SmallVector<Init *, 16> NewBits(BRT->getNumBits());
495     for (unsigned i = 0; i != BRT->getNumBits(); ++i)
496       NewBits[i] = BitInit::get(Value & ((i < 64) ? (1LL << i) : 0));
497 
498     return BitsInit::get(NewBits);
499   }
500 
501   return nullptr;
502 }
503 
504 Init *
505 IntInit::convertInitializerBitRange(ArrayRef<unsigned> Bits) const {
506   SmallVector<Init *, 16> NewBits(Bits.size());
507 
508   for (unsigned i = 0, e = Bits.size(); i != e; ++i) {
509     if (Bits[i] >= 64)
510       return nullptr;
511 
512     NewBits[i] = BitInit::get(Value & (INT64_C(1) << Bits[i]));
513   }
514   return BitsInit::get(NewBits);
515 }
516 
517 CodeInit *CodeInit::get(StringRef V, const SMLoc &Loc) {
518   static StringSet<BumpPtrAllocator &> ThePool(Allocator);
519 
520   CodeInitsConstructed++;
521 
522   // Unlike StringMap, StringSet doesn't accept empty keys.
523   if (V.empty())
524     return new (Allocator) CodeInit("", Loc);
525 
526   // Location tracking prevents us from de-duping CodeInits as we're never
527   // called with the same string and same location twice. However, we can at
528   // least de-dupe the strings for a modest saving.
529   auto &Entry = *ThePool.insert(V).first;
530   return new(Allocator) CodeInit(Entry.getKey(), Loc);
531 }
532 
533 StringInit *StringInit::get(StringRef V) {
534   static StringMap<StringInit*, BumpPtrAllocator &> ThePool(Allocator);
535 
536   auto &Entry = *ThePool.insert(std::make_pair(V, nullptr)).first;
537   if (!Entry.second)
538     Entry.second = new(Allocator) StringInit(Entry.getKey());
539   return Entry.second;
540 }
541 
542 Init *StringInit::convertInitializerTo(RecTy *Ty) const {
543   if (isa<StringRecTy>(Ty))
544     return const_cast<StringInit *>(this);
545   if (isa<CodeRecTy>(Ty))
546     return CodeInit::get(getValue(), SMLoc());
547 
548   return nullptr;
549 }
550 
551 Init *CodeInit::convertInitializerTo(RecTy *Ty) const {
552   if (isa<CodeRecTy>(Ty))
553     return const_cast<CodeInit *>(this);
554   if (isa<StringRecTy>(Ty))
555     return StringInit::get(getValue());
556 
557   return nullptr;
558 }
559 
560 static void ProfileListInit(FoldingSetNodeID &ID,
561                             ArrayRef<Init *> Range,
562                             RecTy *EltTy) {
563   ID.AddInteger(Range.size());
564   ID.AddPointer(EltTy);
565 
566   for (Init *I : Range)
567     ID.AddPointer(I);
568 }
569 
570 ListInit *ListInit::get(ArrayRef<Init *> Range, RecTy *EltTy) {
571   static FoldingSet<ListInit> ThePool;
572 
573   FoldingSetNodeID ID;
574   ProfileListInit(ID, Range, EltTy);
575 
576   void *IP = nullptr;
577   if (ListInit *I = ThePool.FindNodeOrInsertPos(ID, IP))
578     return I;
579 
580   assert(Range.empty() || !isa<TypedInit>(Range[0]) ||
581          cast<TypedInit>(Range[0])->getType()->typeIsConvertibleTo(EltTy));
582 
583   void *Mem = Allocator.Allocate(totalSizeToAlloc<Init *>(Range.size()),
584                                  alignof(ListInit));
585   ListInit *I = new(Mem) ListInit(Range.size(), EltTy);
586   std::uninitialized_copy(Range.begin(), Range.end(),
587                           I->getTrailingObjects<Init *>());
588   ThePool.InsertNode(I, IP);
589   return I;
590 }
591 
592 void ListInit::Profile(FoldingSetNodeID &ID) const {
593   RecTy *EltTy = cast<ListRecTy>(getType())->getElementType();
594 
595   ProfileListInit(ID, getValues(), EltTy);
596 }
597 
598 Init *ListInit::convertInitializerTo(RecTy *Ty) const {
599   if (getType() == Ty)
600     return const_cast<ListInit*>(this);
601 
602   if (auto *LRT = dyn_cast<ListRecTy>(Ty)) {
603     SmallVector<Init*, 8> Elements;
604     Elements.reserve(getValues().size());
605 
606     // Verify that all of the elements of the list are subclasses of the
607     // appropriate class!
608     bool Changed = false;
609     RecTy *ElementType = LRT->getElementType();
610     for (Init *I : getValues())
611       if (Init *CI = I->convertInitializerTo(ElementType)) {
612         Elements.push_back(CI);
613         if (CI != I)
614           Changed = true;
615       } else
616         return nullptr;
617 
618     if (!Changed)
619       return const_cast<ListInit*>(this);
620     return ListInit::get(Elements, ElementType);
621   }
622 
623   return nullptr;
624 }
625 
626 Init *ListInit::convertInitListSlice(ArrayRef<unsigned> Elements) const {
627   SmallVector<Init*, 8> Vals;
628   Vals.reserve(Elements.size());
629   for (unsigned Element : Elements) {
630     if (Element >= size())
631       return nullptr;
632     Vals.push_back(getElement(Element));
633   }
634   return ListInit::get(Vals, getElementType());
635 }
636 
637 Record *ListInit::getElementAsRecord(unsigned i) const {
638   assert(i < NumValues && "List element index out of range!");
639   DefInit *DI = dyn_cast<DefInit>(getElement(i));
640   if (!DI)
641     PrintFatalError("Expected record in list!");
642   return DI->getDef();
643 }
644 
645 Init *ListInit::resolveReferences(Resolver &R) const {
646   SmallVector<Init*, 8> Resolved;
647   Resolved.reserve(size());
648   bool Changed = false;
649 
650   for (Init *CurElt : getValues()) {
651     Init *E = CurElt->resolveReferences(R);
652     Changed |= E != CurElt;
653     Resolved.push_back(E);
654   }
655 
656   if (Changed)
657     return ListInit::get(Resolved, getElementType());
658   return const_cast<ListInit *>(this);
659 }
660 
661 bool ListInit::isConcrete() const {
662   for (Init *Element : *this) {
663     if (!Element->isConcrete())
664       return false;
665   }
666   return true;
667 }
668 
669 std::string ListInit::getAsString() const {
670   std::string Result = "[";
671   const char *sep = "";
672   for (Init *Element : *this) {
673     Result += sep;
674     sep = ", ";
675     Result += Element->getAsString();
676   }
677   return Result + "]";
678 }
679 
680 Init *OpInit::getBit(unsigned Bit) const {
681   if (getType() == BitRecTy::get())
682     return const_cast<OpInit*>(this);
683   return VarBitInit::get(const_cast<OpInit*>(this), Bit);
684 }
685 
686 static void
687 ProfileUnOpInit(FoldingSetNodeID &ID, unsigned Opcode, Init *Op, RecTy *Type) {
688   ID.AddInteger(Opcode);
689   ID.AddPointer(Op);
690   ID.AddPointer(Type);
691 }
692 
693 UnOpInit *UnOpInit::get(UnaryOp Opc, Init *LHS, RecTy *Type) {
694   static FoldingSet<UnOpInit> ThePool;
695 
696   FoldingSetNodeID ID;
697   ProfileUnOpInit(ID, Opc, LHS, Type);
698 
699   void *IP = nullptr;
700   if (UnOpInit *I = ThePool.FindNodeOrInsertPos(ID, IP))
701     return I;
702 
703   UnOpInit *I = new(Allocator) UnOpInit(Opc, LHS, Type);
704   ThePool.InsertNode(I, IP);
705   return I;
706 }
707 
708 void UnOpInit::Profile(FoldingSetNodeID &ID) const {
709   ProfileUnOpInit(ID, getOpcode(), getOperand(), getType());
710 }
711 
712 Init *UnOpInit::Fold(Record *CurRec, bool IsFinal) const {
713   switch (getOpcode()) {
714   case CAST:
715     if (isa<StringRecTy>(getType())) {
716       if (StringInit *LHSs = dyn_cast<StringInit>(LHS))
717         return LHSs;
718 
719       if (DefInit *LHSd = dyn_cast<DefInit>(LHS))
720         return StringInit::get(LHSd->getAsString());
721 
722       if (IntInit *LHSi = dyn_cast<IntInit>(LHS))
723         return StringInit::get(LHSi->getAsString());
724     } else if (isa<RecordRecTy>(getType())) {
725       if (StringInit *Name = dyn_cast<StringInit>(LHS)) {
726         if (!CurRec && !IsFinal)
727           break;
728         assert(CurRec && "NULL pointer");
729         Record *D;
730 
731         // Self-references are allowed, but their resolution is delayed until
732         // the final resolve to ensure that we get the correct type for them.
733         if (Name == CurRec->getNameInit()) {
734           if (!IsFinal)
735             break;
736           D = CurRec;
737         } else {
738           D = CurRec->getRecords().getDef(Name->getValue());
739           if (!D) {
740             if (IsFinal)
741               PrintFatalError(CurRec->getLoc(),
742                               Twine("Undefined reference to record: '") +
743                               Name->getValue() + "'\n");
744             break;
745           }
746         }
747 
748         DefInit *DI = DefInit::get(D);
749         if (!DI->getType()->typeIsA(getType())) {
750           PrintFatalError(CurRec->getLoc(),
751                           Twine("Expected type '") +
752                           getType()->getAsString() + "', got '" +
753                           DI->getType()->getAsString() + "' in: " +
754                           getAsString() + "\n");
755         }
756         return DI;
757       }
758     }
759 
760     if (Init *NewInit = LHS->convertInitializerTo(getType()))
761       return NewInit;
762     break;
763 
764   case NOT:
765     if (IntInit *LHSi =
766             dyn_cast_or_null<IntInit>(LHS->convertInitializerTo(IntRecTy::get())))
767       return IntInit::get(LHSi->getValue() ? 0 : 1);
768     break;
769 
770   case HEAD:
771     if (ListInit *LHSl = dyn_cast<ListInit>(LHS)) {
772       assert(!LHSl->empty() && "Empty list in head");
773       return LHSl->getElement(0);
774     }
775     break;
776 
777   case TAIL:
778     if (ListInit *LHSl = dyn_cast<ListInit>(LHS)) {
779       assert(!LHSl->empty() && "Empty list in tail");
780       // Note the +1.  We can't just pass the result of getValues()
781       // directly.
782       return ListInit::get(LHSl->getValues().slice(1), LHSl->getElementType());
783     }
784     break;
785 
786   case SIZE:
787     if (ListInit *LHSl = dyn_cast<ListInit>(LHS))
788       return IntInit::get(LHSl->size());
789     if (DagInit *LHSd = dyn_cast<DagInit>(LHS))
790       return IntInit::get(LHSd->arg_size());
791     if (StringInit *LHSs = dyn_cast<StringInit>(LHS))
792       return IntInit::get(LHSs->getValue().size());
793     break;
794 
795   case EMPTY:
796     if (ListInit *LHSl = dyn_cast<ListInit>(LHS))
797       return IntInit::get(LHSl->empty());
798     if (DagInit *LHSd = dyn_cast<DagInit>(LHS))
799       return IntInit::get(LHSd->arg_empty());
800     if (StringInit *LHSs = dyn_cast<StringInit>(LHS))
801       return IntInit::get(LHSs->getValue().empty());
802     break;
803 
804   case GETDAGOP:
805     if (DagInit *Dag = dyn_cast<DagInit>(LHS)) {
806       DefInit *DI = DefInit::get(Dag->getOperatorAsDef({}));
807       if (!DI->getType()->typeIsA(getType())) {
808         PrintFatalError(CurRec->getLoc(),
809                         Twine("Expected type '") +
810                         getType()->getAsString() + "', got '" +
811                         DI->getType()->getAsString() + "' in: " +
812                         getAsString() + "\n");
813       } else {
814         return DI;
815       }
816     }
817     break;
818   }
819   return const_cast<UnOpInit *>(this);
820 }
821 
822 Init *UnOpInit::resolveReferences(Resolver &R) const {
823   Init *lhs = LHS->resolveReferences(R);
824 
825   if (LHS != lhs || (R.isFinal() && getOpcode() == CAST))
826     return (UnOpInit::get(getOpcode(), lhs, getType()))
827         ->Fold(R.getCurrentRecord(), R.isFinal());
828   return const_cast<UnOpInit *>(this);
829 }
830 
831 std::string UnOpInit::getAsString() const {
832   std::string Result;
833   switch (getOpcode()) {
834   case CAST: Result = "!cast<" + getType()->getAsString() + ">"; break;
835   case NOT: Result = "!not"; break;
836   case HEAD: Result = "!head"; break;
837   case TAIL: Result = "!tail"; break;
838   case SIZE: Result = "!size"; break;
839   case EMPTY: Result = "!empty"; break;
840   case GETDAGOP: Result = "!getdagop"; break;
841   }
842   return Result + "(" + LHS->getAsString() + ")";
843 }
844 
845 static void
846 ProfileBinOpInit(FoldingSetNodeID &ID, unsigned Opcode, Init *LHS, Init *RHS,
847                  RecTy *Type) {
848   ID.AddInteger(Opcode);
849   ID.AddPointer(LHS);
850   ID.AddPointer(RHS);
851   ID.AddPointer(Type);
852 }
853 
854 BinOpInit *BinOpInit::get(BinaryOp Opc, Init *LHS,
855                           Init *RHS, RecTy *Type) {
856   static FoldingSet<BinOpInit> ThePool;
857 
858   FoldingSetNodeID ID;
859   ProfileBinOpInit(ID, Opc, LHS, RHS, Type);
860 
861   void *IP = nullptr;
862   if (BinOpInit *I = ThePool.FindNodeOrInsertPos(ID, IP))
863     return I;
864 
865   BinOpInit *I = new(Allocator) BinOpInit(Opc, LHS, RHS, Type);
866   ThePool.InsertNode(I, IP);
867   return I;
868 }
869 
870 void BinOpInit::Profile(FoldingSetNodeID &ID) const {
871   ProfileBinOpInit(ID, getOpcode(), getLHS(), getRHS(), getType());
872 }
873 
874 static StringInit *ConcatStringInits(const StringInit *I0,
875                                      const StringInit *I1) {
876   SmallString<80> Concat(I0->getValue());
877   Concat.append(I1->getValue());
878   return StringInit::get(Concat);
879 }
880 
881 static StringInit *interleaveStringList(const ListInit *List,
882                                         const StringInit *Delim) {
883   if (List->size() == 0)
884     return StringInit::get("");
885   SmallString<80> Result(dyn_cast<StringInit>(List->getElement(0))->getValue());
886 
887   for (unsigned I = 1, E = List->size(); I < E; ++I) {
888     Result.append(Delim->getValue());
889     Result.append(dyn_cast<StringInit>(List->getElement(I))->getValue());
890   }
891   return StringInit::get(Result);
892 }
893 
894 static StringInit *interleaveIntList(const ListInit *List,
895                                      const StringInit *Delim) {
896   if (List->size() == 0)
897     return StringInit::get("");
898   SmallString<80> Result(dyn_cast<IntInit>(List->getElement(0)->
899                              getCastTo(IntRecTy::get()))->getAsString());
900 
901   for (unsigned I = 1, E = List->size(); I < E; ++I) {
902     Result.append(Delim->getValue());
903     Result.append(dyn_cast<IntInit>(List->getElement(I)->
904                       getCastTo(IntRecTy::get()))->getAsString());
905   }
906   return StringInit::get(Result);
907 }
908 
909 Init *BinOpInit::getStrConcat(Init *I0, Init *I1) {
910   // Shortcut for the common case of concatenating two strings.
911   if (const StringInit *I0s = dyn_cast<StringInit>(I0))
912     if (const StringInit *I1s = dyn_cast<StringInit>(I1))
913       return ConcatStringInits(I0s, I1s);
914   return BinOpInit::get(BinOpInit::STRCONCAT, I0, I1, StringRecTy::get());
915 }
916 
917 static ListInit *ConcatListInits(const ListInit *LHS,
918                                  const ListInit *RHS) {
919   SmallVector<Init *, 8> Args;
920   Args.insert(Args.end(), LHS->begin(), LHS->end());
921   Args.insert(Args.end(), RHS->begin(), RHS->end());
922   return ListInit::get(Args, LHS->getElementType());
923 }
924 
925 Init *BinOpInit::getListConcat(TypedInit *LHS, Init *RHS) {
926   assert(isa<ListRecTy>(LHS->getType()) && "First arg must be a list");
927 
928   // Shortcut for the common case of concatenating two lists.
929    if (const ListInit *LHSList = dyn_cast<ListInit>(LHS))
930      if (const ListInit *RHSList = dyn_cast<ListInit>(RHS))
931        return ConcatListInits(LHSList, RHSList);
932    return BinOpInit::get(BinOpInit::LISTCONCAT, LHS, RHS, LHS->getType());
933 }
934 
935 Init *BinOpInit::Fold(Record *CurRec) const {
936   switch (getOpcode()) {
937   case CONCAT: {
938     DagInit *LHSs = dyn_cast<DagInit>(LHS);
939     DagInit *RHSs = dyn_cast<DagInit>(RHS);
940     if (LHSs && RHSs) {
941       DefInit *LOp = dyn_cast<DefInit>(LHSs->getOperator());
942       DefInit *ROp = dyn_cast<DefInit>(RHSs->getOperator());
943       if ((!LOp && !isa<UnsetInit>(LHSs->getOperator())) ||
944           (!ROp && !isa<UnsetInit>(RHSs->getOperator())))
945         break;
946       if (LOp && ROp && LOp->getDef() != ROp->getDef()) {
947         PrintFatalError(Twine("Concatenated Dag operators do not match: '") +
948                         LHSs->getAsString() + "' vs. '" + RHSs->getAsString() +
949                         "'");
950       }
951       Init *Op = LOp ? LOp : ROp;
952       if (!Op)
953         Op = UnsetInit::get();
954 
955       SmallVector<Init*, 8> Args;
956       SmallVector<StringInit*, 8> ArgNames;
957       for (unsigned i = 0, e = LHSs->getNumArgs(); i != e; ++i) {
958         Args.push_back(LHSs->getArg(i));
959         ArgNames.push_back(LHSs->getArgName(i));
960       }
961       for (unsigned i = 0, e = RHSs->getNumArgs(); i != e; ++i) {
962         Args.push_back(RHSs->getArg(i));
963         ArgNames.push_back(RHSs->getArgName(i));
964       }
965       return DagInit::get(Op, nullptr, Args, ArgNames);
966     }
967     break;
968   }
969   case LISTCONCAT: {
970     ListInit *LHSs = dyn_cast<ListInit>(LHS);
971     ListInit *RHSs = dyn_cast<ListInit>(RHS);
972     if (LHSs && RHSs) {
973       SmallVector<Init *, 8> Args;
974       Args.insert(Args.end(), LHSs->begin(), LHSs->end());
975       Args.insert(Args.end(), RHSs->begin(), RHSs->end());
976       return ListInit::get(Args, LHSs->getElementType());
977     }
978     break;
979   }
980   case LISTSPLAT: {
981     TypedInit *Value = dyn_cast<TypedInit>(LHS);
982     IntInit *Size = dyn_cast<IntInit>(RHS);
983     if (Value && Size) {
984       SmallVector<Init *, 8> Args(Size->getValue(), Value);
985       return ListInit::get(Args, Value->getType());
986     }
987     break;
988   }
989   case STRCONCAT: {
990     StringInit *LHSs = dyn_cast<StringInit>(LHS);
991     StringInit *RHSs = dyn_cast<StringInit>(RHS);
992     if (LHSs && RHSs)
993       return ConcatStringInits(LHSs, RHSs);
994     break;
995   }
996   case INTERLEAVE: {
997     ListInit *List = dyn_cast<ListInit>(LHS);
998     StringInit *Delim = dyn_cast<StringInit>(RHS);
999     if (List && Delim) {
1000       if (isa<StringRecTy>(List->getElementType()))
1001         return interleaveStringList(List, Delim);
1002       else
1003         return interleaveIntList(List, Delim);
1004     }
1005     break;
1006   }
1007   case EQ:
1008   case NE:
1009   case LE:
1010   case LT:
1011   case GE:
1012   case GT: {
1013     // try to fold eq comparison for 'bit' and 'int', otherwise fallback
1014     // to string objects.
1015     IntInit *L =
1016         dyn_cast_or_null<IntInit>(LHS->convertInitializerTo(IntRecTy::get()));
1017     IntInit *R =
1018         dyn_cast_or_null<IntInit>(RHS->convertInitializerTo(IntRecTy::get()));
1019 
1020     if (L && R) {
1021       bool Result;
1022       switch (getOpcode()) {
1023       case EQ: Result = L->getValue() == R->getValue(); break;
1024       case NE: Result = L->getValue() != R->getValue(); break;
1025       case LE: Result = L->getValue() <= R->getValue(); break;
1026       case LT: Result = L->getValue() < R->getValue(); break;
1027       case GE: Result = L->getValue() >= R->getValue(); break;
1028       case GT: Result = L->getValue() > R->getValue(); break;
1029       default: llvm_unreachable("unhandled comparison");
1030       }
1031       return BitInit::get(Result);
1032     }
1033 
1034     if (getOpcode() == EQ || getOpcode() == NE) {
1035       StringInit *LHSs = dyn_cast<StringInit>(LHS);
1036       StringInit *RHSs = dyn_cast<StringInit>(RHS);
1037 
1038       // Make sure we've resolved
1039       if (LHSs && RHSs) {
1040         bool Equal = LHSs->getValue() == RHSs->getValue();
1041         return BitInit::get(getOpcode() == EQ ? Equal : !Equal);
1042       }
1043     }
1044 
1045     break;
1046   }
1047   case SETDAGOP: {
1048     DagInit *Dag = dyn_cast<DagInit>(LHS);
1049     DefInit *Op = dyn_cast<DefInit>(RHS);
1050     if (Dag && Op) {
1051       SmallVector<Init*, 8> Args;
1052       SmallVector<StringInit*, 8> ArgNames;
1053       for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i) {
1054         Args.push_back(Dag->getArg(i));
1055         ArgNames.push_back(Dag->getArgName(i));
1056       }
1057       return DagInit::get(Op, nullptr, Args, ArgNames);
1058     }
1059     break;
1060   }
1061   case ADD:
1062   case SUB:
1063   case MUL:
1064   case AND:
1065   case OR:
1066   case XOR:
1067   case SHL:
1068   case SRA:
1069   case SRL: {
1070     IntInit *LHSi =
1071       dyn_cast_or_null<IntInit>(LHS->convertInitializerTo(IntRecTy::get()));
1072     IntInit *RHSi =
1073       dyn_cast_or_null<IntInit>(RHS->convertInitializerTo(IntRecTy::get()));
1074     if (LHSi && RHSi) {
1075       int64_t LHSv = LHSi->getValue(), RHSv = RHSi->getValue();
1076       int64_t Result;
1077       switch (getOpcode()) {
1078       default: llvm_unreachable("Bad opcode!");
1079       case ADD: Result = LHSv + RHSv; break;
1080       case SUB: Result = LHSv - RHSv; break;
1081       case MUL: Result = LHSv * RHSv; break;
1082       case AND: Result = LHSv & RHSv; break;
1083       case OR:  Result = LHSv | RHSv; break;
1084       case XOR: Result = LHSv ^ RHSv; break;
1085       case SHL: Result = (uint64_t)LHSv << (uint64_t)RHSv; break;
1086       case SRA: Result = LHSv >> RHSv; break;
1087       case SRL: Result = (uint64_t)LHSv >> (uint64_t)RHSv; break;
1088       }
1089       return IntInit::get(Result);
1090     }
1091     break;
1092   }
1093   }
1094   return const_cast<BinOpInit *>(this);
1095 }
1096 
1097 Init *BinOpInit::resolveReferences(Resolver &R) const {
1098   Init *lhs = LHS->resolveReferences(R);
1099   Init *rhs = RHS->resolveReferences(R);
1100 
1101   if (LHS != lhs || RHS != rhs)
1102     return (BinOpInit::get(getOpcode(), lhs, rhs, getType()))
1103         ->Fold(R.getCurrentRecord());
1104   return const_cast<BinOpInit *>(this);
1105 }
1106 
1107 std::string BinOpInit::getAsString() const {
1108   std::string Result;
1109   switch (getOpcode()) {
1110   case CONCAT: Result = "!con"; break;
1111   case ADD: Result = "!add"; break;
1112   case SUB: Result = "!sub"; break;
1113   case MUL: Result = "!mul"; break;
1114   case AND: Result = "!and"; break;
1115   case OR: Result = "!or"; break;
1116   case XOR: Result = "!xor"; break;
1117   case SHL: Result = "!shl"; break;
1118   case SRA: Result = "!sra"; break;
1119   case SRL: Result = "!srl"; break;
1120   case EQ: Result = "!eq"; break;
1121   case NE: Result = "!ne"; break;
1122   case LE: Result = "!le"; break;
1123   case LT: Result = "!lt"; break;
1124   case GE: Result = "!ge"; break;
1125   case GT: Result = "!gt"; break;
1126   case LISTCONCAT: Result = "!listconcat"; break;
1127   case LISTSPLAT: Result = "!listsplat"; break;
1128   case STRCONCAT: Result = "!strconcat"; break;
1129   case INTERLEAVE: Result = "!interleave"; break;
1130   case SETDAGOP: Result = "!setdagop"; break;
1131   }
1132   return Result + "(" + LHS->getAsString() + ", " + RHS->getAsString() + ")";
1133 }
1134 
1135 static void
1136 ProfileTernOpInit(FoldingSetNodeID &ID, unsigned Opcode, Init *LHS, Init *MHS,
1137                   Init *RHS, RecTy *Type) {
1138   ID.AddInteger(Opcode);
1139   ID.AddPointer(LHS);
1140   ID.AddPointer(MHS);
1141   ID.AddPointer(RHS);
1142   ID.AddPointer(Type);
1143 }
1144 
1145 TernOpInit *TernOpInit::get(TernaryOp Opc, Init *LHS, Init *MHS, Init *RHS,
1146                             RecTy *Type) {
1147   static FoldingSet<TernOpInit> ThePool;
1148 
1149   FoldingSetNodeID ID;
1150   ProfileTernOpInit(ID, Opc, LHS, MHS, RHS, Type);
1151 
1152   void *IP = nullptr;
1153   if (TernOpInit *I = ThePool.FindNodeOrInsertPos(ID, IP))
1154     return I;
1155 
1156   TernOpInit *I = new(Allocator) TernOpInit(Opc, LHS, MHS, RHS, Type);
1157   ThePool.InsertNode(I, IP);
1158   return I;
1159 }
1160 
1161 void TernOpInit::Profile(FoldingSetNodeID &ID) const {
1162   ProfileTernOpInit(ID, getOpcode(), getLHS(), getMHS(), getRHS(), getType());
1163 }
1164 
1165 static Init *ItemApply(Init *LHS, Init *MHSe, Init *RHS, Record *CurRec) {
1166   MapResolver R(CurRec);
1167   R.set(LHS, MHSe);
1168   return RHS->resolveReferences(R);
1169 }
1170 
1171 static Init *ForeachDagApply(Init *LHS, DagInit *MHSd, Init *RHS,
1172                              Record *CurRec) {
1173   bool Change = false;
1174   Init *Val = ItemApply(LHS, MHSd->getOperator(), RHS, CurRec);
1175   if (Val != MHSd->getOperator())
1176     Change = true;
1177 
1178   SmallVector<std::pair<Init *, StringInit *>, 8> NewArgs;
1179   for (unsigned int i = 0; i < MHSd->getNumArgs(); ++i) {
1180     Init *Arg = MHSd->getArg(i);
1181     Init *NewArg;
1182     StringInit *ArgName = MHSd->getArgName(i);
1183 
1184     if (DagInit *Argd = dyn_cast<DagInit>(Arg))
1185       NewArg = ForeachDagApply(LHS, Argd, RHS, CurRec);
1186     else
1187       NewArg = ItemApply(LHS, Arg, RHS, CurRec);
1188 
1189     NewArgs.push_back(std::make_pair(NewArg, ArgName));
1190     if (Arg != NewArg)
1191       Change = true;
1192   }
1193 
1194   if (Change)
1195     return DagInit::get(Val, nullptr, NewArgs);
1196   return MHSd;
1197 }
1198 
1199 // Applies RHS to all elements of MHS, using LHS as a temp variable.
1200 static Init *ForeachHelper(Init *LHS, Init *MHS, Init *RHS, RecTy *Type,
1201                            Record *CurRec) {
1202   if (DagInit *MHSd = dyn_cast<DagInit>(MHS))
1203     return ForeachDagApply(LHS, MHSd, RHS, CurRec);
1204 
1205   if (ListInit *MHSl = dyn_cast<ListInit>(MHS)) {
1206     SmallVector<Init *, 8> NewList(MHSl->begin(), MHSl->end());
1207 
1208     for (Init *&Item : NewList) {
1209       Init *NewItem = ItemApply(LHS, Item, RHS, CurRec);
1210       if (NewItem != Item)
1211         Item = NewItem;
1212     }
1213     return ListInit::get(NewList, cast<ListRecTy>(Type)->getElementType());
1214   }
1215 
1216   return nullptr;
1217 }
1218 
1219 // Evaluates RHS for all elements of MHS, using LHS as a temp variable.
1220 // Creates a new list with the elements that evaluated to true.
1221 static Init *FilterHelper(Init *LHS, Init *MHS, Init *RHS, RecTy *Type,
1222                           Record *CurRec) {
1223   if (ListInit *MHSl = dyn_cast<ListInit>(MHS)) {
1224     SmallVector<Init *, 8> NewList;
1225 
1226     for (Init *Item : MHSl->getValues()) {
1227       Init *Include = ItemApply(LHS, Item, RHS, CurRec);
1228       if (!Include)
1229         return nullptr;
1230       if (IntInit *IncludeInt = dyn_cast_or_null<IntInit>(
1231                                     Include->convertInitializerTo(IntRecTy::get()))) {
1232         if (IncludeInt->getValue())
1233           NewList.push_back(Item);
1234       } else {
1235         return nullptr;
1236       }
1237     }
1238     return ListInit::get(NewList, cast<ListRecTy>(Type)->getElementType());
1239   }
1240 
1241   return nullptr;
1242 }
1243 
1244 Init *TernOpInit::Fold(Record *CurRec) const {
1245   switch (getOpcode()) {
1246   case SUBST: {
1247     DefInit *LHSd = dyn_cast<DefInit>(LHS);
1248     VarInit *LHSv = dyn_cast<VarInit>(LHS);
1249     StringInit *LHSs = dyn_cast<StringInit>(LHS);
1250 
1251     DefInit *MHSd = dyn_cast<DefInit>(MHS);
1252     VarInit *MHSv = dyn_cast<VarInit>(MHS);
1253     StringInit *MHSs = dyn_cast<StringInit>(MHS);
1254 
1255     DefInit *RHSd = dyn_cast<DefInit>(RHS);
1256     VarInit *RHSv = dyn_cast<VarInit>(RHS);
1257     StringInit *RHSs = dyn_cast<StringInit>(RHS);
1258 
1259     if (LHSd && MHSd && RHSd) {
1260       Record *Val = RHSd->getDef();
1261       if (LHSd->getAsString() == RHSd->getAsString())
1262         Val = MHSd->getDef();
1263       return DefInit::get(Val);
1264     }
1265     if (LHSv && MHSv && RHSv) {
1266       std::string Val = std::string(RHSv->getName());
1267       if (LHSv->getAsString() == RHSv->getAsString())
1268         Val = std::string(MHSv->getName());
1269       return VarInit::get(Val, getType());
1270     }
1271     if (LHSs && MHSs && RHSs) {
1272       std::string Val = std::string(RHSs->getValue());
1273 
1274       std::string::size_type found;
1275       std::string::size_type idx = 0;
1276       while (true) {
1277         found = Val.find(std::string(LHSs->getValue()), idx);
1278         if (found == std::string::npos)
1279           break;
1280         Val.replace(found, LHSs->getValue().size(),
1281                     std::string(MHSs->getValue()));
1282         idx = found + MHSs->getValue().size();
1283       }
1284 
1285       return StringInit::get(Val);
1286     }
1287     break;
1288   }
1289 
1290   case FOREACH: {
1291     if (Init *Result = ForeachHelper(LHS, MHS, RHS, getType(), CurRec))
1292       return Result;
1293     break;
1294   }
1295 
1296   case FILTER: {
1297     if (Init *Result = FilterHelper(LHS, MHS, RHS, getType(), CurRec))
1298       return Result;
1299     break;
1300   }
1301 
1302   case IF: {
1303     if (IntInit *LHSi = dyn_cast_or_null<IntInit>(
1304                             LHS->convertInitializerTo(IntRecTy::get()))) {
1305       if (LHSi->getValue())
1306         return MHS;
1307       return RHS;
1308     }
1309     break;
1310   }
1311 
1312   case DAG: {
1313     ListInit *MHSl = dyn_cast<ListInit>(MHS);
1314     ListInit *RHSl = dyn_cast<ListInit>(RHS);
1315     bool MHSok = MHSl || isa<UnsetInit>(MHS);
1316     bool RHSok = RHSl || isa<UnsetInit>(RHS);
1317 
1318     if (isa<UnsetInit>(MHS) && isa<UnsetInit>(RHS))
1319       break; // Typically prevented by the parser, but might happen with template args
1320 
1321     if (MHSok && RHSok && (!MHSl || !RHSl || MHSl->size() == RHSl->size())) {
1322       SmallVector<std::pair<Init *, StringInit *>, 8> Children;
1323       unsigned Size = MHSl ? MHSl->size() : RHSl->size();
1324       for (unsigned i = 0; i != Size; ++i) {
1325         Init *Node = MHSl ? MHSl->getElement(i) : UnsetInit::get();
1326         Init *Name = RHSl ? RHSl->getElement(i) : UnsetInit::get();
1327         if (!isa<StringInit>(Name) && !isa<UnsetInit>(Name))
1328           return const_cast<TernOpInit *>(this);
1329         Children.emplace_back(Node, dyn_cast<StringInit>(Name));
1330       }
1331       return DagInit::get(LHS, nullptr, Children);
1332     }
1333     break;
1334   }
1335   }
1336 
1337   return const_cast<TernOpInit *>(this);
1338 }
1339 
1340 Init *TernOpInit::resolveReferences(Resolver &R) const {
1341   Init *lhs = LHS->resolveReferences(R);
1342 
1343   if (getOpcode() == IF && lhs != LHS) {
1344     if (IntInit *Value = dyn_cast_or_null<IntInit>(
1345                              lhs->convertInitializerTo(IntRecTy::get()))) {
1346       // Short-circuit
1347       if (Value->getValue())
1348         return MHS->resolveReferences(R);
1349       return RHS->resolveReferences(R);
1350     }
1351   }
1352 
1353   Init *mhs = MHS->resolveReferences(R);
1354   Init *rhs;
1355 
1356   if (getOpcode() == FOREACH || getOpcode() == FILTER) {
1357     ShadowResolver SR(R);
1358     SR.addShadow(lhs);
1359     rhs = RHS->resolveReferences(SR);
1360   } else {
1361     rhs = RHS->resolveReferences(R);
1362   }
1363 
1364   if (LHS != lhs || MHS != mhs || RHS != rhs)
1365     return (TernOpInit::get(getOpcode(), lhs, mhs, rhs, getType()))
1366         ->Fold(R.getCurrentRecord());
1367   return const_cast<TernOpInit *>(this);
1368 }
1369 
1370 std::string TernOpInit::getAsString() const {
1371   std::string Result;
1372   bool UnquotedLHS = false;
1373   switch (getOpcode()) {
1374   case SUBST: Result = "!subst"; break;
1375   case FOREACH: Result = "!foreach"; UnquotedLHS = true; break;
1376   case FILTER: Result = "!filter"; UnquotedLHS = true; break;
1377   case IF: Result = "!if"; break;
1378   case DAG: Result = "!dag"; break;
1379   }
1380   return (Result + "(" +
1381           (UnquotedLHS ? LHS->getAsUnquotedString() : LHS->getAsString()) +
1382           ", " + MHS->getAsString() + ", " + RHS->getAsString() + ")");
1383 }
1384 
1385 static void ProfileFoldOpInit(FoldingSetNodeID &ID, Init *A, Init *B,
1386                               Init *Start, Init *List, Init *Expr,
1387                               RecTy *Type) {
1388   ID.AddPointer(Start);
1389   ID.AddPointer(List);
1390   ID.AddPointer(A);
1391   ID.AddPointer(B);
1392   ID.AddPointer(Expr);
1393   ID.AddPointer(Type);
1394 }
1395 
1396 FoldOpInit *FoldOpInit::get(Init *Start, Init *List, Init *A, Init *B,
1397                             Init *Expr, RecTy *Type) {
1398   static FoldingSet<FoldOpInit> ThePool;
1399 
1400   FoldingSetNodeID ID;
1401   ProfileFoldOpInit(ID, Start, List, A, B, Expr, Type);
1402 
1403   void *IP = nullptr;
1404   if (FoldOpInit *I = ThePool.FindNodeOrInsertPos(ID, IP))
1405     return I;
1406 
1407   FoldOpInit *I = new (Allocator) FoldOpInit(Start, List, A, B, Expr, Type);
1408   ThePool.InsertNode(I, IP);
1409   return I;
1410 }
1411 
1412 void FoldOpInit::Profile(FoldingSetNodeID &ID) const {
1413   ProfileFoldOpInit(ID, Start, List, A, B, Expr, getType());
1414 }
1415 
1416 Init *FoldOpInit::Fold(Record *CurRec) const {
1417   if (ListInit *LI = dyn_cast<ListInit>(List)) {
1418     Init *Accum = Start;
1419     for (Init *Elt : *LI) {
1420       MapResolver R(CurRec);
1421       R.set(A, Accum);
1422       R.set(B, Elt);
1423       Accum = Expr->resolveReferences(R);
1424     }
1425     return Accum;
1426   }
1427   return const_cast<FoldOpInit *>(this);
1428 }
1429 
1430 Init *FoldOpInit::resolveReferences(Resolver &R) const {
1431   Init *NewStart = Start->resolveReferences(R);
1432   Init *NewList = List->resolveReferences(R);
1433   ShadowResolver SR(R);
1434   SR.addShadow(A);
1435   SR.addShadow(B);
1436   Init *NewExpr = Expr->resolveReferences(SR);
1437 
1438   if (Start == NewStart && List == NewList && Expr == NewExpr)
1439     return const_cast<FoldOpInit *>(this);
1440 
1441   return get(NewStart, NewList, A, B, NewExpr, getType())
1442       ->Fold(R.getCurrentRecord());
1443 }
1444 
1445 Init *FoldOpInit::getBit(unsigned Bit) const {
1446   return VarBitInit::get(const_cast<FoldOpInit *>(this), Bit);
1447 }
1448 
1449 std::string FoldOpInit::getAsString() const {
1450   return (Twine("!foldl(") + Start->getAsString() + ", " + List->getAsString() +
1451           ", " + A->getAsUnquotedString() + ", " + B->getAsUnquotedString() +
1452           ", " + Expr->getAsString() + ")")
1453       .str();
1454 }
1455 
1456 static void ProfileIsAOpInit(FoldingSetNodeID &ID, RecTy *CheckType,
1457                              Init *Expr) {
1458   ID.AddPointer(CheckType);
1459   ID.AddPointer(Expr);
1460 }
1461 
1462 IsAOpInit *IsAOpInit::get(RecTy *CheckType, Init *Expr) {
1463   static FoldingSet<IsAOpInit> ThePool;
1464 
1465   FoldingSetNodeID ID;
1466   ProfileIsAOpInit(ID, CheckType, Expr);
1467 
1468   void *IP = nullptr;
1469   if (IsAOpInit *I = ThePool.FindNodeOrInsertPos(ID, IP))
1470     return I;
1471 
1472   IsAOpInit *I = new (Allocator) IsAOpInit(CheckType, Expr);
1473   ThePool.InsertNode(I, IP);
1474   return I;
1475 }
1476 
1477 void IsAOpInit::Profile(FoldingSetNodeID &ID) const {
1478   ProfileIsAOpInit(ID, CheckType, Expr);
1479 }
1480 
1481 Init *IsAOpInit::Fold() const {
1482   if (TypedInit *TI = dyn_cast<TypedInit>(Expr)) {
1483     // Is the expression type known to be (a subclass of) the desired type?
1484     if (TI->getType()->typeIsConvertibleTo(CheckType))
1485       return IntInit::get(1);
1486 
1487     if (isa<RecordRecTy>(CheckType)) {
1488       // If the target type is not a subclass of the expression type, or if
1489       // the expression has fully resolved to a record, we know that it can't
1490       // be of the required type.
1491       if (!CheckType->typeIsConvertibleTo(TI->getType()) || isa<DefInit>(Expr))
1492         return IntInit::get(0);
1493     } else {
1494       // We treat non-record types as not castable.
1495       return IntInit::get(0);
1496     }
1497   }
1498   return const_cast<IsAOpInit *>(this);
1499 }
1500 
1501 Init *IsAOpInit::resolveReferences(Resolver &R) const {
1502   Init *NewExpr = Expr->resolveReferences(R);
1503   if (Expr != NewExpr)
1504     return get(CheckType, NewExpr)->Fold();
1505   return const_cast<IsAOpInit *>(this);
1506 }
1507 
1508 Init *IsAOpInit::getBit(unsigned Bit) const {
1509   return VarBitInit::get(const_cast<IsAOpInit *>(this), Bit);
1510 }
1511 
1512 std::string IsAOpInit::getAsString() const {
1513   return (Twine("!isa<") + CheckType->getAsString() + ">(" +
1514           Expr->getAsString() + ")")
1515       .str();
1516 }
1517 
1518 RecTy *TypedInit::getFieldType(StringInit *FieldName) const {
1519   if (RecordRecTy *RecordType = dyn_cast<RecordRecTy>(getType())) {
1520     for (Record *Rec : RecordType->getClasses()) {
1521       if (RecordVal *Field = Rec->getValue(FieldName))
1522         return Field->getType();
1523     }
1524   }
1525   return nullptr;
1526 }
1527 
1528 Init *
1529 TypedInit::convertInitializerTo(RecTy *Ty) const {
1530   if (getType() == Ty || getType()->typeIsA(Ty))
1531     return const_cast<TypedInit *>(this);
1532 
1533   if (isa<BitRecTy>(getType()) && isa<BitsRecTy>(Ty) &&
1534       cast<BitsRecTy>(Ty)->getNumBits() == 1)
1535     return BitsInit::get({const_cast<TypedInit *>(this)});
1536 
1537   return nullptr;
1538 }
1539 
1540 Init *TypedInit::convertInitializerBitRange(ArrayRef<unsigned> Bits) const {
1541   BitsRecTy *T = dyn_cast<BitsRecTy>(getType());
1542   if (!T) return nullptr;  // Cannot subscript a non-bits variable.
1543   unsigned NumBits = T->getNumBits();
1544 
1545   SmallVector<Init *, 16> NewBits;
1546   NewBits.reserve(Bits.size());
1547   for (unsigned Bit : Bits) {
1548     if (Bit >= NumBits)
1549       return nullptr;
1550 
1551     NewBits.push_back(VarBitInit::get(const_cast<TypedInit *>(this), Bit));
1552   }
1553   return BitsInit::get(NewBits);
1554 }
1555 
1556 Init *TypedInit::getCastTo(RecTy *Ty) const {
1557   // Handle the common case quickly
1558   if (getType() == Ty || getType()->typeIsA(Ty))
1559     return const_cast<TypedInit *>(this);
1560 
1561   if (Init *Converted = convertInitializerTo(Ty)) {
1562     assert(!isa<TypedInit>(Converted) ||
1563            cast<TypedInit>(Converted)->getType()->typeIsA(Ty));
1564     return Converted;
1565   }
1566 
1567   if (!getType()->typeIsConvertibleTo(Ty))
1568     return nullptr;
1569 
1570   return UnOpInit::get(UnOpInit::CAST, const_cast<TypedInit *>(this), Ty)
1571       ->Fold(nullptr);
1572 }
1573 
1574 Init *TypedInit::convertInitListSlice(ArrayRef<unsigned> Elements) const {
1575   ListRecTy *T = dyn_cast<ListRecTy>(getType());
1576   if (!T) return nullptr;  // Cannot subscript a non-list variable.
1577 
1578   if (Elements.size() == 1)
1579     return VarListElementInit::get(const_cast<TypedInit *>(this), Elements[0]);
1580 
1581   SmallVector<Init*, 8> ListInits;
1582   ListInits.reserve(Elements.size());
1583   for (unsigned Element : Elements)
1584     ListInits.push_back(VarListElementInit::get(const_cast<TypedInit *>(this),
1585                                                 Element));
1586   return ListInit::get(ListInits, T->getElementType());
1587 }
1588 
1589 
1590 VarInit *VarInit::get(StringRef VN, RecTy *T) {
1591   Init *Value = StringInit::get(VN);
1592   return VarInit::get(Value, T);
1593 }
1594 
1595 VarInit *VarInit::get(Init *VN, RecTy *T) {
1596   using Key = std::pair<RecTy *, Init *>;
1597   static DenseMap<Key, VarInit*> ThePool;
1598 
1599   Key TheKey(std::make_pair(T, VN));
1600 
1601   VarInit *&I = ThePool[TheKey];
1602   if (!I)
1603     I = new(Allocator) VarInit(VN, T);
1604   return I;
1605 }
1606 
1607 StringRef VarInit::getName() const {
1608   StringInit *NameString = cast<StringInit>(getNameInit());
1609   return NameString->getValue();
1610 }
1611 
1612 Init *VarInit::getBit(unsigned Bit) const {
1613   if (getType() == BitRecTy::get())
1614     return const_cast<VarInit*>(this);
1615   return VarBitInit::get(const_cast<VarInit*>(this), Bit);
1616 }
1617 
1618 Init *VarInit::resolveReferences(Resolver &R) const {
1619   if (Init *Val = R.resolve(VarName))
1620     return Val;
1621   return const_cast<VarInit *>(this);
1622 }
1623 
1624 VarBitInit *VarBitInit::get(TypedInit *T, unsigned B) {
1625   using Key = std::pair<TypedInit *, unsigned>;
1626   static DenseMap<Key, VarBitInit*> ThePool;
1627 
1628   Key TheKey(std::make_pair(T, B));
1629 
1630   VarBitInit *&I = ThePool[TheKey];
1631   if (!I)
1632     I = new(Allocator) VarBitInit(T, B);
1633   return I;
1634 }
1635 
1636 std::string VarBitInit::getAsString() const {
1637   return TI->getAsString() + "{" + utostr(Bit) + "}";
1638 }
1639 
1640 Init *VarBitInit::resolveReferences(Resolver &R) const {
1641   Init *I = TI->resolveReferences(R);
1642   if (TI != I)
1643     return I->getBit(getBitNum());
1644 
1645   return const_cast<VarBitInit*>(this);
1646 }
1647 
1648 VarListElementInit *VarListElementInit::get(TypedInit *T,
1649                                             unsigned E) {
1650   using Key = std::pair<TypedInit *, unsigned>;
1651   static DenseMap<Key, VarListElementInit*> ThePool;
1652 
1653   Key TheKey(std::make_pair(T, E));
1654 
1655   VarListElementInit *&I = ThePool[TheKey];
1656   if (!I) I = new(Allocator) VarListElementInit(T, E);
1657   return I;
1658 }
1659 
1660 std::string VarListElementInit::getAsString() const {
1661   return TI->getAsString() + "[" + utostr(Element) + "]";
1662 }
1663 
1664 Init *VarListElementInit::resolveReferences(Resolver &R) const {
1665   Init *NewTI = TI->resolveReferences(R);
1666   if (ListInit *List = dyn_cast<ListInit>(NewTI)) {
1667     // Leave out-of-bounds array references as-is. This can happen without
1668     // being an error, e.g. in the untaken "branch" of an !if expression.
1669     if (getElementNum() < List->size())
1670       return List->getElement(getElementNum());
1671   }
1672   if (NewTI != TI && isa<TypedInit>(NewTI))
1673     return VarListElementInit::get(cast<TypedInit>(NewTI), getElementNum());
1674   return const_cast<VarListElementInit *>(this);
1675 }
1676 
1677 Init *VarListElementInit::getBit(unsigned Bit) const {
1678   if (getType() == BitRecTy::get())
1679     return const_cast<VarListElementInit*>(this);
1680   return VarBitInit::get(const_cast<VarListElementInit*>(this), Bit);
1681 }
1682 
1683 DefInit::DefInit(Record *D)
1684     : TypedInit(IK_DefInit, D->getType()), Def(D) {}
1685 
1686 DefInit *DefInit::get(Record *R) {
1687   return R->getDefInit();
1688 }
1689 
1690 Init *DefInit::convertInitializerTo(RecTy *Ty) const {
1691   if (auto *RRT = dyn_cast<RecordRecTy>(Ty))
1692     if (getType()->typeIsConvertibleTo(RRT))
1693       return const_cast<DefInit *>(this);
1694   return nullptr;
1695 }
1696 
1697 RecTy *DefInit::getFieldType(StringInit *FieldName) const {
1698   if (const RecordVal *RV = Def->getValue(FieldName))
1699     return RV->getType();
1700   return nullptr;
1701 }
1702 
1703 std::string DefInit::getAsString() const { return std::string(Def->getName()); }
1704 
1705 static void ProfileVarDefInit(FoldingSetNodeID &ID,
1706                               Record *Class,
1707                               ArrayRef<Init *> Args) {
1708   ID.AddInteger(Args.size());
1709   ID.AddPointer(Class);
1710 
1711   for (Init *I : Args)
1712     ID.AddPointer(I);
1713 }
1714 
1715 VarDefInit *VarDefInit::get(Record *Class, ArrayRef<Init *> Args) {
1716   static FoldingSet<VarDefInit> ThePool;
1717 
1718   FoldingSetNodeID ID;
1719   ProfileVarDefInit(ID, Class, Args);
1720 
1721   void *IP = nullptr;
1722   if (VarDefInit *I = ThePool.FindNodeOrInsertPos(ID, IP))
1723     return I;
1724 
1725   void *Mem = Allocator.Allocate(totalSizeToAlloc<Init *>(Args.size()),
1726                                  alignof(VarDefInit));
1727   VarDefInit *I = new(Mem) VarDefInit(Class, Args.size());
1728   std::uninitialized_copy(Args.begin(), Args.end(),
1729                           I->getTrailingObjects<Init *>());
1730   ThePool.InsertNode(I, IP);
1731   return I;
1732 }
1733 
1734 void VarDefInit::Profile(FoldingSetNodeID &ID) const {
1735   ProfileVarDefInit(ID, Class, args());
1736 }
1737 
1738 DefInit *VarDefInit::instantiate() {
1739   if (!Def) {
1740     RecordKeeper &Records = Class->getRecords();
1741     auto NewRecOwner = std::make_unique<Record>(Records.getNewAnonymousName(),
1742                                            Class->getLoc(), Records,
1743                                            /*IsAnonymous=*/true);
1744     Record *NewRec = NewRecOwner.get();
1745 
1746     // Copy values from class to instance
1747     for (const RecordVal &Val : Class->getValues())
1748       NewRec->addValue(Val);
1749 
1750     // Substitute and resolve template arguments
1751     ArrayRef<Init *> TArgs = Class->getTemplateArgs();
1752     MapResolver R(NewRec);
1753 
1754     for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
1755       if (i < args_size())
1756         R.set(TArgs[i], getArg(i));
1757       else
1758         R.set(TArgs[i], NewRec->getValue(TArgs[i])->getValue());
1759 
1760       NewRec->removeValue(TArgs[i]);
1761     }
1762 
1763     NewRec->resolveReferences(R);
1764 
1765     // Add superclasses.
1766     ArrayRef<std::pair<Record *, SMRange>> SCs = Class->getSuperClasses();
1767     for (const auto &SCPair : SCs)
1768       NewRec->addSuperClass(SCPair.first, SCPair.second);
1769 
1770     NewRec->addSuperClass(Class,
1771                           SMRange(Class->getLoc().back(),
1772                                   Class->getLoc().back()));
1773 
1774     // Resolve internal references and store in record keeper
1775     NewRec->resolveReferences();
1776     Records.addDef(std::move(NewRecOwner));
1777 
1778     Def = DefInit::get(NewRec);
1779   }
1780 
1781   return Def;
1782 }
1783 
1784 Init *VarDefInit::resolveReferences(Resolver &R) const {
1785   TrackUnresolvedResolver UR(&R);
1786   bool Changed = false;
1787   SmallVector<Init *, 8> NewArgs;
1788   NewArgs.reserve(args_size());
1789 
1790   for (Init *Arg : args()) {
1791     Init *NewArg = Arg->resolveReferences(UR);
1792     NewArgs.push_back(NewArg);
1793     Changed |= NewArg != Arg;
1794   }
1795 
1796   if (Changed) {
1797     auto New = VarDefInit::get(Class, NewArgs);
1798     if (!UR.foundUnresolved())
1799       return New->instantiate();
1800     return New;
1801   }
1802   return const_cast<VarDefInit *>(this);
1803 }
1804 
1805 Init *VarDefInit::Fold() const {
1806   if (Def)
1807     return Def;
1808 
1809   TrackUnresolvedResolver R;
1810   for (Init *Arg : args())
1811     Arg->resolveReferences(R);
1812 
1813   if (!R.foundUnresolved())
1814     return const_cast<VarDefInit *>(this)->instantiate();
1815   return const_cast<VarDefInit *>(this);
1816 }
1817 
1818 std::string VarDefInit::getAsString() const {
1819   std::string Result = Class->getNameInitAsString() + "<";
1820   const char *sep = "";
1821   for (Init *Arg : args()) {
1822     Result += sep;
1823     sep = ", ";
1824     Result += Arg->getAsString();
1825   }
1826   return Result + ">";
1827 }
1828 
1829 FieldInit *FieldInit::get(Init *R, StringInit *FN) {
1830   using Key = std::pair<Init *, StringInit *>;
1831   static DenseMap<Key, FieldInit*> ThePool;
1832 
1833   Key TheKey(std::make_pair(R, FN));
1834 
1835   FieldInit *&I = ThePool[TheKey];
1836   if (!I) I = new(Allocator) FieldInit(R, FN);
1837   return I;
1838 }
1839 
1840 Init *FieldInit::getBit(unsigned Bit) const {
1841   if (getType() == BitRecTy::get())
1842     return const_cast<FieldInit*>(this);
1843   return VarBitInit::get(const_cast<FieldInit*>(this), Bit);
1844 }
1845 
1846 Init *FieldInit::resolveReferences(Resolver &R) const {
1847   Init *NewRec = Rec->resolveReferences(R);
1848   if (NewRec != Rec)
1849     return FieldInit::get(NewRec, FieldName)->Fold(R.getCurrentRecord());
1850   return const_cast<FieldInit *>(this);
1851 }
1852 
1853 Init *FieldInit::Fold(Record *CurRec) const {
1854   if (DefInit *DI = dyn_cast<DefInit>(Rec)) {
1855     Record *Def = DI->getDef();
1856     if (Def == CurRec)
1857       PrintFatalError(CurRec->getLoc(),
1858                       Twine("Attempting to access field '") +
1859                       FieldName->getAsUnquotedString() + "' of '" +
1860                       Rec->getAsString() + "' is a forbidden self-reference");
1861     Init *FieldVal = Def->getValue(FieldName)->getValue();
1862     if (FieldVal->isComplete())
1863       return FieldVal;
1864   }
1865   return const_cast<FieldInit *>(this);
1866 }
1867 
1868 bool FieldInit::isConcrete() const {
1869   if (DefInit *DI = dyn_cast<DefInit>(Rec)) {
1870     Init *FieldVal = DI->getDef()->getValue(FieldName)->getValue();
1871     return FieldVal->isConcrete();
1872   }
1873   return false;
1874 }
1875 
1876 static void ProfileCondOpInit(FoldingSetNodeID &ID,
1877                              ArrayRef<Init *> CondRange,
1878                              ArrayRef<Init *> ValRange,
1879                              const RecTy *ValType) {
1880   assert(CondRange.size() == ValRange.size() &&
1881          "Number of conditions and values must match!");
1882   ID.AddPointer(ValType);
1883   ArrayRef<Init *>::iterator Case = CondRange.begin();
1884   ArrayRef<Init *>::iterator Val = ValRange.begin();
1885 
1886   while (Case != CondRange.end()) {
1887     ID.AddPointer(*Case++);
1888     ID.AddPointer(*Val++);
1889   }
1890 }
1891 
1892 void CondOpInit::Profile(FoldingSetNodeID &ID) const {
1893   ProfileCondOpInit(ID,
1894       makeArrayRef(getTrailingObjects<Init *>(), NumConds),
1895       makeArrayRef(getTrailingObjects<Init *>() + NumConds, NumConds),
1896       ValType);
1897 }
1898 
1899 CondOpInit *
1900 CondOpInit::get(ArrayRef<Init *> CondRange,
1901                 ArrayRef<Init *> ValRange, RecTy *Ty) {
1902   assert(CondRange.size() == ValRange.size() &&
1903          "Number of conditions and values must match!");
1904 
1905   static FoldingSet<CondOpInit> ThePool;
1906   FoldingSetNodeID ID;
1907   ProfileCondOpInit(ID, CondRange, ValRange, Ty);
1908 
1909   void *IP = nullptr;
1910   if (CondOpInit *I = ThePool.FindNodeOrInsertPos(ID, IP))
1911     return I;
1912 
1913   void *Mem = Allocator.Allocate(totalSizeToAlloc<Init *>(2*CondRange.size()),
1914                                  alignof(BitsInit));
1915   CondOpInit *I = new(Mem) CondOpInit(CondRange.size(), Ty);
1916 
1917   std::uninitialized_copy(CondRange.begin(), CondRange.end(),
1918                           I->getTrailingObjects<Init *>());
1919   std::uninitialized_copy(ValRange.begin(), ValRange.end(),
1920                           I->getTrailingObjects<Init *>()+CondRange.size());
1921   ThePool.InsertNode(I, IP);
1922   return I;
1923 }
1924 
1925 Init *CondOpInit::resolveReferences(Resolver &R) const {
1926   SmallVector<Init*, 4> NewConds;
1927   bool Changed = false;
1928   for (const Init *Case : getConds()) {
1929     Init *NewCase = Case->resolveReferences(R);
1930     NewConds.push_back(NewCase);
1931     Changed |= NewCase != Case;
1932   }
1933 
1934   SmallVector<Init*, 4> NewVals;
1935   for (const Init *Val : getVals()) {
1936     Init *NewVal = Val->resolveReferences(R);
1937     NewVals.push_back(NewVal);
1938     Changed |= NewVal != Val;
1939   }
1940 
1941   if (Changed)
1942     return (CondOpInit::get(NewConds, NewVals,
1943             getValType()))->Fold(R.getCurrentRecord());
1944 
1945   return const_cast<CondOpInit *>(this);
1946 }
1947 
1948 Init *CondOpInit::Fold(Record *CurRec) const {
1949   for ( unsigned i = 0; i < NumConds; ++i) {
1950     Init *Cond = getCond(i);
1951     Init *Val = getVal(i);
1952 
1953     if (IntInit *CondI = dyn_cast_or_null<IntInit>(
1954             Cond->convertInitializerTo(IntRecTy::get()))) {
1955       if (CondI->getValue())
1956         return Val->convertInitializerTo(getValType());
1957     } else
1958      return const_cast<CondOpInit *>(this);
1959   }
1960 
1961   PrintFatalError(CurRec->getLoc(),
1962                   CurRec->getName() +
1963                   " does not have any true condition in:" +
1964                   this->getAsString());
1965   return nullptr;
1966 }
1967 
1968 bool CondOpInit::isConcrete() const {
1969   for (const Init *Case : getConds())
1970     if (!Case->isConcrete())
1971       return false;
1972 
1973   for (const Init *Val : getVals())
1974     if (!Val->isConcrete())
1975       return false;
1976 
1977   return true;
1978 }
1979 
1980 bool CondOpInit::isComplete() const {
1981   for (const Init *Case : getConds())
1982     if (!Case->isComplete())
1983       return false;
1984 
1985   for (const Init *Val : getVals())
1986     if (!Val->isConcrete())
1987       return false;
1988 
1989   return true;
1990 }
1991 
1992 std::string CondOpInit::getAsString() const {
1993   std::string Result = "!cond(";
1994   for (unsigned i = 0; i < getNumConds(); i++) {
1995     Result += getCond(i)->getAsString() + ": ";
1996     Result += getVal(i)->getAsString();
1997     if (i != getNumConds()-1)
1998       Result += ", ";
1999   }
2000   return Result + ")";
2001 }
2002 
2003 Init *CondOpInit::getBit(unsigned Bit) const {
2004   return VarBitInit::get(const_cast<CondOpInit *>(this), Bit);
2005 }
2006 
2007 static void ProfileDagInit(FoldingSetNodeID &ID, Init *V, StringInit *VN,
2008                            ArrayRef<Init *> ArgRange,
2009                            ArrayRef<StringInit *> NameRange) {
2010   ID.AddPointer(V);
2011   ID.AddPointer(VN);
2012 
2013   ArrayRef<Init *>::iterator Arg = ArgRange.begin();
2014   ArrayRef<StringInit *>::iterator Name = NameRange.begin();
2015   while (Arg != ArgRange.end()) {
2016     assert(Name != NameRange.end() && "Arg name underflow!");
2017     ID.AddPointer(*Arg++);
2018     ID.AddPointer(*Name++);
2019   }
2020   assert(Name == NameRange.end() && "Arg name overflow!");
2021 }
2022 
2023 DagInit *
2024 DagInit::get(Init *V, StringInit *VN, ArrayRef<Init *> ArgRange,
2025              ArrayRef<StringInit *> NameRange) {
2026   static FoldingSet<DagInit> ThePool;
2027 
2028   FoldingSetNodeID ID;
2029   ProfileDagInit(ID, V, VN, ArgRange, NameRange);
2030 
2031   void *IP = nullptr;
2032   if (DagInit *I = ThePool.FindNodeOrInsertPos(ID, IP))
2033     return I;
2034 
2035   void *Mem = Allocator.Allocate(totalSizeToAlloc<Init *, StringInit *>(ArgRange.size(), NameRange.size()), alignof(BitsInit));
2036   DagInit *I = new(Mem) DagInit(V, VN, ArgRange.size(), NameRange.size());
2037   std::uninitialized_copy(ArgRange.begin(), ArgRange.end(),
2038                           I->getTrailingObjects<Init *>());
2039   std::uninitialized_copy(NameRange.begin(), NameRange.end(),
2040                           I->getTrailingObjects<StringInit *>());
2041   ThePool.InsertNode(I, IP);
2042   return I;
2043 }
2044 
2045 DagInit *
2046 DagInit::get(Init *V, StringInit *VN,
2047              ArrayRef<std::pair<Init*, StringInit*>> args) {
2048   SmallVector<Init *, 8> Args;
2049   SmallVector<StringInit *, 8> Names;
2050 
2051   for (const auto &Arg : args) {
2052     Args.push_back(Arg.first);
2053     Names.push_back(Arg.second);
2054   }
2055 
2056   return DagInit::get(V, VN, Args, Names);
2057 }
2058 
2059 void DagInit::Profile(FoldingSetNodeID &ID) const {
2060   ProfileDagInit(ID, Val, ValName, makeArrayRef(getTrailingObjects<Init *>(), NumArgs), makeArrayRef(getTrailingObjects<StringInit *>(), NumArgNames));
2061 }
2062 
2063 Record *DagInit::getOperatorAsDef(ArrayRef<SMLoc> Loc) const {
2064   if (DefInit *DefI = dyn_cast<DefInit>(Val))
2065     return DefI->getDef();
2066   PrintFatalError(Loc, "Expected record as operator");
2067   return nullptr;
2068 }
2069 
2070 Init *DagInit::resolveReferences(Resolver &R) const {
2071   SmallVector<Init*, 8> NewArgs;
2072   NewArgs.reserve(arg_size());
2073   bool ArgsChanged = false;
2074   for (const Init *Arg : getArgs()) {
2075     Init *NewArg = Arg->resolveReferences(R);
2076     NewArgs.push_back(NewArg);
2077     ArgsChanged |= NewArg != Arg;
2078   }
2079 
2080   Init *Op = Val->resolveReferences(R);
2081   if (Op != Val || ArgsChanged)
2082     return DagInit::get(Op, ValName, NewArgs, getArgNames());
2083 
2084   return const_cast<DagInit *>(this);
2085 }
2086 
2087 bool DagInit::isConcrete() const {
2088   if (!Val->isConcrete())
2089     return false;
2090   for (const Init *Elt : getArgs()) {
2091     if (!Elt->isConcrete())
2092       return false;
2093   }
2094   return true;
2095 }
2096 
2097 std::string DagInit::getAsString() const {
2098   std::string Result = "(" + Val->getAsString();
2099   if (ValName)
2100     Result += ":" + ValName->getAsUnquotedString();
2101   if (!arg_empty()) {
2102     Result += " " + getArg(0)->getAsString();
2103     if (getArgName(0)) Result += ":$" + getArgName(0)->getAsUnquotedString();
2104     for (unsigned i = 1, e = getNumArgs(); i != e; ++i) {
2105       Result += ", " + getArg(i)->getAsString();
2106       if (getArgName(i)) Result += ":$" + getArgName(i)->getAsUnquotedString();
2107     }
2108   }
2109   return Result + ")";
2110 }
2111 
2112 //===----------------------------------------------------------------------===//
2113 //    Other implementations
2114 //===----------------------------------------------------------------------===//
2115 
2116 RecordVal::RecordVal(Init *N, RecTy *T, bool P)
2117   : Name(N), TyAndPrefix(T, P) {
2118   setValue(UnsetInit::get());
2119   assert(Value && "Cannot create unset value for current type!");
2120 }
2121 
2122 // This constructor accepts the same arguments as the above, but also
2123 // a source location.
2124 RecordVal::RecordVal(Init *N, SMLoc Loc, RecTy *T, bool P)
2125     : Name(N), Loc(Loc), TyAndPrefix(T, P) {
2126   setValue(UnsetInit::get());
2127   assert(Value && "Cannot create unset value for current type!");
2128 }
2129 
2130 StringRef RecordVal::getName() const {
2131   return cast<StringInit>(getNameInit())->getValue();
2132 }
2133 
2134 bool RecordVal::setValue(Init *V) {
2135   if (V) {
2136     Value = V->getCastTo(getType());
2137     if (Value) {
2138       assert(!isa<TypedInit>(Value) ||
2139              cast<TypedInit>(Value)->getType()->typeIsA(getType()));
2140       if (BitsRecTy *BTy = dyn_cast<BitsRecTy>(getType())) {
2141         if (!isa<BitsInit>(Value)) {
2142           SmallVector<Init *, 64> Bits;
2143           Bits.reserve(BTy->getNumBits());
2144           for (unsigned I = 0, E = BTy->getNumBits(); I < E; ++I)
2145             Bits.push_back(Value->getBit(I));
2146           Value = BitsInit::get(Bits);
2147         }
2148       }
2149     }
2150     return Value == nullptr;
2151   }
2152   Value = nullptr;
2153   return false;
2154 }
2155 
2156 // This version of setValue takes an source location and resets the
2157 // location in the RecordVal.
2158 bool RecordVal::setValue(Init *V, SMLoc NewLoc) {
2159   Loc = NewLoc;
2160   if (V) {
2161     Value = V->getCastTo(getType());
2162     if (Value) {
2163       assert(!isa<TypedInit>(Value) ||
2164              cast<TypedInit>(Value)->getType()->typeIsA(getType()));
2165       if (BitsRecTy *BTy = dyn_cast<BitsRecTy>(getType())) {
2166         if (!isa<BitsInit>(Value)) {
2167           SmallVector<Init *, 64> Bits;
2168           Bits.reserve(BTy->getNumBits());
2169           for (unsigned I = 0, E = BTy->getNumBits(); I < E; ++I)
2170             Bits.push_back(Value->getBit(I));
2171           Value = BitsInit::get(Bits);
2172         }
2173       }
2174     }
2175     return Value == nullptr;
2176   }
2177   Value = nullptr;
2178   return false;
2179 }
2180 
2181 #include "llvm/TableGen/Record.h"
2182 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2183 LLVM_DUMP_METHOD void RecordVal::dump() const { errs() << *this; }
2184 #endif
2185 
2186 void RecordVal::print(raw_ostream &OS, bool PrintSem) const {
2187   if (getPrefix()) OS << "field ";
2188   OS << *getType() << " " << getNameInitAsString();
2189 
2190   if (getValue())
2191     OS << " = " << *getValue();
2192 
2193   if (PrintSem) OS << ";\n";
2194 }
2195 
2196 unsigned Record::LastID = 0;
2197 
2198 void Record::checkName() {
2199   // Ensure the record name has string type.
2200   const TypedInit *TypedName = cast<const TypedInit>(Name);
2201   if (!isa<StringRecTy>(TypedName->getType()))
2202     PrintFatalError(getLoc(), Twine("Record name '") + Name->getAsString() +
2203                                   "' is not a string!");
2204 }
2205 
2206 RecordRecTy *Record::getType() {
2207   SmallVector<Record *, 4> DirectSCs;
2208   getDirectSuperClasses(DirectSCs);
2209   return RecordRecTy::get(DirectSCs);
2210 }
2211 
2212 DefInit *Record::getDefInit() {
2213   if (!CorrespondingDefInit)
2214     CorrespondingDefInit = new (Allocator) DefInit(this);
2215   return CorrespondingDefInit;
2216 }
2217 
2218 void Record::setName(Init *NewName) {
2219   Name = NewName;
2220   checkName();
2221   // DO NOT resolve record values to the name at this point because
2222   // there might be default values for arguments of this def.  Those
2223   // arguments might not have been resolved yet so we don't want to
2224   // prematurely assume values for those arguments were not passed to
2225   // this def.
2226   //
2227   // Nonetheless, it may be that some of this Record's values
2228   // reference the record name.  Indeed, the reason for having the
2229   // record name be an Init is to provide this flexibility.  The extra
2230   // resolve steps after completely instantiating defs takes care of
2231   // this.  See TGParser::ParseDef and TGParser::ParseDefm.
2232 }
2233 
2234 // NOTE for the next two functions:
2235 // Superclasses are in post-order, so the final one is a direct
2236 // superclass. All of its transitive superclases immediately precede it,
2237 // so we can step through the direct superclasses in reverse order.
2238 
2239 bool Record::hasDirectSuperClass(const Record *Superclass) const {
2240   ArrayRef<std::pair<Record *, SMRange>> SCs = getSuperClasses();
2241 
2242   for (int I = SCs.size() - 1; I >= 0; --I) {
2243     const Record *SC = SCs[I].first;
2244     if (SC == Superclass)
2245       return true;
2246     I -= SC->getSuperClasses().size();
2247   }
2248 
2249   return false;
2250 }
2251 
2252 void Record::getDirectSuperClasses(SmallVectorImpl<Record *> &Classes) const {
2253   ArrayRef<std::pair<Record *, SMRange>> SCs = getSuperClasses();
2254 
2255   while (!SCs.empty()) {
2256     Record *SC = SCs.back().first;
2257     SCs = SCs.drop_back(1 + SC->getSuperClasses().size());
2258     Classes.push_back(SC);
2259   }
2260 }
2261 
2262 void Record::resolveReferences(Resolver &R, const RecordVal *SkipVal) {
2263   for (RecordVal &Value : Values) {
2264     if (SkipVal == &Value) // Skip resolve the same field as the given one
2265       continue;
2266     if (Init *V = Value.getValue()) {
2267       Init *VR = V->resolveReferences(R);
2268       if (Value.setValue(VR)) {
2269         std::string Type;
2270         if (TypedInit *VRT = dyn_cast<TypedInit>(VR))
2271           Type =
2272               (Twine("of type '") + VRT->getType()->getAsString() + "' ").str();
2273         PrintFatalError(getLoc(), Twine("Invalid value ") + Type +
2274                                       "is found when setting '" +
2275                                       Value.getNameInitAsString() +
2276                                       "' of type '" +
2277                                       Value.getType()->getAsString() +
2278                                       "' after resolving references: " +
2279                                       VR->getAsUnquotedString() + "\n");
2280       }
2281     }
2282   }
2283   Init *OldName = getNameInit();
2284   Init *NewName = Name->resolveReferences(R);
2285   if (NewName != OldName) {
2286     // Re-register with RecordKeeper.
2287     setName(NewName);
2288   }
2289 }
2290 
2291 void Record::resolveReferences() {
2292   RecordResolver R(*this);
2293   R.setFinal(true);
2294   resolveReferences(R);
2295 }
2296 
2297 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2298 LLVM_DUMP_METHOD void Record::dump() const { errs() << *this; }
2299 #endif
2300 
2301 raw_ostream &llvm::operator<<(raw_ostream &OS, const Record &R) {
2302   OS << R.getNameInitAsString();
2303 
2304   ArrayRef<Init *> TArgs = R.getTemplateArgs();
2305   if (!TArgs.empty()) {
2306     OS << "<";
2307     bool NeedComma = false;
2308     for (const Init *TA : TArgs) {
2309       if (NeedComma) OS << ", ";
2310       NeedComma = true;
2311       const RecordVal *RV = R.getValue(TA);
2312       assert(RV && "Template argument record not found??");
2313       RV->print(OS, false);
2314     }
2315     OS << ">";
2316   }
2317 
2318   OS << " {";
2319   ArrayRef<std::pair<Record *, SMRange>> SC = R.getSuperClasses();
2320   if (!SC.empty()) {
2321     OS << "\t//";
2322     for (const auto &SuperPair : SC)
2323       OS << " " << SuperPair.first->getNameInitAsString();
2324   }
2325   OS << "\n";
2326 
2327   for (const RecordVal &Val : R.getValues())
2328     if (Val.getPrefix() && !R.isTemplateArg(Val.getNameInit()))
2329       OS << Val;
2330   for (const RecordVal &Val : R.getValues())
2331     if (!Val.getPrefix() && !R.isTemplateArg(Val.getNameInit()))
2332       OS << Val;
2333 
2334   return OS << "}\n";
2335 }
2336 
2337 Init *Record::getValueInit(StringRef FieldName) const {
2338   const RecordVal *R = getValue(FieldName);
2339   if (!R || !R->getValue())
2340     PrintFatalError(getLoc(), "Record `" + getName() +
2341       "' does not have a field named `" + FieldName + "'!\n");
2342   return R->getValue();
2343 }
2344 
2345 StringRef Record::getValueAsString(StringRef FieldName) const {
2346   llvm::Optional<StringRef> S = getValueAsOptionalString(FieldName);
2347   if (!S.hasValue())
2348     PrintFatalError(getLoc(), "Record `" + getName() +
2349       "' does not have a field named `" + FieldName + "'!\n");
2350   return S.getValue();
2351 }
2352 llvm::Optional<StringRef>
2353 Record::getValueAsOptionalString(StringRef FieldName) const {
2354   const RecordVal *R = getValue(FieldName);
2355   if (!R || !R->getValue())
2356     return llvm::Optional<StringRef>();
2357   if (isa<UnsetInit>(R->getValue()))
2358     return llvm::Optional<StringRef>();
2359 
2360   if (StringInit *SI = dyn_cast<StringInit>(R->getValue()))
2361     return SI->getValue();
2362   if (CodeInit *CI = dyn_cast<CodeInit>(R->getValue()))
2363     return CI->getValue();
2364 
2365   PrintFatalError(getLoc(),
2366                   "Record `" + getName() + "', ` field `" + FieldName +
2367                       "' exists but does not have a string initializer!");
2368 }
2369 llvm::Optional<StringRef>
2370 Record::getValueAsOptionalCode(StringRef FieldName) const {
2371   const RecordVal *R = getValue(FieldName);
2372   if (!R || !R->getValue())
2373     return llvm::Optional<StringRef>();
2374   if (isa<UnsetInit>(R->getValue()))
2375     return llvm::Optional<StringRef>();
2376 
2377   if (CodeInit *CI = dyn_cast<CodeInit>(R->getValue()))
2378     return CI->getValue();
2379 
2380   PrintFatalError(getLoc(),
2381                   "Record `" + getName() + "', field `" + FieldName +
2382                       "' exists but does not have a code initializer!");
2383 }
2384 
2385 BitsInit *Record::getValueAsBitsInit(StringRef FieldName) const {
2386   const RecordVal *R = getValue(FieldName);
2387   if (!R || !R->getValue())
2388     PrintFatalError(getLoc(), "Record `" + getName() +
2389       "' does not have a field named `" + FieldName + "'!\n");
2390 
2391   if (BitsInit *BI = dyn_cast<BitsInit>(R->getValue()))
2392     return BI;
2393   PrintFatalError(getLoc(), "Record `" + getName() + "', field `" + FieldName +
2394                                 "' exists but does not have a bits value");
2395 }
2396 
2397 ListInit *Record::getValueAsListInit(StringRef FieldName) const {
2398   const RecordVal *R = getValue(FieldName);
2399   if (!R || !R->getValue())
2400     PrintFatalError(getLoc(), "Record `" + getName() +
2401       "' does not have a field named `" + FieldName + "'!\n");
2402 
2403   if (ListInit *LI = dyn_cast<ListInit>(R->getValue()))
2404     return LI;
2405   PrintFatalError(getLoc(), "Record `" + getName() + "', field `" + FieldName +
2406                                 "' exists but does not have a list value");
2407 }
2408 
2409 std::vector<Record*>
2410 Record::getValueAsListOfDefs(StringRef FieldName) const {
2411   ListInit *List = getValueAsListInit(FieldName);
2412   std::vector<Record*> Defs;
2413   for (Init *I : List->getValues()) {
2414     if (DefInit *DI = dyn_cast<DefInit>(I))
2415       Defs.push_back(DI->getDef());
2416     else
2417       PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
2418         FieldName + "' list is not entirely DefInit!");
2419   }
2420   return Defs;
2421 }
2422 
2423 int64_t Record::getValueAsInt(StringRef FieldName) const {
2424   const RecordVal *R = getValue(FieldName);
2425   if (!R || !R->getValue())
2426     PrintFatalError(getLoc(), "Record `" + getName() +
2427       "' does not have a field named `" + FieldName + "'!\n");
2428 
2429   if (IntInit *II = dyn_cast<IntInit>(R->getValue()))
2430     return II->getValue();
2431   PrintFatalError(getLoc(), Twine("Record `") + getName() + "', field `" +
2432                                 FieldName +
2433                                 "' exists but does not have an int value: " +
2434                                 R->getValue()->getAsString());
2435 }
2436 
2437 std::vector<int64_t>
2438 Record::getValueAsListOfInts(StringRef FieldName) const {
2439   ListInit *List = getValueAsListInit(FieldName);
2440   std::vector<int64_t> Ints;
2441   for (Init *I : List->getValues()) {
2442     if (IntInit *II = dyn_cast<IntInit>(I))
2443       Ints.push_back(II->getValue());
2444     else
2445       PrintFatalError(getLoc(),
2446                       Twine("Record `") + getName() + "', field `" + FieldName +
2447                           "' exists but does not have a list of ints value: " +
2448                           I->getAsString());
2449   }
2450   return Ints;
2451 }
2452 
2453 std::vector<StringRef>
2454 Record::getValueAsListOfStrings(StringRef FieldName) const {
2455   ListInit *List = getValueAsListInit(FieldName);
2456   std::vector<StringRef> Strings;
2457   for (Init *I : List->getValues()) {
2458     if (StringInit *SI = dyn_cast<StringInit>(I))
2459       Strings.push_back(SI->getValue());
2460     else if (CodeInit *CI = dyn_cast<CodeInit>(I))
2461       Strings.push_back(CI->getValue());
2462     else
2463       PrintFatalError(getLoc(),
2464                       Twine("Record `") + getName() + "', field `" + FieldName +
2465                           "' exists but does not have a list of strings value: " +
2466                           I->getAsString());
2467   }
2468   return Strings;
2469 }
2470 
2471 Record *Record::getValueAsDef(StringRef FieldName) const {
2472   const RecordVal *R = getValue(FieldName);
2473   if (!R || !R->getValue())
2474     PrintFatalError(getLoc(), "Record `" + getName() +
2475       "' does not have a field named `" + FieldName + "'!\n");
2476 
2477   if (DefInit *DI = dyn_cast<DefInit>(R->getValue()))
2478     return DI->getDef();
2479   PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
2480     FieldName + "' does not have a def initializer!");
2481 }
2482 
2483 Record *Record::getValueAsOptionalDef(StringRef FieldName) const {
2484   const RecordVal *R = getValue(FieldName);
2485   if (!R || !R->getValue())
2486     PrintFatalError(getLoc(), "Record `" + getName() +
2487       "' does not have a field named `" + FieldName + "'!\n");
2488 
2489   if (DefInit *DI = dyn_cast<DefInit>(R->getValue()))
2490     return DI->getDef();
2491   if (isa<UnsetInit>(R->getValue()))
2492     return nullptr;
2493   PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
2494     FieldName + "' does not have either a def initializer or '?'!");
2495 }
2496 
2497 
2498 bool Record::getValueAsBit(StringRef FieldName) const {
2499   const RecordVal *R = getValue(FieldName);
2500   if (!R || !R->getValue())
2501     PrintFatalError(getLoc(), "Record `" + getName() +
2502       "' does not have a field named `" + FieldName + "'!\n");
2503 
2504   if (BitInit *BI = dyn_cast<BitInit>(R->getValue()))
2505     return BI->getValue();
2506   PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
2507     FieldName + "' does not have a bit initializer!");
2508 }
2509 
2510 bool Record::getValueAsBitOrUnset(StringRef FieldName, bool &Unset) const {
2511   const RecordVal *R = getValue(FieldName);
2512   if (!R || !R->getValue())
2513     PrintFatalError(getLoc(), "Record `" + getName() +
2514       "' does not have a field named `" + FieldName.str() + "'!\n");
2515 
2516   if (isa<UnsetInit>(R->getValue())) {
2517     Unset = true;
2518     return false;
2519   }
2520   Unset = false;
2521   if (BitInit *BI = dyn_cast<BitInit>(R->getValue()))
2522     return BI->getValue();
2523   PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
2524     FieldName + "' does not have a bit initializer!");
2525 }
2526 
2527 DagInit *Record::getValueAsDag(StringRef FieldName) const {
2528   const RecordVal *R = getValue(FieldName);
2529   if (!R || !R->getValue())
2530     PrintFatalError(getLoc(), "Record `" + getName() +
2531       "' does not have a field named `" + FieldName + "'!\n");
2532 
2533   if (DagInit *DI = dyn_cast<DagInit>(R->getValue()))
2534     return DI;
2535   PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
2536     FieldName + "' does not have a dag initializer!");
2537 }
2538 
2539 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2540 LLVM_DUMP_METHOD void RecordKeeper::dump() const { errs() << *this; }
2541 #endif
2542 
2543 raw_ostream &llvm::operator<<(raw_ostream &OS, const RecordKeeper &RK) {
2544   OS << "------------- Classes -----------------\n";
2545   for (const auto &C : RK.getClasses())
2546     OS << "class " << *C.second;
2547 
2548   OS << "------------- Defs -----------------\n";
2549   for (const auto &D : RK.getDefs())
2550     OS << "def " << *D.second;
2551   return OS;
2552 }
2553 
2554 /// GetNewAnonymousName - Generate a unique anonymous name that can be used as
2555 /// an identifier.
2556 Init *RecordKeeper::getNewAnonymousName() {
2557   return StringInit::get("anonymous_" + utostr(AnonCounter++));
2558 }
2559 
2560 std::vector<Record *> RecordKeeper::getAllDerivedDefinitions(
2561     const ArrayRef<StringRef> ClassNames) const {
2562   SmallVector<Record *, 2> ClassRecs;
2563   std::vector<Record *> Defs;
2564 
2565   assert(ClassNames.size() > 0 && "At least one class must be passed.");
2566   for (const auto &ClassName : ClassNames) {
2567     Record *Class = getClass(ClassName);
2568     if (!Class)
2569       PrintFatalError("The class '" + ClassName + "' is not defined\n");
2570     ClassRecs.push_back(Class);
2571   }
2572 
2573   for (const auto &OneDef : getDefs()) {
2574     if (all_of(ClassRecs, [&OneDef](const Record *Class) {
2575                             return OneDef.second->isSubClassOf(Class);
2576                           }))
2577       Defs.push_back(OneDef.second.get());
2578   }
2579 
2580   return Defs;
2581 }
2582 
2583 Init *MapResolver::resolve(Init *VarName) {
2584   auto It = Map.find(VarName);
2585   if (It == Map.end())
2586     return nullptr;
2587 
2588   Init *I = It->second.V;
2589 
2590   if (!It->second.Resolved && Map.size() > 1) {
2591     // Resolve mutual references among the mapped variables, but prevent
2592     // infinite recursion.
2593     Map.erase(It);
2594     I = I->resolveReferences(*this);
2595     Map[VarName] = {I, true};
2596   }
2597 
2598   return I;
2599 }
2600 
2601 Init *RecordResolver::resolve(Init *VarName) {
2602   Init *Val = Cache.lookup(VarName);
2603   if (Val)
2604     return Val;
2605 
2606   for (Init *S : Stack) {
2607     if (S == VarName)
2608       return nullptr; // prevent infinite recursion
2609   }
2610 
2611   if (RecordVal *RV = getCurrentRecord()->getValue(VarName)) {
2612     if (!isa<UnsetInit>(RV->getValue())) {
2613       Val = RV->getValue();
2614       Stack.push_back(VarName);
2615       Val = Val->resolveReferences(*this);
2616       Stack.pop_back();
2617     }
2618   }
2619 
2620   Cache[VarName] = Val;
2621   return Val;
2622 }
2623 
2624 Init *TrackUnresolvedResolver::resolve(Init *VarName) {
2625   Init *I = nullptr;
2626 
2627   if (R) {
2628     I = R->resolve(VarName);
2629     if (I && !FoundUnresolved) {
2630       // Do not recurse into the resolved initializer, as that would change
2631       // the behavior of the resolver we're delegating, but do check to see
2632       // if there are unresolved variables remaining.
2633       TrackUnresolvedResolver Sub;
2634       I->resolveReferences(Sub);
2635       FoundUnresolved |= Sub.FoundUnresolved;
2636     }
2637   }
2638 
2639   if (!I)
2640     FoundUnresolved = true;
2641   return I;
2642 }
2643 
2644 Init *HasReferenceResolver::resolve(Init *VarName)
2645 {
2646   if (VarName == VarNameToTrack)
2647     Found = true;
2648   return nullptr;
2649 }
2650