Converted a1.ll to unittests.
[oota-llvm.git] / utils / TableGen / Record.cpp
1 //===- Record.cpp - Record implementation ---------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // Implement the tablegen record classes.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "Record.h"
15 #include "llvm/Support/DataTypes.h"
16 #include "llvm/Support/Streams.h"
17 #include "llvm/ADT/StringExtras.h"
18 #include <ios>
19
20 using namespace llvm;
21
22 //===----------------------------------------------------------------------===//
23 //    Type implementations
24 //===----------------------------------------------------------------------===//
25
26 void RecTy::dump() const { print(*cerr.stream()); }
27
28 Init *BitRecTy::convertValue(BitsInit *BI) {
29   if (BI->getNumBits() != 1) return 0; // Only accept if just one bit!
30   return BI->getBit(0);
31 }
32
33 bool BitRecTy::baseClassOf(const BitsRecTy *RHS) const {
34   return RHS->getNumBits() == 1;
35 }
36
37 Init *BitRecTy::convertValue(IntInit *II) {
38   int64_t Val = II->getValue();
39   if (Val != 0 && Val != 1) return 0;  // Only accept 0 or 1 for a bit!
40
41   return new BitInit(Val != 0);
42 }
43
44 Init *BitRecTy::convertValue(TypedInit *VI) {
45   if (dynamic_cast<BitRecTy*>(VI->getType()))
46     return VI;  // Accept variable if it is already of bit type!
47   return 0;
48 }
49
50 std::string BitsRecTy::getAsString() const {
51   return "bits<" + utostr(Size) + ">";
52 }
53
54 Init *BitsRecTy::convertValue(UnsetInit *UI) {
55   BitsInit *Ret = new BitsInit(Size);
56
57   for (unsigned i = 0; i != Size; ++i)
58     Ret->setBit(i, new UnsetInit());
59   return Ret;
60 }
61
62 Init *BitsRecTy::convertValue(BitInit *UI) {
63   if (Size != 1) return 0;  // Can only convert single bit...
64   BitsInit *Ret = new BitsInit(1);
65   Ret->setBit(0, UI);
66   return Ret;
67 }
68
69 // convertValue from Int initializer to bits type: Split the integer up into the
70 // appropriate bits...
71 //
72 Init *BitsRecTy::convertValue(IntInit *II) {
73   int64_t Value = II->getValue();
74   // Make sure this bitfield is large enough to hold the integer value...
75   if (Value >= 0) {
76     if (Value & ~((1LL << Size)-1))
77       return 0;
78   } else {
79     if ((Value >> Size) != -1 || ((Value & (1LL << (Size-1))) == 0))
80       return 0;
81   }
82
83   BitsInit *Ret = new BitsInit(Size);
84   for (unsigned i = 0; i != Size; ++i)
85     Ret->setBit(i, new BitInit(Value & (1LL << i)));
86
87   return Ret;
88 }
89
90 Init *BitsRecTy::convertValue(BitsInit *BI) {
91   // If the number of bits is right, return it.  Otherwise we need to expand or
92   // truncate...
93   if (BI->getNumBits() == Size) return BI;
94   return 0;
95 }
96
97 Init *BitsRecTy::convertValue(TypedInit *VI) {
98   if (BitsRecTy *BRT = dynamic_cast<BitsRecTy*>(VI->getType()))
99     if (BRT->Size == Size) {
100       BitsInit *Ret = new BitsInit(Size);
101       for (unsigned i = 0; i != Size; ++i)
102         Ret->setBit(i, new VarBitInit(VI, i));
103       return Ret;
104     }
105   if (Size == 1 && dynamic_cast<BitRecTy*>(VI->getType())) {
106     BitsInit *Ret = new BitsInit(1);
107     Ret->setBit(0, VI);
108     return Ret;
109   }
110
111   return 0;
112 }
113
114 Init *IntRecTy::convertValue(BitInit *BI) {
115   return new IntInit(BI->getValue());
116 }
117
118 Init *IntRecTy::convertValue(BitsInit *BI) {
119   int64_t Result = 0;
120   for (unsigned i = 0, e = BI->getNumBits(); i != e; ++i)
121     if (BitInit *Bit = dynamic_cast<BitInit*>(BI->getBit(i))) {
122       Result |= Bit->getValue() << i;
123     } else {
124       return 0;
125     }
126   return new IntInit(Result);
127 }
128
129 Init *IntRecTy::convertValue(TypedInit *TI) {
130   if (TI->getType()->typeIsConvertibleTo(this))
131     return TI;  // Accept variable if already of the right type!
132   return 0;
133 }
134
135 Init *StringRecTy::convertValue(BinOpInit *BO) {
136   if (BO->getOpcode() == BinOpInit::STRCONCAT) {
137     Init *L = BO->getLHS()->convertInitializerTo(this);
138     Init *R = BO->getRHS()->convertInitializerTo(this);
139     if (L == 0 || R == 0) return 0;
140     if (L != BO->getLHS() || R != BO->getRHS())
141       return new BinOpInit(BinOpInit::STRCONCAT, L, R);
142     return BO;
143   }
144   return 0;
145 }
146
147
148 Init *StringRecTy::convertValue(TypedInit *TI) {
149   if (dynamic_cast<StringRecTy*>(TI->getType()))
150     return TI;  // Accept variable if already of the right type!
151   return 0;
152 }
153
154 std::string ListRecTy::getAsString() const {
155   return "list<" + Ty->getAsString() + ">";
156 }
157
158 Init *ListRecTy::convertValue(ListInit *LI) {
159   std::vector<Init*> Elements;
160
161   // Verify that all of the elements of the list are subclasses of the
162   // appropriate class!
163   for (unsigned i = 0, e = LI->getSize(); i != e; ++i)
164     if (Init *CI = LI->getElement(i)->convertInitializerTo(Ty))
165       Elements.push_back(CI);
166     else
167       return 0;
168
169   return new ListInit(Elements);
170 }
171
172 Init *ListRecTy::convertValue(TypedInit *TI) {
173   // Ensure that TI is compatible with our class.
174   if (ListRecTy *LRT = dynamic_cast<ListRecTy*>(TI->getType()))
175     if (LRT->getElementType()->typeIsConvertibleTo(getElementType()))
176       return TI;
177   return 0;
178 }
179
180 Init *CodeRecTy::convertValue(TypedInit *TI) {
181   if (TI->getType()->typeIsConvertibleTo(this))
182     return TI;
183   return 0;
184 }
185
186 Init *DagRecTy::convertValue(TypedInit *TI) {
187   if (TI->getType()->typeIsConvertibleTo(this))
188     return TI;
189   return 0;
190 }
191
192 Init *DagRecTy::convertValue(BinOpInit *BO) {
193   if (BO->getOpcode() == BinOpInit::CONCAT) {
194     Init *L = BO->getLHS()->convertInitializerTo(this);
195     Init *R = BO->getRHS()->convertInitializerTo(this);
196     if (L == 0 || R == 0) return 0;
197     if (L != BO->getLHS() || R != BO->getRHS())
198       return new BinOpInit(BinOpInit::CONCAT, L, R);
199     return BO;
200   }
201   return 0;
202 }
203
204 std::string RecordRecTy::getAsString() const {
205   return Rec->getName();
206 }
207
208 Init *RecordRecTy::convertValue(DefInit *DI) {
209   // Ensure that DI is a subclass of Rec.
210   if (!DI->getDef()->isSubClassOf(Rec))
211     return 0;
212   return DI;
213 }
214
215 Init *RecordRecTy::convertValue(TypedInit *TI) {
216   // Ensure that TI is compatible with Rec.
217   if (RecordRecTy *RRT = dynamic_cast<RecordRecTy*>(TI->getType()))
218     if (RRT->getRecord()->isSubClassOf(getRecord()) ||
219         RRT->getRecord() == getRecord())
220       return TI;
221   return 0;
222 }
223
224 bool RecordRecTy::baseClassOf(const RecordRecTy *RHS) const {
225   return Rec == RHS->getRecord() || RHS->getRecord()->isSubClassOf(Rec);
226 }
227
228
229 //===----------------------------------------------------------------------===//
230 //    Initializer implementations
231 //===----------------------------------------------------------------------===//
232
233 void Init::dump() const { return print(*cerr.stream()); }
234
235 Init *BitsInit::convertInitializerBitRange(const std::vector<unsigned> &Bits) {
236   BitsInit *BI = new BitsInit(Bits.size());
237   for (unsigned i = 0, e = Bits.size(); i != e; ++i) {
238     if (Bits[i] >= getNumBits()) {
239       delete BI;
240       return 0;
241     }
242     BI->setBit(i, getBit(Bits[i]));
243   }
244   return BI;
245 }
246
247 std::string BitsInit::getAsString() const {
248   //if (!printInHex(OS)) return;
249   //if (!printAsVariable(OS)) return;
250   //if (!printAsUnset(OS)) return;
251
252   std::string Result = "{ ";
253   for (unsigned i = 0, e = getNumBits(); i != e; ++i) {
254     if (i) Result += ", ";
255     if (Init *Bit = getBit(e-i-1))
256       Result += Bit->getAsString();
257     else
258       Result += "*";
259   }
260   return Result + " }";
261 }
262
263 bool BitsInit::printInHex(std::ostream &OS) const {
264   // First, attempt to convert the value into an integer value...
265   int64_t Result = 0;
266   for (unsigned i = 0, e = getNumBits(); i != e; ++i)
267     if (BitInit *Bit = dynamic_cast<BitInit*>(getBit(i))) {
268       Result |= Bit->getValue() << i;
269     } else {
270       return true;
271     }
272
273   OS << "0x" << std::hex << Result << std::dec;
274   return false;
275 }
276
277 bool BitsInit::printAsVariable(std::ostream &OS) const {
278   // Get the variable that we may be set equal to...
279   assert(getNumBits() != 0);
280   VarBitInit *FirstBit = dynamic_cast<VarBitInit*>(getBit(0));
281   if (FirstBit == 0) return true;
282   TypedInit *Var = FirstBit->getVariable();
283
284   // Check to make sure the types are compatible.
285   BitsRecTy *Ty = dynamic_cast<BitsRecTy*>(FirstBit->getVariable()->getType());
286   if (Ty == 0) return true;
287   if (Ty->getNumBits() != getNumBits()) return true; // Incompatible types!
288
289   // Check to make sure all bits are referring to the right bits in the variable
290   for (unsigned i = 0, e = getNumBits(); i != e; ++i) {
291     VarBitInit *Bit = dynamic_cast<VarBitInit*>(getBit(i));
292     if (Bit == 0 || Bit->getVariable() != Var || Bit->getBitNum() != i)
293       return true;
294   }
295
296   Var->print(OS);
297   return false;
298 }
299
300 bool BitsInit::printAsUnset(std::ostream &OS) const {
301   for (unsigned i = 0, e = getNumBits(); i != e; ++i)
302     if (!dynamic_cast<UnsetInit*>(getBit(i)))
303       return true;
304   OS << "?";
305   return false;
306 }
307
308 // resolveReferences - If there are any field references that refer to fields
309 // that have been filled in, we can propagate the values now.
310 //
311 Init *BitsInit::resolveReferences(Record &R, const RecordVal *RV) {
312   bool Changed = false;
313   BitsInit *New = new BitsInit(getNumBits());
314
315   for (unsigned i = 0, e = Bits.size(); i != e; ++i) {
316     Init *B;
317     Init *CurBit = getBit(i);
318
319     do {
320       B = CurBit;
321       CurBit = CurBit->resolveReferences(R, RV);
322       Changed |= B != CurBit;
323     } while (B != CurBit);
324     New->setBit(i, CurBit);
325   }
326
327   if (Changed)
328     return New;
329   delete New;
330   return this;
331 }
332
333 std::string IntInit::getAsString() const {
334   return itostr(Value);
335 }
336
337 Init *IntInit::convertInitializerBitRange(const std::vector<unsigned> &Bits) {
338   BitsInit *BI = new BitsInit(Bits.size());
339
340   for (unsigned i = 0, e = Bits.size(); i != e; ++i) {
341     if (Bits[i] >= 64) {
342       delete BI;
343       return 0;
344     }
345     BI->setBit(i, new BitInit(Value & (INT64_C(1) << Bits[i])));
346   }
347   return BI;
348 }
349
350 Init *ListInit::convertInitListSlice(const std::vector<unsigned> &Elements) {
351   std::vector<Init*> Vals;
352   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
353     if (Elements[i] >= getSize())
354       return 0;
355     Vals.push_back(getElement(Elements[i]));
356   }
357   return new ListInit(Vals);
358 }
359
360 Record *ListInit::getElementAsRecord(unsigned i) const {
361   assert(i < Values.size() && "List element index out of range!");
362   DefInit *DI = dynamic_cast<DefInit*>(Values[i]);
363   if (DI == 0) throw "Expected record in list!";
364   return DI->getDef();
365 }
366
367 Init *ListInit::resolveReferences(Record &R, const RecordVal *RV) {
368   std::vector<Init*> Resolved;
369   Resolved.reserve(getSize());
370   bool Changed = false;
371
372   for (unsigned i = 0, e = getSize(); i != e; ++i) {
373     Init *E;
374     Init *CurElt = getElement(i);
375
376     do {
377       E = CurElt;
378       CurElt = CurElt->resolveReferences(R, RV);
379       Changed |= E != CurElt;
380     } while (E != CurElt);
381     Resolved.push_back(E);
382   }
383
384   if (Changed)
385     return new ListInit(Resolved);
386   return this;
387 }
388
389 std::string ListInit::getAsString() const {
390   std::string Result = "[";
391   for (unsigned i = 0, e = Values.size(); i != e; ++i) {
392     if (i) Result += ", ";
393     Result += Values[i]->getAsString();
394   }
395   return Result + "]";
396 }
397
398 Init *BinOpInit::Fold() {
399   switch (getOpcode()) {
400   default: assert(0 && "Unknown binop");
401   case CONCAT: {
402     DagInit *LHSs = dynamic_cast<DagInit*>(LHS);
403     DagInit *RHSs = dynamic_cast<DagInit*>(RHS);
404     if (LHSs && RHSs) {
405       DefInit *LOp = dynamic_cast<DefInit*>(LHSs->getOperator());
406       DefInit *ROp = dynamic_cast<DefInit*>(RHSs->getOperator());
407       if (LOp->getDef() != ROp->getDef()) {
408         bool LIsOps =
409           LOp->getDef()->getName() == "outs" ||
410           LOp->getDef()->getName() != "ins" ||
411           LOp->getDef()->getName() != "defs";
412         bool RIsOps =
413           ROp->getDef()->getName() == "outs" ||
414           ROp->getDef()->getName() != "ins" ||
415           ROp->getDef()->getName() != "defs";
416         if (!LIsOps || !RIsOps)
417           throw "Concated Dag operators do not match!";
418       }
419       std::vector<Init*> Args;
420       std::vector<std::string> ArgNames;
421       for (unsigned i = 0, e = LHSs->getNumArgs(); i != e; ++i) {
422         Args.push_back(LHSs->getArg(i));
423         ArgNames.push_back(LHSs->getArgName(i));
424       }
425       for (unsigned i = 0, e = RHSs->getNumArgs(); i != e; ++i) {
426         Args.push_back(RHSs->getArg(i));
427         ArgNames.push_back(RHSs->getArgName(i));
428       }
429       return new DagInit(LHSs->getOperator(), "", Args, ArgNames);
430     }
431     break;
432   }
433   case STRCONCAT: {
434     StringInit *LHSs = dynamic_cast<StringInit*>(LHS);
435     StringInit *RHSs = dynamic_cast<StringInit*>(RHS);
436     if (LHSs && RHSs)
437       return new StringInit(LHSs->getValue() + RHSs->getValue());
438     break;
439   }
440   case SHL:
441   case SRA:
442   case SRL: {
443     IntInit *LHSi = dynamic_cast<IntInit*>(LHS);
444     IntInit *RHSi = dynamic_cast<IntInit*>(RHS);
445     if (LHSi && RHSi) {
446       int64_t LHSv = LHSi->getValue(), RHSv = RHSi->getValue();
447       int64_t Result;
448       switch (getOpcode()) {
449       default: assert(0 && "Bad opcode!");
450       case SHL: Result = LHSv << RHSv; break;
451       case SRA: Result = LHSv >> RHSv; break;
452       case SRL: Result = (uint64_t)LHSv >> (uint64_t)RHSv; break;
453       }
454       return new IntInit(Result);
455     }
456     break;
457   }
458   }
459   return this;
460 }
461
462 Init *BinOpInit::resolveReferences(Record &R, const RecordVal *RV) {
463   Init *lhs = LHS->resolveReferences(R, RV);
464   Init *rhs = RHS->resolveReferences(R, RV);
465   
466   if (LHS != lhs || RHS != rhs)
467     return (new BinOpInit(getOpcode(), lhs, rhs))->Fold();
468   return Fold();
469 }
470
471 std::string BinOpInit::getAsString() const {
472   std::string Result;
473   switch (Opc) {
474   case CONCAT: Result = "!con"; break;
475   case SHL: Result = "!shl"; break;
476   case SRA: Result = "!sra"; break;
477   case SRL: Result = "!srl"; break;
478   case STRCONCAT: Result = "!strconcat"; break;
479   }
480   return Result + "(" + LHS->getAsString() + ", " + RHS->getAsString() + ")";
481 }
482
483 Init *TypedInit::convertInitializerBitRange(const std::vector<unsigned> &Bits) {
484   BitsRecTy *T = dynamic_cast<BitsRecTy*>(getType());
485   if (T == 0) return 0;  // Cannot subscript a non-bits variable...
486   unsigned NumBits = T->getNumBits();
487
488   BitsInit *BI = new BitsInit(Bits.size());
489   for (unsigned i = 0, e = Bits.size(); i != e; ++i) {
490     if (Bits[i] >= NumBits) {
491       delete BI;
492       return 0;
493     }
494     BI->setBit(i, new VarBitInit(this, Bits[i]));
495   }
496   return BI;
497 }
498
499 Init *TypedInit::convertInitListSlice(const std::vector<unsigned> &Elements) {
500   ListRecTy *T = dynamic_cast<ListRecTy*>(getType());
501   if (T == 0) return 0;  // Cannot subscript a non-list variable...
502
503   if (Elements.size() == 1)
504     return new VarListElementInit(this, Elements[0]);
505
506   std::vector<Init*> ListInits;
507   ListInits.reserve(Elements.size());
508   for (unsigned i = 0, e = Elements.size(); i != e; ++i)
509     ListInits.push_back(new VarListElementInit(this, Elements[i]));
510   return new ListInit(ListInits);
511 }
512
513
514 Init *VarInit::resolveBitReference(Record &R, const RecordVal *IRV,
515                                    unsigned Bit) {
516   if (R.isTemplateArg(getName())) return 0;
517   if (IRV && IRV->getName() != getName()) return 0;
518
519   RecordVal *RV = R.getValue(getName());
520   assert(RV && "Reference to a non-existant variable?");
521   assert(dynamic_cast<BitsInit*>(RV->getValue()));
522   BitsInit *BI = (BitsInit*)RV->getValue();
523
524   assert(Bit < BI->getNumBits() && "Bit reference out of range!");
525   Init *B = BI->getBit(Bit);
526
527   if (!dynamic_cast<UnsetInit*>(B))  // If the bit is not set...
528     return B;                        // Replace the VarBitInit with it.
529   return 0;
530 }
531
532 Init *VarInit::resolveListElementReference(Record &R, const RecordVal *IRV,
533                                            unsigned Elt) {
534   if (R.isTemplateArg(getName())) return 0;
535   if (IRV && IRV->getName() != getName()) return 0;
536
537   RecordVal *RV = R.getValue(getName());
538   assert(RV && "Reference to a non-existant variable?");
539   ListInit *LI = dynamic_cast<ListInit*>(RV->getValue());
540   assert(LI && "Invalid list element!");
541
542   if (Elt >= LI->getSize())
543     return 0;  // Out of range reference.
544   Init *E = LI->getElement(Elt);
545   if (!dynamic_cast<UnsetInit*>(E))  // If the element is set
546     return E;                        // Replace the VarListElementInit with it.
547   return 0;
548 }
549
550
551 RecTy *VarInit::getFieldType(const std::string &FieldName) const {
552   if (RecordRecTy *RTy = dynamic_cast<RecordRecTy*>(getType()))
553     if (const RecordVal *RV = RTy->getRecord()->getValue(FieldName))
554       return RV->getType();
555   return 0;
556 }
557
558 Init *VarInit::getFieldInit(Record &R, const std::string &FieldName) const {
559   if (dynamic_cast<RecordRecTy*>(getType()))
560     if (const RecordVal *RV = R.getValue(VarName)) {
561       Init *TheInit = RV->getValue();
562       assert(TheInit != this && "Infinite loop detected!");
563       if (Init *I = TheInit->getFieldInit(R, FieldName))
564         return I;
565       else
566         return 0;
567     }
568   return 0;
569 }
570
571 /// resolveReferences - This method is used by classes that refer to other
572 /// variables which may not be defined at the time they expression is formed.
573 /// If a value is set for the variable later, this method will be called on
574 /// users of the value to allow the value to propagate out.
575 ///
576 Init *VarInit::resolveReferences(Record &R, const RecordVal *RV) {
577   if (RecordVal *Val = R.getValue(VarName))
578     if (RV == Val || (RV == 0 && !dynamic_cast<UnsetInit*>(Val->getValue())))
579       return Val->getValue();
580   return this;
581 }
582
583 std::string VarBitInit::getAsString() const {
584    return TI->getAsString() + "{" + utostr(Bit) + "}";
585 }
586
587 Init *VarBitInit::resolveReferences(Record &R, const RecordVal *RV) {
588   if (Init *I = getVariable()->resolveBitReference(R, RV, getBitNum()))
589     return I;
590   return this;
591 }
592
593 std::string VarListElementInit::getAsString() const {
594   return TI->getAsString() + "[" + utostr(Element) + "]";
595 }
596
597 Init *VarListElementInit::resolveReferences(Record &R, const RecordVal *RV) {
598   if (Init *I = getVariable()->resolveListElementReference(R, RV,
599                                                            getElementNum()))
600     return I;
601   return this;
602 }
603
604 Init *VarListElementInit::resolveBitReference(Record &R, const RecordVal *RV,
605                                               unsigned Bit) {
606   // FIXME: This should be implemented, to support references like:
607   // bit B = AA[0]{1};
608   return 0;
609 }
610
611 Init *VarListElementInit::
612 resolveListElementReference(Record &R, const RecordVal *RV, unsigned Elt) {
613   // FIXME: This should be implemented, to support references like:
614   // int B = AA[0][1];
615   return 0;
616 }
617
618 RecTy *DefInit::getFieldType(const std::string &FieldName) const {
619   if (const RecordVal *RV = Def->getValue(FieldName))
620     return RV->getType();
621   return 0;
622 }
623
624 Init *DefInit::getFieldInit(Record &R, const std::string &FieldName) const {
625   return Def->getValue(FieldName)->getValue();
626 }
627
628
629 std::string DefInit::getAsString() const {
630   return Def->getName();
631 }
632
633 Init *FieldInit::resolveBitReference(Record &R, const RecordVal *RV,
634                                      unsigned Bit) {
635   if (Init *BitsVal = Rec->getFieldInit(R, FieldName))
636     if (BitsInit *BI = dynamic_cast<BitsInit*>(BitsVal)) {
637       assert(Bit < BI->getNumBits() && "Bit reference out of range!");
638       Init *B = BI->getBit(Bit);
639
640       if (dynamic_cast<BitInit*>(B))  // If the bit is set...
641         return B;                     // Replace the VarBitInit with it.
642     }
643   return 0;
644 }
645
646 Init *FieldInit::resolveListElementReference(Record &R, const RecordVal *RV,
647                                              unsigned Elt) {
648   if (Init *ListVal = Rec->getFieldInit(R, FieldName))
649     if (ListInit *LI = dynamic_cast<ListInit*>(ListVal)) {
650       if (Elt >= LI->getSize()) return 0;
651       Init *E = LI->getElement(Elt);
652
653       if (!dynamic_cast<UnsetInit*>(E))  // If the bit is set...
654         return E;                  // Replace the VarListElementInit with it.
655     }
656   return 0;
657 }
658
659 Init *FieldInit::resolveReferences(Record &R, const RecordVal *RV) {
660   Init *NewRec = RV ? Rec->resolveReferences(R, RV) : Rec;
661
662   Init *BitsVal = NewRec->getFieldInit(R, FieldName);
663   if (BitsVal) {
664     Init *BVR = BitsVal->resolveReferences(R, RV);
665     return BVR->isComplete() ? BVR : this;
666   }
667
668   if (NewRec != Rec) {
669     return new FieldInit(NewRec, FieldName);
670   }
671   return this;
672 }
673
674 Init *DagInit::resolveReferences(Record &R, const RecordVal *RV) {
675   std::vector<Init*> NewArgs;
676   for (unsigned i = 0, e = Args.size(); i != e; ++i)
677     NewArgs.push_back(Args[i]->resolveReferences(R, RV));
678   
679   Init *Op = Val->resolveReferences(R, RV);
680   
681   if (Args != NewArgs || Op != Val)
682     return new DagInit(Op, "", NewArgs, ArgNames);
683     
684   return this;
685 }
686
687
688 std::string DagInit::getAsString() const {
689   std::string Result = "(" + Val->getAsString();
690   if (!ValName.empty())
691     Result += ":" + ValName;
692   if (Args.size()) {
693     Result += " " + Args[0]->getAsString();
694     if (!ArgNames[0].empty()) Result += ":$" + ArgNames[0];
695     for (unsigned i = 1, e = Args.size(); i != e; ++i) {
696       Result += ", " + Args[i]->getAsString();
697       if (!ArgNames[i].empty()) Result += ":$" + ArgNames[i];
698     }
699   }
700   return Result + ")";
701 }
702
703
704 //===----------------------------------------------------------------------===//
705 //    Other implementations
706 //===----------------------------------------------------------------------===//
707
708 RecordVal::RecordVal(const std::string &N, RecTy *T, unsigned P)
709   : Name(N), Ty(T), Prefix(P) {
710   Value = Ty->convertValue(new UnsetInit());
711   assert(Value && "Cannot create unset value for current type!");
712 }
713
714 void RecordVal::dump() const { cerr << *this; }
715
716 void RecordVal::print(std::ostream &OS, bool PrintSem) const {
717   if (getPrefix()) OS << "field ";
718   OS << *getType() << " " << getName();
719
720   if (getValue())
721     OS << " = " << *getValue();
722
723   if (PrintSem) OS << ";\n";
724 }
725
726 void Record::setName(const std::string &Name) {
727   if (Records.getDef(getName()) == this) {
728     Records.removeDef(getName());
729     this->Name = Name;
730     Records.addDef(this);
731   } else {
732     Records.removeClass(getName());
733     this->Name = Name;
734     Records.addClass(this);
735   }
736 }
737
738 /// resolveReferencesTo - If anything in this record refers to RV, replace the
739 /// reference to RV with the RHS of RV.  If RV is null, we resolve all possible
740 /// references.
741 void Record::resolveReferencesTo(const RecordVal *RV) {
742   for (unsigned i = 0, e = Values.size(); i != e; ++i) {
743     if (Init *V = Values[i].getValue())
744       Values[i].setValue(V->resolveReferences(*this, RV));
745   }
746 }
747
748
749 void Record::dump() const { cerr << *this; }
750
751 std::ostream &llvm::operator<<(std::ostream &OS, const Record &R) {
752   OS << R.getName();
753
754   const std::vector<std::string> &TArgs = R.getTemplateArgs();
755   if (!TArgs.empty()) {
756     OS << "<";
757     for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
758       if (i) OS << ", ";
759       const RecordVal *RV = R.getValue(TArgs[i]);
760       assert(RV && "Template argument record not found??");
761       RV->print(OS, false);
762     }
763     OS << ">";
764   }
765
766   OS << " {";
767   const std::vector<Record*> &SC = R.getSuperClasses();
768   if (!SC.empty()) {
769     OS << "\t//";
770     for (unsigned i = 0, e = SC.size(); i != e; ++i)
771       OS << " " << SC[i]->getName();
772   }
773   OS << "\n";
774
775   const std::vector<RecordVal> &Vals = R.getValues();
776   for (unsigned i = 0, e = Vals.size(); i != e; ++i)
777     if (Vals[i].getPrefix() && !R.isTemplateArg(Vals[i].getName()))
778       OS << Vals[i];
779   for (unsigned i = 0, e = Vals.size(); i != e; ++i)
780     if (!Vals[i].getPrefix() && !R.isTemplateArg(Vals[i].getName()))
781       OS << Vals[i];
782
783   return OS << "}\n";
784 }
785
786 /// getValueInit - Return the initializer for a value with the specified name,
787 /// or throw an exception if the field does not exist.
788 ///
789 Init *Record::getValueInit(const std::string &FieldName) const {
790   const RecordVal *R = getValue(FieldName);
791   if (R == 0 || R->getValue() == 0)
792     throw "Record `" + getName() + "' does not have a field named `" +
793       FieldName + "'!\n";
794   return R->getValue();
795 }
796
797
798 /// getValueAsString - This method looks up the specified field and returns its
799 /// value as a string, throwing an exception if the field does not exist or if
800 /// the value is not a string.
801 ///
802 std::string Record::getValueAsString(const std::string &FieldName) const {
803   const RecordVal *R = getValue(FieldName);
804   if (R == 0 || R->getValue() == 0)
805     throw "Record `" + getName() + "' does not have a field named `" +
806           FieldName + "'!\n";
807
808   if (const StringInit *SI = dynamic_cast<const StringInit*>(R->getValue()))
809     return SI->getValue();
810   throw "Record `" + getName() + "', field `" + FieldName +
811         "' does not have a string initializer!";
812 }
813
814 /// getValueAsBitsInit - This method looks up the specified field and returns
815 /// its value as a BitsInit, throwing an exception if the field does not exist
816 /// or if the value is not the right type.
817 ///
818 BitsInit *Record::getValueAsBitsInit(const std::string &FieldName) const {
819   const RecordVal *R = getValue(FieldName);
820   if (R == 0 || R->getValue() == 0)
821     throw "Record `" + getName() + "' does not have a field named `" +
822           FieldName + "'!\n";
823
824   if (BitsInit *BI = dynamic_cast<BitsInit*>(R->getValue()))
825     return BI;
826   throw "Record `" + getName() + "', field `" + FieldName +
827         "' does not have a BitsInit initializer!";
828 }
829
830 /// getValueAsListInit - This method looks up the specified field and returns
831 /// its value as a ListInit, throwing an exception if the field does not exist
832 /// or if the value is not the right type.
833 ///
834 ListInit *Record::getValueAsListInit(const std::string &FieldName) const {
835   const RecordVal *R = getValue(FieldName);
836   if (R == 0 || R->getValue() == 0)
837     throw "Record `" + getName() + "' does not have a field named `" +
838           FieldName + "'!\n";
839
840   if (ListInit *LI = dynamic_cast<ListInit*>(R->getValue()))
841     return LI;
842   throw "Record `" + getName() + "', field `" + FieldName +
843         "' does not have a list initializer!";
844 }
845
846 /// getValueAsListOfDefs - This method looks up the specified field and returns
847 /// its value as a vector of records, throwing an exception if the field does
848 /// not exist or if the value is not the right type.
849 ///
850 std::vector<Record*> 
851 Record::getValueAsListOfDefs(const std::string &FieldName) const {
852   ListInit *List = getValueAsListInit(FieldName);
853   std::vector<Record*> Defs;
854   for (unsigned i = 0; i < List->getSize(); i++) {
855     if (DefInit *DI = dynamic_cast<DefInit*>(List->getElement(i))) {
856       Defs.push_back(DI->getDef());
857     } else {
858       throw "Record `" + getName() + "', field `" + FieldName +
859             "' list is not entirely DefInit!";
860     }
861   }
862   return Defs;
863 }
864
865 /// getValueAsInt - This method looks up the specified field and returns its
866 /// value as an int64_t, throwing an exception if the field does not exist or if
867 /// the value is not the right type.
868 ///
869 int64_t Record::getValueAsInt(const std::string &FieldName) const {
870   const RecordVal *R = getValue(FieldName);
871   if (R == 0 || R->getValue() == 0)
872     throw "Record `" + getName() + "' does not have a field named `" +
873           FieldName + "'!\n";
874
875   if (IntInit *II = dynamic_cast<IntInit*>(R->getValue()))
876     return II->getValue();
877   throw "Record `" + getName() + "', field `" + FieldName +
878         "' does not have an int initializer!";
879 }
880
881 /// getValueAsListOfInts - This method looks up the specified field and returns
882 /// its value as a vector of integers, throwing an exception if the field does
883 /// not exist or if the value is not the right type.
884 ///
885 std::vector<int64_t> 
886 Record::getValueAsListOfInts(const std::string &FieldName) const {
887   ListInit *List = getValueAsListInit(FieldName);
888   std::vector<int64_t> Ints;
889   for (unsigned i = 0; i < List->getSize(); i++) {
890     if (IntInit *II = dynamic_cast<IntInit*>(List->getElement(i))) {
891       Ints.push_back(II->getValue());
892     } else {
893       throw "Record `" + getName() + "', field `" + FieldName +
894             "' does not have a list of ints initializer!";
895     }
896   }
897   return Ints;
898 }
899
900 /// getValueAsDef - This method looks up the specified field and returns its
901 /// value as a Record, throwing an exception if the field does not exist or if
902 /// the value is not the right type.
903 ///
904 Record *Record::getValueAsDef(const std::string &FieldName) const {
905   const RecordVal *R = getValue(FieldName);
906   if (R == 0 || R->getValue() == 0)
907     throw "Record `" + getName() + "' does not have a field named `" +
908       FieldName + "'!\n";
909
910   if (DefInit *DI = dynamic_cast<DefInit*>(R->getValue()))
911     return DI->getDef();
912   throw "Record `" + getName() + "', field `" + FieldName +
913         "' does not have a def initializer!";
914 }
915
916 /// getValueAsBit - This method looks up the specified field and returns its
917 /// value as a bit, throwing an exception if the field does not exist or if
918 /// the value is not the right type.
919 ///
920 bool Record::getValueAsBit(const std::string &FieldName) const {
921   const RecordVal *R = getValue(FieldName);
922   if (R == 0 || R->getValue() == 0)
923     throw "Record `" + getName() + "' does not have a field named `" +
924       FieldName + "'!\n";
925
926   if (BitInit *BI = dynamic_cast<BitInit*>(R->getValue()))
927     return BI->getValue();
928   throw "Record `" + getName() + "', field `" + FieldName +
929         "' does not have a bit initializer!";
930 }
931
932 /// getValueAsDag - This method looks up the specified field and returns its
933 /// value as an Dag, throwing an exception if the field does not exist or if
934 /// the value is not the right type.
935 ///
936 DagInit *Record::getValueAsDag(const std::string &FieldName) const {
937   const RecordVal *R = getValue(FieldName);
938   if (R == 0 || R->getValue() == 0)
939     throw "Record `" + getName() + "' does not have a field named `" +
940       FieldName + "'!\n";
941
942   if (DagInit *DI = dynamic_cast<DagInit*>(R->getValue()))
943     return DI;
944   throw "Record `" + getName() + "', field `" + FieldName +
945         "' does not have a dag initializer!";
946 }
947
948 std::string Record::getValueAsCode(const std::string &FieldName) const {
949   const RecordVal *R = getValue(FieldName);
950   if (R == 0 || R->getValue() == 0)
951     throw "Record `" + getName() + "' does not have a field named `" +
952       FieldName + "'!\n";
953   
954   if (const CodeInit *CI = dynamic_cast<const CodeInit*>(R->getValue()))
955     return CI->getValue();
956   throw "Record `" + getName() + "', field `" + FieldName +
957     "' does not have a code initializer!";
958 }
959
960
961 void RecordKeeper::dump() const { cerr << *this; }
962
963 std::ostream &llvm::operator<<(std::ostream &OS, const RecordKeeper &RK) {
964   OS << "------------- Classes -----------------\n";
965   const std::map<std::string, Record*> &Classes = RK.getClasses();
966   for (std::map<std::string, Record*>::const_iterator I = Classes.begin(),
967          E = Classes.end(); I != E; ++I)
968     OS << "class " << *I->second;
969
970   OS << "------------- Defs -----------------\n";
971   const std::map<std::string, Record*> &Defs = RK.getDefs();
972   for (std::map<std::string, Record*>::const_iterator I = Defs.begin(),
973          E = Defs.end(); I != E; ++I)
974     OS << "def " << *I->second;
975   return OS;
976 }
977
978
979 /// getAllDerivedDefinitions - This method returns all concrete definitions
980 /// that derive from the specified class name.  If a class with the specified
981 /// name does not exist, an error is printed and true is returned.
982 std::vector<Record*>
983 RecordKeeper::getAllDerivedDefinitions(const std::string &ClassName) const {
984   Record *Class = Records.getClass(ClassName);
985   if (!Class)
986     throw "ERROR: Couldn't find the `" + ClassName + "' class!\n";
987
988   std::vector<Record*> Defs;
989   for (std::map<std::string, Record*>::const_iterator I = getDefs().begin(),
990          E = getDefs().end(); I != E; ++I)
991     if (I->second->isSubClassOf(Class))
992       Defs.push_back(I->second);
993
994   return Defs;
995 }
996