[TableGen] Merge RecTy::typeIsConvertibleTo and RecTy::baseClassOf. NFC
[oota-llvm.git] / include / llvm / TableGen / Record.h
1 //===- llvm/TableGen/Record.h - Classes for Table Records -------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the main TableGen data structures, including the TableGen
11 // types, values, and high-level data structures.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #ifndef LLVM_TABLEGEN_RECORD_H
16 #define LLVM_TABLEGEN_RECORD_H
17
18 #include "llvm/ADT/ArrayRef.h"
19 #include "llvm/ADT/FoldingSet.h"
20 #include "llvm/Support/Allocator.h"
21 #include "llvm/Support/Casting.h"
22 #include "llvm/Support/DataTypes.h"
23 #include "llvm/Support/ErrorHandling.h"
24 #include "llvm/Support/SourceMgr.h"
25 #include "llvm/Support/raw_ostream.h"
26 #include <map>
27
28 namespace llvm {
29
30 // RecTy subclasses.
31 class BitRecTy;
32 class BitsRecTy;
33 class IntRecTy;
34 class StringRecTy;
35 class ListRecTy;
36 class DagRecTy;
37 class RecordRecTy;
38
39 // Init subclasses.
40 class Init;
41 class UnsetInit;
42 class BitInit;
43 class BitsInit;
44 class IntInit;
45 class StringInit;
46 class ListInit;
47 class UnOpInit;
48 class BinOpInit;
49 class TernOpInit;
50 class DefInit;
51 class DagInit;
52 class TypedInit;
53 class VarInit;
54 class FieldInit;
55 class VarBitInit;
56 class VarListElementInit;
57
58 // Other classes.
59 class Record;
60 class RecordVal;
61 struct MultiClass;
62 class RecordKeeper;
63
64 //===----------------------------------------------------------------------===//
65 //  Type Classes
66 //===----------------------------------------------------------------------===//
67
68 class RecTy {
69 public:
70   /// \brief Subclass discriminator (for dyn_cast<> et al.)
71   enum RecTyKind {
72     BitRecTyKind,
73     BitsRecTyKind,
74     IntRecTyKind,
75     StringRecTyKind,
76     ListRecTyKind,
77     DagRecTyKind,
78     RecordRecTyKind
79   };
80
81 private:
82   RecTyKind Kind;
83   std::unique_ptr<ListRecTy> ListTy;
84
85 public:
86   RecTyKind getRecTyKind() const { return Kind; }
87
88   RecTy(RecTyKind K) : Kind(K), ListTy(nullptr) {}
89   virtual ~RecTy() {}
90
91   virtual std::string getAsString() const = 0;
92   void print(raw_ostream &OS) const { OS << getAsString(); }
93   void dump() const;
94
95   /// typeIsConvertibleTo - Return true if all values of 'this' type can be
96   /// converted to the specified type.
97   virtual bool typeIsConvertibleTo(const RecTy *RHS) const;
98
99   /// getListTy - Returns the type representing list<this>.
100   ListRecTy *getListTy();
101 };
102
103 inline raw_ostream &operator<<(raw_ostream &OS, const RecTy &Ty) {
104   Ty.print(OS);
105   return OS;
106 }
107
108 /// BitRecTy - 'bit' - Represent a single bit
109 ///
110 class BitRecTy : public RecTy {
111   static BitRecTy Shared;
112   BitRecTy() : RecTy(BitRecTyKind) {}
113
114 public:
115   static bool classof(const RecTy *RT) {
116     return RT->getRecTyKind() == BitRecTyKind;
117   }
118
119   static BitRecTy *get() { return &Shared; }
120
121   std::string getAsString() const override { return "bit"; }
122
123   bool typeIsConvertibleTo(const RecTy *RHS) const override;
124 };
125
126 /// BitsRecTy - 'bits<n>' - Represent a fixed number of bits
127 ///
128 class BitsRecTy : public RecTy {
129   unsigned Size;
130   explicit BitsRecTy(unsigned Sz) : RecTy(BitsRecTyKind), Size(Sz) {}
131
132 public:
133   static bool classof(const RecTy *RT) {
134     return RT->getRecTyKind() == BitsRecTyKind;
135   }
136
137   static BitsRecTy *get(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
146 /// IntRecTy - 'int' - Represent an integer value of no particular size
147 ///
148 class IntRecTy : public RecTy {
149   static IntRecTy Shared;
150   IntRecTy() : RecTy(IntRecTyKind) {}
151
152 public:
153   static bool classof(const RecTy *RT) {
154     return RT->getRecTyKind() == IntRecTyKind;
155   }
156
157   static IntRecTy *get() { return &Shared; }
158
159   std::string getAsString() const override { return "int"; }
160
161   bool typeIsConvertibleTo(const RecTy *RHS) const override;
162 };
163
164 /// StringRecTy - 'string' - Represent an string value
165 ///
166 class StringRecTy : public RecTy {
167   static StringRecTy Shared;
168   StringRecTy() : RecTy(StringRecTyKind) {}
169
170   virtual void anchor();
171 public:
172   static bool classof(const RecTy *RT) {
173     return RT->getRecTyKind() == StringRecTyKind;
174   }
175
176   static StringRecTy *get() { return &Shared; }
177
178   std::string getAsString() const override { return "string"; }
179 };
180
181 /// ListRecTy - 'list<Ty>' - Represent a list of values, all of which must be of
182 /// the specified type.
183 ///
184 class ListRecTy : public RecTy {
185   RecTy *Ty;
186   explicit ListRecTy(RecTy *T) : RecTy(ListRecTyKind), Ty(T) {}
187   friend ListRecTy *RecTy::getListTy();
188
189 public:
190   static bool classof(const RecTy *RT) {
191     return RT->getRecTyKind() == ListRecTyKind;
192   }
193
194   static ListRecTy *get(RecTy *T) { return T->getListTy(); }
195   RecTy *getElementType() const { return Ty; }
196
197   std::string getAsString() const override;
198
199   bool typeIsConvertibleTo(const RecTy *RHS) const override;
200 };
201
202 /// DagRecTy - 'dag' - Represent a dag fragment
203 ///
204 class DagRecTy : public RecTy {
205   static DagRecTy Shared;
206   DagRecTy() : RecTy(DagRecTyKind) {}
207
208   virtual void anchor();
209 public:
210   static bool classof(const RecTy *RT) {
211     return RT->getRecTyKind() == DagRecTyKind;
212   }
213
214   static DagRecTy *get() { return &Shared; }
215
216   std::string getAsString() const override { return "dag"; }
217 };
218
219 /// RecordRecTy - '[classname]' - Represent an instance of a class, such as:
220 /// (R32 X = EAX).
221 ///
222 class RecordRecTy : public RecTy {
223   Record *Rec;
224   explicit RecordRecTy(Record *R) : RecTy(RecordRecTyKind), Rec(R) {}
225   friend class Record;
226
227 public:
228   static bool classof(const RecTy *RT) {
229     return RT->getRecTyKind() == RecordRecTyKind;
230   }
231
232   static RecordRecTy *get(Record *R);
233
234   Record *getRecord() const { return Rec; }
235
236   std::string getAsString() const override;
237
238   bool typeIsConvertibleTo(const RecTy *RHS) const override;
239 };
240
241 /// resolveTypes - Find a common type that T1 and T2 convert to.
242 /// Return 0 if no such type exists.
243 ///
244 RecTy *resolveTypes(RecTy *T1, RecTy *T2);
245
246 //===----------------------------------------------------------------------===//
247 //  Initializer Classes
248 //===----------------------------------------------------------------------===//
249
250 class Init {
251 protected:
252   /// \brief Discriminator enum (for isa<>, dyn_cast<>, et al.)
253   ///
254   /// This enum is laid out by a preorder traversal of the inheritance
255   /// hierarchy, and does not contain an entry for abstract classes, as per
256   /// the recommendation in docs/HowToSetUpLLVMStyleRTTI.rst.
257   ///
258   /// We also explicitly include "first" and "last" values for each
259   /// interior node of the inheritance tree, to make it easier to read the
260   /// corresponding classof().
261   ///
262   /// We could pack these a bit tighter by not having the IK_FirstXXXInit
263   /// and IK_LastXXXInit be their own values, but that would degrade
264   /// readability for really no benefit.
265   enum InitKind {
266     IK_BitInit,
267     IK_FirstTypedInit,
268     IK_BitsInit,
269     IK_DagInit,
270     IK_DefInit,
271     IK_FieldInit,
272     IK_IntInit,
273     IK_ListInit,
274     IK_FirstOpInit,
275     IK_BinOpInit,
276     IK_TernOpInit,
277     IK_UnOpInit,
278     IK_LastOpInit,
279     IK_StringInit,
280     IK_VarInit,
281     IK_VarListElementInit,
282     IK_LastTypedInit,
283     IK_UnsetInit,
284     IK_VarBitInit
285   };
286
287 private:
288   const InitKind Kind;
289   Init(const Init &) = delete;
290   Init &operator=(const Init &) = delete;
291   virtual void anchor();
292
293 public:
294   InitKind getKind() const { return Kind; }
295
296 protected:
297   explicit Init(InitKind K) : Kind(K) {}
298
299 public:
300   virtual ~Init() {}
301
302   /// isComplete - This virtual method should be overridden by values that may
303   /// not be completely specified yet.
304   virtual bool isComplete() const { return true; }
305
306   /// print - Print out this value.
307   void print(raw_ostream &OS) const { OS << getAsString(); }
308
309   /// getAsString - Convert this value to a string form.
310   virtual std::string getAsString() const = 0;
311   /// getAsUnquotedString - Convert this value to a string form,
312   /// without adding quote markers.  This primaruly affects
313   /// StringInits where we will not surround the string value with
314   /// quotes.
315   virtual std::string getAsUnquotedString() const { return getAsString(); }
316
317   /// dump - Debugging method that may be called through a debugger, just
318   /// invokes print on stderr.
319   void dump() const;
320
321   /// convertInitializerTo - This virtual function converts to the appropriate
322   /// Init based on the passed in type.
323   virtual Init *convertInitializerTo(RecTy *Ty) const = 0;
324
325   /// convertInitializerBitRange - This method is used to implement the bitrange
326   /// selection operator.  Given an initializer, it selects the specified bits
327   /// out, returning them as a new init of bits type.  If it is not legal to use
328   /// the bit subscript operator on this initializer, return null.
329   ///
330   virtual Init *
331   convertInitializerBitRange(const std::vector<unsigned> &Bits) const {
332     return nullptr;
333   }
334
335   /// convertInitListSlice - This method is used to implement the list slice
336   /// selection operator.  Given an initializer, it selects the specified list
337   /// elements, returning them as a new init of list type.  If it is not legal
338   /// to take a slice of this, return null.
339   ///
340   virtual Init *
341   convertInitListSlice(const std::vector<unsigned> &Elements) const {
342     return nullptr;
343   }
344
345   /// getFieldType - This method is used to implement the FieldInit class.
346   /// Implementors of this method should return the type of the named field if
347   /// they are of record type.
348   ///
349   virtual RecTy *getFieldType(const std::string &FieldName) const {
350     return nullptr;
351   }
352
353   /// getFieldInit - This method complements getFieldType to return the
354   /// initializer for the specified field.  If getFieldType returns non-null
355   /// this method should return non-null, otherwise it returns null.
356   ///
357   virtual Init *getFieldInit(Record &R, const RecordVal *RV,
358                              const std::string &FieldName) const {
359     return nullptr;
360   }
361
362   /// resolveReferences - This method is used by classes that refer to other
363   /// variables which may not be defined at the time the expression is formed.
364   /// If a value is set for the variable later, this method will be called on
365   /// users of the value to allow the value to propagate out.
366   ///
367   virtual Init *resolveReferences(Record &R, const RecordVal *RV) const {
368     return const_cast<Init *>(this);
369   }
370
371   /// getBit - This method is used to return the initializer for the specified
372   /// bit.
373   virtual Init *getBit(unsigned Bit) const = 0;
374
375   /// getBitVar - This method is used to retrieve the initializer for bit
376   /// reference. For non-VarBitInit, it simply returns itself.
377   virtual Init *getBitVar() const { return const_cast<Init*>(this); }
378
379   /// getBitNum - This method is used to retrieve the bit number of a bit
380   /// reference. For non-VarBitInit, it simply returns 0.
381   virtual unsigned getBitNum() const { return 0; }
382 };
383
384 inline raw_ostream &operator<<(raw_ostream &OS, const Init &I) {
385   I.print(OS); return OS;
386 }
387
388 /// TypedInit - This is the common super-class of types that have a specific,
389 /// explicit, type.
390 ///
391 class TypedInit : public Init {
392   RecTy *Ty;
393
394   TypedInit(const TypedInit &Other) = delete;
395   TypedInit &operator=(const TypedInit &Other) = delete;
396
397 protected:
398   explicit TypedInit(InitKind K, RecTy *T) : Init(K), Ty(T) {}
399   ~TypedInit() {
400     // If this is a DefInit we need to delete the RecordRecTy.
401     if (getKind() == IK_DefInit)
402       delete Ty;
403   }
404
405 public:
406   static bool classof(const Init *I) {
407     return I->getKind() >= IK_FirstTypedInit &&
408            I->getKind() <= IK_LastTypedInit;
409   }
410   RecTy *getType() const { return Ty; }
411
412   Init *convertInitializerTo(RecTy *Ty) const override;
413
414   Init *
415   convertInitializerBitRange(const std::vector<unsigned> &Bits) const override;
416   Init *
417   convertInitListSlice(const std::vector<unsigned> &Elements) const override;
418
419   /// getFieldType - This method is used to implement the FieldInit class.
420   /// Implementors of this method should return the type of the named field if
421   /// they are of record type.
422   ///
423   RecTy *getFieldType(const std::string &FieldName) const override;
424
425   /// resolveListElementReference - This method is used to implement
426   /// VarListElementInit::resolveReferences.  If the list element is resolvable
427   /// now, we return the resolved value, otherwise we return null.
428   virtual Init *resolveListElementReference(Record &R, const RecordVal *RV,
429                                             unsigned Elt) const = 0;
430 };
431
432 /// UnsetInit - ? - Represents an uninitialized value
433 ///
434 class UnsetInit : public Init {
435   UnsetInit() : Init(IK_UnsetInit) {}
436   UnsetInit(const UnsetInit &) = delete;
437   UnsetInit &operator=(const UnsetInit &Other) = delete;
438
439 public:
440   static bool classof(const Init *I) {
441     return I->getKind() == IK_UnsetInit;
442   }
443   static UnsetInit *get();
444
445   Init *convertInitializerTo(RecTy *Ty) const override;
446
447   Init *getBit(unsigned Bit) const override {
448     return const_cast<UnsetInit*>(this);
449   }
450
451   bool isComplete() const override { return false; }
452   std::string getAsString() const override { return "?"; }
453 };
454
455 /// BitInit - true/false - Represent a concrete initializer for a bit.
456 ///
457 class BitInit : public Init {
458   bool Value;
459
460   explicit BitInit(bool V) : Init(IK_BitInit), Value(V) {}
461   BitInit(const BitInit &Other) = delete;
462   BitInit &operator=(BitInit &Other) = delete;
463
464 public:
465   static bool classof(const Init *I) {
466     return I->getKind() == IK_BitInit;
467   }
468   static BitInit *get(bool V);
469
470   bool getValue() const { return Value; }
471
472   Init *convertInitializerTo(RecTy *Ty) const override;
473
474   Init *getBit(unsigned Bit) const override {
475     assert(Bit < 1 && "Bit index out of range!");
476     return const_cast<BitInit*>(this);
477   }
478
479   std::string getAsString() const override { return Value ? "1" : "0"; }
480 };
481
482 /// BitsInit - { a, b, c } - Represents an initializer for a BitsRecTy value.
483 /// It contains a vector of bits, whose size is determined by the type.
484 ///
485 class BitsInit : public TypedInit, public FoldingSetNode {
486   std::vector<Init*> Bits;
487
488   BitsInit(ArrayRef<Init *> Range)
489     : TypedInit(IK_BitsInit, BitsRecTy::get(Range.size())),
490       Bits(Range.begin(), Range.end()) {}
491
492   BitsInit(const BitsInit &Other) = delete;
493   BitsInit &operator=(const BitsInit &Other) = delete;
494
495 public:
496   static bool classof(const Init *I) {
497     return I->getKind() == IK_BitsInit;
498   }
499   static BitsInit *get(ArrayRef<Init *> Range);
500
501   void Profile(FoldingSetNodeID &ID) const;
502
503   unsigned getNumBits() const { return Bits.size(); }
504
505   Init *convertInitializerTo(RecTy *Ty) const override;
506   Init *
507   convertInitializerBitRange(const std::vector<unsigned> &Bits) const override;
508
509   bool isComplete() const override {
510     for (unsigned i = 0; i != getNumBits(); ++i)
511       if (!getBit(i)->isComplete()) return false;
512     return true;
513   }
514   bool allInComplete() const {
515     for (unsigned i = 0; i != getNumBits(); ++i)
516       if (getBit(i)->isComplete()) return false;
517     return true;
518   }
519   std::string getAsString() const override;
520
521   /// resolveListElementReference - This method is used to implement
522   /// VarListElementInit::resolveReferences.  If the list element is resolvable
523   /// now, we return the resolved value, otherwise we return null.
524   Init *resolveListElementReference(Record &R, const RecordVal *RV,
525                                     unsigned Elt) const override {
526     llvm_unreachable("Illegal element reference off bits<n>");
527   }
528
529   Init *resolveReferences(Record &R, const RecordVal *RV) const override;
530
531   Init *getBit(unsigned Bit) const override {
532     assert(Bit < Bits.size() && "Bit index out of range!");
533     return Bits[Bit];
534   }
535 };
536
537 /// IntInit - 7 - Represent an initialization by a literal integer value.
538 ///
539 class IntInit : public TypedInit {
540   int64_t Value;
541
542   explicit IntInit(int64_t V)
543     : TypedInit(IK_IntInit, IntRecTy::get()), Value(V) {}
544
545   IntInit(const IntInit &Other) = delete;
546   IntInit &operator=(const IntInit &Other) = delete;
547
548 public:
549   static bool classof(const Init *I) {
550     return I->getKind() == IK_IntInit;
551   }
552   static IntInit *get(int64_t V);
553
554   int64_t getValue() const { return Value; }
555
556   Init *convertInitializerTo(RecTy *Ty) const override;
557   Init *
558   convertInitializerBitRange(const std::vector<unsigned> &Bits) const override;
559
560   std::string getAsString() const override;
561
562   /// resolveListElementReference - This method is used to implement
563   /// VarListElementInit::resolveReferences.  If the list element is resolvable
564   /// now, we return the resolved value, otherwise we return null.
565   Init *resolveListElementReference(Record &R, const RecordVal *RV,
566                                     unsigned Elt) const override {
567     llvm_unreachable("Illegal element reference off int");
568   }
569
570   Init *getBit(unsigned Bit) const override {
571     return BitInit::get((Value & (1ULL << Bit)) != 0);
572   }
573 };
574
575 /// StringInit - "foo" - Represent an initialization by a string value.
576 ///
577 class StringInit : public TypedInit {
578   std::string Value;
579
580   explicit StringInit(const std::string &V)
581     : TypedInit(IK_StringInit, StringRecTy::get()), Value(V) {}
582
583   StringInit(const StringInit &Other) = delete;
584   StringInit &operator=(const StringInit &Other) = delete;
585
586 public:
587   static bool classof(const Init *I) {
588     return I->getKind() == IK_StringInit;
589   }
590   static StringInit *get(StringRef);
591
592   const std::string &getValue() const { return Value; }
593
594   Init *convertInitializerTo(RecTy *Ty) const override;
595
596   std::string getAsString() const override { return "\"" + Value + "\""; }
597   std::string getAsUnquotedString() const override { return Value; }
598
599   /// resolveListElementReference - This method is used to implement
600   /// VarListElementInit::resolveReferences.  If the list element is resolvable
601   /// now, we return the resolved value, otherwise we return null.
602   Init *resolveListElementReference(Record &R, const RecordVal *RV,
603                                     unsigned Elt) const override {
604     llvm_unreachable("Illegal element reference off string");
605   }
606
607   Init *getBit(unsigned Bit) const override {
608     llvm_unreachable("Illegal bit reference off string");
609   }
610 };
611
612 /// ListInit - [AL, AH, CL] - Represent a list of defs
613 ///
614 class ListInit : public TypedInit, public FoldingSetNode {
615   std::vector<Init*> Values;
616
617 public:
618   typedef std::vector<Init*>::const_iterator const_iterator;
619
620 private:
621   explicit ListInit(ArrayRef<Init *> Range, RecTy *EltTy)
622     : TypedInit(IK_ListInit, ListRecTy::get(EltTy)),
623       Values(Range.begin(), Range.end()) {}
624
625   ListInit(const ListInit &Other) = delete;
626   ListInit &operator=(const ListInit &Other) = delete;
627
628 public:
629   static bool classof(const Init *I) {
630     return I->getKind() == IK_ListInit;
631   }
632   static ListInit *get(ArrayRef<Init *> Range, RecTy *EltTy);
633
634   void Profile(FoldingSetNodeID &ID) const;
635
636   unsigned getSize() const { return Values.size(); }
637   Init *getElement(unsigned i) const {
638     assert(i < Values.size() && "List element index out of range!");
639     return Values[i];
640   }
641
642   Record *getElementAsRecord(unsigned i) const;
643
644   Init *
645     convertInitListSlice(const std::vector<unsigned> &Elements) const override;
646
647   Init *convertInitializerTo(RecTy *Ty) const override;
648
649   /// resolveReferences - This method is used by classes that refer to other
650   /// variables which may not be defined at the time they expression is formed.
651   /// If a value is set for the variable later, this method will be called on
652   /// users of the value to allow the value to propagate out.
653   ///
654   Init *resolveReferences(Record &R, const RecordVal *RV) const override;
655
656   std::string getAsString() const override;
657
658   ArrayRef<Init*> getValues() const { return Values; }
659
660   inline const_iterator begin() const { return Values.begin(); }
661   inline const_iterator end  () const { return Values.end();   }
662
663   inline bool           empty() const { return Values.empty(); }
664
665   /// resolveListElementReference - This method is used to implement
666   /// VarListElementInit::resolveReferences.  If the list element is resolvable
667   /// now, we return the resolved value, otherwise we return null.
668   Init *resolveListElementReference(Record &R, const RecordVal *RV,
669                                     unsigned Elt) const override;
670
671   Init *getBit(unsigned Bit) const override {
672     llvm_unreachable("Illegal bit reference off list");
673   }
674 };
675
676 /// OpInit - Base class for operators
677 ///
678 class OpInit : public TypedInit {
679   OpInit(const OpInit &Other) = delete;
680   OpInit &operator=(OpInit &Other) = delete;
681
682 protected:
683   explicit OpInit(InitKind K, RecTy *Type) : TypedInit(K, Type) {}
684
685 public:
686   static bool classof(const Init *I) {
687     return I->getKind() >= IK_FirstOpInit &&
688            I->getKind() <= IK_LastOpInit;
689   }
690   // Clone - Clone this operator, replacing arguments with the new list
691   virtual OpInit *clone(std::vector<Init *> &Operands) const = 0;
692
693   virtual int getNumOperands() const = 0;
694   virtual Init *getOperand(int i) const = 0;
695
696   // Fold - If possible, fold this to a simpler init.  Return this if not
697   // possible to fold.
698   virtual Init *Fold(Record *CurRec, MultiClass *CurMultiClass) const = 0;
699
700   Init *resolveListElementReference(Record &R, const RecordVal *RV,
701                                     unsigned Elt) const override;
702
703   Init *getBit(unsigned Bit) const override;
704 };
705
706 /// UnOpInit - !op (X) - Transform an init.
707 ///
708 class UnOpInit : public OpInit {
709 public:
710   enum UnaryOp { CAST, HEAD, TAIL, EMPTY };
711
712 private:
713   UnaryOp Opc;
714   Init *LHS;
715
716   UnOpInit(UnaryOp opc, Init *lhs, RecTy *Type)
717     : OpInit(IK_UnOpInit, Type), Opc(opc), LHS(lhs) {}
718
719   UnOpInit(const UnOpInit &Other) = delete;
720   UnOpInit &operator=(const UnOpInit &Other) = delete;
721
722 public:
723   static bool classof(const Init *I) {
724     return I->getKind() == IK_UnOpInit;
725   }
726   static UnOpInit *get(UnaryOp opc, Init *lhs, RecTy *Type);
727
728   // Clone - Clone this operator, replacing arguments with the new list
729   OpInit *clone(std::vector<Init *> &Operands) const override {
730     assert(Operands.size() == 1 &&
731            "Wrong number of operands for unary operation");
732     return UnOpInit::get(getOpcode(), *Operands.begin(), getType());
733   }
734
735   int getNumOperands() const override { return 1; }
736   Init *getOperand(int i) const override {
737     assert(i == 0 && "Invalid operand id for unary operator");
738     return getOperand();
739   }
740
741   UnaryOp getOpcode() const { return Opc; }
742   Init *getOperand() const { return LHS; }
743
744   // Fold - If possible, fold this to a simpler init.  Return this if not
745   // possible to fold.
746   Init *Fold(Record *CurRec, MultiClass *CurMultiClass) const override;
747
748   Init *resolveReferences(Record &R, const RecordVal *RV) const override;
749
750   std::string getAsString() const override;
751 };
752
753 /// BinOpInit - !op (X, Y) - Combine two inits.
754 ///
755 class BinOpInit : public OpInit {
756 public:
757   enum BinaryOp { ADD, AND, SHL, SRA, SRL, LISTCONCAT, STRCONCAT, CONCAT, EQ };
758
759 private:
760   BinaryOp Opc;
761   Init *LHS, *RHS;
762
763   BinOpInit(BinaryOp opc, Init *lhs, Init *rhs, RecTy *Type) :
764       OpInit(IK_BinOpInit, Type), Opc(opc), LHS(lhs), RHS(rhs) {}
765
766   BinOpInit(const BinOpInit &Other) = delete;
767   BinOpInit &operator=(const BinOpInit &Other) = delete;
768
769 public:
770   static bool classof(const Init *I) {
771     return I->getKind() == IK_BinOpInit;
772   }
773   static BinOpInit *get(BinaryOp opc, Init *lhs, Init *rhs,
774                         RecTy *Type);
775
776   // Clone - Clone this operator, replacing arguments with the new list
777   OpInit *clone(std::vector<Init *> &Operands) const override {
778     assert(Operands.size() == 2 &&
779            "Wrong number of operands for binary operation");
780     return BinOpInit::get(getOpcode(), Operands[0], Operands[1], getType());
781   }
782
783   int getNumOperands() const override { return 2; }
784   Init *getOperand(int i) const override {
785     assert((i == 0 || i == 1) && "Invalid operand id for binary operator");
786     if (i == 0) {
787       return getLHS();
788     } else {
789       return getRHS();
790     }
791   }
792
793   BinaryOp getOpcode() const { return Opc; }
794   Init *getLHS() const { return LHS; }
795   Init *getRHS() const { return RHS; }
796
797   // Fold - If possible, fold this to a simpler init.  Return this if not
798   // possible to fold.
799   Init *Fold(Record *CurRec, MultiClass *CurMultiClass) const override;
800
801   Init *resolveReferences(Record &R, const RecordVal *RV) const override;
802
803   std::string getAsString() const override;
804 };
805
806 /// TernOpInit - !op (X, Y, Z) - Combine two inits.
807 ///
808 class TernOpInit : public OpInit {
809 public:
810   enum TernaryOp { SUBST, FOREACH, IF };
811
812 private:
813   TernaryOp Opc;
814   Init *LHS, *MHS, *RHS;
815
816   TernOpInit(TernaryOp opc, Init *lhs, Init *mhs, Init *rhs,
817              RecTy *Type) :
818       OpInit(IK_TernOpInit, Type), Opc(opc), LHS(lhs), MHS(mhs), RHS(rhs) {}
819
820   TernOpInit(const TernOpInit &Other) = delete;
821   TernOpInit &operator=(const TernOpInit &Other) = delete;
822
823 public:
824   static bool classof(const Init *I) {
825     return I->getKind() == IK_TernOpInit;
826   }
827   static TernOpInit *get(TernaryOp opc, Init *lhs,
828                          Init *mhs, Init *rhs,
829                          RecTy *Type);
830
831   // Clone - Clone this operator, replacing arguments with the new list
832   OpInit *clone(std::vector<Init *> &Operands) const override {
833     assert(Operands.size() == 3 &&
834            "Wrong number of operands for ternary operation");
835     return TernOpInit::get(getOpcode(), Operands[0], Operands[1], Operands[2],
836                            getType());
837   }
838
839   int getNumOperands() const override { return 3; }
840   Init *getOperand(int i) const override {
841     assert((i == 0 || i == 1 || i == 2) &&
842            "Invalid operand id for ternary operator");
843     if (i == 0) {
844       return getLHS();
845     } else if (i == 1) {
846       return getMHS();
847     } else {
848       return getRHS();
849     }
850   }
851
852   TernaryOp getOpcode() const { return Opc; }
853   Init *getLHS() const { return LHS; }
854   Init *getMHS() const { return MHS; }
855   Init *getRHS() const { return RHS; }
856
857   // Fold - If possible, fold this to a simpler init.  Return this if not
858   // possible to fold.
859   Init *Fold(Record *CurRec, MultiClass *CurMultiClass) const override;
860
861   bool isComplete() const override { return false; }
862
863   Init *resolveReferences(Record &R, const RecordVal *RV) const override;
864
865   std::string getAsString() const override;
866 };
867
868 /// VarInit - 'Opcode' - Represent a reference to an entire variable object.
869 ///
870 class VarInit : public TypedInit {
871   Init *VarName;
872
873   explicit VarInit(const std::string &VN, RecTy *T)
874       : TypedInit(IK_VarInit, T), VarName(StringInit::get(VN)) {}
875   explicit VarInit(Init *VN, RecTy *T)
876       : TypedInit(IK_VarInit, T), VarName(VN) {}
877
878   VarInit(const VarInit &Other) = delete;
879   VarInit &operator=(const VarInit &Other) = delete;
880
881 public:
882   static bool classof(const Init *I) {
883     return I->getKind() == IK_VarInit;
884   }
885   static VarInit *get(const std::string &VN, RecTy *T);
886   static VarInit *get(Init *VN, RecTy *T);
887
888   const std::string &getName() const;
889   Init *getNameInit() const { return VarName; }
890   std::string getNameInitAsString() const {
891     return getNameInit()->getAsUnquotedString();
892   }
893
894   Init *resolveListElementReference(Record &R, const RecordVal *RV,
895                                     unsigned Elt) const override;
896
897   RecTy *getFieldType(const std::string &FieldName) const override;
898   Init *getFieldInit(Record &R, const RecordVal *RV,
899                      const std::string &FieldName) const override;
900
901   /// resolveReferences - This method is used by classes that refer to other
902   /// variables which may not be defined at the time they expression is formed.
903   /// If a value is set for the variable later, this method will be called on
904   /// users of the value to allow the value to propagate out.
905   ///
906   Init *resolveReferences(Record &R, const RecordVal *RV) const override;
907
908   Init *getBit(unsigned Bit) const override;
909
910   std::string getAsString() const override { return getName(); }
911 };
912
913 /// VarBitInit - Opcode{0} - Represent access to one bit of a variable or field.
914 ///
915 class VarBitInit : public Init {
916   TypedInit *TI;
917   unsigned Bit;
918
919   VarBitInit(TypedInit *T, unsigned B) : Init(IK_VarBitInit), TI(T), Bit(B) {
920     assert(T->getType() &&
921            (isa<IntRecTy>(T->getType()) ||
922             (isa<BitsRecTy>(T->getType()) &&
923              cast<BitsRecTy>(T->getType())->getNumBits() > B)) &&
924            "Illegal VarBitInit expression!");
925   }
926
927   VarBitInit(const VarBitInit &Other) = delete;
928   VarBitInit &operator=(const VarBitInit &Other) = delete;
929
930 public:
931   static bool classof(const Init *I) {
932     return I->getKind() == IK_VarBitInit;
933   }
934   static VarBitInit *get(TypedInit *T, unsigned B);
935
936   Init *convertInitializerTo(RecTy *Ty) const override;
937
938   Init *getBitVar() const override { return TI; }
939   unsigned getBitNum() const override { return Bit; }
940
941   std::string getAsString() const override;
942   Init *resolveReferences(Record &R, const RecordVal *RV) const override;
943
944   Init *getBit(unsigned B) const override {
945     assert(B < 1 && "Bit index out of range!");
946     return const_cast<VarBitInit*>(this);
947   }
948 };
949
950 /// VarListElementInit - List[4] - Represent access to one element of a var or
951 /// field.
952 class VarListElementInit : public TypedInit {
953   TypedInit *TI;
954   unsigned Element;
955
956   VarListElementInit(TypedInit *T, unsigned E)
957       : TypedInit(IK_VarListElementInit,
958                   cast<ListRecTy>(T->getType())->getElementType()),
959         TI(T), Element(E) {
960     assert(T->getType() && isa<ListRecTy>(T->getType()) &&
961            "Illegal VarBitInit expression!");
962   }
963
964   VarListElementInit(const VarListElementInit &Other) = delete;
965   void operator=(const VarListElementInit &Other) = delete;
966
967 public:
968   static bool classof(const Init *I) {
969     return I->getKind() == IK_VarListElementInit;
970   }
971   static VarListElementInit *get(TypedInit *T, unsigned E);
972
973   TypedInit *getVariable() const { return TI; }
974   unsigned getElementNum() const { return Element; }
975
976   /// resolveListElementReference - This method is used to implement
977   /// VarListElementInit::resolveReferences.  If the list element is resolvable
978   /// now, we return the resolved value, otherwise we return null.
979   Init *resolveListElementReference(Record &R, const RecordVal *RV,
980                                     unsigned Elt) const override;
981
982   std::string getAsString() const override;
983   Init *resolveReferences(Record &R, const RecordVal *RV) const override;
984
985   Init *getBit(unsigned Bit) const override;
986 };
987
988 /// DefInit - AL - Represent a reference to a 'def' in the description
989 ///
990 class DefInit : public TypedInit {
991   Record *Def;
992
993   DefInit(Record *D, RecordRecTy *T) : TypedInit(IK_DefInit, T), Def(D) {}
994   friend class Record;
995
996   DefInit(const DefInit &Other) = delete;
997   DefInit &operator=(const DefInit &Other) = delete;
998
999 public:
1000   static bool classof(const Init *I) {
1001     return I->getKind() == IK_DefInit;
1002   }
1003   static DefInit *get(Record*);
1004
1005   Init *convertInitializerTo(RecTy *Ty) const override;
1006
1007   Record *getDef() const { return Def; }
1008
1009   //virtual Init *convertInitializerBitRange(const std::vector<unsigned> &Bits);
1010
1011   RecTy *getFieldType(const std::string &FieldName) const override;
1012   Init *getFieldInit(Record &R, const RecordVal *RV,
1013                      const std::string &FieldName) const override;
1014
1015   std::string getAsString() const override;
1016
1017   Init *getBit(unsigned Bit) const override {
1018     llvm_unreachable("Illegal bit reference off def");
1019   }
1020
1021   /// resolveListElementReference - This method is used to implement
1022   /// VarListElementInit::resolveReferences.  If the list element is resolvable
1023   /// now, we return the resolved value, otherwise we return null.
1024   Init *resolveListElementReference(Record &R, const RecordVal *RV,
1025                                     unsigned Elt) const override {
1026     llvm_unreachable("Illegal element reference off def");
1027   }
1028 };
1029
1030 /// FieldInit - X.Y - Represent a reference to a subfield of a variable
1031 ///
1032 class FieldInit : public TypedInit {
1033   Init *Rec;                // Record we are referring to
1034   std::string FieldName;    // Field we are accessing
1035
1036   FieldInit(Init *R, const std::string &FN)
1037       : TypedInit(IK_FieldInit, R->getFieldType(FN)), Rec(R), FieldName(FN) {
1038     assert(getType() && "FieldInit with non-record type!");
1039   }
1040
1041   FieldInit(const FieldInit &Other) = delete;
1042   FieldInit &operator=(const FieldInit &Other) = delete;
1043
1044 public:
1045   static bool classof(const Init *I) {
1046     return I->getKind() == IK_FieldInit;
1047   }
1048   static FieldInit *get(Init *R, const std::string &FN);
1049   static FieldInit *get(Init *R, const Init *FN);
1050
1051   Init *getBit(unsigned Bit) const override;
1052
1053   Init *resolveListElementReference(Record &R, const RecordVal *RV,
1054                                     unsigned Elt) const override;
1055
1056   Init *resolveReferences(Record &R, const RecordVal *RV) const override;
1057
1058   std::string getAsString() const override {
1059     return Rec->getAsString() + "." + FieldName;
1060   }
1061 };
1062
1063 /// DagInit - (v a, b) - Represent a DAG tree value.  DAG inits are required
1064 /// to have at least one value then a (possibly empty) list of arguments.  Each
1065 /// argument can have a name associated with it.
1066 ///
1067 class DagInit : public TypedInit, public FoldingSetNode {
1068   Init *Val;
1069   std::string ValName;
1070   std::vector<Init*> Args;
1071   std::vector<std::string> ArgNames;
1072
1073   DagInit(Init *V, const std::string &VN,
1074           ArrayRef<Init *> ArgRange,
1075           ArrayRef<std::string> NameRange)
1076       : TypedInit(IK_DagInit, DagRecTy::get()), Val(V), ValName(VN),
1077           Args(ArgRange.begin(), ArgRange.end()),
1078           ArgNames(NameRange.begin(), NameRange.end()) {}
1079
1080   DagInit(const DagInit &Other) = delete;
1081   DagInit &operator=(const DagInit &Other) = delete;
1082
1083 public:
1084   static bool classof(const Init *I) {
1085     return I->getKind() == IK_DagInit;
1086   }
1087   static DagInit *get(Init *V, const std::string &VN,
1088                       ArrayRef<Init *> ArgRange,
1089                       ArrayRef<std::string> NameRange);
1090   static DagInit *get(Init *V, const std::string &VN,
1091                       const std::vector<
1092                         std::pair<Init*, std::string> > &args);
1093
1094   void Profile(FoldingSetNodeID &ID) const;
1095
1096   Init *convertInitializerTo(RecTy *Ty) const override;
1097
1098   Init *getOperator() const { return Val; }
1099
1100   const std::string &getName() const { return ValName; }
1101
1102   unsigned getNumArgs() const { return Args.size(); }
1103   Init *getArg(unsigned Num) const {
1104     assert(Num < Args.size() && "Arg number out of range!");
1105     return Args[Num];
1106   }
1107   const std::string &getArgName(unsigned Num) const {
1108     assert(Num < ArgNames.size() && "Arg number out of range!");
1109     return ArgNames[Num];
1110   }
1111
1112   Init *resolveReferences(Record &R, const RecordVal *RV) const override;
1113
1114   std::string getAsString() const override;
1115
1116   typedef std::vector<Init*>::const_iterator       const_arg_iterator;
1117   typedef std::vector<std::string>::const_iterator const_name_iterator;
1118
1119   inline const_arg_iterator  arg_begin() const { return Args.begin(); }
1120   inline const_arg_iterator  arg_end  () const { return Args.end();   }
1121
1122   inline size_t              arg_size () const { return Args.size();  }
1123   inline bool                arg_empty() const { return Args.empty(); }
1124
1125   inline const_name_iterator name_begin() const { return ArgNames.begin(); }
1126   inline const_name_iterator name_end  () const { return ArgNames.end();   }
1127
1128   inline size_t              name_size () const { return ArgNames.size();  }
1129   inline bool                name_empty() const { return ArgNames.empty(); }
1130
1131   Init *getBit(unsigned Bit) const override {
1132     llvm_unreachable("Illegal bit reference off dag");
1133   }
1134
1135   Init *resolveListElementReference(Record &R, const RecordVal *RV,
1136                                     unsigned Elt) const override {
1137     llvm_unreachable("Illegal element reference off dag");
1138   }
1139 };
1140
1141 //===----------------------------------------------------------------------===//
1142 //  High-Level Classes
1143 //===----------------------------------------------------------------------===//
1144
1145 class RecordVal {
1146   Init *Name;
1147   RecTy *Ty;
1148   unsigned Prefix;
1149   Init *Value;
1150
1151 public:
1152   RecordVal(Init *N, RecTy *T, unsigned P);
1153   RecordVal(const std::string &N, RecTy *T, unsigned P);
1154
1155   const std::string &getName() const;
1156   const Init *getNameInit() const { return Name; }
1157   std::string getNameInitAsString() const {
1158     return getNameInit()->getAsUnquotedString();
1159   }
1160
1161   unsigned getPrefix() const { return Prefix; }
1162   RecTy *getType() const { return Ty; }
1163   Init *getValue() const { return Value; }
1164
1165   bool setValue(Init *V) {
1166     if (V) {
1167       Value = V->convertInitializerTo(Ty);
1168       return Value == nullptr;
1169     }
1170     Value = nullptr;
1171     return false;
1172   }
1173
1174   void dump() const;
1175   void print(raw_ostream &OS, bool PrintSem = true) const;
1176 };
1177
1178 inline raw_ostream &operator<<(raw_ostream &OS, const RecordVal &RV) {
1179   RV.print(OS << "  ");
1180   return OS;
1181 }
1182
1183 class Record {
1184   static unsigned LastID;
1185
1186   // Unique record ID.
1187   unsigned ID;
1188   Init *Name;
1189   // Location where record was instantiated, followed by the location of
1190   // multiclass prototypes used.
1191   SmallVector<SMLoc, 4> Locs;
1192   std::vector<Init *> TemplateArgs;
1193   std::vector<RecordVal> Values;
1194   std::vector<Record *> SuperClasses;
1195   std::vector<SMRange> SuperClassRanges;
1196
1197   // Tracks Record instances. Not owned by Record.
1198   RecordKeeper &TrackedRecords;
1199
1200   DefInit *TheInit;
1201   bool IsAnonymous;
1202
1203   // Class-instance values can be used by other defs.  For example, Struct<i>
1204   // is used here as a template argument to another class:
1205   //
1206   //   multiclass MultiClass<int i> {
1207   //     def Def : Class<Struct<i>>;
1208   //
1209   // These need to get fully resolved before instantiating any other
1210   // definitions that usie them (e.g. Def).  However, inside a multiclass they
1211   // can't be immediately resolved so we mark them ResolveFirst to fully
1212   // resolve them later as soon as the multiclass is instantiated.
1213   bool ResolveFirst;
1214
1215   void init();
1216   void checkName();
1217
1218 public:
1219   // Constructs a record.
1220   explicit Record(const std::string &N, ArrayRef<SMLoc> locs,
1221                   RecordKeeper &records, bool Anonymous = false) :
1222     ID(LastID++), Name(StringInit::get(N)), Locs(locs.begin(), locs.end()),
1223     TrackedRecords(records), TheInit(nullptr), IsAnonymous(Anonymous),
1224     ResolveFirst(false) {
1225     init();
1226   }
1227   explicit Record(Init *N, ArrayRef<SMLoc> locs, RecordKeeper &records,
1228                   bool Anonymous = false) :
1229     ID(LastID++), Name(N), Locs(locs.begin(), locs.end()),
1230     TrackedRecords(records), TheInit(nullptr), IsAnonymous(Anonymous),
1231     ResolveFirst(false) {
1232     init();
1233   }
1234
1235   // When copy-constructing a Record, we must still guarantee a globally unique
1236   // ID number.  All other fields can be copied normally.
1237   Record(const Record &O) :
1238     ID(LastID++), Name(O.Name), Locs(O.Locs), TemplateArgs(O.TemplateArgs),
1239     Values(O.Values), SuperClasses(O.SuperClasses),
1240     SuperClassRanges(O.SuperClassRanges), TrackedRecords(O.TrackedRecords),
1241     TheInit(O.TheInit), IsAnonymous(O.IsAnonymous),
1242     ResolveFirst(O.ResolveFirst) { }
1243
1244   static unsigned getNewUID() { return LastID++; }
1245
1246   unsigned getID() const { return ID; }
1247
1248   const std::string &getName() const;
1249   Init *getNameInit() const {
1250     return Name;
1251   }
1252   const std::string getNameInitAsString() const {
1253     return getNameInit()->getAsUnquotedString();
1254   }
1255
1256   void setName(Init *Name);               // Also updates RecordKeeper.
1257   void setName(const std::string &Name);  // Also updates RecordKeeper.
1258
1259   ArrayRef<SMLoc> getLoc() const { return Locs; }
1260
1261   /// get the corresponding DefInit.
1262   DefInit *getDefInit();
1263
1264   const std::vector<Init *> &getTemplateArgs() const {
1265     return TemplateArgs;
1266   }
1267   const std::vector<RecordVal> &getValues() const { return Values; }
1268   const std::vector<Record*>   &getSuperClasses() const { return SuperClasses; }
1269   ArrayRef<SMRange> getSuperClassRanges() const { return SuperClassRanges; }
1270
1271   bool isTemplateArg(Init *Name) const {
1272     for (unsigned i = 0, e = TemplateArgs.size(); i != e; ++i)
1273       if (TemplateArgs[i] == Name) return true;
1274     return false;
1275   }
1276   bool isTemplateArg(StringRef Name) const {
1277     return isTemplateArg(StringInit::get(Name));
1278   }
1279
1280   const RecordVal *getValue(const Init *Name) const {
1281     for (unsigned i = 0, e = Values.size(); i != e; ++i)
1282       if (Values[i].getNameInit() == Name) return &Values[i];
1283     return nullptr;
1284   }
1285   const RecordVal *getValue(StringRef Name) const {
1286     return getValue(StringInit::get(Name));
1287   }
1288   RecordVal *getValue(const Init *Name) {
1289     for (unsigned i = 0, e = Values.size(); i != e; ++i)
1290       if (Values[i].getNameInit() == Name) return &Values[i];
1291     return nullptr;
1292   }
1293   RecordVal *getValue(StringRef Name) {
1294     return getValue(StringInit::get(Name));
1295   }
1296
1297   void addTemplateArg(Init *Name) {
1298     assert(!isTemplateArg(Name) && "Template arg already defined!");
1299     TemplateArgs.push_back(Name);
1300   }
1301   void addTemplateArg(StringRef Name) {
1302     addTemplateArg(StringInit::get(Name));
1303   }
1304
1305   void addValue(const RecordVal &RV) {
1306     assert(getValue(RV.getNameInit()) == nullptr && "Value already added!");
1307     Values.push_back(RV);
1308     if (Values.size() > 1)
1309       // Keep NAME at the end of the list.  It makes record dumps a
1310       // bit prettier and allows TableGen tests to be written more
1311       // naturally.  Tests can use CHECK-NEXT to look for Record
1312       // fields they expect to see after a def.  They can't do that if
1313       // NAME is the first Record field.
1314       std::swap(Values[Values.size() - 2], Values[Values.size() - 1]);
1315   }
1316
1317   void removeValue(Init *Name) {
1318     for (unsigned i = 0, e = Values.size(); i != e; ++i)
1319       if (Values[i].getNameInit() == Name) {
1320         Values.erase(Values.begin()+i);
1321         return;
1322       }
1323     llvm_unreachable("Cannot remove an entry that does not exist!");
1324   }
1325
1326   void removeValue(StringRef Name) {
1327     removeValue(StringInit::get(Name));
1328   }
1329
1330   bool isSubClassOf(const Record *R) const {
1331     for (unsigned i = 0, e = SuperClasses.size(); i != e; ++i)
1332       if (SuperClasses[i] == R)
1333         return true;
1334     return false;
1335   }
1336
1337   bool isSubClassOf(StringRef Name) const {
1338     for (unsigned i = 0, e = SuperClasses.size(); i != e; ++i)
1339       if (SuperClasses[i]->getNameInitAsString() == Name)
1340         return true;
1341     return false;
1342   }
1343
1344   void addSuperClass(Record *R, SMRange Range) {
1345     assert(!isSubClassOf(R) && "Already subclassing record!");
1346     SuperClasses.push_back(R);
1347     SuperClassRanges.push_back(Range);
1348   }
1349
1350   /// resolveReferences - If there are any field references that refer to fields
1351   /// that have been filled in, we can propagate the values now.
1352   ///
1353   void resolveReferences() { resolveReferencesTo(nullptr); }
1354
1355   /// resolveReferencesTo - If anything in this record refers to RV, replace the
1356   /// reference to RV with the RHS of RV.  If RV is null, we resolve all
1357   /// possible references.
1358   void resolveReferencesTo(const RecordVal *RV);
1359
1360   RecordKeeper &getRecords() const {
1361     return TrackedRecords;
1362   }
1363
1364   bool isAnonymous() const {
1365     return IsAnonymous;
1366   }
1367
1368   bool isResolveFirst() const {
1369     return ResolveFirst;
1370   }
1371
1372   void setResolveFirst(bool b) {
1373     ResolveFirst = b;
1374   }
1375
1376   void dump() const;
1377
1378   //===--------------------------------------------------------------------===//
1379   // High-level methods useful to tablegen back-ends
1380   //
1381
1382   /// getValueInit - Return the initializer for a value with the specified name,
1383   /// or throw an exception if the field does not exist.
1384   ///
1385   Init *getValueInit(StringRef FieldName) const;
1386
1387   /// Return true if the named field is unset.
1388   bool isValueUnset(StringRef FieldName) const {
1389     return getValueInit(FieldName) == UnsetInit::get();
1390   }
1391
1392   /// getValueAsString - This method looks up the specified field and returns
1393   /// its value as a string, throwing an exception if the field does not exist
1394   /// or if the value is not a string.
1395   ///
1396   std::string getValueAsString(StringRef FieldName) const;
1397
1398   /// getValueAsBitsInit - This method looks up the specified field and returns
1399   /// its value as a BitsInit, throwing an exception if the field does not exist
1400   /// or if the value is not the right type.
1401   ///
1402   BitsInit *getValueAsBitsInit(StringRef FieldName) const;
1403
1404   /// getValueAsListInit - This method looks up the specified field and returns
1405   /// its value as a ListInit, throwing an exception if the field does not exist
1406   /// or if the value is not the right type.
1407   ///
1408   ListInit *getValueAsListInit(StringRef FieldName) const;
1409
1410   /// getValueAsListOfDefs - This method looks up the specified field and
1411   /// returns its value as a vector of records, throwing an exception if the
1412   /// field does not exist or if the value is not the right type.
1413   ///
1414   std::vector<Record*> getValueAsListOfDefs(StringRef FieldName) const;
1415
1416   /// getValueAsListOfInts - This method looks up the specified field and
1417   /// returns its value as a vector of integers, throwing an exception if the
1418   /// field does not exist or if the value is not the right type.
1419   ///
1420   std::vector<int64_t> getValueAsListOfInts(StringRef FieldName) const;
1421
1422   /// getValueAsListOfStrings - This method looks up the specified field and
1423   /// returns its value as a vector of strings, throwing an exception if the
1424   /// field does not exist or if the value is not the right type.
1425   ///
1426   std::vector<std::string> getValueAsListOfStrings(StringRef FieldName) const;
1427
1428   /// getValueAsDef - This method looks up the specified field and returns its
1429   /// value as a Record, throwing an exception if the field does not exist or if
1430   /// the value is not the right type.
1431   ///
1432   Record *getValueAsDef(StringRef FieldName) const;
1433
1434   /// getValueAsBit - This method looks up the specified field and returns its
1435   /// value as a bit, throwing an exception if the field does not exist or if
1436   /// the value is not the right type.
1437   ///
1438   bool getValueAsBit(StringRef FieldName) const;
1439
1440   /// getValueAsBitOrUnset - This method looks up the specified field and
1441   /// returns its value as a bit. If the field is unset, sets Unset to true and
1442   /// returns false.
1443   ///
1444   bool getValueAsBitOrUnset(StringRef FieldName, bool &Unset) const;
1445
1446   /// getValueAsInt - This method looks up the specified field and returns its
1447   /// value as an int64_t, throwing an exception if the field does not exist or
1448   /// if the value is not the right type.
1449   ///
1450   int64_t getValueAsInt(StringRef FieldName) const;
1451
1452   /// getValueAsDag - This method looks up the specified field and returns its
1453   /// value as an Dag, throwing an exception if the field does not exist or if
1454   /// the value is not the right type.
1455   ///
1456   DagInit *getValueAsDag(StringRef FieldName) const;
1457 };
1458
1459 raw_ostream &operator<<(raw_ostream &OS, const Record &R);
1460
1461 struct MultiClass {
1462   Record Rec;  // Placeholder for template args and Name.
1463   typedef std::vector<std::unique_ptr<Record>> RecordVector;
1464   RecordVector DefPrototypes;
1465
1466   void dump() const;
1467
1468   MultiClass(const std::string &Name, SMLoc Loc, RecordKeeper &Records) :
1469     Rec(Name, Loc, Records) {}
1470 };
1471
1472 class RecordKeeper {
1473   typedef std::map<std::string, std::unique_ptr<Record>> RecordMap;
1474   RecordMap Classes, Defs;
1475
1476 public:
1477   const RecordMap &getClasses() const { return Classes; }
1478   const RecordMap &getDefs() const { return Defs; }
1479
1480   Record *getClass(const std::string &Name) const {
1481     auto I = Classes.find(Name);
1482     return I == Classes.end() ? nullptr : I->second.get();
1483   }
1484   Record *getDef(const std::string &Name) const {
1485     auto I = Defs.find(Name);
1486     return I == Defs.end() ? nullptr : I->second.get();
1487   }
1488   void addClass(std::unique_ptr<Record> R) {
1489     bool Ins = Classes.insert(std::make_pair(R->getName(),
1490                                              std::move(R))).second;
1491     (void)Ins;
1492     assert(Ins && "Class already exists");
1493   }
1494   void addDef(std::unique_ptr<Record> R) {
1495     bool Ins = Defs.insert(std::make_pair(R->getName(),
1496                                           std::move(R))).second;
1497     (void)Ins;
1498     assert(Ins && "Record already exists");
1499   }
1500
1501   //===--------------------------------------------------------------------===//
1502   // High-level helper methods, useful for tablegen backends...
1503
1504   /// getAllDerivedDefinitions - This method returns all concrete definitions
1505   /// that derive from the specified class name.  If a class with the specified
1506   /// name does not exist, an exception is thrown.
1507   std::vector<Record*>
1508   getAllDerivedDefinitions(const std::string &ClassName) const;
1509
1510   void dump() const;
1511 };
1512
1513 /// LessRecord - Sorting predicate to sort record pointers by name.
1514 ///
1515 struct LessRecord {
1516   bool operator()(const Record *Rec1, const Record *Rec2) const {
1517     return StringRef(Rec1->getName()).compare_numeric(Rec2->getName()) < 0;
1518   }
1519 };
1520
1521 /// LessRecordByID - Sorting predicate to sort record pointers by their
1522 /// unique ID. If you just need a deterministic order, use this, since it
1523 /// just compares two `unsigned`; the other sorting predicates require
1524 /// string manipulation.
1525 struct LessRecordByID {
1526   bool operator()(const Record *LHS, const Record *RHS) const {
1527     return LHS->getID() < RHS->getID();
1528   }
1529 };
1530
1531 /// LessRecordFieldName - Sorting predicate to sort record pointers by their
1532 /// name field.
1533 ///
1534 struct LessRecordFieldName {
1535   bool operator()(const Record *Rec1, const Record *Rec2) const {
1536     return Rec1->getValueAsString("Name") < Rec2->getValueAsString("Name");
1537   }
1538 };
1539
1540 struct LessRecordRegister {
1541   static size_t min(size_t a, size_t b) { return a < b ? a : b; }
1542   static bool ascii_isdigit(char x) { return x >= '0' && x <= '9'; }
1543
1544   struct RecordParts {
1545     SmallVector<std::pair< bool, StringRef>, 4> Parts;
1546
1547     RecordParts(StringRef Rec) {
1548       if (Rec.empty())
1549         return;
1550
1551       size_t Len = 0;
1552       const char *Start = Rec.data();
1553       const char *Curr = Start;
1554       bool isDigitPart = ascii_isdigit(Curr[0]);
1555       for (size_t I = 0, E = Rec.size(); I != E; ++I, ++Len) {
1556         bool isDigit = ascii_isdigit(Curr[I]);
1557         if (isDigit != isDigitPart) {
1558           Parts.push_back(std::make_pair(isDigitPart, StringRef(Start, Len)));
1559           Len = 0;
1560           Start = &Curr[I];
1561           isDigitPart = ascii_isdigit(Curr[I]);
1562         }
1563       }
1564       // Push the last part.
1565       Parts.push_back(std::make_pair(isDigitPart, StringRef(Start, Len)));
1566     }
1567
1568     size_t size() { return Parts.size(); }
1569
1570     std::pair<bool, StringRef> getPart(size_t i) {
1571       assert (i < Parts.size() && "Invalid idx!");
1572       return Parts[i];
1573     }
1574   };
1575
1576   bool operator()(const Record *Rec1, const Record *Rec2) const {
1577     RecordParts LHSParts(StringRef(Rec1->getName()));
1578     RecordParts RHSParts(StringRef(Rec2->getName()));
1579
1580     size_t LHSNumParts = LHSParts.size();
1581     size_t RHSNumParts = RHSParts.size();
1582     assert (LHSNumParts && RHSNumParts && "Expected at least one part!");
1583
1584     if (LHSNumParts != RHSNumParts)
1585       return LHSNumParts < RHSNumParts;
1586
1587     // We expect the registers to be of the form [_a-zA-z]+([0-9]*[_a-zA-Z]*)*.
1588     for (size_t I = 0, E = LHSNumParts; I < E; I+=2) {
1589       std::pair<bool, StringRef> LHSPart = LHSParts.getPart(I);
1590       std::pair<bool, StringRef> RHSPart = RHSParts.getPart(I);
1591       // Expect even part to always be alpha.
1592       assert (LHSPart.first == false && RHSPart.first == false &&
1593               "Expected both parts to be alpha.");
1594       if (int Res = LHSPart.second.compare(RHSPart.second))
1595         return Res < 0;
1596     }
1597     for (size_t I = 1, E = LHSNumParts; I < E; I+=2) {
1598       std::pair<bool, StringRef> LHSPart = LHSParts.getPart(I);
1599       std::pair<bool, StringRef> RHSPart = RHSParts.getPart(I);
1600       // Expect odd part to always be numeric.
1601       assert (LHSPart.first == true && RHSPart.first == true &&
1602               "Expected both parts to be numeric.");
1603       if (LHSPart.second.size() != RHSPart.second.size())
1604         return LHSPart.second.size() < RHSPart.second.size();
1605
1606       unsigned LHSVal, RHSVal;
1607
1608       bool LHSFailed = LHSPart.second.getAsInteger(10, LHSVal); (void)LHSFailed;
1609       assert(!LHSFailed && "Unable to convert LHS to integer.");
1610       bool RHSFailed = RHSPart.second.getAsInteger(10, RHSVal); (void)RHSFailed;
1611       assert(!RHSFailed && "Unable to convert RHS to integer.");
1612
1613       if (LHSVal != RHSVal)
1614         return LHSVal < RHSVal;
1615     }
1616     return LHSNumParts < RHSNumParts;
1617   }
1618 };
1619
1620 raw_ostream &operator<<(raw_ostream &OS, const RecordKeeper &RK);
1621
1622 /// QualifyName - Return an Init with a qualifier prefix referring
1623 /// to CurRec's name.
1624 Init *QualifyName(Record &CurRec, MultiClass *CurMultiClass,
1625                   Init *Name, const std::string &Scoper);
1626
1627 /// QualifyName - Return an Init with a qualifier prefix referring
1628 /// to CurRec's name.
1629 Init *QualifyName(Record &CurRec, MultiClass *CurMultiClass,
1630                   const std::string &Name, const std::string &Scoper);
1631
1632 } // End llvm namespace
1633
1634 #endif