Fix PR4207.
[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, new StringRecTy);
142     return BO;
143   }
144   if (BO->getOpcode() == BinOpInit::NAMECONCAT) {
145     if (BO->getType()->getAsString() == getAsString()) {
146       Init *L = BO->getLHS()->convertInitializerTo(this);
147       Init *R = BO->getRHS()->convertInitializerTo(this);
148       if (L == 0 || R == 0) return 0;
149       if (L != BO->getLHS() || R != BO->getRHS())
150         return new BinOpInit(BinOpInit::NAMECONCAT, L, R, new StringRecTy);
151       return BO;
152     }
153   }
154
155   return convertValue((TypedInit*)BO);
156 }
157
158
159 Init *StringRecTy::convertValue(TypedInit *TI) {
160   if (dynamic_cast<StringRecTy*>(TI->getType()))
161     return TI;  // Accept variable if already of the right type!
162   return 0;
163 }
164
165 std::string ListRecTy::getAsString() const {
166   return "list<" + Ty->getAsString() + ">";
167 }
168
169 Init *ListRecTy::convertValue(ListInit *LI) {
170   std::vector<Init*> Elements;
171
172   // Verify that all of the elements of the list are subclasses of the
173   // appropriate class!
174   for (unsigned i = 0, e = LI->getSize(); i != e; ++i)
175     if (Init *CI = LI->getElement(i)->convertInitializerTo(Ty))
176       Elements.push_back(CI);
177     else
178       return 0;
179
180   return new ListInit(Elements);
181 }
182
183 Init *ListRecTy::convertValue(TypedInit *TI) {
184   // Ensure that TI is compatible with our class.
185   if (ListRecTy *LRT = dynamic_cast<ListRecTy*>(TI->getType()))
186     if (LRT->getElementType()->typeIsConvertibleTo(getElementType()))
187       return TI;
188   return 0;
189 }
190
191 Init *CodeRecTy::convertValue(TypedInit *TI) {
192   if (TI->getType()->typeIsConvertibleTo(this))
193     return TI;
194   return 0;
195 }
196
197 Init *DagRecTy::convertValue(TypedInit *TI) {
198   if (TI->getType()->typeIsConvertibleTo(this))
199     return TI;
200   return 0;
201 }
202
203 Init *DagRecTy::convertValue(BinOpInit *BO) {
204   if (BO->getOpcode() == BinOpInit::CONCAT) {
205     Init *L = BO->getLHS()->convertInitializerTo(this);
206     Init *R = BO->getRHS()->convertInitializerTo(this);
207     if (L == 0 || R == 0) return 0;
208     if (L != BO->getLHS() || R != BO->getRHS())
209       return new BinOpInit(BinOpInit::CONCAT, L, R, new DagRecTy);
210     return BO;
211   }
212   if (BO->getOpcode() == BinOpInit::NAMECONCAT) {
213     if (BO->getType()->getAsString() == getAsString()) {
214       Init *L = BO->getLHS()->convertInitializerTo(this);
215       Init *R = BO->getRHS()->convertInitializerTo(this);
216       if (L == 0 || R == 0) return 0;
217       if (L != BO->getLHS() || R != BO->getRHS())
218         return new BinOpInit(BinOpInit::CONCAT, L, R, new DagRecTy);
219       return BO;
220     }
221   }
222   return 0;
223 }
224
225 std::string RecordRecTy::getAsString() const {
226   return Rec->getName();
227 }
228
229 Init *RecordRecTy::convertValue(DefInit *DI) {
230   // Ensure that DI is a subclass of Rec.
231   if (!DI->getDef()->isSubClassOf(Rec))
232     return 0;
233   return DI;
234 }
235
236 Init *RecordRecTy::convertValue(TypedInit *TI) {
237   // Ensure that TI is compatible with Rec.
238   if (RecordRecTy *RRT = dynamic_cast<RecordRecTy*>(TI->getType()))
239     if (RRT->getRecord()->isSubClassOf(getRecord()) ||
240         RRT->getRecord() == getRecord())
241       return TI;
242   return 0;
243 }
244
245 bool RecordRecTy::baseClassOf(const RecordRecTy *RHS) const {
246   return Rec == RHS->getRecord() || RHS->getRecord()->isSubClassOf(Rec);
247 }
248
249
250 //===----------------------------------------------------------------------===//
251 //    Initializer implementations
252 //===----------------------------------------------------------------------===//
253
254 void Init::dump() const { return print(*cerr.stream()); }
255
256 Init *BitsInit::convertInitializerBitRange(const std::vector<unsigned> &Bits) {
257   BitsInit *BI = new BitsInit(Bits.size());
258   for (unsigned i = 0, e = Bits.size(); i != e; ++i) {
259     if (Bits[i] >= getNumBits()) {
260       delete BI;
261       return 0;
262     }
263     BI->setBit(i, getBit(Bits[i]));
264   }
265   return BI;
266 }
267
268 std::string BitsInit::getAsString() const {
269   //if (!printInHex(OS)) return;
270   //if (!printAsVariable(OS)) return;
271   //if (!printAsUnset(OS)) return;
272
273   std::string Result = "{ ";
274   for (unsigned i = 0, e = getNumBits(); i != e; ++i) {
275     if (i) Result += ", ";
276     if (Init *Bit = getBit(e-i-1))
277       Result += Bit->getAsString();
278     else
279       Result += "*";
280   }
281   return Result + " }";
282 }
283
284 bool BitsInit::printInHex(std::ostream &OS) const {
285   // First, attempt to convert the value into an integer value...
286   int64_t Result = 0;
287   for (unsigned i = 0, e = getNumBits(); i != e; ++i)
288     if (BitInit *Bit = dynamic_cast<BitInit*>(getBit(i))) {
289       Result |= Bit->getValue() << i;
290     } else {
291       return true;
292     }
293
294   OS << "0x" << std::hex << Result << std::dec;
295   return false;
296 }
297
298 bool BitsInit::printAsVariable(std::ostream &OS) const {
299   // Get the variable that we may be set equal to...
300   assert(getNumBits() != 0);
301   VarBitInit *FirstBit = dynamic_cast<VarBitInit*>(getBit(0));
302   if (FirstBit == 0) return true;
303   TypedInit *Var = FirstBit->getVariable();
304
305   // Check to make sure the types are compatible.
306   BitsRecTy *Ty = dynamic_cast<BitsRecTy*>(FirstBit->getVariable()->getType());
307   if (Ty == 0) return true;
308   if (Ty->getNumBits() != getNumBits()) return true; // Incompatible types!
309
310   // Check to make sure all bits are referring to the right bits in the variable
311   for (unsigned i = 0, e = getNumBits(); i != e; ++i) {
312     VarBitInit *Bit = dynamic_cast<VarBitInit*>(getBit(i));
313     if (Bit == 0 || Bit->getVariable() != Var || Bit->getBitNum() != i)
314       return true;
315   }
316
317   Var->print(OS);
318   return false;
319 }
320
321 bool BitsInit::printAsUnset(std::ostream &OS) const {
322   for (unsigned i = 0, e = getNumBits(); i != e; ++i)
323     if (!dynamic_cast<UnsetInit*>(getBit(i)))
324       return true;
325   OS << "?";
326   return false;
327 }
328
329 // resolveReferences - If there are any field references that refer to fields
330 // that have been filled in, we can propagate the values now.
331 //
332 Init *BitsInit::resolveReferences(Record &R, const RecordVal *RV) {
333   bool Changed = false;
334   BitsInit *New = new BitsInit(getNumBits());
335
336   for (unsigned i = 0, e = Bits.size(); i != e; ++i) {
337     Init *B;
338     Init *CurBit = getBit(i);
339
340     do {
341       B = CurBit;
342       CurBit = CurBit->resolveReferences(R, RV);
343       Changed |= B != CurBit;
344     } while (B != CurBit);
345     New->setBit(i, CurBit);
346   }
347
348   if (Changed)
349     return New;
350   delete New;
351   return this;
352 }
353
354 std::string IntInit::getAsString() const {
355   return itostr(Value);
356 }
357
358 Init *IntInit::convertInitializerBitRange(const std::vector<unsigned> &Bits) {
359   BitsInit *BI = new BitsInit(Bits.size());
360
361   for (unsigned i = 0, e = Bits.size(); i != e; ++i) {
362     if (Bits[i] >= 64) {
363       delete BI;
364       return 0;
365     }
366     BI->setBit(i, new BitInit(Value & (INT64_C(1) << Bits[i])));
367   }
368   return BI;
369 }
370
371 Init *ListInit::convertInitListSlice(const std::vector<unsigned> &Elements) {
372   std::vector<Init*> Vals;
373   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
374     if (Elements[i] >= getSize())
375       return 0;
376     Vals.push_back(getElement(Elements[i]));
377   }
378   return new ListInit(Vals);
379 }
380
381 Record *ListInit::getElementAsRecord(unsigned i) const {
382   assert(i < Values.size() && "List element index out of range!");
383   DefInit *DI = dynamic_cast<DefInit*>(Values[i]);
384   if (DI == 0) throw "Expected record in list!";
385   return DI->getDef();
386 }
387
388 Init *ListInit::resolveReferences(Record &R, const RecordVal *RV) {
389   std::vector<Init*> Resolved;
390   Resolved.reserve(getSize());
391   bool Changed = false;
392
393   for (unsigned i = 0, e = getSize(); i != e; ++i) {
394     Init *E;
395     Init *CurElt = getElement(i);
396
397     do {
398       E = CurElt;
399       CurElt = CurElt->resolveReferences(R, RV);
400       Changed |= E != CurElt;
401     } while (E != CurElt);
402     Resolved.push_back(E);
403   }
404
405   if (Changed)
406     return new ListInit(Resolved);
407   return this;
408 }
409
410 std::string ListInit::getAsString() const {
411   std::string Result = "[";
412   for (unsigned i = 0, e = Values.size(); i != e; ++i) {
413     if (i) Result += ", ";
414     Result += Values[i]->getAsString();
415   }
416   return Result + "]";
417 }
418
419 Init *BinOpInit::Fold(Record *CurRec, MultiClass *CurMultiClass) {
420   switch (getOpcode()) {
421   default: assert(0 && "Unknown binop");
422   case CONCAT: {
423     DagInit *LHSs = dynamic_cast<DagInit*>(LHS);
424     DagInit *RHSs = dynamic_cast<DagInit*>(RHS);
425     if (LHSs && RHSs) {
426       DefInit *LOp = dynamic_cast<DefInit*>(LHSs->getOperator());
427       DefInit *ROp = dynamic_cast<DefInit*>(RHSs->getOperator());
428       if (LOp->getDef() != ROp->getDef()) {
429         bool LIsOps =
430           LOp->getDef()->getName() == "outs" ||
431           LOp->getDef()->getName() != "ins" ||
432           LOp->getDef()->getName() != "defs";
433         bool RIsOps =
434           ROp->getDef()->getName() == "outs" ||
435           ROp->getDef()->getName() != "ins" ||
436           ROp->getDef()->getName() != "defs";
437         if (!LIsOps || !RIsOps)
438           throw "Concated Dag operators do not match!";
439       }
440       std::vector<Init*> Args;
441       std::vector<std::string> ArgNames;
442       for (unsigned i = 0, e = LHSs->getNumArgs(); i != e; ++i) {
443         Args.push_back(LHSs->getArg(i));
444         ArgNames.push_back(LHSs->getArgName(i));
445       }
446       for (unsigned i = 0, e = RHSs->getNumArgs(); i != e; ++i) {
447         Args.push_back(RHSs->getArg(i));
448         ArgNames.push_back(RHSs->getArgName(i));
449       }
450       return new DagInit(LHSs->getOperator(), "", Args, ArgNames);
451     }
452     break;
453   }
454   case STRCONCAT: {
455     StringInit *LHSs = dynamic_cast<StringInit*>(LHS);
456     StringInit *RHSs = dynamic_cast<StringInit*>(RHS);
457     if (LHSs && RHSs)
458       return new StringInit(LHSs->getValue() + RHSs->getValue());
459     break;
460   }
461   case NAMECONCAT: {
462     StringInit *LHSs = dynamic_cast<StringInit*>(LHS);
463     StringInit *RHSs = dynamic_cast<StringInit*>(RHS);
464     if (LHSs && RHSs) {
465       std::string Name(LHSs->getValue() + RHSs->getValue());
466
467       // From TGParser::ParseIDValue
468       if (CurRec) {
469         if (const RecordVal *RV = CurRec->getValue(Name)) {
470           if (RV->getType() != getType()) {
471             throw "type mismatch in nameconcat";
472           }
473           return new VarInit(Name, RV->getType());
474         }
475         
476         std::string TemplateArgName = CurRec->getName()+":"+Name;
477         if (CurRec->isTemplateArg(TemplateArgName)) {
478           const RecordVal *RV = CurRec->getValue(TemplateArgName);
479           assert(RV && "Template arg doesn't exist??");
480
481           if (RV->getType() != getType()) {
482             throw "type mismatch in nameconcat";
483           }
484
485           return new VarInit(TemplateArgName, RV->getType());
486         }
487       }
488
489       if (CurMultiClass) {
490         std::string MCName = CurMultiClass->Rec.getName()+"::"+Name;
491         if (CurMultiClass->Rec.isTemplateArg(MCName)) {
492           const RecordVal *RV = CurMultiClass->Rec.getValue(MCName);
493           assert(RV && "Template arg doesn't exist??");
494
495           if (RV->getType() != getType()) {
496             throw "type mismatch in nameconcat";
497           }
498           
499           return new VarInit(MCName, RV->getType());
500         }
501       }
502
503       if (Record *D = Records.getDef(Name))
504         return new DefInit(D);
505
506       cerr << "Variable not defined: '" + Name + "'\n";
507       assert(0 && "Variable not found");
508       return 0;
509     }
510     break;
511   }
512   case SHL:
513   case SRA:
514   case SRL: {
515     IntInit *LHSi = dynamic_cast<IntInit*>(LHS);
516     IntInit *RHSi = dynamic_cast<IntInit*>(RHS);
517     if (LHSi && RHSi) {
518       int64_t LHSv = LHSi->getValue(), RHSv = RHSi->getValue();
519       int64_t Result;
520       switch (getOpcode()) {
521       default: assert(0 && "Bad opcode!");
522       case SHL: Result = LHSv << RHSv; break;
523       case SRA: Result = LHSv >> RHSv; break;
524       case SRL: Result = (uint64_t)LHSv >> (uint64_t)RHSv; break;
525       }
526       return new IntInit(Result);
527     }
528     break;
529   }
530   }
531   return this;
532 }
533
534 Init *BinOpInit::resolveReferences(Record &R, const RecordVal *RV) {
535   Init *lhs = LHS->resolveReferences(R, RV);
536   Init *rhs = RHS->resolveReferences(R, RV);
537   
538   if (LHS != lhs || RHS != rhs)
539     return (new BinOpInit(getOpcode(), lhs, rhs, getType()))->Fold(&R, 0);
540   return Fold(&R, 0);
541 }
542
543 std::string BinOpInit::getAsString() const {
544   std::string Result;
545   switch (Opc) {
546   case CONCAT: Result = "!con"; break;
547   case SHL: Result = "!shl"; break;
548   case SRA: Result = "!sra"; break;
549   case SRL: Result = "!srl"; break;
550   case STRCONCAT: Result = "!strconcat"; break;
551   case NAMECONCAT: 
552     Result = "!nameconcat<" + getType()->getAsString() + ">"; break;
553   }
554   return Result + "(" + LHS->getAsString() + ", " + RHS->getAsString() + ")";
555 }
556
557 Init *BinOpInit::resolveBitReference(Record &R, const RecordVal *IRV,
558                                    unsigned Bit) {
559   Init *Folded = Fold(&R, 0);
560
561   if (Folded != this) {
562     TypedInit *Typed = dynamic_cast<TypedInit *>(Folded);
563     if (Typed) {
564       return Typed->resolveBitReference(R, IRV, Bit);
565     }    
566   }
567   
568   return 0;
569 }
570
571 Init *BinOpInit::resolveListElementReference(Record &R, const RecordVal *IRV,
572                                            unsigned Elt) {
573   Init *Folded = Fold(&R, 0);
574
575   if (Folded != this) {
576     TypedInit *Typed = dynamic_cast<TypedInit *>(Folded);
577     if (Typed) {
578       return Typed->resolveListElementReference(R, IRV, Elt);
579     }    
580   }
581   
582   return 0;
583 }
584
585 Init *TypedInit::convertInitializerBitRange(const std::vector<unsigned> &Bits) {
586   BitsRecTy *T = dynamic_cast<BitsRecTy*>(getType());
587   if (T == 0) return 0;  // Cannot subscript a non-bits variable...
588   unsigned NumBits = T->getNumBits();
589
590   BitsInit *BI = new BitsInit(Bits.size());
591   for (unsigned i = 0, e = Bits.size(); i != e; ++i) {
592     if (Bits[i] >= NumBits) {
593       delete BI;
594       return 0;
595     }
596     BI->setBit(i, new VarBitInit(this, Bits[i]));
597   }
598   return BI;
599 }
600
601 Init *TypedInit::convertInitListSlice(const std::vector<unsigned> &Elements) {
602   ListRecTy *T = dynamic_cast<ListRecTy*>(getType());
603   if (T == 0) return 0;  // Cannot subscript a non-list variable...
604
605   if (Elements.size() == 1)
606     return new VarListElementInit(this, Elements[0]);
607
608   std::vector<Init*> ListInits;
609   ListInits.reserve(Elements.size());
610   for (unsigned i = 0, e = Elements.size(); i != e; ++i)
611     ListInits.push_back(new VarListElementInit(this, Elements[i]));
612   return new ListInit(ListInits);
613 }
614
615
616 Init *VarInit::resolveBitReference(Record &R, const RecordVal *IRV,
617                                    unsigned Bit) {
618   if (R.isTemplateArg(getName())) return 0;
619   if (IRV && IRV->getName() != getName()) return 0;
620
621   RecordVal *RV = R.getValue(getName());
622   assert(RV && "Reference to a non-existant variable?");
623   assert(dynamic_cast<BitsInit*>(RV->getValue()));
624   BitsInit *BI = (BitsInit*)RV->getValue();
625
626   assert(Bit < BI->getNumBits() && "Bit reference out of range!");
627   Init *B = BI->getBit(Bit);
628
629   if (!dynamic_cast<UnsetInit*>(B))  // If the bit is not set...
630     return B;                        // Replace the VarBitInit with it.
631   return 0;
632 }
633
634 Init *VarInit::resolveListElementReference(Record &R, const RecordVal *IRV,
635                                            unsigned Elt) {
636   if (R.isTemplateArg(getName())) return 0;
637   if (IRV && IRV->getName() != getName()) return 0;
638
639   RecordVal *RV = R.getValue(getName());
640   assert(RV && "Reference to a non-existant variable?");
641   ListInit *LI = dynamic_cast<ListInit*>(RV->getValue());
642   if (!LI) {
643     VarInit *VI = dynamic_cast<VarInit*>(RV->getValue());
644     assert(VI && "Invalid list element!");
645     return new VarListElementInit(VI, Elt);
646   }
647   
648   if (Elt >= LI->getSize())
649     return 0;  // Out of range reference.
650   Init *E = LI->getElement(Elt);
651   if (!dynamic_cast<UnsetInit*>(E))  // If the element is set
652     return E;                        // Replace the VarListElementInit with it.
653   return 0;
654 }
655
656
657 RecTy *VarInit::getFieldType(const std::string &FieldName) const {
658   if (RecordRecTy *RTy = dynamic_cast<RecordRecTy*>(getType()))
659     if (const RecordVal *RV = RTy->getRecord()->getValue(FieldName))
660       return RV->getType();
661   return 0;
662 }
663
664 Init *VarInit::getFieldInit(Record &R, const std::string &FieldName) const {
665   if (dynamic_cast<RecordRecTy*>(getType()))
666     if (const RecordVal *RV = R.getValue(VarName)) {
667       Init *TheInit = RV->getValue();
668       assert(TheInit != this && "Infinite loop detected!");
669       if (Init *I = TheInit->getFieldInit(R, FieldName))
670         return I;
671       else
672         return 0;
673     }
674   return 0;
675 }
676
677 /// resolveReferences - This method is used by classes that refer to other
678 /// variables which may not be defined at the time they expression is formed.
679 /// If a value is set for the variable later, this method will be called on
680 /// users of the value to allow the value to propagate out.
681 ///
682 Init *VarInit::resolveReferences(Record &R, const RecordVal *RV) {
683   if (RecordVal *Val = R.getValue(VarName))
684     if (RV == Val || (RV == 0 && !dynamic_cast<UnsetInit*>(Val->getValue())))
685       return Val->getValue();
686   return this;
687 }
688
689 std::string VarBitInit::getAsString() const {
690    return TI->getAsString() + "{" + utostr(Bit) + "}";
691 }
692
693 Init *VarBitInit::resolveReferences(Record &R, const RecordVal *RV) {
694   if (Init *I = getVariable()->resolveBitReference(R, RV, getBitNum()))
695     return I;
696   return this;
697 }
698
699 std::string VarListElementInit::getAsString() const {
700   return TI->getAsString() + "[" + utostr(Element) + "]";
701 }
702
703 Init *VarListElementInit::resolveReferences(Record &R, const RecordVal *RV) {
704   if (Init *I = getVariable()->resolveListElementReference(R, RV,
705                                                            getElementNum()))
706     return I;
707   return this;
708 }
709
710 Init *VarListElementInit::resolveBitReference(Record &R, const RecordVal *RV,
711                                               unsigned Bit) {
712   // FIXME: This should be implemented, to support references like:
713   // bit B = AA[0]{1};
714   return 0;
715 }
716
717 Init *VarListElementInit::
718 resolveListElementReference(Record &R, const RecordVal *RV, unsigned Elt) {
719   // FIXME: This should be implemented, to support references like:
720   // int B = AA[0][1];
721   return 0;
722 }
723
724 RecTy *DefInit::getFieldType(const std::string &FieldName) const {
725   if (const RecordVal *RV = Def->getValue(FieldName))
726     return RV->getType();
727   return 0;
728 }
729
730 Init *DefInit::getFieldInit(Record &R, const std::string &FieldName) const {
731   return Def->getValue(FieldName)->getValue();
732 }
733
734
735 std::string DefInit::getAsString() const {
736   return Def->getName();
737 }
738
739 Init *FieldInit::resolveBitReference(Record &R, const RecordVal *RV,
740                                      unsigned Bit) {
741   if (Init *BitsVal = Rec->getFieldInit(R, FieldName))
742     if (BitsInit *BI = dynamic_cast<BitsInit*>(BitsVal)) {
743       assert(Bit < BI->getNumBits() && "Bit reference out of range!");
744       Init *B = BI->getBit(Bit);
745
746       if (dynamic_cast<BitInit*>(B))  // If the bit is set...
747         return B;                     // Replace the VarBitInit with it.
748     }
749   return 0;
750 }
751
752 Init *FieldInit::resolveListElementReference(Record &R, const RecordVal *RV,
753                                              unsigned Elt) {
754   if (Init *ListVal = Rec->getFieldInit(R, FieldName))
755     if (ListInit *LI = dynamic_cast<ListInit*>(ListVal)) {
756       if (Elt >= LI->getSize()) return 0;
757       Init *E = LI->getElement(Elt);
758
759       if (!dynamic_cast<UnsetInit*>(E))  // If the bit is set...
760         return E;                  // Replace the VarListElementInit with it.
761     }
762   return 0;
763 }
764
765 Init *FieldInit::resolveReferences(Record &R, const RecordVal *RV) {
766   Init *NewRec = RV ? Rec->resolveReferences(R, RV) : Rec;
767
768   Init *BitsVal = NewRec->getFieldInit(R, FieldName);
769   if (BitsVal) {
770     Init *BVR = BitsVal->resolveReferences(R, RV);
771     return BVR->isComplete() ? BVR : this;
772   }
773
774   if (NewRec != Rec) {
775     return new FieldInit(NewRec, FieldName);
776   }
777   return this;
778 }
779
780 Init *DagInit::resolveReferences(Record &R, const RecordVal *RV) {
781   std::vector<Init*> NewArgs;
782   for (unsigned i = 0, e = Args.size(); i != e; ++i)
783     NewArgs.push_back(Args[i]->resolveReferences(R, RV));
784   
785   Init *Op = Val->resolveReferences(R, RV);
786   
787   if (Args != NewArgs || Op != Val)
788     return new DagInit(Op, "", NewArgs, ArgNames);
789     
790   return this;
791 }
792
793
794 std::string DagInit::getAsString() const {
795   std::string Result = "(" + Val->getAsString();
796   if (!ValName.empty())
797     Result += ":" + ValName;
798   if (Args.size()) {
799     Result += " " + Args[0]->getAsString();
800     if (!ArgNames[0].empty()) Result += ":$" + ArgNames[0];
801     for (unsigned i = 1, e = Args.size(); i != e; ++i) {
802       Result += ", " + Args[i]->getAsString();
803       if (!ArgNames[i].empty()) Result += ":$" + ArgNames[i];
804     }
805   }
806   return Result + ")";
807 }
808
809
810 //===----------------------------------------------------------------------===//
811 //    Other implementations
812 //===----------------------------------------------------------------------===//
813
814 RecordVal::RecordVal(const std::string &N, RecTy *T, unsigned P)
815   : Name(N), Ty(T), Prefix(P) {
816   Value = Ty->convertValue(new UnsetInit());
817   assert(Value && "Cannot create unset value for current type!");
818 }
819
820 void RecordVal::dump() const { cerr << *this; }
821
822 void RecordVal::print(std::ostream &OS, bool PrintSem) const {
823   if (getPrefix()) OS << "field ";
824   OS << *getType() << " " << getName();
825
826   if (getValue())
827     OS << " = " << *getValue();
828
829   if (PrintSem) OS << ";\n";
830 }
831
832 void Record::setName(const std::string &Name) {
833   if (Records.getDef(getName()) == this) {
834     Records.removeDef(getName());
835     this->Name = Name;
836     Records.addDef(this);
837   } else {
838     Records.removeClass(getName());
839     this->Name = Name;
840     Records.addClass(this);
841   }
842 }
843
844 /// resolveReferencesTo - If anything in this record refers to RV, replace the
845 /// reference to RV with the RHS of RV.  If RV is null, we resolve all possible
846 /// references.
847 void Record::resolveReferencesTo(const RecordVal *RV) {
848   for (unsigned i = 0, e = Values.size(); i != e; ++i) {
849     if (Init *V = Values[i].getValue())
850       Values[i].setValue(V->resolveReferences(*this, RV));
851   }
852 }
853
854
855 void Record::dump() const { cerr << *this; }
856
857 std::ostream &llvm::operator<<(std::ostream &OS, const Record &R) {
858   OS << R.getName();
859
860   const std::vector<std::string> &TArgs = R.getTemplateArgs();
861   if (!TArgs.empty()) {
862     OS << "<";
863     for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
864       if (i) OS << ", ";
865       const RecordVal *RV = R.getValue(TArgs[i]);
866       assert(RV && "Template argument record not found??");
867       RV->print(OS, false);
868     }
869     OS << ">";
870   }
871
872   OS << " {";
873   const std::vector<Record*> &SC = R.getSuperClasses();
874   if (!SC.empty()) {
875     OS << "\t//";
876     for (unsigned i = 0, e = SC.size(); i != e; ++i)
877       OS << " " << SC[i]->getName();
878   }
879   OS << "\n";
880
881   const std::vector<RecordVal> &Vals = R.getValues();
882   for (unsigned i = 0, e = Vals.size(); i != e; ++i)
883     if (Vals[i].getPrefix() && !R.isTemplateArg(Vals[i].getName()))
884       OS << Vals[i];
885   for (unsigned i = 0, e = Vals.size(); i != e; ++i)
886     if (!Vals[i].getPrefix() && !R.isTemplateArg(Vals[i].getName()))
887       OS << Vals[i];
888
889   return OS << "}\n";
890 }
891
892 /// getValueInit - Return the initializer for a value with the specified name,
893 /// or throw an exception if the field does not exist.
894 ///
895 Init *Record::getValueInit(const std::string &FieldName) const {
896   const RecordVal *R = getValue(FieldName);
897   if (R == 0 || R->getValue() == 0)
898     throw "Record `" + getName() + "' does not have a field named `" +
899       FieldName + "'!\n";
900   return R->getValue();
901 }
902
903
904 /// getValueAsString - This method looks up the specified field and returns its
905 /// value as a string, throwing an exception if the field does not exist or if
906 /// the value is not a string.
907 ///
908 std::string Record::getValueAsString(const std::string &FieldName) const {
909   const RecordVal *R = getValue(FieldName);
910   if (R == 0 || R->getValue() == 0)
911     throw "Record `" + getName() + "' does not have a field named `" +
912           FieldName + "'!\n";
913
914   if (const StringInit *SI = dynamic_cast<const StringInit*>(R->getValue()))
915     return SI->getValue();
916   throw "Record `" + getName() + "', field `" + FieldName +
917         "' does not have a string initializer!";
918 }
919
920 /// getValueAsBitsInit - This method looks up the specified field and returns
921 /// its value as a BitsInit, throwing an exception if the field does not exist
922 /// or if the value is not the right type.
923 ///
924 BitsInit *Record::getValueAsBitsInit(const std::string &FieldName) const {
925   const RecordVal *R = getValue(FieldName);
926   if (R == 0 || R->getValue() == 0)
927     throw "Record `" + getName() + "' does not have a field named `" +
928           FieldName + "'!\n";
929
930   if (BitsInit *BI = dynamic_cast<BitsInit*>(R->getValue()))
931     return BI;
932   throw "Record `" + getName() + "', field `" + FieldName +
933         "' does not have a BitsInit initializer!";
934 }
935
936 /// getValueAsListInit - This method looks up the specified field and returns
937 /// its value as a ListInit, throwing an exception if the field does not exist
938 /// or if the value is not the right type.
939 ///
940 ListInit *Record::getValueAsListInit(const std::string &FieldName) const {
941   const RecordVal *R = getValue(FieldName);
942   if (R == 0 || R->getValue() == 0)
943     throw "Record `" + getName() + "' does not have a field named `" +
944           FieldName + "'!\n";
945
946   if (ListInit *LI = dynamic_cast<ListInit*>(R->getValue()))
947     return LI;
948   throw "Record `" + getName() + "', field `" + FieldName +
949         "' does not have a list initializer!";
950 }
951
952 /// getValueAsListOfDefs - This method looks up the specified field and returns
953 /// its value as a vector of records, throwing an exception if the field does
954 /// not exist or if the value is not the right type.
955 ///
956 std::vector<Record*> 
957 Record::getValueAsListOfDefs(const std::string &FieldName) const {
958   ListInit *List = getValueAsListInit(FieldName);
959   std::vector<Record*> Defs;
960   for (unsigned i = 0; i < List->getSize(); i++) {
961     if (DefInit *DI = dynamic_cast<DefInit*>(List->getElement(i))) {
962       Defs.push_back(DI->getDef());
963     } else {
964       throw "Record `" + getName() + "', field `" + FieldName +
965             "' list is not entirely DefInit!";
966     }
967   }
968   return Defs;
969 }
970
971 /// getValueAsInt - This method looks up the specified field and returns its
972 /// value as an int64_t, throwing an exception if the field does not exist or if
973 /// the value is not the right type.
974 ///
975 int64_t Record::getValueAsInt(const std::string &FieldName) const {
976   const RecordVal *R = getValue(FieldName);
977   if (R == 0 || R->getValue() == 0)
978     throw "Record `" + getName() + "' does not have a field named `" +
979           FieldName + "'!\n";
980
981   if (IntInit *II = dynamic_cast<IntInit*>(R->getValue()))
982     return II->getValue();
983   throw "Record `" + getName() + "', field `" + FieldName +
984         "' does not have an int initializer!";
985 }
986
987 /// getValueAsListOfInts - This method looks up the specified field and returns
988 /// its value as a vector of integers, throwing an exception if the field does
989 /// not exist or if the value is not the right type.
990 ///
991 std::vector<int64_t> 
992 Record::getValueAsListOfInts(const std::string &FieldName) const {
993   ListInit *List = getValueAsListInit(FieldName);
994   std::vector<int64_t> Ints;
995   for (unsigned i = 0; i < List->getSize(); i++) {
996     if (IntInit *II = dynamic_cast<IntInit*>(List->getElement(i))) {
997       Ints.push_back(II->getValue());
998     } else {
999       throw "Record `" + getName() + "', field `" + FieldName +
1000             "' does not have a list of ints initializer!";
1001     }
1002   }
1003   return Ints;
1004 }
1005
1006 /// getValueAsDef - This method looks up the specified field and returns its
1007 /// value as a Record, throwing an exception if the field does not exist or if
1008 /// the value is not the right type.
1009 ///
1010 Record *Record::getValueAsDef(const std::string &FieldName) const {
1011   const RecordVal *R = getValue(FieldName);
1012   if (R == 0 || R->getValue() == 0)
1013     throw "Record `" + getName() + "' does not have a field named `" +
1014       FieldName + "'!\n";
1015
1016   if (DefInit *DI = dynamic_cast<DefInit*>(R->getValue()))
1017     return DI->getDef();
1018   throw "Record `" + getName() + "', field `" + FieldName +
1019         "' does not have a def initializer!";
1020 }
1021
1022 /// getValueAsBit - This method looks up the specified field and returns its
1023 /// value as a bit, throwing an exception if the field does not exist or if
1024 /// the value is not the right type.
1025 ///
1026 bool Record::getValueAsBit(const std::string &FieldName) const {
1027   const RecordVal *R = getValue(FieldName);
1028   if (R == 0 || R->getValue() == 0)
1029     throw "Record `" + getName() + "' does not have a field named `" +
1030       FieldName + "'!\n";
1031
1032   if (BitInit *BI = dynamic_cast<BitInit*>(R->getValue()))
1033     return BI->getValue();
1034   throw "Record `" + getName() + "', field `" + FieldName +
1035         "' does not have a bit initializer!";
1036 }
1037
1038 /// getValueAsDag - This method looks up the specified field and returns its
1039 /// value as an Dag, throwing an exception if the field does not exist or if
1040 /// the value is not the right type.
1041 ///
1042 DagInit *Record::getValueAsDag(const std::string &FieldName) const {
1043   const RecordVal *R = getValue(FieldName);
1044   if (R == 0 || R->getValue() == 0)
1045     throw "Record `" + getName() + "' does not have a field named `" +
1046       FieldName + "'!\n";
1047
1048   if (DagInit *DI = dynamic_cast<DagInit*>(R->getValue()))
1049     return DI;
1050   throw "Record `" + getName() + "', field `" + FieldName +
1051         "' does not have a dag initializer!";
1052 }
1053
1054 std::string Record::getValueAsCode(const std::string &FieldName) const {
1055   const RecordVal *R = getValue(FieldName);
1056   if (R == 0 || R->getValue() == 0)
1057     throw "Record `" + getName() + "' does not have a field named `" +
1058       FieldName + "'!\n";
1059   
1060   if (const CodeInit *CI = dynamic_cast<const CodeInit*>(R->getValue()))
1061     return CI->getValue();
1062   throw "Record `" + getName() + "', field `" + FieldName +
1063     "' does not have a code initializer!";
1064 }
1065
1066
1067 void MultiClass::dump() const {
1068   cerr << "Record:\n";
1069   Rec.dump();
1070   
1071   cerr << "Defs:\n";
1072   for (RecordVector::const_iterator r = DefPrototypes.begin(),
1073          rend = DefPrototypes.end();
1074        r != rend;
1075        ++r) {
1076     (*r)->dump();
1077   }
1078 }
1079
1080
1081 void RecordKeeper::dump() const { cerr << *this; }
1082
1083 std::ostream &llvm::operator<<(std::ostream &OS, const RecordKeeper &RK) {
1084   OS << "------------- Classes -----------------\n";
1085   const std::map<std::string, Record*> &Classes = RK.getClasses();
1086   for (std::map<std::string, Record*>::const_iterator I = Classes.begin(),
1087          E = Classes.end(); I != E; ++I)
1088     OS << "class " << *I->second;
1089
1090   OS << "------------- Defs -----------------\n";
1091   const std::map<std::string, Record*> &Defs = RK.getDefs();
1092   for (std::map<std::string, Record*>::const_iterator I = Defs.begin(),
1093          E = Defs.end(); I != E; ++I)
1094     OS << "def " << *I->second;
1095   return OS;
1096 }
1097
1098
1099 /// getAllDerivedDefinitions - This method returns all concrete definitions
1100 /// that derive from the specified class name.  If a class with the specified
1101 /// name does not exist, an error is printed and true is returned.
1102 std::vector<Record*>
1103 RecordKeeper::getAllDerivedDefinitions(const std::string &ClassName) const {
1104   Record *Class = Records.getClass(ClassName);
1105   if (!Class)
1106     throw "ERROR: Couldn't find the `" + ClassName + "' class!\n";
1107
1108   std::vector<Record*> Defs;
1109   for (std::map<std::string, Record*>::const_iterator I = getDefs().begin(),
1110          E = getDefs().end(); I != E; ++I)
1111     if (I->second->isSubClassOf(Class))
1112       Defs.push_back(I->second);
1113
1114   return Defs;
1115 }
1116