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