1 //===- llvm/TableGen/Record.h - Classes for Table Records -------*- C++ -*-===//
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 // This file defines the main TableGen data structures, including the TableGen
10 // types, values, and high-level data structures.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #ifndef LLVM_TABLEGEN_RECORD_H
15 #define LLVM_TABLEGEN_RECORD_H
16 
17 #include "llvm/ADT/ArrayRef.h"
18 #include "llvm/ADT/DenseMap.h"
19 #include "llvm/ADT/DenseSet.h"
20 #include "llvm/ADT/FoldingSet.h"
21 #include "llvm/ADT/PointerIntPair.h"
22 #include "llvm/ADT/SmallVector.h"
23 #include "llvm/ADT/StringExtras.h"
24 #include "llvm/ADT/StringRef.h"
25 #include "llvm/Support/Casting.h"
26 #include "llvm/Support/ErrorHandling.h"
27 #include "llvm/Support/SMLoc.h"
28 #include "llvm/Support/Timer.h"
29 #include "llvm/Support/TrailingObjects.h"
30 #include "llvm/Support/raw_ostream.h"
31 #include <cassert>
32 #include <cstddef>
33 #include <cstdint>
34 #include <map>
35 #include <memory>
36 #include <string>
37 #include <utility>
38 #include <vector>
39 
40 namespace llvm {
41 namespace detail {
42 struct RecordKeeperImpl;
43 } // namespace detail
44 
45 class ListRecTy;
46 class Record;
47 class RecordKeeper;
48 class RecordVal;
49 class Resolver;
50 class StringInit;
51 class TypedInit;
52 
53 //===----------------------------------------------------------------------===//
54 //  Type Classes
55 //===----------------------------------------------------------------------===//
56 
57 class RecTy {
58 public:
59   /// Subclass discriminator (for dyn_cast<> et al.)
60   enum RecTyKind {
61     BitRecTyKind,
62     BitsRecTyKind,
63     IntRecTyKind,
64     StringRecTyKind,
65     ListRecTyKind,
66     DagRecTyKind,
67     RecordRecTyKind
68   };
69 
70 private:
71   RecTyKind Kind;
72   /// The RecordKeeper that uniqued this Type.
73   RecordKeeper &RK;
74   /// ListRecTy of the list that has elements of this type.
75   ListRecTy *ListTy = nullptr;
76 
77 public:
78   RecTy(RecTyKind K, RecordKeeper &RK) : Kind(K), RK(RK) {}
79   virtual ~RecTy() = default;
80 
81   RecTyKind getRecTyKind() const { return Kind; }
82 
83   /// Return the RecordKeeper that uniqued this Type.
84   RecordKeeper &getRecordKeeper() const { return RK; }
85 
86   virtual std::string getAsString() const = 0;
87   void print(raw_ostream &OS) const { OS << getAsString(); }
88   void dump() const;
89 
90   /// Return true if all values of 'this' type can be converted to the specified
91   /// type.
92   virtual bool typeIsConvertibleTo(const RecTy *RHS) const;
93 
94   /// Return true if 'this' type is equal to or a subtype of RHS. For example,
95   /// a bit set is not an int, but they are convertible.
96   virtual bool typeIsA(const RecTy *RHS) const;
97 
98   /// Returns the type representing list<thistype>.
99   ListRecTy *getListTy();
100 };
101 
102 inline raw_ostream &operator<<(raw_ostream &OS, const RecTy &Ty) {
103   Ty.print(OS);
104   return OS;
105 }
106 
107 /// 'bit' - Represent a single bit
108 class BitRecTy : public RecTy {
109   friend detail::RecordKeeperImpl;
110 
111   BitRecTy(RecordKeeper &RK) : RecTy(BitRecTyKind, RK) {}
112 
113 public:
114   static bool classof(const RecTy *RT) {
115     return RT->getRecTyKind() == BitRecTyKind;
116   }
117 
118   static BitRecTy *get(RecordKeeper &RK);
119 
120   std::string getAsString() const override { return "bit"; }
121 
122   bool typeIsConvertibleTo(const RecTy *RHS) const override;
123 };
124 
125 /// 'bits<n>' - Represent a fixed number of bits
126 class BitsRecTy : public RecTy {
127   unsigned Size;
128 
129   explicit BitsRecTy(RecordKeeper &RK, unsigned Sz)
130       : RecTy(BitsRecTyKind, RK), Size(Sz) {}
131 
132 public:
133   static bool classof(const RecTy *RT) {
134     return RT->getRecTyKind() == BitsRecTyKind;
135   }
136 
137   static BitsRecTy *get(RecordKeeper &RK, unsigned Sz);
138 
139   unsigned getNumBits() const { return Size; }
140 
141   std::string getAsString() const override;
142 
143   bool typeIsConvertibleTo(const RecTy *RHS) const override;
144 
145   bool typeIsA(const RecTy *RHS) const override;
146 };
147 
148 /// 'int' - Represent an integer value of no particular size
149 class IntRecTy : public RecTy {
150   friend detail::RecordKeeperImpl;
151 
152   IntRecTy(RecordKeeper &RK) : RecTy(IntRecTyKind, RK) {}
153 
154 public:
155   static bool classof(const RecTy *RT) {
156     return RT->getRecTyKind() == IntRecTyKind;
157   }
158 
159   static IntRecTy *get(RecordKeeper &RK);
160 
161   std::string getAsString() const override { return "int"; }
162 
163   bool typeIsConvertibleTo(const RecTy *RHS) const override;
164 };
165 
166 /// 'string' - Represent an string value
167 class StringRecTy : public RecTy {
168   friend detail::RecordKeeperImpl;
169 
170   StringRecTy(RecordKeeper &RK) : RecTy(StringRecTyKind, RK) {}
171 
172 public:
173   static bool classof(const RecTy *RT) {
174     return RT->getRecTyKind() == StringRecTyKind;
175   }
176 
177   static StringRecTy *get(RecordKeeper &RK);
178 
179   std::string getAsString() const override;
180 
181   bool typeIsConvertibleTo(const RecTy *RHS) const override;
182 };
183 
184 /// 'list<Ty>' - Represent a list of element values, all of which must be of
185 /// the specified type. The type is stored in ElementTy.
186 class ListRecTy : public RecTy {
187   friend ListRecTy *RecTy::getListTy();
188 
189   RecTy *ElementTy;
190 
191   explicit ListRecTy(RecTy *T)
192       : RecTy(ListRecTyKind, T->getRecordKeeper()), ElementTy(T) {}
193 
194 public:
195   static bool classof(const RecTy *RT) {
196     return RT->getRecTyKind() == ListRecTyKind;
197   }
198 
199   static ListRecTy *get(RecTy *T) { return T->getListTy(); }
200   RecTy *getElementType() const { return ElementTy; }
201 
202   std::string getAsString() const override;
203 
204   bool typeIsConvertibleTo(const RecTy *RHS) const override;
205 
206   bool typeIsA(const RecTy *RHS) const override;
207 };
208 
209 /// 'dag' - Represent a dag fragment
210 class DagRecTy : public RecTy {
211   friend detail::RecordKeeperImpl;
212 
213   DagRecTy(RecordKeeper &RK) : RecTy(DagRecTyKind, RK) {}
214 
215 public:
216   static bool classof(const RecTy *RT) {
217     return RT->getRecTyKind() == DagRecTyKind;
218   }
219 
220   static DagRecTy *get(RecordKeeper &RK);
221 
222   std::string getAsString() const override;
223 };
224 
225 /// '[classname]' - Type of record values that have zero or more superclasses.
226 ///
227 /// The list of superclasses is non-redundant, i.e. only contains classes that
228 /// are not the superclass of some other listed class.
229 class RecordRecTy final : public RecTy, public FoldingSetNode,
230                           public TrailingObjects<RecordRecTy, Record *> {
231   friend class Record;
232   friend detail::RecordKeeperImpl;
233 
234   unsigned NumClasses;
235 
236   explicit RecordRecTy(RecordKeeper &RK, unsigned Num)
237       : RecTy(RecordRecTyKind, RK), NumClasses(Num) {}
238 
239 public:
240   RecordRecTy(const RecordRecTy &) = delete;
241   RecordRecTy &operator=(const RecordRecTy &) = delete;
242 
243   // Do not use sized deallocation due to trailing objects.
244   void operator delete(void *p) { ::operator delete(p); }
245 
246   static bool classof(const RecTy *RT) {
247     return RT->getRecTyKind() == RecordRecTyKind;
248   }
249 
250   /// Get the record type with the given non-redundant list of superclasses.
251   static RecordRecTy *get(RecordKeeper &RK, ArrayRef<Record *> Classes);
252   static RecordRecTy *get(Record *Class);
253 
254   void Profile(FoldingSetNodeID &ID) const;
255 
256   ArrayRef<Record *> getClasses() const {
257     return makeArrayRef(getTrailingObjects<Record *>(), NumClasses);
258   }
259 
260   using const_record_iterator = Record * const *;
261 
262   const_record_iterator classes_begin() const { return getClasses().begin(); }
263   const_record_iterator classes_end() const { return getClasses().end(); }
264 
265   std::string getAsString() const override;
266 
267   bool isSubClassOf(Record *Class) const;
268   bool typeIsConvertibleTo(const RecTy *RHS) const override;
269 
270   bool typeIsA(const RecTy *RHS) const override;
271 };
272 
273 /// Find a common type that T1 and T2 convert to.
274 /// Return 0 if no such type exists.
275 RecTy *resolveTypes(RecTy *T1, RecTy *T2);
276 
277 //===----------------------------------------------------------------------===//
278 //  Initializer Classes
279 //===----------------------------------------------------------------------===//
280 
281 class Init {
282 protected:
283   /// Discriminator enum (for isa<>, dyn_cast<>, et al.)
284   ///
285   /// This enum is laid out by a preorder traversal of the inheritance
286   /// hierarchy, and does not contain an entry for abstract classes, as per
287   /// the recommendation in docs/HowToSetUpLLVMStyleRTTI.rst.
288   ///
289   /// We also explicitly include "first" and "last" values for each
290   /// interior node of the inheritance tree, to make it easier to read the
291   /// corresponding classof().
292   ///
293   /// We could pack these a bit tighter by not having the IK_FirstXXXInit
294   /// and IK_LastXXXInit be their own values, but that would degrade
295   /// readability for really no benefit.
296   enum InitKind : uint8_t {
297     IK_First, // unused; silence a spurious warning
298     IK_FirstTypedInit,
299     IK_BitInit,
300     IK_BitsInit,
301     IK_DagInit,
302     IK_DefInit,
303     IK_FieldInit,
304     IK_IntInit,
305     IK_ListInit,
306     IK_FirstOpInit,
307     IK_BinOpInit,
308     IK_TernOpInit,
309     IK_UnOpInit,
310     IK_LastOpInit,
311     IK_CondOpInit,
312     IK_FoldOpInit,
313     IK_IsAOpInit,
314     IK_ExistsOpInit,
315     IK_AnonymousNameInit,
316     IK_StringInit,
317     IK_VarInit,
318     IK_VarListElementInit,
319     IK_VarBitInit,
320     IK_VarDefInit,
321     IK_LastTypedInit,
322     IK_UnsetInit
323   };
324 
325 private:
326   const InitKind Kind;
327 
328 protected:
329   uint8_t Opc; // Used by UnOpInit, BinOpInit, and TernOpInit
330 
331 private:
332   virtual void anchor();
333 
334 public:
335   /// Get the kind (type) of the value.
336   InitKind getKind() const { return Kind; }
337 
338   /// Get the record keeper that initialized this Init.
339   RecordKeeper &getRecordKeeper() const;
340 
341 protected:
342   explicit Init(InitKind K, uint8_t Opc = 0) : Kind(K), Opc(Opc) {}
343 
344 public:
345   Init(const Init &) = delete;
346   Init &operator=(const Init &) = delete;
347   virtual ~Init() = default;
348 
349   /// Is this a complete value with no unset (uninitialized) subvalues?
350   virtual bool isComplete() const { return true; }
351 
352   /// Is this a concrete and fully resolved value without any references or
353   /// stuck operations? Unset values are concrete.
354   virtual bool isConcrete() const { return false; }
355 
356   /// Print this value.
357   void print(raw_ostream &OS) const { OS << getAsString(); }
358 
359   /// Convert this value to a literal form.
360   virtual std::string getAsString() const = 0;
361 
362   /// Convert this value to a literal form,
363   /// without adding quotes around a string.
364   virtual std::string getAsUnquotedString() const { return getAsString(); }
365 
366   /// Debugging method that may be called through a debugger; just
367   /// invokes print on stderr.
368   void dump() const;
369 
370   /// If this value is convertible to type \p Ty, return a value whose
371   /// type is \p Ty, generating a !cast operation if required.
372   /// Otherwise, return null.
373   virtual Init *getCastTo(RecTy *Ty) const = 0;
374 
375   /// Convert to a value whose type is \p Ty, or return null if this
376   /// is not possible. This can happen if the value's type is convertible
377   /// to \p Ty, but there are unresolved references.
378   virtual Init *convertInitializerTo(RecTy *Ty) const = 0;
379 
380   /// This function is used to implement the bit range
381   /// selection operator. Given a value, it selects the specified bits,
382   /// returning them as a new \p Init of type \p bits. If it is not legal
383   /// to use the bit selection operator on this value, null is returned.
384   virtual Init *convertInitializerBitRange(ArrayRef<unsigned> Bits) const {
385     return nullptr;
386   }
387 
388   /// This function is used to implement the list slice
389   /// selection operator.  Given a value, it selects the specified list
390   /// elements, returning them as a new \p Init of type \p list. If it
391   /// is not legal to use the slice operator, null is returned.
392   virtual Init *convertInitListSlice(ArrayRef<unsigned> Elements) const {
393     return nullptr;
394   }
395 
396   /// This function is used to implement the FieldInit class.
397   /// Implementors of this method should return the type of the named
398   /// field if they are of type record.
399   virtual RecTy *getFieldType(StringInit *FieldName) const {
400     return nullptr;
401   }
402 
403   /// This function is used by classes that refer to other
404   /// variables which may not be defined at the time the expression is formed.
405   /// If a value is set for the variable later, this method will be called on
406   /// users of the value to allow the value to propagate out.
407   virtual Init *resolveReferences(Resolver &R) const {
408     return const_cast<Init *>(this);
409   }
410 
411   /// Get the \p Init value of the specified bit.
412   virtual Init *getBit(unsigned Bit) const = 0;
413 };
414 
415 inline raw_ostream &operator<<(raw_ostream &OS, const Init &I) {
416   I.print(OS); return OS;
417 }
418 
419 /// This is the common superclass of types that have a specific,
420 /// explicit type, stored in ValueTy.
421 class TypedInit : public Init {
422   RecTy *ValueTy;
423 
424 protected:
425   explicit TypedInit(InitKind K, RecTy *T, uint8_t Opc = 0)
426       : Init(K, Opc), ValueTy(T) {}
427 
428 public:
429   TypedInit(const TypedInit &) = delete;
430   TypedInit &operator=(const TypedInit &) = delete;
431 
432   static bool classof(const Init *I) {
433     return I->getKind() >= IK_FirstTypedInit &&
434            I->getKind() <= IK_LastTypedInit;
435   }
436 
437   /// Get the type of the Init as a RecTy.
438   RecTy *getType() const { return ValueTy; }
439 
440   /// Get the record keeper that initialized this Init.
441   RecordKeeper &getRecordKeeper() const { return ValueTy->getRecordKeeper(); }
442 
443   Init *getCastTo(RecTy *Ty) const override;
444   Init *convertInitializerTo(RecTy *Ty) const override;
445 
446   Init *convertInitializerBitRange(ArrayRef<unsigned> Bits) const override;
447   Init *convertInitListSlice(ArrayRef<unsigned> Elements) const override;
448 
449   /// This method is used to implement the FieldInit class.
450   /// Implementors of this method should return the type of the named field if
451   /// they are of type record.
452   RecTy *getFieldType(StringInit *FieldName) const override;
453 };
454 
455 /// '?' - Represents an uninitialized value.
456 class UnsetInit : public Init {
457   friend detail::RecordKeeperImpl;
458 
459   /// The record keeper that initialized this Init.
460   RecordKeeper &RK;
461 
462   UnsetInit(RecordKeeper &RK) : Init(IK_UnsetInit), RK(RK) {}
463 
464 public:
465   UnsetInit(const UnsetInit &) = delete;
466   UnsetInit &operator=(const UnsetInit &) = delete;
467 
468   static bool classof(const Init *I) {
469     return I->getKind() == IK_UnsetInit;
470   }
471 
472   /// Get the singleton unset Init.
473   static UnsetInit *get(RecordKeeper &RK);
474 
475   /// Get the record keeper that initialized this Init.
476   RecordKeeper &getRecordKeeper() const { return RK; }
477 
478   Init *getCastTo(RecTy *Ty) const override;
479   Init *convertInitializerTo(RecTy *Ty) const override;
480 
481   Init *getBit(unsigned Bit) const override {
482     return const_cast<UnsetInit*>(this);
483   }
484 
485   /// Is this a complete value with no unset (uninitialized) subvalues?
486   bool isComplete() const override { return false; }
487 
488   bool isConcrete() const override { return true; }
489 
490   /// Get the string representation of the Init.
491   std::string getAsString() const override { return "?"; }
492 };
493 
494 /// 'true'/'false' - Represent a concrete initializer for a bit.
495 class BitInit final : public TypedInit {
496   friend detail::RecordKeeperImpl;
497 
498   bool Value;
499 
500   explicit BitInit(bool V, RecTy *T) : TypedInit(IK_BitInit, T), Value(V) {}
501 
502 public:
503   BitInit(const BitInit &) = delete;
504   BitInit &operator=(BitInit &) = delete;
505 
506   static bool classof(const Init *I) {
507     return I->getKind() == IK_BitInit;
508   }
509 
510   static BitInit *get(RecordKeeper &RK, bool V);
511 
512   bool getValue() const { return Value; }
513 
514   Init *convertInitializerTo(RecTy *Ty) const override;
515 
516   Init *getBit(unsigned Bit) const override {
517     assert(Bit < 1 && "Bit index out of range!");
518     return const_cast<BitInit*>(this);
519   }
520 
521   bool isConcrete() const override { return true; }
522   std::string getAsString() const override { return Value ? "1" : "0"; }
523 };
524 
525 /// '{ a, b, c }' - Represents an initializer for a BitsRecTy value.
526 /// It contains a vector of bits, whose size is determined by the type.
527 class BitsInit final : public TypedInit, public FoldingSetNode,
528                        public TrailingObjects<BitsInit, Init *> {
529   unsigned NumBits;
530 
531   BitsInit(RecordKeeper &RK, unsigned N)
532       : TypedInit(IK_BitsInit, BitsRecTy::get(RK, N)), NumBits(N) {}
533 
534 public:
535   BitsInit(const BitsInit &) = delete;
536   BitsInit &operator=(const BitsInit &) = delete;
537 
538   // Do not use sized deallocation due to trailing objects.
539   void operator delete(void *p) { ::operator delete(p); }
540 
541   static bool classof(const Init *I) {
542     return I->getKind() == IK_BitsInit;
543   }
544 
545   static BitsInit *get(RecordKeeper &RK, ArrayRef<Init *> Range);
546 
547   void Profile(FoldingSetNodeID &ID) const;
548 
549   unsigned getNumBits() const { return NumBits; }
550 
551   Init *convertInitializerTo(RecTy *Ty) const override;
552   Init *convertInitializerBitRange(ArrayRef<unsigned> Bits) const override;
553 
554   bool isComplete() const override {
555     for (unsigned i = 0; i != getNumBits(); ++i)
556       if (!getBit(i)->isComplete()) return false;
557     return true;
558   }
559 
560   bool allInComplete() const {
561     for (unsigned i = 0; i != getNumBits(); ++i)
562       if (getBit(i)->isComplete()) return false;
563     return true;
564   }
565 
566   bool isConcrete() const override;
567   std::string getAsString() const override;
568 
569   Init *resolveReferences(Resolver &R) const override;
570 
571   Init *getBit(unsigned Bit) const override {
572     assert(Bit < NumBits && "Bit index out of range!");
573     return getTrailingObjects<Init *>()[Bit];
574   }
575 };
576 
577 /// '7' - Represent an initialization by a literal integer value.
578 class IntInit : public TypedInit {
579   int64_t Value;
580 
581   explicit IntInit(RecordKeeper &RK, int64_t V)
582       : TypedInit(IK_IntInit, IntRecTy::get(RK)), Value(V) {}
583 
584 public:
585   IntInit(const IntInit &) = delete;
586   IntInit &operator=(const IntInit &) = delete;
587 
588   static bool classof(const Init *I) {
589     return I->getKind() == IK_IntInit;
590   }
591 
592   static IntInit *get(RecordKeeper &RK, int64_t V);
593 
594   int64_t getValue() const { return Value; }
595 
596   Init *convertInitializerTo(RecTy *Ty) const override;
597   Init *convertInitializerBitRange(ArrayRef<unsigned> Bits) const override;
598 
599   bool isConcrete() const override { return true; }
600   std::string getAsString() const override;
601 
602   Init *getBit(unsigned Bit) const override {
603     return BitInit::get(getRecordKeeper(), (Value & (1ULL << Bit)) != 0);
604   }
605 };
606 
607 /// "anonymous_n" - Represent an anonymous record name
608 class AnonymousNameInit : public TypedInit {
609   unsigned Value;
610 
611   explicit AnonymousNameInit(RecordKeeper &RK, unsigned V)
612       : TypedInit(IK_AnonymousNameInit, StringRecTy::get(RK)), Value(V) {}
613 
614 public:
615   AnonymousNameInit(const AnonymousNameInit &) = delete;
616   AnonymousNameInit &operator=(const AnonymousNameInit &) = delete;
617 
618   static bool classof(const Init *I) {
619     return I->getKind() == IK_AnonymousNameInit;
620   }
621 
622   static AnonymousNameInit *get(RecordKeeper &RK, unsigned);
623 
624   unsigned getValue() const { return Value; }
625 
626   StringInit *getNameInit() const;
627 
628   std::string getAsString() const override;
629 
630   Init *resolveReferences(Resolver &R) const override;
631 
632   Init *getBit(unsigned Bit) const override {
633     llvm_unreachable("Illegal bit reference off string");
634   }
635 };
636 
637 /// "foo" - Represent an initialization by a string value.
638 class StringInit : public TypedInit {
639 public:
640   enum StringFormat {
641     SF_String, // Format as "text"
642     SF_Code,   // Format as [{text}]
643   };
644 
645 private:
646   StringRef Value;
647   StringFormat Format;
648 
649   explicit StringInit(RecordKeeper &RK, StringRef V, StringFormat Fmt)
650       : TypedInit(IK_StringInit, StringRecTy::get(RK)), Value(V), Format(Fmt) {}
651 
652 public:
653   StringInit(const StringInit &) = delete;
654   StringInit &operator=(const StringInit &) = delete;
655 
656   static bool classof(const Init *I) {
657     return I->getKind() == IK_StringInit;
658   }
659 
660   static StringInit *get(RecordKeeper &RK, StringRef,
661                          StringFormat Fmt = SF_String);
662 
663   static StringFormat determineFormat(StringFormat Fmt1, StringFormat Fmt2) {
664     return (Fmt1 == SF_Code || Fmt2 == SF_Code) ? SF_Code : SF_String;
665   }
666 
667   StringRef getValue() const { return Value; }
668   StringFormat getFormat() const { return Format; }
669   bool hasCodeFormat() const { return Format == SF_Code; }
670 
671   Init *convertInitializerTo(RecTy *Ty) const override;
672 
673   bool isConcrete() const override { return true; }
674 
675   std::string getAsString() const override {
676     if (Format == SF_String)
677       return "\"" + Value.str() + "\"";
678     else
679       return "[{" + Value.str() + "}]";
680   }
681 
682   std::string getAsUnquotedString() const override {
683     return std::string(Value);
684   }
685 
686   Init *getBit(unsigned Bit) const override {
687     llvm_unreachable("Illegal bit reference off string");
688   }
689 };
690 
691 /// [AL, AH, CL] - Represent a list of defs
692 ///
693 class ListInit final : public TypedInit, public FoldingSetNode,
694                        public TrailingObjects<ListInit, Init *> {
695   unsigned NumValues;
696 
697 public:
698   using const_iterator = Init *const *;
699 
700 private:
701   explicit ListInit(unsigned N, RecTy *EltTy)
702       : TypedInit(IK_ListInit, ListRecTy::get(EltTy)), NumValues(N) {}
703 
704 public:
705   ListInit(const ListInit &) = delete;
706   ListInit &operator=(const ListInit &) = delete;
707 
708   // Do not use sized deallocation due to trailing objects.
709   void operator delete(void *p) { ::operator delete(p); }
710 
711   static bool classof(const Init *I) {
712     return I->getKind() == IK_ListInit;
713   }
714   static ListInit *get(ArrayRef<Init *> Range, RecTy *EltTy);
715 
716   void Profile(FoldingSetNodeID &ID) const;
717 
718   Init *getElement(unsigned i) const {
719     assert(i < NumValues && "List element index out of range!");
720     return getTrailingObjects<Init *>()[i];
721   }
722   RecTy *getElementType() const {
723     return cast<ListRecTy>(getType())->getElementType();
724   }
725 
726   Record *getElementAsRecord(unsigned i) const;
727 
728   Init *convertInitListSlice(ArrayRef<unsigned> Elements) const override;
729 
730   Init *convertInitializerTo(RecTy *Ty) const override;
731 
732   /// This method is used by classes that refer to other
733   /// variables which may not be defined at the time they expression is formed.
734   /// If a value is set for the variable later, this method will be called on
735   /// users of the value to allow the value to propagate out.
736   ///
737   Init *resolveReferences(Resolver &R) const override;
738 
739   bool isComplete() const override;
740   bool isConcrete() const override;
741   std::string getAsString() const override;
742 
743   ArrayRef<Init*> getValues() const {
744     return makeArrayRef(getTrailingObjects<Init *>(), NumValues);
745   }
746 
747   const_iterator begin() const { return getTrailingObjects<Init *>(); }
748   const_iterator end  () const { return begin() + NumValues; }
749 
750   size_t         size () const { return NumValues;  }
751   bool           empty() const { return NumValues == 0; }
752 
753   Init *getBit(unsigned Bit) const override {
754     llvm_unreachable("Illegal bit reference off list");
755   }
756 };
757 
758 /// Base class for operators
759 ///
760 class OpInit : public TypedInit {
761 protected:
762   explicit OpInit(InitKind K, RecTy *Type, uint8_t Opc)
763     : TypedInit(K, Type, Opc) {}
764 
765 public:
766   OpInit(const OpInit &) = delete;
767   OpInit &operator=(OpInit &) = delete;
768 
769   static bool classof(const Init *I) {
770     return I->getKind() >= IK_FirstOpInit &&
771            I->getKind() <= IK_LastOpInit;
772   }
773 
774   // Clone - Clone this operator, replacing arguments with the new list
775   virtual OpInit *clone(ArrayRef<Init *> Operands) const = 0;
776 
777   virtual unsigned getNumOperands() const = 0;
778   virtual Init *getOperand(unsigned i) const = 0;
779 
780   Init *getBit(unsigned Bit) const override;
781 };
782 
783 /// !op (X) - Transform an init.
784 ///
785 class UnOpInit : public OpInit, public FoldingSetNode {
786 public:
787   enum UnaryOp : uint8_t { CAST, NOT, HEAD, TAIL, SIZE, EMPTY, GETDAGOP };
788 
789 private:
790   Init *LHS;
791 
792   UnOpInit(UnaryOp opc, Init *lhs, RecTy *Type)
793     : OpInit(IK_UnOpInit, Type, opc), LHS(lhs) {}
794 
795 public:
796   UnOpInit(const UnOpInit &) = delete;
797   UnOpInit &operator=(const UnOpInit &) = delete;
798 
799   static bool classof(const Init *I) {
800     return I->getKind() == IK_UnOpInit;
801   }
802 
803   static UnOpInit *get(UnaryOp opc, Init *lhs, RecTy *Type);
804 
805   void Profile(FoldingSetNodeID &ID) const;
806 
807   // Clone - Clone this operator, replacing arguments with the new list
808   OpInit *clone(ArrayRef<Init *> Operands) const override {
809     assert(Operands.size() == 1 &&
810            "Wrong number of operands for unary operation");
811     return UnOpInit::get(getOpcode(), *Operands.begin(), getType());
812   }
813 
814   unsigned getNumOperands() const override { return 1; }
815 
816   Init *getOperand(unsigned i) const override {
817     assert(i == 0 && "Invalid operand id for unary operator");
818     return getOperand();
819   }
820 
821   UnaryOp getOpcode() const { return (UnaryOp)Opc; }
822   Init *getOperand() const { return LHS; }
823 
824   // Fold - If possible, fold this to a simpler init.  Return this if not
825   // possible to fold.
826   Init *Fold(Record *CurRec, bool IsFinal = false) const;
827 
828   Init *resolveReferences(Resolver &R) const override;
829 
830   std::string getAsString() const override;
831 };
832 
833 /// !op (X, Y) - Combine two inits.
834 class BinOpInit : public OpInit, public FoldingSetNode {
835 public:
836   enum BinaryOp : uint8_t { ADD, SUB, MUL, AND, OR, XOR, SHL, SRA, SRL, LISTCONCAT,
837                             LISTSPLAT, STRCONCAT, INTERLEAVE, CONCAT, EQ,
838                             NE, LE, LT, GE, GT, SETDAGOP };
839 
840 private:
841   Init *LHS, *RHS;
842 
843   BinOpInit(BinaryOp opc, Init *lhs, Init *rhs, RecTy *Type) :
844       OpInit(IK_BinOpInit, Type, opc), LHS(lhs), RHS(rhs) {}
845 
846 public:
847   BinOpInit(const BinOpInit &) = delete;
848   BinOpInit &operator=(const BinOpInit &) = delete;
849 
850   static bool classof(const Init *I) {
851     return I->getKind() == IK_BinOpInit;
852   }
853 
854   static BinOpInit *get(BinaryOp opc, Init *lhs, Init *rhs,
855                         RecTy *Type);
856   static Init *getStrConcat(Init *lhs, Init *rhs);
857   static Init *getListConcat(TypedInit *lhs, Init *rhs);
858 
859   void Profile(FoldingSetNodeID &ID) const;
860 
861   // Clone - Clone this operator, replacing arguments with the new list
862   OpInit *clone(ArrayRef<Init *> Operands) const override {
863     assert(Operands.size() == 2 &&
864            "Wrong number of operands for binary operation");
865     return BinOpInit::get(getOpcode(), Operands[0], Operands[1], getType());
866   }
867 
868   unsigned getNumOperands() const override { return 2; }
869   Init *getOperand(unsigned i) const override {
870     switch (i) {
871     default: llvm_unreachable("Invalid operand id for binary operator");
872     case 0: return getLHS();
873     case 1: return getRHS();
874     }
875   }
876 
877   BinaryOp getOpcode() const { return (BinaryOp)Opc; }
878   Init *getLHS() const { return LHS; }
879   Init *getRHS() const { return RHS; }
880 
881   // Fold - If possible, fold this to a simpler init.  Return this if not
882   // possible to fold.
883   Init *Fold(Record *CurRec) const;
884 
885   Init *resolveReferences(Resolver &R) const override;
886 
887   std::string getAsString() const override;
888 };
889 
890 /// !op (X, Y, Z) - Combine two inits.
891 class TernOpInit : public OpInit, public FoldingSetNode {
892 public:
893   enum TernaryOp : uint8_t { SUBST, FOREACH, FILTER, IF, DAG, SUBSTR, FIND };
894 
895 private:
896   Init *LHS, *MHS, *RHS;
897 
898   TernOpInit(TernaryOp opc, Init *lhs, Init *mhs, Init *rhs,
899              RecTy *Type) :
900       OpInit(IK_TernOpInit, Type, opc), LHS(lhs), MHS(mhs), RHS(rhs) {}
901 
902 public:
903   TernOpInit(const TernOpInit &) = delete;
904   TernOpInit &operator=(const TernOpInit &) = delete;
905 
906   static bool classof(const Init *I) {
907     return I->getKind() == IK_TernOpInit;
908   }
909 
910   static TernOpInit *get(TernaryOp opc, Init *lhs,
911                          Init *mhs, Init *rhs,
912                          RecTy *Type);
913 
914   void Profile(FoldingSetNodeID &ID) const;
915 
916   // Clone - Clone this operator, replacing arguments with the new list
917   OpInit *clone(ArrayRef<Init *> Operands) const override {
918     assert(Operands.size() == 3 &&
919            "Wrong number of operands for ternary operation");
920     return TernOpInit::get(getOpcode(), Operands[0], Operands[1], Operands[2],
921                            getType());
922   }
923 
924   unsigned getNumOperands() const override { return 3; }
925   Init *getOperand(unsigned i) const override {
926     switch (i) {
927     default: llvm_unreachable("Invalid operand id for ternary operator");
928     case 0: return getLHS();
929     case 1: return getMHS();
930     case 2: return getRHS();
931     }
932   }
933 
934   TernaryOp getOpcode() const { return (TernaryOp)Opc; }
935   Init *getLHS() const { return LHS; }
936   Init *getMHS() const { return MHS; }
937   Init *getRHS() const { return RHS; }
938 
939   // Fold - If possible, fold this to a simpler init.  Return this if not
940   // possible to fold.
941   Init *Fold(Record *CurRec) const;
942 
943   bool isComplete() const override {
944     return LHS->isComplete() && MHS->isComplete() && RHS->isComplete();
945   }
946 
947   Init *resolveReferences(Resolver &R) const override;
948 
949   std::string getAsString() const override;
950 };
951 
952 /// !cond(condition_1: value1, ... , condition_n: value)
953 /// Selects the first value for which condition is true.
954 /// Otherwise reports an error.
955 class CondOpInit final : public TypedInit, public FoldingSetNode,
956                       public TrailingObjects<CondOpInit, Init *> {
957   unsigned NumConds;
958   RecTy *ValType;
959 
960   CondOpInit(unsigned NC, RecTy *Type)
961     : TypedInit(IK_CondOpInit, Type),
962       NumConds(NC), ValType(Type) {}
963 
964   size_t numTrailingObjects(OverloadToken<Init *>) const {
965     return 2*NumConds;
966   }
967 
968 public:
969   CondOpInit(const CondOpInit &) = delete;
970   CondOpInit &operator=(const CondOpInit &) = delete;
971 
972   static bool classof(const Init *I) {
973     return I->getKind() == IK_CondOpInit;
974   }
975 
976   static CondOpInit *get(ArrayRef<Init*> C, ArrayRef<Init*> V,
977                         RecTy *Type);
978 
979   void Profile(FoldingSetNodeID &ID) const;
980 
981   RecTy *getValType() const { return ValType; }
982 
983   unsigned getNumConds() const { return NumConds; }
984 
985   Init *getCond(unsigned Num) const {
986     assert(Num < NumConds && "Condition number out of range!");
987     return getTrailingObjects<Init *>()[Num];
988   }
989 
990   Init *getVal(unsigned Num) const {
991     assert(Num < NumConds && "Val number out of range!");
992     return getTrailingObjects<Init *>()[Num+NumConds];
993   }
994 
995   ArrayRef<Init *> getConds() const {
996     return makeArrayRef(getTrailingObjects<Init *>(), NumConds);
997   }
998 
999   ArrayRef<Init *> getVals() const {
1000     return makeArrayRef(getTrailingObjects<Init *>()+NumConds, NumConds);
1001   }
1002 
1003   Init *Fold(Record *CurRec) const;
1004 
1005   Init *resolveReferences(Resolver &R) const override;
1006 
1007   bool isConcrete() const override;
1008   bool isComplete() const override;
1009   std::string getAsString() const override;
1010 
1011   using const_case_iterator = SmallVectorImpl<Init*>::const_iterator;
1012   using const_val_iterator = SmallVectorImpl<Init*>::const_iterator;
1013 
1014   inline const_case_iterator  arg_begin() const { return getConds().begin(); }
1015   inline const_case_iterator  arg_end  () const { return getConds().end(); }
1016 
1017   inline size_t              case_size () const { return NumConds; }
1018   inline bool                case_empty() const { return NumConds == 0; }
1019 
1020   inline const_val_iterator name_begin() const { return getVals().begin();}
1021   inline const_val_iterator name_end  () const { return getVals().end(); }
1022 
1023   inline size_t              val_size () const { return NumConds; }
1024   inline bool                val_empty() const { return NumConds == 0; }
1025 
1026   Init *getBit(unsigned Bit) const override;
1027 };
1028 
1029 /// !foldl (a, b, expr, start, lst) - Fold over a list.
1030 class FoldOpInit : public TypedInit, public FoldingSetNode {
1031 private:
1032   Init *Start;
1033   Init *List;
1034   Init *A;
1035   Init *B;
1036   Init *Expr;
1037 
1038   FoldOpInit(Init *Start, Init *List, Init *A, Init *B, Init *Expr, RecTy *Type)
1039       : TypedInit(IK_FoldOpInit, Type), Start(Start), List(List), A(A), B(B),
1040         Expr(Expr) {}
1041 
1042 public:
1043   FoldOpInit(const FoldOpInit &) = delete;
1044   FoldOpInit &operator=(const FoldOpInit &) = delete;
1045 
1046   static bool classof(const Init *I) { return I->getKind() == IK_FoldOpInit; }
1047 
1048   static FoldOpInit *get(Init *Start, Init *List, Init *A, Init *B, Init *Expr,
1049                          RecTy *Type);
1050 
1051   void Profile(FoldingSetNodeID &ID) const;
1052 
1053   // Fold - If possible, fold this to a simpler init.  Return this if not
1054   // possible to fold.
1055   Init *Fold(Record *CurRec) const;
1056 
1057   bool isComplete() const override { return false; }
1058 
1059   Init *resolveReferences(Resolver &R) const override;
1060 
1061   Init *getBit(unsigned Bit) const override;
1062 
1063   std::string getAsString() const override;
1064 };
1065 
1066 /// !isa<type>(expr) - Dynamically determine the type of an expression.
1067 class IsAOpInit : public TypedInit, public FoldingSetNode {
1068 private:
1069   RecTy *CheckType;
1070   Init *Expr;
1071 
1072   IsAOpInit(RecTy *CheckType, Init *Expr)
1073       : TypedInit(IK_IsAOpInit, IntRecTy::get(CheckType->getRecordKeeper())),
1074         CheckType(CheckType), Expr(Expr) {}
1075 
1076 public:
1077   IsAOpInit(const IsAOpInit &) = delete;
1078   IsAOpInit &operator=(const IsAOpInit &) = delete;
1079 
1080   static bool classof(const Init *I) { return I->getKind() == IK_IsAOpInit; }
1081 
1082   static IsAOpInit *get(RecTy *CheckType, Init *Expr);
1083 
1084   void Profile(FoldingSetNodeID &ID) const;
1085 
1086   // Fold - If possible, fold this to a simpler init.  Return this if not
1087   // possible to fold.
1088   Init *Fold() const;
1089 
1090   bool isComplete() const override { return false; }
1091 
1092   Init *resolveReferences(Resolver &R) const override;
1093 
1094   Init *getBit(unsigned Bit) const override;
1095 
1096   std::string getAsString() const override;
1097 };
1098 
1099 /// !exists<type>(expr) - Dynamically determine if a record of `type` named
1100 /// `expr` exists.
1101 class ExistsOpInit : public TypedInit, public FoldingSetNode {
1102 private:
1103   RecTy *CheckType;
1104   Init *Expr;
1105 
1106   ExistsOpInit(RecTy *CheckType, Init *Expr)
1107       : TypedInit(IK_ExistsOpInit, IntRecTy::get(CheckType->getRecordKeeper())),
1108         CheckType(CheckType), Expr(Expr) {}
1109 
1110 public:
1111   ExistsOpInit(const ExistsOpInit &) = delete;
1112   ExistsOpInit &operator=(const ExistsOpInit &) = delete;
1113 
1114   static bool classof(const Init *I) { return I->getKind() == IK_ExistsOpInit; }
1115 
1116   static ExistsOpInit *get(RecTy *CheckType, Init *Expr);
1117 
1118   void Profile(FoldingSetNodeID &ID) const;
1119 
1120   // Fold - If possible, fold this to a simpler init.  Return this if not
1121   // possible to fold.
1122   Init *Fold(Record *CurRec, bool IsFinal = false) const;
1123 
1124   bool isComplete() const override { return false; }
1125 
1126   Init *resolveReferences(Resolver &R) const override;
1127 
1128   Init *getBit(unsigned Bit) const override;
1129 
1130   std::string getAsString() const override;
1131 };
1132 
1133 /// 'Opcode' - Represent a reference to an entire variable object.
1134 class VarInit : public TypedInit {
1135   Init *VarName;
1136 
1137   explicit VarInit(Init *VN, RecTy *T)
1138       : TypedInit(IK_VarInit, T), VarName(VN) {}
1139 
1140 public:
1141   VarInit(const VarInit &) = delete;
1142   VarInit &operator=(const VarInit &) = delete;
1143 
1144   static bool classof(const Init *I) {
1145     return I->getKind() == IK_VarInit;
1146   }
1147 
1148   static VarInit *get(StringRef VN, RecTy *T);
1149   static VarInit *get(Init *VN, RecTy *T);
1150 
1151   StringRef getName() const;
1152   Init *getNameInit() const { return VarName; }
1153 
1154   std::string getNameInitAsString() const {
1155     return getNameInit()->getAsUnquotedString();
1156   }
1157 
1158   /// This method is used by classes that refer to other
1159   /// variables which may not be defined at the time they expression is formed.
1160   /// If a value is set for the variable later, this method will be called on
1161   /// users of the value to allow the value to propagate out.
1162   ///
1163   Init *resolveReferences(Resolver &R) const override;
1164 
1165   Init *getBit(unsigned Bit) const override;
1166 
1167   std::string getAsString() const override { return std::string(getName()); }
1168 };
1169 
1170 /// Opcode{0} - Represent access to one bit of a variable or field.
1171 class VarBitInit final : public TypedInit {
1172   TypedInit *TI;
1173   unsigned Bit;
1174 
1175   VarBitInit(TypedInit *T, unsigned B)
1176       : TypedInit(IK_VarBitInit, BitRecTy::get(T->getRecordKeeper())), TI(T),
1177         Bit(B) {
1178     assert(T->getType() &&
1179            (isa<IntRecTy>(T->getType()) ||
1180             (isa<BitsRecTy>(T->getType()) &&
1181              cast<BitsRecTy>(T->getType())->getNumBits() > B)) &&
1182            "Illegal VarBitInit expression!");
1183   }
1184 
1185 public:
1186   VarBitInit(const VarBitInit &) = delete;
1187   VarBitInit &operator=(const VarBitInit &) = delete;
1188 
1189   static bool classof(const Init *I) {
1190     return I->getKind() == IK_VarBitInit;
1191   }
1192 
1193   static VarBitInit *get(TypedInit *T, unsigned B);
1194 
1195   Init *getBitVar() const { return TI; }
1196   unsigned getBitNum() const { return Bit; }
1197 
1198   std::string getAsString() const override;
1199   Init *resolveReferences(Resolver &R) const override;
1200 
1201   Init *getBit(unsigned B) const override {
1202     assert(B < 1 && "Bit index out of range!");
1203     return const_cast<VarBitInit*>(this);
1204   }
1205 };
1206 
1207 /// List[4] - Represent access to one element of a var or
1208 /// field.
1209 class VarListElementInit : public TypedInit {
1210   TypedInit *TI;
1211   unsigned Element;
1212 
1213   VarListElementInit(TypedInit *T, unsigned E)
1214       : TypedInit(IK_VarListElementInit,
1215                   cast<ListRecTy>(T->getType())->getElementType()),
1216         TI(T), Element(E) {
1217     assert(T->getType() && isa<ListRecTy>(T->getType()) &&
1218            "Illegal VarBitInit expression!");
1219   }
1220 
1221 public:
1222   VarListElementInit(const VarListElementInit &) = delete;
1223   VarListElementInit &operator=(const VarListElementInit &) = delete;
1224 
1225   static bool classof(const Init *I) {
1226     return I->getKind() == IK_VarListElementInit;
1227   }
1228 
1229   static VarListElementInit *get(TypedInit *T, unsigned E);
1230 
1231   TypedInit *getVariable() const { return TI; }
1232   unsigned getElementNum() const { return Element; }
1233 
1234   std::string getAsString() const override;
1235   Init *resolveReferences(Resolver &R) const override;
1236 
1237   Init *getBit(unsigned Bit) const override;
1238 };
1239 
1240 /// AL - Represent a reference to a 'def' in the description
1241 class DefInit : public TypedInit {
1242   friend class Record;
1243 
1244   Record *Def;
1245 
1246   explicit DefInit(Record *D);
1247 
1248 public:
1249   DefInit(const DefInit &) = delete;
1250   DefInit &operator=(const DefInit &) = delete;
1251 
1252   static bool classof(const Init *I) {
1253     return I->getKind() == IK_DefInit;
1254   }
1255 
1256   static DefInit *get(Record*);
1257 
1258   Init *convertInitializerTo(RecTy *Ty) const override;
1259 
1260   Record *getDef() const { return Def; }
1261 
1262   //virtual Init *convertInitializerBitRange(ArrayRef<unsigned> Bits);
1263 
1264   RecTy *getFieldType(StringInit *FieldName) const override;
1265 
1266   bool isConcrete() const override { return true; }
1267   std::string getAsString() const override;
1268 
1269   Init *getBit(unsigned Bit) const override {
1270     llvm_unreachable("Illegal bit reference off def");
1271   }
1272 };
1273 
1274 /// classname<targs...> - Represent an uninstantiated anonymous class
1275 /// instantiation.
1276 class VarDefInit final : public TypedInit, public FoldingSetNode,
1277                          public TrailingObjects<VarDefInit, Init *> {
1278   Record *Class;
1279   DefInit *Def = nullptr; // after instantiation
1280   unsigned NumArgs;
1281 
1282   explicit VarDefInit(Record *Class, unsigned N);
1283 
1284   DefInit *instantiate();
1285 
1286 public:
1287   VarDefInit(const VarDefInit &) = delete;
1288   VarDefInit &operator=(const VarDefInit &) = delete;
1289 
1290   // Do not use sized deallocation due to trailing objects.
1291   void operator delete(void *p) { ::operator delete(p); }
1292 
1293   static bool classof(const Init *I) {
1294     return I->getKind() == IK_VarDefInit;
1295   }
1296   static VarDefInit *get(Record *Class, ArrayRef<Init *> Args);
1297 
1298   void Profile(FoldingSetNodeID &ID) const;
1299 
1300   Init *resolveReferences(Resolver &R) const override;
1301   Init *Fold() const;
1302 
1303   std::string getAsString() const override;
1304 
1305   Init *getArg(unsigned i) const {
1306     assert(i < NumArgs && "Argument index out of range!");
1307     return getTrailingObjects<Init *>()[i];
1308   }
1309 
1310   using const_iterator = Init *const *;
1311 
1312   const_iterator args_begin() const { return getTrailingObjects<Init *>(); }
1313   const_iterator args_end  () const { return args_begin() + NumArgs; }
1314 
1315   size_t         args_size () const { return NumArgs; }
1316   bool           args_empty() const { return NumArgs == 0; }
1317 
1318   ArrayRef<Init *> args() const { return makeArrayRef(args_begin(), NumArgs); }
1319 
1320   Init *getBit(unsigned Bit) const override {
1321     llvm_unreachable("Illegal bit reference off anonymous def");
1322   }
1323 };
1324 
1325 /// X.Y - Represent a reference to a subfield of a variable
1326 class FieldInit : public TypedInit {
1327   Init *Rec;                // Record we are referring to
1328   StringInit *FieldName;    // Field we are accessing
1329 
1330   FieldInit(Init *R, StringInit *FN)
1331       : TypedInit(IK_FieldInit, R->getFieldType(FN)), Rec(R), FieldName(FN) {
1332 #ifndef NDEBUG
1333     if (!getType()) {
1334       llvm::errs() << "In Record = " << Rec->getAsString()
1335                    << ", got FieldName = " << *FieldName
1336                    << " with non-record type!\n";
1337       llvm_unreachable("FieldInit with non-record type!");
1338     }
1339 #endif
1340   }
1341 
1342 public:
1343   FieldInit(const FieldInit &) = delete;
1344   FieldInit &operator=(const FieldInit &) = delete;
1345 
1346   static bool classof(const Init *I) {
1347     return I->getKind() == IK_FieldInit;
1348   }
1349 
1350   static FieldInit *get(Init *R, StringInit *FN);
1351 
1352   Init *getRecord() const { return Rec; }
1353   StringInit *getFieldName() const { return FieldName; }
1354 
1355   Init *getBit(unsigned Bit) const override;
1356 
1357   Init *resolveReferences(Resolver &R) const override;
1358   Init *Fold(Record *CurRec) const;
1359 
1360   bool isConcrete() const override;
1361   std::string getAsString() const override {
1362     return Rec->getAsString() + "." + FieldName->getValue().str();
1363   }
1364 };
1365 
1366 /// (v a, b) - Represent a DAG tree value.  DAG inits are required
1367 /// to have at least one value then a (possibly empty) list of arguments.  Each
1368 /// argument can have a name associated with it.
1369 class DagInit final : public TypedInit, public FoldingSetNode,
1370                       public TrailingObjects<DagInit, Init *, StringInit *> {
1371   friend TrailingObjects;
1372 
1373   Init *Val;
1374   StringInit *ValName;
1375   unsigned NumArgs;
1376   unsigned NumArgNames;
1377 
1378   DagInit(Init *V, StringInit *VN, unsigned NumArgs, unsigned NumArgNames)
1379       : TypedInit(IK_DagInit, DagRecTy::get(V->getRecordKeeper())), Val(V),
1380         ValName(VN), NumArgs(NumArgs), NumArgNames(NumArgNames) {}
1381 
1382   size_t numTrailingObjects(OverloadToken<Init *>) const { return NumArgs; }
1383 
1384 public:
1385   DagInit(const DagInit &) = delete;
1386   DagInit &operator=(const DagInit &) = delete;
1387 
1388   static bool classof(const Init *I) {
1389     return I->getKind() == IK_DagInit;
1390   }
1391 
1392   static DagInit *get(Init *V, StringInit *VN, ArrayRef<Init *> ArgRange,
1393                       ArrayRef<StringInit*> NameRange);
1394   static DagInit *get(Init *V, StringInit *VN,
1395                       ArrayRef<std::pair<Init*, StringInit*>> Args);
1396 
1397   void Profile(FoldingSetNodeID &ID) const;
1398 
1399   Init *getOperator() const { return Val; }
1400   Record *getOperatorAsDef(ArrayRef<SMLoc> Loc) const;
1401 
1402   StringInit *getName() const { return ValName; }
1403 
1404   StringRef getNameStr() const {
1405     return ValName ? ValName->getValue() : StringRef();
1406   }
1407 
1408   unsigned getNumArgs() const { return NumArgs; }
1409 
1410   Init *getArg(unsigned Num) const {
1411     assert(Num < NumArgs && "Arg number out of range!");
1412     return getTrailingObjects<Init *>()[Num];
1413   }
1414 
1415   StringInit *getArgName(unsigned Num) const {
1416     assert(Num < NumArgNames && "Arg number out of range!");
1417     return getTrailingObjects<StringInit *>()[Num];
1418   }
1419 
1420   StringRef getArgNameStr(unsigned Num) const {
1421     StringInit *Init = getArgName(Num);
1422     return Init ? Init->getValue() : StringRef();
1423   }
1424 
1425   ArrayRef<Init *> getArgs() const {
1426     return makeArrayRef(getTrailingObjects<Init *>(), NumArgs);
1427   }
1428 
1429   ArrayRef<StringInit *> getArgNames() const {
1430     return makeArrayRef(getTrailingObjects<StringInit *>(), NumArgNames);
1431   }
1432 
1433   Init *resolveReferences(Resolver &R) const override;
1434 
1435   bool isConcrete() const override;
1436   std::string getAsString() const override;
1437 
1438   using const_arg_iterator = SmallVectorImpl<Init*>::const_iterator;
1439   using const_name_iterator = SmallVectorImpl<StringInit*>::const_iterator;
1440 
1441   inline const_arg_iterator  arg_begin() const { return getArgs().begin(); }
1442   inline const_arg_iterator  arg_end  () const { return getArgs().end(); }
1443 
1444   inline size_t              arg_size () const { return NumArgs; }
1445   inline bool                arg_empty() const { return NumArgs == 0; }
1446 
1447   inline const_name_iterator name_begin() const { return getArgNames().begin();}
1448   inline const_name_iterator name_end  () const { return getArgNames().end(); }
1449 
1450   inline size_t              name_size () const { return NumArgNames; }
1451   inline bool                name_empty() const { return NumArgNames == 0; }
1452 
1453   Init *getBit(unsigned Bit) const override {
1454     llvm_unreachable("Illegal bit reference off dag");
1455   }
1456 };
1457 
1458 //===----------------------------------------------------------------------===//
1459 //  High-Level Classes
1460 //===----------------------------------------------------------------------===//
1461 
1462 /// This class represents a field in a record, including its name, type,
1463 /// value, and source location.
1464 class RecordVal {
1465   friend class Record;
1466 
1467 public:
1468   enum FieldKind {
1469     FK_Normal,        // A normal record field.
1470     FK_NonconcreteOK, // A field that can be nonconcrete ('field' keyword).
1471     FK_TemplateArg,   // A template argument.
1472   };
1473 
1474 private:
1475   Init *Name;
1476   SMLoc Loc; // Source location of definition of name.
1477   PointerIntPair<RecTy *, 2, FieldKind> TyAndKind;
1478   Init *Value;
1479   bool IsUsed = false;
1480 
1481 public:
1482   RecordVal(Init *N, RecTy *T, FieldKind K);
1483   RecordVal(Init *N, SMLoc Loc, RecTy *T, FieldKind K);
1484 
1485   /// Get the record keeper used to unique this value.
1486   RecordKeeper &getRecordKeeper() const { return Name->getRecordKeeper(); }
1487 
1488   /// Get the name of the field as a StringRef.
1489   StringRef getName() const;
1490 
1491   /// Get the name of the field as an Init.
1492   Init *getNameInit() const { return Name; }
1493 
1494   /// Get the name of the field as a std::string.
1495   std::string getNameInitAsString() const {
1496     return getNameInit()->getAsUnquotedString();
1497   }
1498 
1499   /// Get the source location of the point where the field was defined.
1500   const SMLoc &getLoc() const { return Loc; }
1501 
1502   /// Is this a field where nonconcrete values are okay?
1503   bool isNonconcreteOK() const {
1504     return TyAndKind.getInt() == FK_NonconcreteOK;
1505   }
1506 
1507   /// Is this a template argument?
1508   bool isTemplateArg() const {
1509     return TyAndKind.getInt() == FK_TemplateArg;
1510   }
1511 
1512   /// Get the type of the field value as a RecTy.
1513   RecTy *getType() const { return TyAndKind.getPointer(); }
1514 
1515   /// Get the type of the field for printing purposes.
1516   std::string getPrintType() const;
1517 
1518   /// Get the value of the field as an Init.
1519   Init *getValue() const { return Value; }
1520 
1521   /// Set the value of the field from an Init.
1522   bool setValue(Init *V);
1523 
1524   /// Set the value and source location of the field.
1525   bool setValue(Init *V, SMLoc NewLoc);
1526 
1527   /// Whether this value is used. Useful for reporting warnings, for example
1528   /// when a template argument is unused.
1529   void setUsed(bool Used) { IsUsed = Used; }
1530   bool isUsed() const { return IsUsed; }
1531 
1532   void dump() const;
1533 
1534   /// Print the value to an output stream, possibly with a semicolon.
1535   void print(raw_ostream &OS, bool PrintSem = true) const;
1536 };
1537 
1538 inline raw_ostream &operator<<(raw_ostream &OS, const RecordVal &RV) {
1539   RV.print(OS << "  ");
1540   return OS;
1541 }
1542 
1543 class Record {
1544 public:
1545   struct AssertionInfo {
1546     SMLoc Loc;
1547     Init *Condition;
1548     Init *Message;
1549 
1550     // User-defined constructor to support std::make_unique(). It can be
1551     // removed in C++20 when braced initialization is supported.
1552     AssertionInfo(SMLoc Loc, Init *Condition, Init *Message)
1553         : Loc(Loc), Condition(Condition), Message(Message) {}
1554   };
1555 
1556 private:
1557   Init *Name;
1558   // Location where record was instantiated, followed by the location of
1559   // multiclass prototypes used.
1560   SmallVector<SMLoc, 4> Locs;
1561   SmallVector<SMLoc, 0> ForwardDeclarationLocs;
1562   SmallVector<Init *, 0> TemplateArgs;
1563   SmallVector<RecordVal, 0> Values;
1564   SmallVector<AssertionInfo, 0> Assertions;
1565 
1566   // All superclasses in the inheritance forest in post-order (yes, it
1567   // must be a forest; diamond-shaped inheritance is not allowed).
1568   SmallVector<std::pair<Record *, SMRange>, 0> SuperClasses;
1569 
1570   // Tracks Record instances. Not owned by Record.
1571   RecordKeeper &TrackedRecords;
1572 
1573   // The DefInit corresponding to this record.
1574   DefInit *CorrespondingDefInit = nullptr;
1575 
1576   // Unique record ID.
1577   unsigned ID;
1578 
1579   bool IsAnonymous;
1580   bool IsClass;
1581 
1582   void checkName();
1583 
1584 public:
1585   // Constructs a record.
1586   explicit Record(Init *N, ArrayRef<SMLoc> locs, RecordKeeper &records,
1587                   bool Anonymous = false, bool Class = false)
1588       : Name(N), Locs(locs.begin(), locs.end()), TrackedRecords(records),
1589         ID(getNewUID(N->getRecordKeeper())), IsAnonymous(Anonymous),
1590         IsClass(Class) {
1591     checkName();
1592   }
1593 
1594   explicit Record(StringRef N, ArrayRef<SMLoc> locs, RecordKeeper &records,
1595                   bool Class = false)
1596       : Record(StringInit::get(records, N), locs, records, false, Class) {}
1597 
1598   // When copy-constructing a Record, we must still guarantee a globally unique
1599   // ID number. Don't copy CorrespondingDefInit either, since it's owned by the
1600   // original record. All other fields can be copied normally.
1601   Record(const Record &O)
1602       : Name(O.Name), Locs(O.Locs), TemplateArgs(O.TemplateArgs),
1603         Values(O.Values), Assertions(O.Assertions),
1604         SuperClasses(O.SuperClasses), TrackedRecords(O.TrackedRecords),
1605         ID(getNewUID(O.getRecords())), IsAnonymous(O.IsAnonymous),
1606         IsClass(O.IsClass) {}
1607 
1608   static unsigned getNewUID(RecordKeeper &RK);
1609 
1610   unsigned getID() const { return ID; }
1611 
1612   StringRef getName() const { return cast<StringInit>(Name)->getValue(); }
1613 
1614   Init *getNameInit() const {
1615     return Name;
1616   }
1617 
1618   std::string getNameInitAsString() const {
1619     return getNameInit()->getAsUnquotedString();
1620   }
1621 
1622   void setName(Init *Name);      // Also updates RecordKeeper.
1623 
1624   ArrayRef<SMLoc> getLoc() const { return Locs; }
1625   void appendLoc(SMLoc Loc) { Locs.push_back(Loc); }
1626 
1627   ArrayRef<SMLoc> getForwardDeclarationLocs() const {
1628     return ForwardDeclarationLocs;
1629   }
1630 
1631   // Update a class location when encountering a (re-)definition.
1632   void updateClassLoc(SMLoc Loc);
1633 
1634   // Make the type that this record should have based on its superclasses.
1635   RecordRecTy *getType();
1636 
1637   /// get the corresponding DefInit.
1638   DefInit *getDefInit();
1639 
1640   bool isClass() const { return IsClass; }
1641 
1642   ArrayRef<Init *> getTemplateArgs() const {
1643     return TemplateArgs;
1644   }
1645 
1646   ArrayRef<RecordVal> getValues() const { return Values; }
1647 
1648   ArrayRef<AssertionInfo> getAssertions() const { return Assertions; }
1649 
1650   ArrayRef<std::pair<Record *, SMRange>>  getSuperClasses() const {
1651     return SuperClasses;
1652   }
1653 
1654   /// Determine whether this record has the specified direct superclass.
1655   bool hasDirectSuperClass(const Record *SuperClass) const;
1656 
1657   /// Append the direct superclasses of this record to Classes.
1658   void getDirectSuperClasses(SmallVectorImpl<Record *> &Classes) const;
1659 
1660   bool isTemplateArg(Init *Name) const {
1661     return llvm::is_contained(TemplateArgs, Name);
1662   }
1663 
1664   const RecordVal *getValue(const Init *Name) const {
1665     for (const RecordVal &Val : Values)
1666       if (Val.Name == Name) return &Val;
1667     return nullptr;
1668   }
1669 
1670   const RecordVal *getValue(StringRef Name) const {
1671     return getValue(StringInit::get(getRecords(), Name));
1672   }
1673 
1674   RecordVal *getValue(const Init *Name) {
1675     return const_cast<RecordVal *>(static_cast<const Record *>(this)->getValue(Name));
1676   }
1677 
1678   RecordVal *getValue(StringRef Name) {
1679     return const_cast<RecordVal *>(static_cast<const Record *>(this)->getValue(Name));
1680   }
1681 
1682   void addTemplateArg(Init *Name) {
1683     assert(!isTemplateArg(Name) && "Template arg already defined!");
1684     TemplateArgs.push_back(Name);
1685   }
1686 
1687   void addValue(const RecordVal &RV) {
1688     assert(getValue(RV.getNameInit()) == nullptr && "Value already added!");
1689     Values.push_back(RV);
1690   }
1691 
1692   void removeValue(Init *Name) {
1693     for (unsigned i = 0, e = Values.size(); i != e; ++i)
1694       if (Values[i].getNameInit() == Name) {
1695         Values.erase(Values.begin()+i);
1696         return;
1697       }
1698     llvm_unreachable("Cannot remove an entry that does not exist!");
1699   }
1700 
1701   void removeValue(StringRef Name) {
1702     removeValue(StringInit::get(getRecords(), Name));
1703   }
1704 
1705   void addAssertion(SMLoc Loc, Init *Condition, Init *Message) {
1706     Assertions.push_back(AssertionInfo(Loc, Condition, Message));
1707   }
1708 
1709   void appendAssertions(const Record *Rec) {
1710     Assertions.append(Rec->Assertions);
1711   }
1712 
1713   void checkRecordAssertions();
1714   void checkUnusedTemplateArgs();
1715 
1716   bool isSubClassOf(const Record *R) const {
1717     for (const auto &SCPair : SuperClasses)
1718       if (SCPair.first == R)
1719         return true;
1720     return false;
1721   }
1722 
1723   bool isSubClassOf(StringRef Name) const {
1724     for (const auto &SCPair : SuperClasses) {
1725       if (const auto *SI = dyn_cast<StringInit>(SCPair.first->getNameInit())) {
1726         if (SI->getValue() == Name)
1727           return true;
1728       } else if (SCPair.first->getNameInitAsString() == Name) {
1729         return true;
1730       }
1731     }
1732     return false;
1733   }
1734 
1735   void addSuperClass(Record *R, SMRange Range) {
1736     assert(!CorrespondingDefInit &&
1737            "changing type of record after it has been referenced");
1738     assert(!isSubClassOf(R) && "Already subclassing record!");
1739     SuperClasses.push_back(std::make_pair(R, Range));
1740   }
1741 
1742   /// If there are any field references that refer to fields that have been
1743   /// filled in, we can propagate the values now.
1744   ///
1745   /// This is a final resolve: any error messages, e.g. due to undefined !cast
1746   /// references, are generated now.
1747   void resolveReferences(Init *NewName = nullptr);
1748 
1749   /// Apply the resolver to the name of the record as well as to the
1750   /// initializers of all fields of the record except SkipVal.
1751   ///
1752   /// The resolver should not resolve any of the fields itself, to avoid
1753   /// recursion / infinite loops.
1754   void resolveReferences(Resolver &R, const RecordVal *SkipVal = nullptr);
1755 
1756   RecordKeeper &getRecords() const {
1757     return TrackedRecords;
1758   }
1759 
1760   bool isAnonymous() const {
1761     return IsAnonymous;
1762   }
1763 
1764   void dump() const;
1765 
1766   //===--------------------------------------------------------------------===//
1767   // High-level methods useful to tablegen back-ends
1768   //
1769 
1770   /// Return the source location for the named field.
1771   SMLoc getFieldLoc(StringRef FieldName) const;
1772 
1773   /// Return the initializer for a value with the specified name, or throw an
1774   /// exception if the field does not exist.
1775   Init *getValueInit(StringRef FieldName) const;
1776 
1777   /// Return true if the named field is unset.
1778   bool isValueUnset(StringRef FieldName) const {
1779     return isa<UnsetInit>(getValueInit(FieldName));
1780   }
1781 
1782   /// This method looks up the specified field and returns its value as a
1783   /// string, throwing an exception if the field does not exist or if the value
1784   /// is not a string.
1785   StringRef getValueAsString(StringRef FieldName) const;
1786 
1787   /// This method looks up the specified field and returns its value as a
1788   /// string, throwing an exception if the value is not a string and
1789   /// llvm::Optional() if the field does not exist.
1790   llvm::Optional<StringRef> getValueAsOptionalString(StringRef FieldName) const;
1791 
1792   /// This method looks up the specified field and returns its value as a
1793   /// BitsInit, throwing an exception if the field does not exist or if the
1794   /// value is not the right type.
1795   BitsInit *getValueAsBitsInit(StringRef FieldName) const;
1796 
1797   /// This method looks up the specified field and returns its value as a
1798   /// ListInit, throwing an exception if the field does not exist or if the
1799   /// value is not the right type.
1800   ListInit *getValueAsListInit(StringRef FieldName) const;
1801 
1802   /// This method looks up the specified field and returns its value as a
1803   /// vector of records, throwing an exception if the field does not exist or
1804   /// if the value is not the right type.
1805   std::vector<Record*> getValueAsListOfDefs(StringRef FieldName) const;
1806 
1807   /// This method looks up the specified field and returns its value as a
1808   /// vector of integers, throwing an exception if the field does not exist or
1809   /// if the value is not the right type.
1810   std::vector<int64_t> getValueAsListOfInts(StringRef FieldName) const;
1811 
1812   /// This method looks up the specified field and returns its value as a
1813   /// vector of strings, throwing an exception if the field does not exist or
1814   /// if the value is not the right type.
1815   std::vector<StringRef> getValueAsListOfStrings(StringRef FieldName) const;
1816 
1817   /// This method looks up the specified field and returns its value as a
1818   /// Record, throwing an exception if the field does not exist or if the value
1819   /// is not the right type.
1820   Record *getValueAsDef(StringRef FieldName) const;
1821 
1822   /// This method looks up the specified field and returns its value as a
1823   /// Record, returning null if the field exists but is "uninitialized" (i.e.
1824   /// set to `?`), and throwing an exception if the field does not exist or if
1825   /// its value is not the right type.
1826   Record *getValueAsOptionalDef(StringRef FieldName) const;
1827 
1828   /// This method looks up the specified field and returns its value as a bit,
1829   /// throwing an exception if the field does not exist or if the value is not
1830   /// the right type.
1831   bool getValueAsBit(StringRef FieldName) const;
1832 
1833   /// This method looks up the specified field and returns its value as a bit.
1834   /// If the field is unset, sets Unset to true and returns false.
1835   bool getValueAsBitOrUnset(StringRef FieldName, bool &Unset) const;
1836 
1837   /// This method looks up the specified field and returns its value as an
1838   /// int64_t, throwing an exception if the field does not exist or if the
1839   /// value is not the right type.
1840   int64_t getValueAsInt(StringRef FieldName) const;
1841 
1842   /// This method looks up the specified field and returns its value as an Dag,
1843   /// throwing an exception if the field does not exist or if the value is not
1844   /// the right type.
1845   DagInit *getValueAsDag(StringRef FieldName) const;
1846 };
1847 
1848 raw_ostream &operator<<(raw_ostream &OS, const Record &R);
1849 
1850 class RecordKeeper {
1851   using RecordMap = std::map<std::string, std::unique_ptr<Record>, std::less<>>;
1852   using GlobalMap = std::map<std::string, Init *, std::less<>>;
1853 
1854 public:
1855   RecordKeeper();
1856   ~RecordKeeper();
1857 
1858   /// Return the internal implementation of the RecordKeeper.
1859   detail::RecordKeeperImpl &getImpl() { return *Impl; }
1860 
1861   /// Get the main TableGen input file's name.
1862   const std::string getInputFilename() const { return InputFilename; }
1863 
1864   /// Get the map of classes.
1865   const RecordMap &getClasses() const { return Classes; }
1866 
1867   /// Get the map of records (defs).
1868   const RecordMap &getDefs() const { return Defs; }
1869 
1870   /// Get the map of global variables.
1871   const GlobalMap &getGlobals() const { return ExtraGlobals; }
1872 
1873   /// Get the class with the specified name.
1874   Record *getClass(StringRef Name) const {
1875     auto I = Classes.find(Name);
1876     return I == Classes.end() ? nullptr : I->second.get();
1877   }
1878 
1879   /// Get the concrete record with the specified name.
1880   Record *getDef(StringRef Name) const {
1881     auto I = Defs.find(Name);
1882     return I == Defs.end() ? nullptr : I->second.get();
1883   }
1884 
1885   /// Get the \p Init value of the specified global variable.
1886   Init *getGlobal(StringRef Name) const {
1887     if (Record *R = getDef(Name))
1888       return R->getDefInit();
1889     auto It = ExtraGlobals.find(Name);
1890     return It == ExtraGlobals.end() ? nullptr : It->second;
1891   }
1892 
1893   void saveInputFilename(std::string Filename) {
1894     InputFilename = Filename;
1895   }
1896 
1897   void addClass(std::unique_ptr<Record> R) {
1898     bool Ins = Classes.insert(std::make_pair(std::string(R->getName()),
1899                                              std::move(R))).second;
1900     (void)Ins;
1901     assert(Ins && "Class already exists");
1902   }
1903 
1904   void addDef(std::unique_ptr<Record> R) {
1905     bool Ins = Defs.insert(std::make_pair(std::string(R->getName()),
1906                                           std::move(R))).second;
1907     (void)Ins;
1908     assert(Ins && "Record already exists");
1909   }
1910 
1911   void addExtraGlobal(StringRef Name, Init *I) {
1912     bool Ins = ExtraGlobals.insert(std::make_pair(std::string(Name), I)).second;
1913     (void)Ins;
1914     assert(!getDef(Name));
1915     assert(Ins && "Global already exists");
1916   }
1917 
1918   Init *getNewAnonymousName();
1919 
1920   /// Start phase timing; called if the --time-phases option is specified.
1921   void startPhaseTiming() {
1922     TimingGroup = new TimerGroup("TableGen", "TableGen Phase Timing");
1923   }
1924 
1925   /// Start timing a phase. Automatically stops any previous phase timer.
1926   void startTimer(StringRef Name);
1927 
1928   /// Stop timing a phase.
1929   void stopTimer();
1930 
1931   /// Start timing the overall backend. If the backend itself starts a timer,
1932   /// then this timer is cleared.
1933   void startBackendTimer(StringRef Name);
1934 
1935   /// Stop timing the overall backend.
1936   void stopBackendTimer();
1937 
1938   /// Stop phase timing and print the report.
1939   void stopPhaseTiming() {
1940     if (TimingGroup)
1941       delete TimingGroup;
1942   }
1943 
1944   //===--------------------------------------------------------------------===//
1945   // High-level helper methods, useful for tablegen backends.
1946 
1947   /// Get all the concrete records that inherit from the one specified
1948   /// class. The class must be defined.
1949   std::vector<Record *> getAllDerivedDefinitions(StringRef ClassName) const;
1950 
1951   /// Get all the concrete records that inherit from all the specified
1952   /// classes. The classes must be defined.
1953   std::vector<Record *> getAllDerivedDefinitions(
1954       ArrayRef<StringRef> ClassNames) const;
1955 
1956   /// Get all the concrete records that inherit from specified class, if the
1957   /// class is defined. Returns an empty vector if the class is not defined.
1958   std::vector<Record *>
1959   getAllDerivedDefinitionsIfDefined(StringRef ClassName) const;
1960 
1961   void dump() const;
1962 
1963 private:
1964   RecordKeeper(RecordKeeper &&) = delete;
1965   RecordKeeper(const RecordKeeper &) = delete;
1966   RecordKeeper &operator=(RecordKeeper &&) = delete;
1967   RecordKeeper &operator=(const RecordKeeper &) = delete;
1968 
1969   std::string InputFilename;
1970   RecordMap Classes, Defs;
1971   mutable StringMap<std::vector<Record *>> ClassRecordsMap;
1972   GlobalMap ExtraGlobals;
1973 
1974   // These members are for the phase timing feature. We need a timer group,
1975   // the last timer started, and a flag to say whether the last timer
1976   // is the special "backend overall timer."
1977   TimerGroup *TimingGroup = nullptr;
1978   Timer *LastTimer = nullptr;
1979   bool BackendTimer = false;
1980 
1981   /// The internal uniquer implementation of the RecordKeeper.
1982   std::unique_ptr<detail::RecordKeeperImpl> Impl;
1983 };
1984 
1985 /// Sorting predicate to sort record pointers by name.
1986 struct LessRecord {
1987   bool operator()(const Record *Rec1, const Record *Rec2) const {
1988     return StringRef(Rec1->getName()).compare_numeric(Rec2->getName()) < 0;
1989   }
1990 };
1991 
1992 /// Sorting predicate to sort record pointers by their
1993 /// unique ID. If you just need a deterministic order, use this, since it
1994 /// just compares two `unsigned`; the other sorting predicates require
1995 /// string manipulation.
1996 struct LessRecordByID {
1997   bool operator()(const Record *LHS, const Record *RHS) const {
1998     return LHS->getID() < RHS->getID();
1999   }
2000 };
2001 
2002 /// Sorting predicate to sort record pointers by their
2003 /// name field.
2004 struct LessRecordFieldName {
2005   bool operator()(const Record *Rec1, const Record *Rec2) const {
2006     return Rec1->getValueAsString("Name") < Rec2->getValueAsString("Name");
2007   }
2008 };
2009 
2010 struct LessRecordRegister {
2011   struct RecordParts {
2012     SmallVector<std::pair< bool, StringRef>, 4> Parts;
2013 
2014     RecordParts(StringRef Rec) {
2015       if (Rec.empty())
2016         return;
2017 
2018       size_t Len = 0;
2019       const char *Start = Rec.data();
2020       const char *Curr = Start;
2021       bool IsDigitPart = isDigit(Curr[0]);
2022       for (size_t I = 0, E = Rec.size(); I != E; ++I, ++Len) {
2023         bool IsDigit = isDigit(Curr[I]);
2024         if (IsDigit != IsDigitPart) {
2025           Parts.push_back(std::make_pair(IsDigitPart, StringRef(Start, Len)));
2026           Len = 0;
2027           Start = &Curr[I];
2028           IsDigitPart = isDigit(Curr[I]);
2029         }
2030       }
2031       // Push the last part.
2032       Parts.push_back(std::make_pair(IsDigitPart, StringRef(Start, Len)));
2033     }
2034 
2035     size_t size() { return Parts.size(); }
2036 
2037     std::pair<bool, StringRef> getPart(size_t i) {
2038       assert (i < Parts.size() && "Invalid idx!");
2039       return Parts[i];
2040     }
2041   };
2042 
2043   bool operator()(const Record *Rec1, const Record *Rec2) const {
2044     RecordParts LHSParts(StringRef(Rec1->getName()));
2045     RecordParts RHSParts(StringRef(Rec2->getName()));
2046 
2047     size_t LHSNumParts = LHSParts.size();
2048     size_t RHSNumParts = RHSParts.size();
2049     assert (LHSNumParts && RHSNumParts && "Expected at least one part!");
2050 
2051     if (LHSNumParts != RHSNumParts)
2052       return LHSNumParts < RHSNumParts;
2053 
2054     // We expect the registers to be of the form [_a-zA-Z]+([0-9]*[_a-zA-Z]*)*.
2055     for (size_t I = 0, E = LHSNumParts; I < E; I+=2) {
2056       std::pair<bool, StringRef> LHSPart = LHSParts.getPart(I);
2057       std::pair<bool, StringRef> RHSPart = RHSParts.getPart(I);
2058       // Expect even part to always be alpha.
2059       assert (LHSPart.first == false && RHSPart.first == false &&
2060               "Expected both parts to be alpha.");
2061       if (int Res = LHSPart.second.compare(RHSPart.second))
2062         return Res < 0;
2063     }
2064     for (size_t I = 1, E = LHSNumParts; I < E; I+=2) {
2065       std::pair<bool, StringRef> LHSPart = LHSParts.getPart(I);
2066       std::pair<bool, StringRef> RHSPart = RHSParts.getPart(I);
2067       // Expect odd part to always be numeric.
2068       assert (LHSPart.first == true && RHSPart.first == true &&
2069               "Expected both parts to be numeric.");
2070       if (LHSPart.second.size() != RHSPart.second.size())
2071         return LHSPart.second.size() < RHSPart.second.size();
2072 
2073       unsigned LHSVal, RHSVal;
2074 
2075       bool LHSFailed = LHSPart.second.getAsInteger(10, LHSVal); (void)LHSFailed;
2076       assert(!LHSFailed && "Unable to convert LHS to integer.");
2077       bool RHSFailed = RHSPart.second.getAsInteger(10, RHSVal); (void)RHSFailed;
2078       assert(!RHSFailed && "Unable to convert RHS to integer.");
2079 
2080       if (LHSVal != RHSVal)
2081         return LHSVal < RHSVal;
2082     }
2083     return LHSNumParts < RHSNumParts;
2084   }
2085 };
2086 
2087 raw_ostream &operator<<(raw_ostream &OS, const RecordKeeper &RK);
2088 
2089 //===----------------------------------------------------------------------===//
2090 //  Resolvers
2091 //===----------------------------------------------------------------------===//
2092 
2093 /// Interface for looking up the initializer for a variable name, used by
2094 /// Init::resolveReferences.
2095 class Resolver {
2096   Record *CurRec;
2097   bool IsFinal = false;
2098 
2099 public:
2100   explicit Resolver(Record *CurRec) : CurRec(CurRec) {}
2101   virtual ~Resolver() = default;
2102 
2103   Record *getCurrentRecord() const { return CurRec; }
2104 
2105   /// Return the initializer for the given variable name (should normally be a
2106   /// StringInit), or nullptr if the name could not be resolved.
2107   virtual Init *resolve(Init *VarName) = 0;
2108 
2109   // Whether bits in a BitsInit should stay unresolved if resolving them would
2110   // result in a ? (UnsetInit). This behavior is used to represent instruction
2111   // encodings by keeping references to unset variables within a record.
2112   virtual bool keepUnsetBits() const { return false; }
2113 
2114   // Whether this is the final resolve step before adding a record to the
2115   // RecordKeeper. Error reporting during resolve and related constant folding
2116   // should only happen when this is true.
2117   bool isFinal() const { return IsFinal; }
2118 
2119   void setFinal(bool Final) { IsFinal = Final; }
2120 };
2121 
2122 /// Resolve arbitrary mappings.
2123 class MapResolver final : public Resolver {
2124   struct MappedValue {
2125     Init *V;
2126     bool Resolved;
2127 
2128     MappedValue() : V(nullptr), Resolved(false) {}
2129     MappedValue(Init *V, bool Resolved) : V(V), Resolved(Resolved) {}
2130   };
2131 
2132   DenseMap<Init *, MappedValue> Map;
2133 
2134 public:
2135   explicit MapResolver(Record *CurRec = nullptr) : Resolver(CurRec) {}
2136 
2137   void set(Init *Key, Init *Value) { Map[Key] = {Value, false}; }
2138 
2139   bool isComplete(Init *VarName) const {
2140     auto It = Map.find(VarName);
2141     assert(It != Map.end() && "key must be present in map");
2142     return It->second.V->isComplete();
2143   }
2144 
2145   Init *resolve(Init *VarName) override;
2146 };
2147 
2148 /// Resolve all variables from a record except for unset variables.
2149 class RecordResolver final : public Resolver {
2150   DenseMap<Init *, Init *> Cache;
2151   SmallVector<Init *, 4> Stack;
2152   Init *Name = nullptr;
2153 
2154 public:
2155   explicit RecordResolver(Record &R) : Resolver(&R) {}
2156 
2157   void setName(Init *NewName) { Name = NewName; }
2158 
2159   Init *resolve(Init *VarName) override;
2160 
2161   bool keepUnsetBits() const override { return true; }
2162 };
2163 
2164 /// Delegate resolving to a sub-resolver, but shadow some variable names.
2165 class ShadowResolver final : public Resolver {
2166   Resolver &R;
2167   DenseSet<Init *> Shadowed;
2168 
2169 public:
2170   explicit ShadowResolver(Resolver &R)
2171       : Resolver(R.getCurrentRecord()), R(R) {
2172     setFinal(R.isFinal());
2173   }
2174 
2175   void addShadow(Init *Key) { Shadowed.insert(Key); }
2176 
2177   Init *resolve(Init *VarName) override {
2178     if (Shadowed.count(VarName))
2179       return nullptr;
2180     return R.resolve(VarName);
2181   }
2182 };
2183 
2184 /// (Optionally) delegate resolving to a sub-resolver, and keep track whether
2185 /// there were unresolved references.
2186 class TrackUnresolvedResolver final : public Resolver {
2187   Resolver *R;
2188   bool FoundUnresolved = false;
2189 
2190 public:
2191   explicit TrackUnresolvedResolver(Resolver *R = nullptr)
2192       : Resolver(R ? R->getCurrentRecord() : nullptr), R(R) {}
2193 
2194   bool foundUnresolved() const { return FoundUnresolved; }
2195 
2196   Init *resolve(Init *VarName) override;
2197 };
2198 
2199 /// Do not resolve anything, but keep track of whether a given variable was
2200 /// referenced.
2201 class HasReferenceResolver final : public Resolver {
2202   Init *VarNameToTrack;
2203   bool Found = false;
2204 
2205 public:
2206   explicit HasReferenceResolver(Init *VarNameToTrack)
2207       : Resolver(nullptr), VarNameToTrack(VarNameToTrack) {}
2208 
2209   bool found() const { return Found; }
2210 
2211   Init *resolve(Init *VarName) override;
2212 };
2213 
2214 void EmitDetailedRecords(RecordKeeper &RK, raw_ostream &OS);
2215 void EmitJSON(RecordKeeper &RK, raw_ostream &OS);
2216 
2217 } // end namespace llvm
2218 
2219 #endif // LLVM_TABLEGEN_RECORD_H
2220