[AVX] Make Inits Foldable
[oota-llvm.git] / utils / TableGen / TGParser.cpp
1 //===- TGParser.cpp - Parser for TableGen Files ---------------------------===//
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 Parser for TableGen.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "TGParser.h"
15 #include "Record.h"
16 #include "llvm/ADT/StringExtras.h"
17 #include <algorithm>
18 #include <sstream>
19 #include "llvm/ADT/SmallVector.h"
20 #include "llvm/Support/CommandLine.h"
21 using namespace llvm;
22
23 //===----------------------------------------------------------------------===//
24 // Support Code for the Semantic Actions.
25 //===----------------------------------------------------------------------===//
26
27 namespace llvm {
28 struct SubClassReference {
29   SMLoc RefLoc;
30   Record *Rec;
31   std::vector<const Init*> TemplateArgs;
32   SubClassReference() : Rec(0) {}
33
34   bool isInvalid() const { return Rec == 0; }
35 };
36
37 struct SubMultiClassReference {
38   SMLoc RefLoc;
39   MultiClass *MC;
40   std::vector<const Init*> TemplateArgs;
41   SubMultiClassReference() : MC(0) {}
42
43   bool isInvalid() const { return MC == 0; }
44   void dump() const;
45 };
46
47 void SubMultiClassReference::dump() const {
48   errs() << "Multiclass:\n";
49
50   MC->dump();
51
52   errs() << "Template args:\n";
53   for (std::vector<const Init *>::const_iterator i = TemplateArgs.begin(),
54          iend = TemplateArgs.end();
55        i != iend;
56        ++i) {
57     (*i)->dump();
58   }
59 }
60
61 } // end namespace llvm
62
63 bool TGParser::AddValue(Record *CurRec, SMLoc Loc, const RecordVal &RV) {
64   if (CurRec == 0)
65     CurRec = &CurMultiClass->Rec;
66
67   if (RecordVal *ERV = CurRec->getValue(RV.getName())) {
68     // The value already exists in the class, treat this as a set.
69     if (ERV->setValue(RV.getValue()))
70       return Error(Loc, "New definition of '" + RV.getName() + "' of type '" +
71                    RV.getType()->getAsString() + "' is incompatible with " +
72                    "previous definition of type '" +
73                    ERV->getType()->getAsString() + "'");
74   } else {
75     CurRec->addValue(RV);
76   }
77   return false;
78 }
79
80 /// SetValue -
81 /// Return true on error, false on success.
82 bool TGParser::SetValue(Record *CurRec, SMLoc Loc, const std::string &ValName,
83                         const std::vector<unsigned> &BitList, const Init *V) {
84   if (!V) return false;
85
86   if (CurRec == 0) CurRec = &CurMultiClass->Rec;
87
88   RecordVal *RV = CurRec->getValue(ValName);
89   if (RV == 0)
90     return Error(Loc, "Value '" + ValName + "' unknown!");
91
92   // Do not allow assignments like 'X = X'.  This will just cause infinite loops
93   // in the resolution machinery.
94   if (BitList.empty())
95     if (const VarInit *VI = dynamic_cast<const VarInit*>(V))
96       if (VI->getName() == ValName)
97         return false;
98
99   // If we are assigning to a subset of the bits in the value... then we must be
100   // assigning to a field of BitsRecTy, which must have a BitsInit
101   // initializer.
102   //
103   if (!BitList.empty()) {
104     const BitsInit *CurVal = dynamic_cast<const BitsInit*>(RV->getValue());
105     if (CurVal == 0)
106       return Error(Loc, "Value '" + ValName + "' is not a bits type");
107
108     // Convert the incoming value to a bits type of the appropriate size...
109     const Init *BI = V->convertInitializerTo(new BitsRecTy(BitList.size()));
110     if (BI == 0) {
111       V->convertInitializerTo(new BitsRecTy(BitList.size()));
112       return Error(Loc, "Initializer is not compatible with bit range");
113     }
114
115     // We should have a BitsInit type now.
116     const BitsInit *BInit = dynamic_cast<const BitsInit*>(BI);
117     assert(BInit != 0);
118
119     SmallVector<const Init *, 16> NewBits(CurVal->getNumBits());
120
121     // Loop over bits, assigning values as appropriate.
122     for (unsigned i = 0, e = BitList.size(); i != e; ++i) {
123       unsigned Bit = BitList[i];
124       if (NewBits[Bit])
125         return Error(Loc, "Cannot set bit #" + utostr(Bit) + " of value '" +
126                      ValName + "' more than once");
127       NewBits[Bit] = BInit->getBit(i);
128     }
129
130     for (unsigned i = 0, e = CurVal->getNumBits(); i != e; ++i)
131       if (NewBits[i] == 0)
132         NewBits[i] = CurVal->getBit(i);
133
134     V = BitsInit::Create(NewBits.begin(), NewBits.end());
135   }
136
137   if (RV->setValue(V))
138    return Error(Loc, "Value '" + ValName + "' of type '" +
139                 RV->getType()->getAsString() +
140                 "' is incompatible with initializer '" + V->getAsString() +"'");
141   return false;
142 }
143
144 /// AddSubClass - Add SubClass as a subclass to CurRec, resolving its template
145 /// args as SubClass's template arguments.
146 bool TGParser::AddSubClass(Record *CurRec, SubClassReference &SubClass) {
147   Record *SC = SubClass.Rec;
148   // Add all of the values in the subclass into the current class.
149   const std::vector<RecordVal> &Vals = SC->getValues();
150   for (unsigned i = 0, e = Vals.size(); i != e; ++i)
151     if (AddValue(CurRec, SubClass.RefLoc, Vals[i]))
152       return true;
153
154   const std::vector<std::string> &TArgs = SC->getTemplateArgs();
155
156   // Ensure that an appropriate number of template arguments are specified.
157   if (TArgs.size() < SubClass.TemplateArgs.size())
158     return Error(SubClass.RefLoc, "More template args specified than expected");
159
160   // Loop over all of the template arguments, setting them to the specified
161   // value or leaving them as the default if necessary.
162   for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
163     if (i < SubClass.TemplateArgs.size()) {
164       // If a value is specified for this template arg, set it now.
165       if (SetValue(CurRec, SubClass.RefLoc, TArgs[i], std::vector<unsigned>(),
166                    SubClass.TemplateArgs[i]))
167         return true;
168
169       // Resolve it next.
170       CurRec->resolveReferencesTo(CurRec->getValue(TArgs[i]));
171
172       // Now remove it.
173       CurRec->removeValue(TArgs[i]);
174
175     } else if (!CurRec->getValue(TArgs[i])->getValue()->isComplete()) {
176       return Error(SubClass.RefLoc,"Value not specified for template argument #"
177                    + utostr(i) + " (" + TArgs[i] + ") of subclass '" +
178                    SC->getName() + "'!");
179     }
180   }
181
182   // Since everything went well, we can now set the "superclass" list for the
183   // current record.
184   const std::vector<Record*> &SCs = SC->getSuperClasses();
185   for (unsigned i = 0, e = SCs.size(); i != e; ++i) {
186     if (CurRec->isSubClassOf(SCs[i]))
187       return Error(SubClass.RefLoc,
188                    "Already subclass of '" + SCs[i]->getName() + "'!\n");
189     CurRec->addSuperClass(SCs[i]);
190   }
191
192   if (CurRec->isSubClassOf(SC))
193     return Error(SubClass.RefLoc,
194                  "Already subclass of '" + SC->getName() + "'!\n");
195   CurRec->addSuperClass(SC);
196   return false;
197 }
198
199 /// AddSubMultiClass - Add SubMultiClass as a subclass to
200 /// CurMC, resolving its template args as SubMultiClass's
201 /// template arguments.
202 bool TGParser::AddSubMultiClass(MultiClass *CurMC,
203                                 SubMultiClassReference &SubMultiClass) {
204   MultiClass *SMC = SubMultiClass.MC;
205   Record *CurRec = &CurMC->Rec;
206
207   const std::vector<RecordVal> &MCVals = CurRec->getValues();
208
209   // Add all of the values in the subclass into the current class.
210   const std::vector<RecordVal> &SMCVals = SMC->Rec.getValues();
211   for (unsigned i = 0, e = SMCVals.size(); i != e; ++i)
212     if (AddValue(CurRec, SubMultiClass.RefLoc, SMCVals[i]))
213       return true;
214
215   int newDefStart = CurMC->DefPrototypes.size();
216
217   // Add all of the defs in the subclass into the current multiclass.
218   for (MultiClass::RecordVector::const_iterator i = SMC->DefPrototypes.begin(),
219          iend = SMC->DefPrototypes.end();
220        i != iend;
221        ++i) {
222     // Clone the def and add it to the current multiclass
223     Record *NewDef = new Record(**i);
224
225     // Add all of the values in the superclass into the current def.
226     for (unsigned i = 0, e = MCVals.size(); i != e; ++i)
227       if (AddValue(NewDef, SubMultiClass.RefLoc, MCVals[i]))
228         return true;
229
230     CurMC->DefPrototypes.push_back(NewDef);
231   }
232
233   const std::vector<std::string> &SMCTArgs = SMC->Rec.getTemplateArgs();
234
235   // Ensure that an appropriate number of template arguments are
236   // specified.
237   if (SMCTArgs.size() < SubMultiClass.TemplateArgs.size())
238     return Error(SubMultiClass.RefLoc,
239                  "More template args specified than expected");
240
241   // Loop over all of the template arguments, setting them to the specified
242   // value or leaving them as the default if necessary.
243   for (unsigned i = 0, e = SMCTArgs.size(); i != e; ++i) {
244     if (i < SubMultiClass.TemplateArgs.size()) {
245       // If a value is specified for this template arg, set it in the
246       // superclass now.
247       if (SetValue(CurRec, SubMultiClass.RefLoc, SMCTArgs[i],
248                    std::vector<unsigned>(),
249                    SubMultiClass.TemplateArgs[i]))
250         return true;
251
252       // Resolve it next.
253       CurRec->resolveReferencesTo(CurRec->getValue(SMCTArgs[i]));
254
255       // Now remove it.
256       CurRec->removeValue(SMCTArgs[i]);
257
258       // If a value is specified for this template arg, set it in the
259       // new defs now.
260       for (MultiClass::RecordVector::iterator j =
261              CurMC->DefPrototypes.begin() + newDefStart,
262              jend = CurMC->DefPrototypes.end();
263            j != jend;
264            ++j) {
265         Record *Def = *j;
266
267         if (SetValue(Def, SubMultiClass.RefLoc, SMCTArgs[i],
268                      std::vector<unsigned>(),
269                      SubMultiClass.TemplateArgs[i]))
270           return true;
271
272         // Resolve it next.
273         Def->resolveReferencesTo(Def->getValue(SMCTArgs[i]));
274
275         // Now remove it
276         Def->removeValue(SMCTArgs[i]);
277       }
278     } else if (!CurRec->getValue(SMCTArgs[i])->getValue()->isComplete()) {
279       return Error(SubMultiClass.RefLoc,
280                    "Value not specified for template argument #"
281                    + utostr(i) + " (" + SMCTArgs[i] + ") of subclass '" +
282                    SMC->Rec.getName() + "'!");
283     }
284   }
285
286   return false;
287 }
288
289 //===----------------------------------------------------------------------===//
290 // Parser Code
291 //===----------------------------------------------------------------------===//
292
293 /// isObjectStart - Return true if this is a valid first token for an Object.
294 static bool isObjectStart(tgtok::TokKind K) {
295   return K == tgtok::Class || K == tgtok::Def ||
296          K == tgtok::Defm || K == tgtok::Let || K == tgtok::MultiClass;
297 }
298
299 static std::string GetNewAnonymousName() {
300   static unsigned AnonCounter = 0;
301   return "anonymous."+utostr(AnonCounter++);
302 }
303
304 /// ParseObjectName - If an object name is specified, return it.  Otherwise,
305 /// return an anonymous name.
306 ///   ObjectName ::= ID
307 ///   ObjectName ::= /*empty*/
308 ///
309 std::string TGParser::ParseObjectName() {
310   if (Lex.getCode() != tgtok::Id)
311     return GetNewAnonymousName();
312
313   std::string Ret = Lex.getCurStrVal();
314   Lex.Lex();
315   return Ret;
316 }
317
318
319 /// ParseClassID - Parse and resolve a reference to a class name.  This returns
320 /// null on error.
321 ///
322 ///    ClassID ::= ID
323 ///
324 Record *TGParser::ParseClassID() {
325   if (Lex.getCode() != tgtok::Id) {
326     TokError("expected name for ClassID");
327     return 0;
328   }
329
330   Record *Result = Records.getClass(Lex.getCurStrVal());
331   if (Result == 0)
332     TokError("Couldn't find class '" + Lex.getCurStrVal() + "'");
333
334   Lex.Lex();
335   return Result;
336 }
337
338 /// ParseMultiClassID - Parse and resolve a reference to a multiclass name.
339 /// This returns null on error.
340 ///
341 ///    MultiClassID ::= ID
342 ///
343 MultiClass *TGParser::ParseMultiClassID() {
344   if (Lex.getCode() != tgtok::Id) {
345     TokError("expected name for ClassID");
346     return 0;
347   }
348
349   MultiClass *Result = MultiClasses[Lex.getCurStrVal()];
350   if (Result == 0)
351     TokError("Couldn't find class '" + Lex.getCurStrVal() + "'");
352
353   Lex.Lex();
354   return Result;
355 }
356
357 Record *TGParser::ParseDefmID() {
358   if (Lex.getCode() != tgtok::Id) {
359     TokError("expected multiclass name");
360     return 0;
361   }
362
363   MultiClass *MC = MultiClasses[Lex.getCurStrVal()];
364   if (MC == 0) {
365     TokError("Couldn't find multiclass '" + Lex.getCurStrVal() + "'");
366     return 0;
367   }
368
369   Lex.Lex();
370   return &MC->Rec;
371 }
372
373
374 /// ParseSubClassReference - Parse a reference to a subclass or to a templated
375 /// subclass.  This returns a SubClassRefTy with a null Record* on error.
376 ///
377 ///  SubClassRef ::= ClassID
378 ///  SubClassRef ::= ClassID '<' ValueList '>'
379 ///
380 SubClassReference TGParser::
381 ParseSubClassReference(Record *CurRec, bool isDefm) {
382   SubClassReference Result;
383   Result.RefLoc = Lex.getLoc();
384
385   if (isDefm)
386     Result.Rec = ParseDefmID();
387   else
388     Result.Rec = ParseClassID();
389   if (Result.Rec == 0) return Result;
390
391   // If there is no template arg list, we're done.
392   if (Lex.getCode() != tgtok::less)
393     return Result;
394   Lex.Lex();  // Eat the '<'
395
396   if (Lex.getCode() == tgtok::greater) {
397     TokError("subclass reference requires a non-empty list of template values");
398     Result.Rec = 0;
399     return Result;
400   }
401
402   Result.TemplateArgs = ParseValueList(CurRec, Result.Rec);
403   if (Result.TemplateArgs.empty()) {
404     Result.Rec = 0;   // Error parsing value list.
405     return Result;
406   }
407
408   if (Lex.getCode() != tgtok::greater) {
409     TokError("expected '>' in template value list");
410     Result.Rec = 0;
411     return Result;
412   }
413   Lex.Lex();
414
415   return Result;
416 }
417
418 /// ParseSubMultiClassReference - Parse a reference to a subclass or to a
419 /// templated submulticlass.  This returns a SubMultiClassRefTy with a null
420 /// Record* on error.
421 ///
422 ///  SubMultiClassRef ::= MultiClassID
423 ///  SubMultiClassRef ::= MultiClassID '<' ValueList '>'
424 ///
425 SubMultiClassReference TGParser::
426 ParseSubMultiClassReference(MultiClass *CurMC) {
427   SubMultiClassReference Result;
428   Result.RefLoc = Lex.getLoc();
429
430   Result.MC = ParseMultiClassID();
431   if (Result.MC == 0) return Result;
432
433   // If there is no template arg list, we're done.
434   if (Lex.getCode() != tgtok::less)
435     return Result;
436   Lex.Lex();  // Eat the '<'
437
438   if (Lex.getCode() == tgtok::greater) {
439     TokError("subclass reference requires a non-empty list of template values");
440     Result.MC = 0;
441     return Result;
442   }
443
444   Result.TemplateArgs = ParseValueList(&CurMC->Rec, &Result.MC->Rec);
445   if (Result.TemplateArgs.empty()) {
446     Result.MC = 0;   // Error parsing value list.
447     return Result;
448   }
449
450   if (Lex.getCode() != tgtok::greater) {
451     TokError("expected '>' in template value list");
452     Result.MC = 0;
453     return Result;
454   }
455   Lex.Lex();
456
457   return Result;
458 }
459
460 /// ParseRangePiece - Parse a bit/value range.
461 ///   RangePiece ::= INTVAL
462 ///   RangePiece ::= INTVAL '-' INTVAL
463 ///   RangePiece ::= INTVAL INTVAL
464 bool TGParser::ParseRangePiece(std::vector<unsigned> &Ranges) {
465   if (Lex.getCode() != tgtok::IntVal) {
466     TokError("expected integer or bitrange");
467     return true;
468   }
469   int64_t Start = Lex.getCurIntVal();
470   int64_t End;
471
472   if (Start < 0)
473     return TokError("invalid range, cannot be negative");
474
475   switch (Lex.Lex()) {  // eat first character.
476   default:
477     Ranges.push_back(Start);
478     return false;
479   case tgtok::minus:
480     if (Lex.Lex() != tgtok::IntVal) {
481       TokError("expected integer value as end of range");
482       return true;
483     }
484     End = Lex.getCurIntVal();
485     break;
486   case tgtok::IntVal:
487     End = -Lex.getCurIntVal();
488     break;
489   }
490   if (End < 0)
491     return TokError("invalid range, cannot be negative");
492   Lex.Lex();
493
494   // Add to the range.
495   if (Start < End) {
496     for (; Start <= End; ++Start)
497       Ranges.push_back(Start);
498   } else {
499     for (; Start >= End; --Start)
500       Ranges.push_back(Start);
501   }
502   return false;
503 }
504
505 /// ParseRangeList - Parse a list of scalars and ranges into scalar values.
506 ///
507 ///   RangeList ::= RangePiece (',' RangePiece)*
508 ///
509 std::vector<unsigned> TGParser::ParseRangeList() {
510   std::vector<unsigned> Result;
511
512   // Parse the first piece.
513   if (ParseRangePiece(Result))
514     return std::vector<unsigned>();
515   while (Lex.getCode() == tgtok::comma) {
516     Lex.Lex();  // Eat the comma.
517
518     // Parse the next range piece.
519     if (ParseRangePiece(Result))
520       return std::vector<unsigned>();
521   }
522   return Result;
523 }
524
525 /// ParseOptionalRangeList - Parse either a range list in <>'s or nothing.
526 ///   OptionalRangeList ::= '<' RangeList '>'
527 ///   OptionalRangeList ::= /*empty*/
528 bool TGParser::ParseOptionalRangeList(std::vector<unsigned> &Ranges) {
529   if (Lex.getCode() != tgtok::less)
530     return false;
531
532   SMLoc StartLoc = Lex.getLoc();
533   Lex.Lex(); // eat the '<'
534
535   // Parse the range list.
536   Ranges = ParseRangeList();
537   if (Ranges.empty()) return true;
538
539   if (Lex.getCode() != tgtok::greater) {
540     TokError("expected '>' at end of range list");
541     return Error(StartLoc, "to match this '<'");
542   }
543   Lex.Lex();   // eat the '>'.
544   return false;
545 }
546
547 /// ParseOptionalBitList - Parse either a bit list in {}'s or nothing.
548 ///   OptionalBitList ::= '{' RangeList '}'
549 ///   OptionalBitList ::= /*empty*/
550 bool TGParser::ParseOptionalBitList(std::vector<unsigned> &Ranges) {
551   if (Lex.getCode() != tgtok::l_brace)
552     return false;
553
554   SMLoc StartLoc = Lex.getLoc();
555   Lex.Lex(); // eat the '{'
556
557   // Parse the range list.
558   Ranges = ParseRangeList();
559   if (Ranges.empty()) return true;
560
561   if (Lex.getCode() != tgtok::r_brace) {
562     TokError("expected '}' at end of bit list");
563     return Error(StartLoc, "to match this '{'");
564   }
565   Lex.Lex();   // eat the '}'.
566   return false;
567 }
568
569
570 /// ParseType - Parse and return a tblgen type.  This returns null on error.
571 ///
572 ///   Type ::= STRING                       // string type
573 ///   Type ::= BIT                          // bit type
574 ///   Type ::= BITS '<' INTVAL '>'          // bits<x> type
575 ///   Type ::= INT                          // int type
576 ///   Type ::= LIST '<' Type '>'            // list<x> type
577 ///   Type ::= CODE                         // code type
578 ///   Type ::= DAG                          // dag type
579 ///   Type ::= ClassID                      // Record Type
580 ///
581 RecTy *TGParser::ParseType() {
582   switch (Lex.getCode()) {
583   default: TokError("Unknown token when expecting a type"); return 0;
584   case tgtok::String: Lex.Lex(); return new StringRecTy();
585   case tgtok::Bit:    Lex.Lex(); return new BitRecTy();
586   case tgtok::Int:    Lex.Lex(); return new IntRecTy();
587   case tgtok::Code:   Lex.Lex(); return new CodeRecTy();
588   case tgtok::Dag:    Lex.Lex(); return new DagRecTy();
589   case tgtok::Id:
590     if (Record *R = ParseClassID()) return new RecordRecTy(R);
591     return 0;
592   case tgtok::Bits: {
593     if (Lex.Lex() != tgtok::less) { // Eat 'bits'
594       TokError("expected '<' after bits type");
595       return 0;
596     }
597     if (Lex.Lex() != tgtok::IntVal) {  // Eat '<'
598       TokError("expected integer in bits<n> type");
599       return 0;
600     }
601     uint64_t Val = Lex.getCurIntVal();
602     if (Lex.Lex() != tgtok::greater) {  // Eat count.
603       TokError("expected '>' at end of bits<n> type");
604       return 0;
605     }
606     Lex.Lex();  // Eat '>'
607     return new BitsRecTy(Val);
608   }
609   case tgtok::List: {
610     if (Lex.Lex() != tgtok::less) { // Eat 'bits'
611       TokError("expected '<' after list type");
612       return 0;
613     }
614     Lex.Lex();  // Eat '<'
615     RecTy *SubType = ParseType();
616     if (SubType == 0) return 0;
617
618     if (Lex.getCode() != tgtok::greater) {
619       TokError("expected '>' at end of list<ty> type");
620       return 0;
621     }
622     Lex.Lex();  // Eat '>'
623     return new ListRecTy(SubType);
624   }
625   }
626 }
627
628 /// ParseIDValue - Parse an ID as a value and decode what it means.
629 ///
630 ///  IDValue ::= ID [def local value]
631 ///  IDValue ::= ID [def template arg]
632 ///  IDValue ::= ID [multiclass local value]
633 ///  IDValue ::= ID [multiclass template argument]
634 ///  IDValue ::= ID [def name]
635 ///
636 const Init *TGParser::ParseIDValue(Record *CurRec) {
637   assert(Lex.getCode() == tgtok::Id && "Expected ID in ParseIDValue");
638   std::string Name = Lex.getCurStrVal();
639   SMLoc Loc = Lex.getLoc();
640   Lex.Lex();
641   return ParseIDValue(CurRec, Name, Loc);
642 }
643
644 /// ParseIDValue - This is just like ParseIDValue above, but it assumes the ID
645 /// has already been read.
646 const Init *TGParser::ParseIDValue(Record *CurRec,
647                              const std::string &Name, SMLoc NameLoc) {
648   if (CurRec) {
649     if (const RecordVal *RV = CurRec->getValue(Name))
650       return VarInit::Create(Name, RV->getType());
651
652     std::string TemplateArgName = CurRec->getName()+":"+Name;
653     if (CurRec->isTemplateArg(TemplateArgName)) {
654       const RecordVal *RV = CurRec->getValue(TemplateArgName);
655       assert(RV && "Template arg doesn't exist??");
656       return VarInit::Create(TemplateArgName, RV->getType());
657     }
658   }
659
660   if (CurMultiClass) {
661     std::string MCName = CurMultiClass->Rec.getName()+"::"+Name;
662     if (CurMultiClass->Rec.isTemplateArg(MCName)) {
663       const RecordVal *RV = CurMultiClass->Rec.getValue(MCName);
664       assert(RV && "Template arg doesn't exist??");
665       return VarInit::Create(MCName, RV->getType());
666     }
667   }
668
669   if (Record *D = Records.getDef(Name))
670     return DefInit::Create(D);
671
672   Error(NameLoc, "Variable not defined: '" + Name + "'");
673   return 0;
674 }
675
676 /// ParseOperation - Parse an operator.  This returns null on error.
677 ///
678 /// Operation ::= XOperator ['<' Type '>'] '(' Args ')'
679 ///
680 const Init *TGParser::ParseOperation(Record *CurRec) {
681   switch (Lex.getCode()) {
682   default:
683     TokError("unknown operation");
684     return 0;
685     break;
686   case tgtok::XHead:
687   case tgtok::XTail:
688   case tgtok::XEmpty:
689   case tgtok::XCast: {  // Value ::= !unop '(' Value ')'
690     UnOpInit::UnaryOp Code;
691     RecTy *Type = 0;
692
693     switch (Lex.getCode()) {
694     default: assert(0 && "Unhandled code!");
695     case tgtok::XCast:
696       Lex.Lex();  // eat the operation
697       Code = UnOpInit::CAST;
698
699       Type = ParseOperatorType();
700
701       if (Type == 0) {
702         TokError("did not get type for unary operator");
703         return 0;
704       }
705
706       break;
707     case tgtok::XHead:
708       Lex.Lex();  // eat the operation
709       Code = UnOpInit::HEAD;
710       break;
711     case tgtok::XTail:
712       Lex.Lex();  // eat the operation
713       Code = UnOpInit::TAIL;
714       break;
715     case tgtok::XEmpty:
716       Lex.Lex();  // eat the operation
717       Code = UnOpInit::EMPTY;
718       Type = new IntRecTy;
719       break;
720     }
721     if (Lex.getCode() != tgtok::l_paren) {
722       TokError("expected '(' after unary operator");
723       return 0;
724     }
725     Lex.Lex();  // eat the '('
726
727     const Init *LHS = ParseValue(CurRec);
728     if (LHS == 0) return 0;
729
730     if (Code == UnOpInit::HEAD
731         || Code == UnOpInit::TAIL
732         || Code == UnOpInit::EMPTY) {
733       const ListInit *LHSl = dynamic_cast<const ListInit*>(LHS);
734       const StringInit *LHSs = dynamic_cast<const StringInit*>(LHS);
735       const TypedInit *LHSt = dynamic_cast<const TypedInit*>(LHS);
736       if (LHSl == 0 && LHSs == 0 && LHSt == 0) {
737         TokError("expected list or string type argument in unary operator");
738         return 0;
739       }
740       if (LHSt) {
741         ListRecTy *LType = dynamic_cast<ListRecTy*>(LHSt->getType());
742         StringRecTy *SType = dynamic_cast<StringRecTy*>(LHSt->getType());
743         if (LType == 0 && SType == 0) {
744           TokError("expected list or string type argumnet in unary operator");
745           return 0;
746         }
747       }
748
749       if (Code == UnOpInit::HEAD
750           || Code == UnOpInit::TAIL) {
751         if (LHSl == 0 && LHSt == 0) {
752           TokError("expected list type argumnet in unary operator");
753           return 0;
754         }
755
756         if (LHSl && LHSl->getSize() == 0) {
757           TokError("empty list argument in unary operator");
758           return 0;
759         }
760         if (LHSl) {
761           const Init *Item = LHSl->getElement(0);
762           const TypedInit *Itemt = dynamic_cast<const TypedInit*>(Item);
763           if (Itemt == 0) {
764             TokError("untyped list element in unary operator");
765             return 0;
766           }
767           if (Code == UnOpInit::HEAD) {
768             Type = Itemt->getType();
769           } else {
770             Type = new ListRecTy(Itemt->getType());
771           }
772         } else {
773           assert(LHSt && "expected list type argument in unary operator");
774           ListRecTy *LType = dynamic_cast<ListRecTy*>(LHSt->getType());
775           if (LType == 0) {
776             TokError("expected list type argumnet in unary operator");
777             return 0;
778           }
779           if (Code == UnOpInit::HEAD) {
780             Type = LType->getElementType();
781           } else {
782             Type = LType;
783           }
784         }
785       }
786     }
787
788     if (Lex.getCode() != tgtok::r_paren) {
789       TokError("expected ')' in unary operator");
790       return 0;
791     }
792     Lex.Lex();  // eat the ')'
793     return (UnOpInit::Create(Code, LHS, Type))->Fold(CurRec, CurMultiClass);
794   }
795
796   case tgtok::XConcat:
797   case tgtok::XSRA:
798   case tgtok::XSRL:
799   case tgtok::XSHL:
800   case tgtok::XEq:
801   case tgtok::XStrConcat: {  // Value ::= !binop '(' Value ',' Value ')'
802     tgtok::TokKind OpTok = Lex.getCode();
803     SMLoc OpLoc = Lex.getLoc();
804     Lex.Lex();  // eat the operation
805
806     BinOpInit::BinaryOp Code;
807     RecTy *Type = 0;
808
809     switch (OpTok) {
810     default: assert(0 && "Unhandled code!");
811     case tgtok::XConcat: Code = BinOpInit::CONCAT; Type = new DagRecTy(); break;
812     case tgtok::XSRA:    Code = BinOpInit::SRA;    Type = new IntRecTy(); break;
813     case tgtok::XSRL:    Code = BinOpInit::SRL;    Type = new IntRecTy(); break;
814     case tgtok::XSHL:    Code = BinOpInit::SHL;    Type = new IntRecTy(); break;
815     case tgtok::XEq:     Code = BinOpInit::EQ;     Type = new BitRecTy(); break;
816     case tgtok::XStrConcat:
817       Code = BinOpInit::STRCONCAT;
818       Type = new StringRecTy();
819       break;
820     }
821
822     if (Lex.getCode() != tgtok::l_paren) {
823       TokError("expected '(' after binary operator");
824       return 0;
825     }
826     Lex.Lex();  // eat the '('
827
828     SmallVector<const Init*, 2> InitList;
829
830     InitList.push_back(ParseValue(CurRec));
831     if (InitList.back() == 0) return 0;
832
833     while (Lex.getCode() == tgtok::comma) {
834       Lex.Lex();  // eat the ','
835
836       InitList.push_back(ParseValue(CurRec));
837       if (InitList.back() == 0) return 0;
838     }
839
840     if (Lex.getCode() != tgtok::r_paren) {
841       TokError("expected ')' in operator");
842       return 0;
843     }
844     Lex.Lex();  // eat the ')'
845
846     // We allow multiple operands to associative operators like !strconcat as
847     // shorthand for nesting them.
848     if (Code == BinOpInit::STRCONCAT) {
849       while (InitList.size() > 2) {
850         const Init *RHS = InitList.pop_back_val();
851         RHS = (BinOpInit::Create(Code, InitList.back(), RHS, Type))
852                       ->Fold(CurRec, CurMultiClass);
853         InitList.back() = RHS;
854       }
855     }
856
857     if (InitList.size() == 2)
858       return (BinOpInit::Create(Code, InitList[0], InitList[1], Type))
859         ->Fold(CurRec, CurMultiClass);
860
861     Error(OpLoc, "expected two operands to operator");
862     return 0;
863   }
864
865   case tgtok::XIf:
866   case tgtok::XForEach:
867   case tgtok::XSubst: {  // Value ::= !ternop '(' Value ',' Value ',' Value ')'
868     TernOpInit::TernaryOp Code;
869     RecTy *Type = 0;
870
871     tgtok::TokKind LexCode = Lex.getCode();
872     Lex.Lex();  // eat the operation
873     switch (LexCode) {
874     default: assert(0 && "Unhandled code!");
875     case tgtok::XIf:
876       Code = TernOpInit::IF;
877       break;
878     case tgtok::XForEach:
879       Code = TernOpInit::FOREACH;
880       break;
881     case tgtok::XSubst:
882       Code = TernOpInit::SUBST;
883       break;
884     }
885     if (Lex.getCode() != tgtok::l_paren) {
886       TokError("expected '(' after ternary operator");
887       return 0;
888     }
889     Lex.Lex();  // eat the '('
890
891     const Init *LHS = ParseValue(CurRec);
892     if (LHS == 0) return 0;
893
894     if (Lex.getCode() != tgtok::comma) {
895       TokError("expected ',' in ternary operator");
896       return 0;
897     }
898     Lex.Lex();  // eat the ','
899
900     const Init *MHS = ParseValue(CurRec);
901     if (MHS == 0) return 0;
902
903     if (Lex.getCode() != tgtok::comma) {
904       TokError("expected ',' in ternary operator");
905       return 0;
906     }
907     Lex.Lex();  // eat the ','
908
909     const Init *RHS = ParseValue(CurRec);
910     if (RHS == 0) return 0;
911
912     if (Lex.getCode() != tgtok::r_paren) {
913       TokError("expected ')' in binary operator");
914       return 0;
915     }
916     Lex.Lex();  // eat the ')'
917
918     switch (LexCode) {
919     default: assert(0 && "Unhandled code!");
920     case tgtok::XIf: {
921       // FIXME: The `!if' operator doesn't handle non-TypedInit well at
922       // all. This can be made much more robust.
923       const TypedInit *MHSt = dynamic_cast<const TypedInit*>(MHS);
924       const TypedInit *RHSt = dynamic_cast<const TypedInit*>(RHS);
925
926       RecTy *MHSTy = 0;
927       RecTy *RHSTy = 0;
928
929       if (MHSt == 0 && RHSt == 0) {
930         const BitsInit *MHSbits = dynamic_cast<const BitsInit*>(MHS);
931         const BitsInit *RHSbits = dynamic_cast<const BitsInit*>(RHS);
932
933         if (MHSbits && RHSbits &&
934             MHSbits->getNumBits() == RHSbits->getNumBits()) {
935           Type = new BitRecTy();
936           break;
937         } else {
938           const BitInit *MHSbit = dynamic_cast<const BitInit*>(MHS);
939           const BitInit *RHSbit = dynamic_cast<const BitInit*>(RHS);
940
941           if (MHSbit && RHSbit) {
942             Type = new BitRecTy();
943             break;
944           }
945         }
946       } else if (MHSt != 0 && RHSt != 0) {
947         MHSTy = MHSt->getType();
948         RHSTy = RHSt->getType();
949       }
950
951       if (!MHSTy || !RHSTy) {
952         TokError("could not get type for !if");
953         return 0;
954       }
955
956       if (MHSTy->typeIsConvertibleTo(RHSTy)) {
957         Type = RHSTy;
958       } else if (RHSTy->typeIsConvertibleTo(MHSTy)) {
959         Type = MHSTy;
960       } else {
961         TokError("inconsistent types for !if");
962         return 0;
963       }
964       break;
965     }
966     case tgtok::XForEach: {
967       const TypedInit *MHSt = dynamic_cast<const TypedInit *>(MHS);
968       if (MHSt == 0) {
969         TokError("could not get type for !foreach");
970         return 0;
971       }
972       Type = MHSt->getType();
973       break;
974     }
975     case tgtok::XSubst: {
976       const TypedInit *RHSt = dynamic_cast<const TypedInit *>(RHS);
977       if (RHSt == 0) {
978         TokError("could not get type for !subst");
979         return 0;
980       }
981       Type = RHSt->getType();
982       break;
983     }
984     }
985     return (TernOpInit::Create(Code, LHS, MHS, RHS, Type))->Fold(CurRec,
986                                                              CurMultiClass);
987   }
988   }
989   TokError("could not parse operation");
990   return 0;
991 }
992
993 /// ParseOperatorType - Parse a type for an operator.  This returns
994 /// null on error.
995 ///
996 /// OperatorType ::= '<' Type '>'
997 ///
998 RecTy *TGParser::ParseOperatorType() {
999   RecTy *Type = 0;
1000
1001   if (Lex.getCode() != tgtok::less) {
1002     TokError("expected type name for operator");
1003     return 0;
1004   }
1005   Lex.Lex();  // eat the <
1006
1007   Type = ParseType();
1008
1009   if (Type == 0) {
1010     TokError("expected type name for operator");
1011     return 0;
1012   }
1013
1014   if (Lex.getCode() != tgtok::greater) {
1015     TokError("expected type name for operator");
1016     return 0;
1017   }
1018   Lex.Lex();  // eat the >
1019
1020   return Type;
1021 }
1022
1023
1024 /// ParseSimpleValue - Parse a tblgen value.  This returns null on error.
1025 ///
1026 ///   SimpleValue ::= IDValue
1027 ///   SimpleValue ::= INTVAL
1028 ///   SimpleValue ::= STRVAL+
1029 ///   SimpleValue ::= CODEFRAGMENT
1030 ///   SimpleValue ::= '?'
1031 ///   SimpleValue ::= '{' ValueList '}'
1032 ///   SimpleValue ::= ID '<' ValueListNE '>'
1033 ///   SimpleValue ::= '[' ValueList ']'
1034 ///   SimpleValue ::= '(' IDValue DagArgList ')'
1035 ///   SimpleValue ::= CONCATTOK '(' Value ',' Value ')'
1036 ///   SimpleValue ::= SHLTOK '(' Value ',' Value ')'
1037 ///   SimpleValue ::= SRATOK '(' Value ',' Value ')'
1038 ///   SimpleValue ::= SRLTOK '(' Value ',' Value ')'
1039 ///   SimpleValue ::= STRCONCATTOK '(' Value ',' Value ')'
1040 ///
1041 const Init *TGParser::ParseSimpleValue(Record *CurRec, RecTy *ItemType) {
1042   const Init *R = 0;
1043   switch (Lex.getCode()) {
1044   default: TokError("Unknown token when parsing a value"); break;
1045   case tgtok::IntVal: R = IntInit::Create(Lex.getCurIntVal()); Lex.Lex(); break;
1046   case tgtok::StrVal: {
1047     std::string Val = Lex.getCurStrVal();
1048     Lex.Lex();
1049
1050     // Handle multiple consecutive concatenated strings.
1051     while (Lex.getCode() == tgtok::StrVal) {
1052       Val += Lex.getCurStrVal();
1053       Lex.Lex();
1054     }
1055
1056     R = StringInit::Create(Val);
1057     break;
1058   }
1059   case tgtok::CodeFragment:
1060     R = CodeInit::Create(Lex.getCurStrVal());
1061     Lex.Lex();
1062     break;
1063   case tgtok::question:
1064     R = UnsetInit::Create();
1065     Lex.Lex();
1066     break;
1067   case tgtok::Id: {
1068     SMLoc NameLoc = Lex.getLoc();
1069     std::string Name = Lex.getCurStrVal();
1070     if (Lex.Lex() != tgtok::less)  // consume the Id.
1071       return ParseIDValue(CurRec, Name, NameLoc);    // Value ::= IDValue
1072
1073     // Value ::= ID '<' ValueListNE '>'
1074     if (Lex.Lex() == tgtok::greater) {
1075       TokError("expected non-empty value list");
1076       return 0;
1077     }
1078
1079     // This is a CLASS<initvalslist> expression.  This is supposed to synthesize
1080     // a new anonymous definition, deriving from CLASS<initvalslist> with no
1081     // body.
1082     Record *Class = Records.getClass(Name);
1083     if (!Class) {
1084       Error(NameLoc, "Expected a class name, got '" + Name + "'");
1085       return 0;
1086     }
1087
1088     std::vector<const Init*> ValueList = ParseValueList(CurRec, Class);
1089     if (ValueList.empty()) return 0;
1090
1091     if (Lex.getCode() != tgtok::greater) {
1092       TokError("expected '>' at end of value list");
1093       return 0;
1094     }
1095     Lex.Lex();  // eat the '>'
1096
1097     // Create the new record, set it as CurRec temporarily.
1098     static unsigned AnonCounter = 0;
1099     Record *NewRec = new Record("anonymous.val."+utostr(AnonCounter++),
1100                                 NameLoc,
1101                                 Records);
1102     SubClassReference SCRef;
1103     SCRef.RefLoc = NameLoc;
1104     SCRef.Rec = Class;
1105     SCRef.TemplateArgs = ValueList;
1106     // Add info about the subclass to NewRec.
1107     if (AddSubClass(NewRec, SCRef))
1108       return 0;
1109     NewRec->resolveReferences();
1110     Records.addDef(NewRec);
1111
1112     // The result of the expression is a reference to the new record.
1113     return DefInit::Create(NewRec);
1114   }
1115   case tgtok::l_brace: {           // Value ::= '{' ValueList '}'
1116     SMLoc BraceLoc = Lex.getLoc();
1117     Lex.Lex(); // eat the '{'
1118     std::vector<const Init*> Vals;
1119
1120     if (Lex.getCode() != tgtok::r_brace) {
1121       Vals = ParseValueList(CurRec);
1122       if (Vals.empty()) return 0;
1123     }
1124     if (Lex.getCode() != tgtok::r_brace) {
1125       TokError("expected '}' at end of bit list value");
1126       return 0;
1127     }
1128     Lex.Lex();  // eat the '}'
1129
1130     SmallVector<const Init *, 16> NewBits(Vals.size());
1131
1132     for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
1133       const Init *Bit = Vals[i]->convertInitializerTo(new BitRecTy());
1134       if (Bit == 0) {
1135         Error(BraceLoc, "Element #" + utostr(i) + " (" + Vals[i]->getAsString()+
1136               ") is not convertable to a bit");
1137         return 0;
1138       }
1139       NewBits[Vals.size()-i-1] = Bit;
1140     }
1141     return BitsInit::Create(NewBits.begin(), NewBits.end());
1142   }
1143   case tgtok::l_square: {          // Value ::= '[' ValueList ']'
1144     Lex.Lex(); // eat the '['
1145     std::vector<const Init*> Vals;
1146
1147     RecTy *DeducedEltTy = 0;
1148     ListRecTy *GivenListTy = 0;
1149
1150     if (ItemType != 0) {
1151       ListRecTy *ListType = dynamic_cast<ListRecTy*>(ItemType);
1152       if (ListType == 0) {
1153         std::stringstream s;
1154         s << "Type mismatch for list, expected list type, got "
1155           << ItemType->getAsString();
1156         TokError(s.str());
1157         return 0;
1158       }
1159       GivenListTy = ListType;
1160     }
1161
1162     if (Lex.getCode() != tgtok::r_square) {
1163       Vals = ParseValueList(CurRec, 0,
1164                             GivenListTy ? GivenListTy->getElementType() : 0);
1165       if (Vals.empty()) return 0;
1166     }
1167     if (Lex.getCode() != tgtok::r_square) {
1168       TokError("expected ']' at end of list value");
1169       return 0;
1170     }
1171     Lex.Lex();  // eat the ']'
1172
1173     RecTy *GivenEltTy = 0;
1174     if (Lex.getCode() == tgtok::less) {
1175       // Optional list element type
1176       Lex.Lex();  // eat the '<'
1177
1178       GivenEltTy = ParseType();
1179       if (GivenEltTy == 0) {
1180         // Couldn't parse element type
1181         return 0;
1182       }
1183
1184       if (Lex.getCode() != tgtok::greater) {
1185         TokError("expected '>' at end of list element type");
1186         return 0;
1187       }
1188       Lex.Lex();  // eat the '>'
1189     }
1190
1191     // Check elements
1192     RecTy *EltTy = 0;
1193     for (std::vector<const Init *>::iterator i = Vals.begin(), ie = Vals.end();
1194          i != ie;
1195          ++i) {
1196       const TypedInit *TArg = dynamic_cast<const TypedInit*>(*i);
1197       if (TArg == 0) {
1198         TokError("Untyped list element");
1199         return 0;
1200       }
1201       if (EltTy != 0) {
1202         EltTy = resolveTypes(EltTy, TArg->getType());
1203         if (EltTy == 0) {
1204           TokError("Incompatible types in list elements");
1205           return 0;
1206         }
1207       } else {
1208         EltTy = TArg->getType();
1209       }
1210     }
1211
1212     if (GivenEltTy != 0) {
1213       if (EltTy != 0) {
1214         // Verify consistency
1215         if (!EltTy->typeIsConvertibleTo(GivenEltTy)) {
1216           TokError("Incompatible types in list elements");
1217           return 0;
1218         }
1219       }
1220       EltTy = GivenEltTy;
1221     }
1222
1223     if (EltTy == 0) {
1224       if (ItemType == 0) {
1225         TokError("No type for list");
1226         return 0;
1227       }
1228       DeducedEltTy = GivenListTy->getElementType();
1229     } else {
1230       // Make sure the deduced type is compatible with the given type
1231       if (GivenListTy) {
1232         if (!EltTy->typeIsConvertibleTo(GivenListTy->getElementType())) {
1233           TokError("Element type mismatch for list");
1234           return 0;
1235         }
1236       }
1237       DeducedEltTy = EltTy;
1238     }
1239
1240     return ListInit::Create(Vals, DeducedEltTy);
1241   }
1242   case tgtok::l_paren: {         // Value ::= '(' IDValue DagArgList ')'
1243     Lex.Lex();   // eat the '('
1244     if (Lex.getCode() != tgtok::Id && Lex.getCode() != tgtok::XCast) {
1245       TokError("expected identifier in dag init");
1246       return 0;
1247     }
1248
1249     const Init *Operator = ParseValue(CurRec);
1250     if (Operator == 0) return 0;
1251
1252     // If the operator name is present, parse it.
1253     std::string OperatorName;
1254     if (Lex.getCode() == tgtok::colon) {
1255       if (Lex.Lex() != tgtok::VarName) { // eat the ':'
1256         TokError("expected variable name in dag operator");
1257         return 0;
1258       }
1259       OperatorName = Lex.getCurStrVal();
1260       Lex.Lex();  // eat the VarName.
1261     }
1262
1263     std::vector<std::pair<const Init*, std::string> > DagArgs;
1264     if (Lex.getCode() != tgtok::r_paren) {
1265       DagArgs = ParseDagArgList(CurRec);
1266       if (DagArgs.empty()) return 0;
1267     }
1268
1269     if (Lex.getCode() != tgtok::r_paren) {
1270       TokError("expected ')' in dag init");
1271       return 0;
1272     }
1273     Lex.Lex();  // eat the ')'
1274
1275     return DagInit::Create(Operator, OperatorName, DagArgs);
1276   }
1277
1278   case tgtok::XHead:
1279   case tgtok::XTail:
1280   case tgtok::XEmpty:
1281   case tgtok::XCast:  // Value ::= !unop '(' Value ')'
1282   case tgtok::XConcat:
1283   case tgtok::XSRA:
1284   case tgtok::XSRL:
1285   case tgtok::XSHL:
1286   case tgtok::XEq:
1287   case tgtok::XStrConcat:   // Value ::= !binop '(' Value ',' Value ')'
1288   case tgtok::XIf:
1289   case tgtok::XForEach:
1290   case tgtok::XSubst: {  // Value ::= !ternop '(' Value ',' Value ',' Value ')'
1291     return ParseOperation(CurRec);
1292   }
1293   }
1294
1295   return R;
1296 }
1297
1298 /// ParseValue - Parse a tblgen value.  This returns null on error.
1299 ///
1300 ///   Value       ::= SimpleValue ValueSuffix*
1301 ///   ValueSuffix ::= '{' BitList '}'
1302 ///   ValueSuffix ::= '[' BitList ']'
1303 ///   ValueSuffix ::= '.' ID
1304 ///
1305 const Init *TGParser::ParseValue(Record *CurRec, RecTy *ItemType) {
1306   const Init *Result = ParseSimpleValue(CurRec, ItemType);
1307   if (Result == 0) return 0;
1308
1309   // Parse the suffixes now if present.
1310   while (1) {
1311     switch (Lex.getCode()) {
1312     default: return Result;
1313     case tgtok::l_brace: {
1314       SMLoc CurlyLoc = Lex.getLoc();
1315       Lex.Lex(); // eat the '{'
1316       std::vector<unsigned> Ranges = ParseRangeList();
1317       if (Ranges.empty()) return 0;
1318
1319       // Reverse the bitlist.
1320       std::reverse(Ranges.begin(), Ranges.end());
1321       Result = Result->convertInitializerBitRange(Ranges);
1322       if (Result == 0) {
1323         Error(CurlyLoc, "Invalid bit range for value");
1324         return 0;
1325       }
1326
1327       // Eat the '}'.
1328       if (Lex.getCode() != tgtok::r_brace) {
1329         TokError("expected '}' at end of bit range list");
1330         return 0;
1331       }
1332       Lex.Lex();
1333       break;
1334     }
1335     case tgtok::l_square: {
1336       SMLoc SquareLoc = Lex.getLoc();
1337       Lex.Lex(); // eat the '['
1338       std::vector<unsigned> Ranges = ParseRangeList();
1339       if (Ranges.empty()) return 0;
1340
1341       Result = Result->convertInitListSlice(Ranges);
1342       if (Result == 0) {
1343         Error(SquareLoc, "Invalid range for list slice");
1344         return 0;
1345       }
1346
1347       // Eat the ']'.
1348       if (Lex.getCode() != tgtok::r_square) {
1349         TokError("expected ']' at end of list slice");
1350         return 0;
1351       }
1352       Lex.Lex();
1353       break;
1354     }
1355     case tgtok::period:
1356       if (Lex.Lex() != tgtok::Id) {  // eat the .
1357         TokError("expected field identifier after '.'");
1358         return 0;
1359       }
1360       if (!Result->getFieldType(Lex.getCurStrVal())) {
1361         TokError("Cannot access field '" + Lex.getCurStrVal() + "' of value '" +
1362                  Result->getAsString() + "'");
1363         return 0;
1364       }
1365       Result = FieldInit::Create(Result, Lex.getCurStrVal());
1366       Lex.Lex();  // eat field name
1367       break;
1368     }
1369   }
1370 }
1371
1372 /// ParseDagArgList - Parse the argument list for a dag literal expression.
1373 ///
1374 ///    ParseDagArgList ::= Value (':' VARNAME)?
1375 ///    ParseDagArgList ::= ParseDagArgList ',' Value (':' VARNAME)?
1376 std::vector<std::pair<const Init*, std::string> >
1377 TGParser::ParseDagArgList(Record *CurRec) {
1378   std::vector<std::pair<const Init*, std::string> > Result;
1379
1380   while (1) {
1381     const Init *Val = ParseValue(CurRec);
1382     if (Val == 0) return std::vector<std::pair<const Init*, std::string> >();
1383
1384     // If the variable name is present, add it.
1385     std::string VarName;
1386     if (Lex.getCode() == tgtok::colon) {
1387       if (Lex.Lex() != tgtok::VarName) { // eat the ':'
1388         TokError("expected variable name in dag literal");
1389         return std::vector<std::pair<const Init*, std::string> >();
1390       }
1391       VarName = Lex.getCurStrVal();
1392       Lex.Lex();  // eat the VarName.
1393     }
1394
1395     Result.push_back(std::make_pair(Val, VarName));
1396
1397     if (Lex.getCode() != tgtok::comma) break;
1398     Lex.Lex(); // eat the ','
1399   }
1400
1401   return Result;
1402 }
1403
1404
1405 /// ParseValueList - Parse a comma separated list of values, returning them as a
1406 /// vector.  Note that this always expects to be able to parse at least one
1407 /// value.  It returns an empty list if this is not possible.
1408 ///
1409 ///   ValueList ::= Value (',' Value)
1410 ///
1411 std::vector<const Init*> TGParser::ParseValueList(Record *CurRec,
1412                                                   Record *ArgsRec,
1413                                                   RecTy *EltTy) {
1414   std::vector<const Init*> Result;
1415   RecTy *ItemType = EltTy;
1416   unsigned int ArgN = 0;
1417   if (ArgsRec != 0 && EltTy == 0) {
1418     const std::vector<std::string> &TArgs = ArgsRec->getTemplateArgs();
1419     const RecordVal *RV = ArgsRec->getValue(TArgs[ArgN]);
1420     assert(RV && "Template argument record not found??");
1421     ItemType = RV->getType();
1422     ++ArgN;
1423   }
1424   Result.push_back(ParseValue(CurRec, ItemType));
1425   if (Result.back() == 0) return std::vector<const Init*>();
1426
1427   while (Lex.getCode() == tgtok::comma) {
1428     Lex.Lex();  // Eat the comma
1429
1430     if (ArgsRec != 0 && EltTy == 0) {
1431       const std::vector<std::string> &TArgs = ArgsRec->getTemplateArgs();
1432       if (ArgN >= TArgs.size()) {
1433         TokError("too many template arguments");
1434         return std::vector<const Init*>();
1435       }
1436       const RecordVal *RV = ArgsRec->getValue(TArgs[ArgN]);
1437       assert(RV && "Template argument record not found??");
1438       ItemType = RV->getType();
1439       ++ArgN;
1440     }
1441     Result.push_back(ParseValue(CurRec, ItemType));
1442     if (Result.back() == 0) return std::vector<const Init*>();
1443   }
1444
1445   return Result;
1446 }
1447
1448
1449 /// ParseDeclaration - Read a declaration, returning the name of field ID, or an
1450 /// empty string on error.  This can happen in a number of different context's,
1451 /// including within a def or in the template args for a def (which which case
1452 /// CurRec will be non-null) and within the template args for a multiclass (in
1453 /// which case CurRec will be null, but CurMultiClass will be set).  This can
1454 /// also happen within a def that is within a multiclass, which will set both
1455 /// CurRec and CurMultiClass.
1456 ///
1457 ///  Declaration ::= FIELD? Type ID ('=' Value)?
1458 ///
1459 std::string TGParser::ParseDeclaration(Record *CurRec,
1460                                        bool ParsingTemplateArgs) {
1461   // Read the field prefix if present.
1462   bool HasField = Lex.getCode() == tgtok::Field;
1463   if (HasField) Lex.Lex();
1464
1465   RecTy *Type = ParseType();
1466   if (Type == 0) return "";
1467
1468   if (Lex.getCode() != tgtok::Id) {
1469     TokError("Expected identifier in declaration");
1470     return "";
1471   }
1472
1473   SMLoc IdLoc = Lex.getLoc();
1474   std::string DeclName = Lex.getCurStrVal();
1475   Lex.Lex();
1476
1477   if (ParsingTemplateArgs) {
1478     if (CurRec) {
1479       DeclName = CurRec->getName() + ":" + DeclName;
1480     } else {
1481       assert(CurMultiClass);
1482     }
1483     if (CurMultiClass)
1484       DeclName = CurMultiClass->Rec.getName() + "::" + DeclName;
1485   }
1486
1487   // Add the value.
1488   if (AddValue(CurRec, IdLoc, RecordVal(DeclName, Type, HasField)))
1489     return "";
1490
1491   // If a value is present, parse it.
1492   if (Lex.getCode() == tgtok::equal) {
1493     Lex.Lex();
1494     SMLoc ValLoc = Lex.getLoc();
1495     const Init *Val = ParseValue(CurRec, Type);
1496     if (Val == 0 ||
1497         SetValue(CurRec, ValLoc, DeclName, std::vector<unsigned>(), Val))
1498       return "";
1499   }
1500
1501   return DeclName;
1502 }
1503
1504 /// ParseTemplateArgList - Read a template argument list, which is a non-empty
1505 /// sequence of template-declarations in <>'s.  If CurRec is non-null, these are
1506 /// template args for a def, which may or may not be in a multiclass.  If null,
1507 /// these are the template args for a multiclass.
1508 ///
1509 ///    TemplateArgList ::= '<' Declaration (',' Declaration)* '>'
1510 ///
1511 bool TGParser::ParseTemplateArgList(Record *CurRec) {
1512   assert(Lex.getCode() == tgtok::less && "Not a template arg list!");
1513   Lex.Lex(); // eat the '<'
1514
1515   Record *TheRecToAddTo = CurRec ? CurRec : &CurMultiClass->Rec;
1516
1517   // Read the first declaration.
1518   std::string TemplArg = ParseDeclaration(CurRec, true/*templateargs*/);
1519   if (TemplArg.empty())
1520     return true;
1521
1522   TheRecToAddTo->addTemplateArg(TemplArg);
1523
1524   while (Lex.getCode() == tgtok::comma) {
1525     Lex.Lex(); // eat the ','
1526
1527     // Read the following declarations.
1528     TemplArg = ParseDeclaration(CurRec, true/*templateargs*/);
1529     if (TemplArg.empty())
1530       return true;
1531     TheRecToAddTo->addTemplateArg(TemplArg);
1532   }
1533
1534   if (Lex.getCode() != tgtok::greater)
1535     return TokError("expected '>' at end of template argument list");
1536   Lex.Lex(); // eat the '>'.
1537   return false;
1538 }
1539
1540
1541 /// ParseBodyItem - Parse a single item at within the body of a def or class.
1542 ///
1543 ///   BodyItem ::= Declaration ';'
1544 ///   BodyItem ::= LET ID OptionalBitList '=' Value ';'
1545 bool TGParser::ParseBodyItem(Record *CurRec) {
1546   if (Lex.getCode() != tgtok::Let) {
1547     if (ParseDeclaration(CurRec, false).empty())
1548       return true;
1549
1550     if (Lex.getCode() != tgtok::semi)
1551       return TokError("expected ';' after declaration");
1552     Lex.Lex();
1553     return false;
1554   }
1555
1556   // LET ID OptionalRangeList '=' Value ';'
1557   if (Lex.Lex() != tgtok::Id)
1558     return TokError("expected field identifier after let");
1559
1560   SMLoc IdLoc = Lex.getLoc();
1561   std::string FieldName = Lex.getCurStrVal();
1562   Lex.Lex();  // eat the field name.
1563
1564   std::vector<unsigned> BitList;
1565   if (ParseOptionalBitList(BitList))
1566     return true;
1567   std::reverse(BitList.begin(), BitList.end());
1568
1569   if (Lex.getCode() != tgtok::equal)
1570     return TokError("expected '=' in let expression");
1571   Lex.Lex();  // eat the '='.
1572
1573   RecordVal *Field = CurRec->getValue(FieldName);
1574   if (Field == 0)
1575     return TokError("Value '" + FieldName + "' unknown!");
1576
1577   RecTy *Type = Field->getType();
1578
1579   const Init *Val = ParseValue(CurRec, Type);
1580   if (Val == 0) return true;
1581
1582   if (Lex.getCode() != tgtok::semi)
1583     return TokError("expected ';' after let expression");
1584   Lex.Lex();
1585
1586   return SetValue(CurRec, IdLoc, FieldName, BitList, Val);
1587 }
1588
1589 /// ParseBody - Read the body of a class or def.  Return true on error, false on
1590 /// success.
1591 ///
1592 ///   Body     ::= ';'
1593 ///   Body     ::= '{' BodyList '}'
1594 ///   BodyList BodyItem*
1595 ///
1596 bool TGParser::ParseBody(Record *CurRec) {
1597   // If this is a null definition, just eat the semi and return.
1598   if (Lex.getCode() == tgtok::semi) {
1599     Lex.Lex();
1600     return false;
1601   }
1602
1603   if (Lex.getCode() != tgtok::l_brace)
1604     return TokError("Expected ';' or '{' to start body");
1605   // Eat the '{'.
1606   Lex.Lex();
1607
1608   while (Lex.getCode() != tgtok::r_brace)
1609     if (ParseBodyItem(CurRec))
1610       return true;
1611
1612   // Eat the '}'.
1613   Lex.Lex();
1614   return false;
1615 }
1616
1617 /// ParseObjectBody - Parse the body of a def or class.  This consists of an
1618 /// optional ClassList followed by a Body.  CurRec is the current def or class
1619 /// that is being parsed.
1620 ///
1621 ///   ObjectBody      ::= BaseClassList Body
1622 ///   BaseClassList   ::= /*empty*/
1623 ///   BaseClassList   ::= ':' BaseClassListNE
1624 ///   BaseClassListNE ::= SubClassRef (',' SubClassRef)*
1625 ///
1626 bool TGParser::ParseObjectBody(Record *CurRec) {
1627   // If there is a baseclass list, read it.
1628   if (Lex.getCode() == tgtok::colon) {
1629     Lex.Lex();
1630
1631     // Read all of the subclasses.
1632     SubClassReference SubClass = ParseSubClassReference(CurRec, false);
1633     while (1) {
1634       // Check for error.
1635       if (SubClass.Rec == 0) return true;
1636
1637       // Add it.
1638       if (AddSubClass(CurRec, SubClass))
1639         return true;
1640
1641       if (Lex.getCode() != tgtok::comma) break;
1642       Lex.Lex(); // eat ','.
1643       SubClass = ParseSubClassReference(CurRec, false);
1644     }
1645   }
1646
1647   // Process any variables on the let stack.
1648   for (unsigned i = 0, e = LetStack.size(); i != e; ++i)
1649     for (unsigned j = 0, e = LetStack[i].size(); j != e; ++j)
1650       if (SetValue(CurRec, LetStack[i][j].Loc, LetStack[i][j].Name,
1651                    LetStack[i][j].Bits, LetStack[i][j].Value))
1652         return true;
1653
1654   return ParseBody(CurRec);
1655 }
1656
1657 /// ParseDef - Parse and return a top level or multiclass def, return the record
1658 /// corresponding to it.  This returns null on error.
1659 ///
1660 ///   DefInst ::= DEF ObjectName ObjectBody
1661 ///
1662 bool TGParser::ParseDef(MultiClass *CurMultiClass) {
1663   SMLoc DefLoc = Lex.getLoc();
1664   assert(Lex.getCode() == tgtok::Def && "Unknown tok");
1665   Lex.Lex();  // Eat the 'def' token.
1666
1667   // Parse ObjectName and make a record for it.
1668   Record *CurRec = new Record(ParseObjectName(), DefLoc, Records);
1669
1670   if (!CurMultiClass) {
1671     // Top-level def definition.
1672
1673     // Ensure redefinition doesn't happen.
1674     if (Records.getDef(CurRec->getName())) {
1675       Error(DefLoc, "def '" + CurRec->getName() + "' already defined");
1676       return true;
1677     }
1678     Records.addDef(CurRec);
1679   } else {
1680     // Otherwise, a def inside a multiclass, add it to the multiclass.
1681     for (unsigned i = 0, e = CurMultiClass->DefPrototypes.size(); i != e; ++i)
1682       if (CurMultiClass->DefPrototypes[i]->getName() == CurRec->getName()) {
1683         Error(DefLoc, "def '" + CurRec->getName() +
1684               "' already defined in this multiclass!");
1685         return true;
1686       }
1687     CurMultiClass->DefPrototypes.push_back(CurRec);
1688   }
1689
1690   if (ParseObjectBody(CurRec))
1691     return true;
1692
1693   if (CurMultiClass == 0)  // Def's in multiclasses aren't really defs.
1694     CurRec->resolveReferences();
1695
1696   // If ObjectBody has template arguments, it's an error.
1697   assert(CurRec->getTemplateArgs().empty() && "How'd this get template args?");
1698
1699   if (CurMultiClass) {
1700     // Copy the template arguments for the multiclass into the def.
1701     const std::vector<std::string> &TArgs =
1702                                 CurMultiClass->Rec.getTemplateArgs();
1703
1704     for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
1705       const RecordVal *RV = CurMultiClass->Rec.getValue(TArgs[i]);
1706       assert(RV && "Template arg doesn't exist?");
1707       CurRec->addValue(*RV);
1708     }
1709   }
1710
1711   return false;
1712 }
1713
1714
1715 /// ParseClass - Parse a tblgen class definition.
1716 ///
1717 ///   ClassInst ::= CLASS ID TemplateArgList? ObjectBody
1718 ///
1719 bool TGParser::ParseClass() {
1720   assert(Lex.getCode() == tgtok::Class && "Unexpected token!");
1721   Lex.Lex();
1722
1723   if (Lex.getCode() != tgtok::Id)
1724     return TokError("expected class name after 'class' keyword");
1725
1726   Record *CurRec = Records.getClass(Lex.getCurStrVal());
1727   if (CurRec) {
1728     // If the body was previously defined, this is an error.
1729     if (!CurRec->getValues().empty() ||
1730         !CurRec->getSuperClasses().empty() ||
1731         !CurRec->getTemplateArgs().empty())
1732       return TokError("Class '" + CurRec->getName() + "' already defined");
1733   } else {
1734     // If this is the first reference to this class, create and add it.
1735     CurRec = new Record(Lex.getCurStrVal(), Lex.getLoc(), Records);
1736     Records.addClass(CurRec);
1737   }
1738   Lex.Lex(); // eat the name.
1739
1740   // If there are template args, parse them.
1741   if (Lex.getCode() == tgtok::less)
1742     if (ParseTemplateArgList(CurRec))
1743       return true;
1744
1745   // Finally, parse the object body.
1746   return ParseObjectBody(CurRec);
1747 }
1748
1749 /// ParseLetList - Parse a non-empty list of assignment expressions into a list
1750 /// of LetRecords.
1751 ///
1752 ///   LetList ::= LetItem (',' LetItem)*
1753 ///   LetItem ::= ID OptionalRangeList '=' Value
1754 ///
1755 std::vector<LetRecord> TGParser::ParseLetList() {
1756   std::vector<LetRecord> Result;
1757
1758   while (1) {
1759     if (Lex.getCode() != tgtok::Id) {
1760       TokError("expected identifier in let definition");
1761       return std::vector<LetRecord>();
1762     }
1763     std::string Name = Lex.getCurStrVal();
1764     SMLoc NameLoc = Lex.getLoc();
1765     Lex.Lex();  // Eat the identifier.
1766
1767     // Check for an optional RangeList.
1768     std::vector<unsigned> Bits;
1769     if (ParseOptionalRangeList(Bits))
1770       return std::vector<LetRecord>();
1771     std::reverse(Bits.begin(), Bits.end());
1772
1773     if (Lex.getCode() != tgtok::equal) {
1774       TokError("expected '=' in let expression");
1775       return std::vector<LetRecord>();
1776     }
1777     Lex.Lex();  // eat the '='.
1778
1779     const Init *Val = ParseValue(0);
1780     if (Val == 0) return std::vector<LetRecord>();
1781
1782     // Now that we have everything, add the record.
1783     Result.push_back(LetRecord(Name, Bits, Val, NameLoc));
1784
1785     if (Lex.getCode() != tgtok::comma)
1786       return Result;
1787     Lex.Lex();  // eat the comma.
1788   }
1789 }
1790
1791 /// ParseTopLevelLet - Parse a 'let' at top level.  This can be a couple of
1792 /// different related productions. This works inside multiclasses too.
1793 ///
1794 ///   Object ::= LET LetList IN '{' ObjectList '}'
1795 ///   Object ::= LET LetList IN Object
1796 ///
1797 bool TGParser::ParseTopLevelLet(MultiClass *CurMultiClass) {
1798   assert(Lex.getCode() == tgtok::Let && "Unexpected token");
1799   Lex.Lex();
1800
1801   // Add this entry to the let stack.
1802   std::vector<LetRecord> LetInfo = ParseLetList();
1803   if (LetInfo.empty()) return true;
1804   LetStack.push_back(LetInfo);
1805
1806   if (Lex.getCode() != tgtok::In)
1807     return TokError("expected 'in' at end of top-level 'let'");
1808   Lex.Lex();
1809
1810   // If this is a scalar let, just handle it now
1811   if (Lex.getCode() != tgtok::l_brace) {
1812     // LET LetList IN Object
1813     if (ParseObject(CurMultiClass))
1814       return true;
1815   } else {   // Object ::= LETCommand '{' ObjectList '}'
1816     SMLoc BraceLoc = Lex.getLoc();
1817     // Otherwise, this is a group let.
1818     Lex.Lex();  // eat the '{'.
1819
1820     // Parse the object list.
1821     if (ParseObjectList(CurMultiClass))
1822       return true;
1823
1824     if (Lex.getCode() != tgtok::r_brace) {
1825       TokError("expected '}' at end of top level let command");
1826       return Error(BraceLoc, "to match this '{'");
1827     }
1828     Lex.Lex();
1829   }
1830
1831   // Outside this let scope, this let block is not active.
1832   LetStack.pop_back();
1833   return false;
1834 }
1835
1836 /// ParseMultiClass - Parse a multiclass definition.
1837 ///
1838 ///  MultiClassInst ::= MULTICLASS ID TemplateArgList?
1839 ///                     ':' BaseMultiClassList '{' MultiClassDef+ '}'
1840 ///
1841 bool TGParser::ParseMultiClass() {
1842   assert(Lex.getCode() == tgtok::MultiClass && "Unexpected token");
1843   Lex.Lex();  // Eat the multiclass token.
1844
1845   if (Lex.getCode() != tgtok::Id)
1846     return TokError("expected identifier after multiclass for name");
1847   std::string Name = Lex.getCurStrVal();
1848
1849   if (MultiClasses.count(Name))
1850     return TokError("multiclass '" + Name + "' already defined");
1851
1852   CurMultiClass = MultiClasses[Name] = new MultiClass(Name, 
1853                                                       Lex.getLoc(), Records);
1854   Lex.Lex();  // Eat the identifier.
1855
1856   // If there are template args, parse them.
1857   if (Lex.getCode() == tgtok::less)
1858     if (ParseTemplateArgList(0))
1859       return true;
1860
1861   bool inherits = false;
1862
1863   // If there are submulticlasses, parse them.
1864   if (Lex.getCode() == tgtok::colon) {
1865     inherits = true;
1866
1867     Lex.Lex();
1868
1869     // Read all of the submulticlasses.
1870     SubMultiClassReference SubMultiClass =
1871       ParseSubMultiClassReference(CurMultiClass);
1872     while (1) {
1873       // Check for error.
1874       if (SubMultiClass.MC == 0) return true;
1875
1876       // Add it.
1877       if (AddSubMultiClass(CurMultiClass, SubMultiClass))
1878         return true;
1879
1880       if (Lex.getCode() != tgtok::comma) break;
1881       Lex.Lex(); // eat ','.
1882       SubMultiClass = ParseSubMultiClassReference(CurMultiClass);
1883     }
1884   }
1885
1886   if (Lex.getCode() != tgtok::l_brace) {
1887     if (!inherits)
1888       return TokError("expected '{' in multiclass definition");
1889     else if (Lex.getCode() != tgtok::semi)
1890       return TokError("expected ';' in multiclass definition");
1891     else
1892       Lex.Lex();  // eat the ';'.
1893   } else {
1894     if (Lex.Lex() == tgtok::r_brace)  // eat the '{'.
1895       return TokError("multiclass must contain at least one def");
1896
1897     while (Lex.getCode() != tgtok::r_brace) {
1898       switch (Lex.getCode()) {
1899         default:
1900           return TokError("expected 'let', 'def' or 'defm' in multiclass body");
1901         case tgtok::Let:
1902         case tgtok::Def:
1903         case tgtok::Defm:
1904           if (ParseObject(CurMultiClass))
1905             return true;
1906          break;
1907       }
1908     }
1909     Lex.Lex();  // eat the '}'.
1910   }
1911
1912   CurMultiClass = 0;
1913   return false;
1914 }
1915
1916 /// ParseDefm - Parse the instantiation of a multiclass.
1917 ///
1918 ///   DefMInst ::= DEFM ID ':' DefmSubClassRef ';'
1919 ///
1920 bool TGParser::ParseDefm(MultiClass *CurMultiClass) {
1921   assert(Lex.getCode() == tgtok::Defm && "Unexpected token!");
1922
1923   std::string DefmPrefix;
1924   if (Lex.Lex() == tgtok::Id) {  // eat the defm.
1925     DefmPrefix = Lex.getCurStrVal();
1926     Lex.Lex();  // Eat the defm prefix.
1927   }
1928
1929   SMLoc DefmPrefixLoc = Lex.getLoc();
1930   if (Lex.getCode() != tgtok::colon)
1931     return TokError("expected ':' after defm identifier");
1932
1933   // Keep track of the new generated record definitions.
1934   std::vector<Record*> NewRecDefs;
1935
1936   // This record also inherits from a regular class (non-multiclass)?
1937   bool InheritFromClass = false;
1938
1939   // eat the colon.
1940   Lex.Lex();
1941
1942   SMLoc SubClassLoc = Lex.getLoc();
1943   SubClassReference Ref = ParseSubClassReference(0, true);
1944
1945   while (1) {
1946     if (Ref.Rec == 0) return true;
1947
1948     // To instantiate a multiclass, we need to first get the multiclass, then
1949     // instantiate each def contained in the multiclass with the SubClassRef
1950     // template parameters.
1951     MultiClass *MC = MultiClasses[Ref.Rec->getName()];
1952     assert(MC && "Didn't lookup multiclass correctly?");
1953     std::vector<const Init*> &TemplateVals = Ref.TemplateArgs;
1954
1955     // Verify that the correct number of template arguments were specified.
1956     const std::vector<std::string> &TArgs = MC->Rec.getTemplateArgs();
1957     if (TArgs.size() < TemplateVals.size())
1958       return Error(SubClassLoc,
1959                    "more template args specified than multiclass expects");
1960
1961     // Loop over all the def's in the multiclass, instantiating each one.
1962     for (unsigned i = 0, e = MC->DefPrototypes.size(); i != e; ++i) {
1963       Record *DefProto = MC->DefPrototypes[i];
1964
1965       // Add in the defm name.  If the defm prefix is empty, give each
1966       // instantiated def a unique name.  Otherwise, if "#NAME#" exists in the
1967       // name, substitute the prefix for #NAME#.  Otherwise, use the defm name
1968       // as a prefix.
1969       std::string DefName = DefProto->getName();
1970       if (DefmPrefix.empty()) {
1971         DefName = GetNewAnonymousName();
1972       } else {
1973         std::string::size_type idx = DefName.find("#NAME#");
1974         if (idx != std::string::npos) {
1975           DefName.replace(idx, 6, DefmPrefix);
1976         } else {
1977           // Add the suffix to the defm name to get the new name.
1978           DefName = DefmPrefix + DefName;
1979         }
1980       }
1981
1982       Record *CurRec = new Record(DefName, DefmPrefixLoc, Records);
1983
1984       SubClassReference Ref;
1985       Ref.RefLoc = DefmPrefixLoc;
1986       Ref.Rec = DefProto;
1987       AddSubClass(CurRec, Ref);
1988
1989       // Loop over all of the template arguments, setting them to the specified
1990       // value or leaving them as the default if necessary.
1991       for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
1992         // Check if a value is specified for this temp-arg.
1993         if (i < TemplateVals.size()) {
1994           // Set it now.
1995           if (SetValue(CurRec, DefmPrefixLoc, TArgs[i], std::vector<unsigned>(),
1996                        TemplateVals[i]))
1997             return true;
1998
1999           // Resolve it next.
2000           CurRec->resolveReferencesTo(CurRec->getValue(TArgs[i]));
2001
2002           // Now remove it.
2003           CurRec->removeValue(TArgs[i]);
2004
2005         } else if (!CurRec->getValue(TArgs[i])->getValue()->isComplete()) {
2006           return Error(SubClassLoc,
2007                        "value not specified for template argument #"+
2008                        utostr(i) + " (" + TArgs[i] + ") of multiclassclass '" +
2009                        MC->Rec.getName() + "'");
2010         }
2011       }
2012
2013       // If the mdef is inside a 'let' expression, add to each def.
2014       for (unsigned i = 0, e = LetStack.size(); i != e; ++i)
2015         for (unsigned j = 0, e = LetStack[i].size(); j != e; ++j)
2016           if (SetValue(CurRec, LetStack[i][j].Loc, LetStack[i][j].Name,
2017                        LetStack[i][j].Bits, LetStack[i][j].Value)) {
2018             Error(DefmPrefixLoc, "when instantiating this defm");
2019             return true;
2020           }
2021
2022       // Ensure redefinition doesn't happen.
2023       if (Records.getDef(CurRec->getName()))
2024         return Error(DefmPrefixLoc, "def '" + CurRec->getName() +
2025                      "' already defined, instantiating defm with subdef '" +
2026                      DefProto->getName() + "'");
2027
2028       // Don't create a top level definition for defm inside multiclasses,
2029       // instead, only update the prototypes and bind the template args
2030       // with the new created definition.
2031       if (CurMultiClass) {
2032         for (unsigned i = 0, e = CurMultiClass->DefPrototypes.size();
2033              i != e; ++i) {
2034           if (CurMultiClass->DefPrototypes[i]->getName() == CurRec->getName()) {
2035             Error(DefmPrefixLoc, "defm '" + CurRec->getName() +
2036                   "' already defined in this multiclass!");
2037             return 0;
2038           }
2039         }
2040         CurMultiClass->DefPrototypes.push_back(CurRec);
2041
2042         // Copy the template arguments for the multiclass into the new def.
2043         const std::vector<std::string> &TA =
2044           CurMultiClass->Rec.getTemplateArgs();
2045
2046         for (unsigned i = 0, e = TA.size(); i != e; ++i) {
2047           const RecordVal *RV = CurMultiClass->Rec.getValue(TA[i]);
2048           assert(RV && "Template arg doesn't exist?");
2049           CurRec->addValue(*RV);
2050         }
2051       } else {
2052         Records.addDef(CurRec);
2053       }
2054
2055       NewRecDefs.push_back(CurRec);
2056     }
2057
2058     if (Lex.getCode() != tgtok::comma) break;
2059     Lex.Lex(); // eat ','.
2060
2061     SubClassLoc = Lex.getLoc();
2062
2063     // A defm can inherit from regular classes (non-multiclass) as
2064     // long as they come in the end of the inheritance list.
2065     InheritFromClass = (Records.getClass(Lex.getCurStrVal()) != 0);
2066
2067     if (InheritFromClass)
2068       break;
2069
2070     Ref = ParseSubClassReference(0, true);
2071   }
2072
2073   if (InheritFromClass) {
2074     // Process all the classes to inherit as if they were part of a
2075     // regular 'def' and inherit all record values.
2076     SubClassReference SubClass = ParseSubClassReference(0, false);
2077     while (1) {
2078       // Check for error.
2079       if (SubClass.Rec == 0) return true;
2080
2081       // Get the expanded definition prototypes and teach them about
2082       // the record values the current class to inherit has
2083       for (unsigned i = 0, e = NewRecDefs.size(); i != e; ++i) {
2084         Record *CurRec = NewRecDefs[i];
2085
2086         // Add it.
2087         if (AddSubClass(CurRec, SubClass))
2088           return true;
2089
2090         // Process any variables on the let stack.
2091         for (unsigned i = 0, e = LetStack.size(); i != e; ++i)
2092           for (unsigned j = 0, e = LetStack[i].size(); j != e; ++j)
2093             if (SetValue(CurRec, LetStack[i][j].Loc, LetStack[i][j].Name,
2094                          LetStack[i][j].Bits, LetStack[i][j].Value))
2095               return true;
2096       }
2097
2098       if (Lex.getCode() != tgtok::comma) break;
2099       Lex.Lex(); // eat ','.
2100       SubClass = ParseSubClassReference(0, false);
2101     }
2102   }
2103
2104   if (!CurMultiClass)
2105     for (unsigned i = 0, e = NewRecDefs.size(); i != e; ++i)
2106       NewRecDefs[i]->resolveReferences();
2107
2108   if (Lex.getCode() != tgtok::semi)
2109     return TokError("expected ';' at end of defm");
2110   Lex.Lex();
2111
2112   return false;
2113 }
2114
2115 /// ParseObject
2116 ///   Object ::= ClassInst
2117 ///   Object ::= DefInst
2118 ///   Object ::= MultiClassInst
2119 ///   Object ::= DefMInst
2120 ///   Object ::= LETCommand '{' ObjectList '}'
2121 ///   Object ::= LETCommand Object
2122 bool TGParser::ParseObject(MultiClass *MC) {
2123   switch (Lex.getCode()) {
2124   default:
2125     return TokError("Expected class, def, defm, multiclass or let definition");
2126   case tgtok::Let:   return ParseTopLevelLet(MC);
2127   case tgtok::Def:   return ParseDef(MC);
2128   case tgtok::Defm:  return ParseDefm(MC);
2129   case tgtok::Class: return ParseClass();
2130   case tgtok::MultiClass: return ParseMultiClass();
2131   }
2132 }
2133
2134 /// ParseObjectList
2135 ///   ObjectList :== Object*
2136 bool TGParser::ParseObjectList(MultiClass *MC) {
2137   while (isObjectStart(Lex.getCode())) {
2138     if (ParseObject(MC))
2139       return true;
2140   }
2141   return false;
2142 }
2143
2144 bool TGParser::ParseFile() {
2145   Lex.Lex(); // Prime the lexer.
2146   if (ParseObjectList()) return true;
2147
2148   // If we have unread input at the end of the file, report it.
2149   if (Lex.getCode() == tgtok::Eof)
2150     return false;
2151
2152   return TokError("Unexpected input at top level");
2153 }
2154