blob: 9d579c2ef7e3de829202fc0203ed35620f5400ab [file] [log] [blame]
Chris Lattnerf4601652007-11-22 20:49:04 +00001//===- TGParser.cpp - Parser for TableGen Files ---------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner30609102007-12-29 20:37:13 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnerf4601652007-11-22 20:49:04 +00007//
8//===----------------------------------------------------------------------===//
9//
10// Implement the Parser for TableGen.
11//
12//===----------------------------------------------------------------------===//
13
Chuck Rose IIIaa917922007-11-26 23:19:59 +000014#include <algorithm>
15
Chris Lattnerf4601652007-11-22 20:49:04 +000016#include "TGParser.h"
17#include "Record.h"
18#include "llvm/ADT/StringExtras.h"
19using namespace llvm;
20
21//===----------------------------------------------------------------------===//
22// Support Code for the Semantic Actions.
23//===----------------------------------------------------------------------===//
24
25namespace llvm {
26struct MultiClass {
27 Record Rec; // Placeholder for template args and Name.
28 std::vector<Record*> DefPrototypes;
29
Chris Lattner7b9ffe42009-03-13 16:09:24 +000030 MultiClass(const std::string &Name, TGLoc Loc) : Rec(Name, Loc) {}
Chris Lattnerf4601652007-11-22 20:49:04 +000031};
32
33struct SubClassReference {
Chris Lattner1c8ae592009-03-13 16:01:53 +000034 TGLoc RefLoc;
Chris Lattnerf4601652007-11-22 20:49:04 +000035 Record *Rec;
36 std::vector<Init*> TemplateArgs;
Chris Lattner1c8ae592009-03-13 16:01:53 +000037 SubClassReference() : Rec(0) {}
Chris Lattnerf4601652007-11-22 20:49:04 +000038
39 bool isInvalid() const { return Rec == 0; }
40};
41
42} // end namespace llvm
43
Chris Lattner1c8ae592009-03-13 16:01:53 +000044bool TGParser::AddValue(Record *CurRec, TGLoc Loc, const RecordVal &RV) {
Chris Lattnerf4601652007-11-22 20:49:04 +000045 if (CurRec == 0)
46 CurRec = &CurMultiClass->Rec;
47
48 if (RecordVal *ERV = CurRec->getValue(RV.getName())) {
49 // The value already exists in the class, treat this as a set.
50 if (ERV->setValue(RV.getValue()))
51 return Error(Loc, "New definition of '" + RV.getName() + "' of type '" +
52 RV.getType()->getAsString() + "' is incompatible with " +
53 "previous definition of type '" +
54 ERV->getType()->getAsString() + "'");
55 } else {
56 CurRec->addValue(RV);
57 }
58 return false;
59}
60
61/// SetValue -
62/// Return true on error, false on success.
Chris Lattner1c8ae592009-03-13 16:01:53 +000063bool TGParser::SetValue(Record *CurRec, TGLoc Loc, const std::string &ValName,
Chris Lattnerf4601652007-11-22 20:49:04 +000064 const std::vector<unsigned> &BitList, Init *V) {
65 if (!V) return false;
66
67 if (CurRec == 0) CurRec = &CurMultiClass->Rec;
68
69 RecordVal *RV = CurRec->getValue(ValName);
70 if (RV == 0)
71 return Error(Loc, "Value '" + ValName + "' unknown!");
72
73 // Do not allow assignments like 'X = X'. This will just cause infinite loops
74 // in the resolution machinery.
75 if (BitList.empty())
76 if (VarInit *VI = dynamic_cast<VarInit*>(V))
77 if (VI->getName() == ValName)
78 return false;
79
80 // If we are assigning to a subset of the bits in the value... then we must be
81 // assigning to a field of BitsRecTy, which must have a BitsInit
82 // initializer.
83 //
84 if (!BitList.empty()) {
85 BitsInit *CurVal = dynamic_cast<BitsInit*>(RV->getValue());
86 if (CurVal == 0)
87 return Error(Loc, "Value '" + ValName + "' is not a bits type");
88
89 // Convert the incoming value to a bits type of the appropriate size...
90 Init *BI = V->convertInitializerTo(new BitsRecTy(BitList.size()));
91 if (BI == 0) {
92 V->convertInitializerTo(new BitsRecTy(BitList.size()));
93 return Error(Loc, "Initializer is not compatible with bit range");
94 }
95
96 // We should have a BitsInit type now.
97 BitsInit *BInit = dynamic_cast<BitsInit*>(BI);
98 assert(BInit != 0);
99
100 BitsInit *NewVal = new BitsInit(CurVal->getNumBits());
101
102 // Loop over bits, assigning values as appropriate.
103 for (unsigned i = 0, e = BitList.size(); i != e; ++i) {
104 unsigned Bit = BitList[i];
105 if (NewVal->getBit(Bit))
106 return Error(Loc, "Cannot set bit #" + utostr(Bit) + " of value '" +
107 ValName + "' more than once");
108 NewVal->setBit(Bit, BInit->getBit(i));
109 }
110
111 for (unsigned i = 0, e = CurVal->getNumBits(); i != e; ++i)
112 if (NewVal->getBit(i) == 0)
113 NewVal->setBit(i, CurVal->getBit(i));
114
115 V = NewVal;
116 }
117
118 if (RV->setValue(V))
119 return Error(Loc, "Value '" + ValName + "' of type '" +
120 RV->getType()->getAsString() +
Chris Lattner5d814862007-11-22 21:06:59 +0000121 "' is incompatible with initializer '" + V->getAsString() +"'");
Chris Lattnerf4601652007-11-22 20:49:04 +0000122 return false;
123}
124
125/// AddSubClass - Add SubClass as a subclass to CurRec, resolving its template
126/// args as SubClass's template arguments.
Cedric Venetaff9c272009-02-14 16:06:42 +0000127bool TGParser::AddSubClass(Record *CurRec, SubClassReference &SubClass) {
Chris Lattnerf4601652007-11-22 20:49:04 +0000128 Record *SC = SubClass.Rec;
129 // Add all of the values in the subclass into the current class.
130 const std::vector<RecordVal> &Vals = SC->getValues();
131 for (unsigned i = 0, e = Vals.size(); i != e; ++i)
132 if (AddValue(CurRec, SubClass.RefLoc, Vals[i]))
133 return true;
134
135 const std::vector<std::string> &TArgs = SC->getTemplateArgs();
136
137 // Ensure that an appropriate number of template arguments are specified.
138 if (TArgs.size() < SubClass.TemplateArgs.size())
139 return Error(SubClass.RefLoc, "More template args specified than expected");
140
141 // Loop over all of the template arguments, setting them to the specified
142 // value or leaving them as the default if necessary.
143 for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
144 if (i < SubClass.TemplateArgs.size()) {
145 // If a value is specified for this template arg, set it now.
146 if (SetValue(CurRec, SubClass.RefLoc, TArgs[i], std::vector<unsigned>(),
147 SubClass.TemplateArgs[i]))
148 return true;
149
150 // Resolve it next.
151 CurRec->resolveReferencesTo(CurRec->getValue(TArgs[i]));
152
153 // Now remove it.
154 CurRec->removeValue(TArgs[i]);
155
156 } else if (!CurRec->getValue(TArgs[i])->getValue()->isComplete()) {
157 return Error(SubClass.RefLoc,"Value not specified for template argument #"
158 + utostr(i) + " (" + TArgs[i] + ") of subclass '" +
159 SC->getName() + "'!");
160 }
161 }
162
163 // Since everything went well, we can now set the "superclass" list for the
164 // current record.
165 const std::vector<Record*> &SCs = SC->getSuperClasses();
166 for (unsigned i = 0, e = SCs.size(); i != e; ++i) {
167 if (CurRec->isSubClassOf(SCs[i]))
168 return Error(SubClass.RefLoc,
169 "Already subclass of '" + SCs[i]->getName() + "'!\n");
170 CurRec->addSuperClass(SCs[i]);
171 }
172
173 if (CurRec->isSubClassOf(SC))
174 return Error(SubClass.RefLoc,
175 "Already subclass of '" + SC->getName() + "'!\n");
176 CurRec->addSuperClass(SC);
177 return false;
178}
179
180//===----------------------------------------------------------------------===//
181// Parser Code
182//===----------------------------------------------------------------------===//
183
184/// isObjectStart - Return true if this is a valid first token for an Object.
185static bool isObjectStart(tgtok::TokKind K) {
186 return K == tgtok::Class || K == tgtok::Def ||
187 K == tgtok::Defm || K == tgtok::Let || K == tgtok::MultiClass;
188}
189
190/// ParseObjectName - If an object name is specified, return it. Otherwise,
191/// return an anonymous name.
192/// ObjectName ::= ID
193/// ObjectName ::= /*empty*/
194///
195std::string TGParser::ParseObjectName() {
196 if (Lex.getCode() == tgtok::Id) {
197 std::string Ret = Lex.getCurStrVal();
198 Lex.Lex();
199 return Ret;
200 }
201
202 static unsigned AnonCounter = 0;
203 return "anonymous."+utostr(AnonCounter++);
204}
205
206
207/// ParseClassID - Parse and resolve a reference to a class name. This returns
208/// null on error.
209///
210/// ClassID ::= ID
211///
212Record *TGParser::ParseClassID() {
213 if (Lex.getCode() != tgtok::Id) {
214 TokError("expected name for ClassID");
215 return 0;
216 }
217
218 Record *Result = Records.getClass(Lex.getCurStrVal());
219 if (Result == 0)
220 TokError("Couldn't find class '" + Lex.getCurStrVal() + "'");
221
222 Lex.Lex();
223 return Result;
224}
225
226Record *TGParser::ParseDefmID() {
227 if (Lex.getCode() != tgtok::Id) {
228 TokError("expected multiclass name");
229 return 0;
230 }
231
232 MultiClass *MC = MultiClasses[Lex.getCurStrVal()];
233 if (MC == 0) {
234 TokError("Couldn't find multiclass '" + Lex.getCurStrVal() + "'");
235 return 0;
236 }
237
238 Lex.Lex();
239 return &MC->Rec;
240}
241
242
243
244/// ParseSubClassReference - Parse a reference to a subclass or to a templated
245/// subclass. This returns a SubClassRefTy with a null Record* on error.
246///
247/// SubClassRef ::= ClassID
248/// SubClassRef ::= ClassID '<' ValueList '>'
249///
250SubClassReference TGParser::
251ParseSubClassReference(Record *CurRec, bool isDefm) {
252 SubClassReference Result;
253 Result.RefLoc = Lex.getLoc();
254
255 if (isDefm)
256 Result.Rec = ParseDefmID();
257 else
258 Result.Rec = ParseClassID();
259 if (Result.Rec == 0) return Result;
260
261 // If there is no template arg list, we're done.
262 if (Lex.getCode() != tgtok::less)
263 return Result;
264 Lex.Lex(); // Eat the '<'
265
266 if (Lex.getCode() == tgtok::greater) {
267 TokError("subclass reference requires a non-empty list of template values");
268 Result.Rec = 0;
269 return Result;
270 }
271
272 Result.TemplateArgs = ParseValueList(CurRec);
273 if (Result.TemplateArgs.empty()) {
274 Result.Rec = 0; // Error parsing value list.
275 return Result;
276 }
277
278 if (Lex.getCode() != tgtok::greater) {
279 TokError("expected '>' in template value list");
280 Result.Rec = 0;
281 return Result;
282 }
283 Lex.Lex();
284
285 return Result;
286}
287
288/// ParseRangePiece - Parse a bit/value range.
289/// RangePiece ::= INTVAL
290/// RangePiece ::= INTVAL '-' INTVAL
291/// RangePiece ::= INTVAL INTVAL
292bool TGParser::ParseRangePiece(std::vector<unsigned> &Ranges) {
Chris Lattner811281e2008-01-10 07:01:53 +0000293 if (Lex.getCode() != tgtok::IntVal) {
294 TokError("expected integer or bitrange");
295 return true;
296 }
Dan Gohman63f97202008-10-17 01:33:43 +0000297 int64_t Start = Lex.getCurIntVal();
298 int64_t End;
Chris Lattnerf4601652007-11-22 20:49:04 +0000299
300 if (Start < 0)
301 return TokError("invalid range, cannot be negative");
302
303 switch (Lex.Lex()) { // eat first character.
304 default:
305 Ranges.push_back(Start);
306 return false;
307 case tgtok::minus:
308 if (Lex.Lex() != tgtok::IntVal) {
309 TokError("expected integer value as end of range");
310 return true;
311 }
312 End = Lex.getCurIntVal();
313 break;
314 case tgtok::IntVal:
315 End = -Lex.getCurIntVal();
316 break;
317 }
318 if (End < 0)
319 return TokError("invalid range, cannot be negative");
320 Lex.Lex();
321
322 // Add to the range.
323 if (Start < End) {
324 for (; Start <= End; ++Start)
325 Ranges.push_back(Start);
326 } else {
327 for (; Start >= End; --Start)
328 Ranges.push_back(Start);
329 }
330 return false;
331}
332
333/// ParseRangeList - Parse a list of scalars and ranges into scalar values.
334///
335/// RangeList ::= RangePiece (',' RangePiece)*
336///
337std::vector<unsigned> TGParser::ParseRangeList() {
338 std::vector<unsigned> Result;
339
340 // Parse the first piece.
341 if (ParseRangePiece(Result))
342 return std::vector<unsigned>();
343 while (Lex.getCode() == tgtok::comma) {
344 Lex.Lex(); // Eat the comma.
345
346 // Parse the next range piece.
347 if (ParseRangePiece(Result))
348 return std::vector<unsigned>();
349 }
350 return Result;
351}
352
353/// ParseOptionalRangeList - Parse either a range list in <>'s or nothing.
354/// OptionalRangeList ::= '<' RangeList '>'
355/// OptionalRangeList ::= /*empty*/
356bool TGParser::ParseOptionalRangeList(std::vector<unsigned> &Ranges) {
357 if (Lex.getCode() != tgtok::less)
358 return false;
359
Chris Lattner1c8ae592009-03-13 16:01:53 +0000360 TGLoc StartLoc = Lex.getLoc();
Chris Lattnerf4601652007-11-22 20:49:04 +0000361 Lex.Lex(); // eat the '<'
362
363 // Parse the range list.
364 Ranges = ParseRangeList();
365 if (Ranges.empty()) return true;
366
367 if (Lex.getCode() != tgtok::greater) {
368 TokError("expected '>' at end of range list");
369 return Error(StartLoc, "to match this '<'");
370 }
371 Lex.Lex(); // eat the '>'.
372 return false;
373}
374
375/// ParseOptionalBitList - Parse either a bit list in {}'s or nothing.
376/// OptionalBitList ::= '{' RangeList '}'
377/// OptionalBitList ::= /*empty*/
378bool TGParser::ParseOptionalBitList(std::vector<unsigned> &Ranges) {
379 if (Lex.getCode() != tgtok::l_brace)
380 return false;
381
Chris Lattner1c8ae592009-03-13 16:01:53 +0000382 TGLoc StartLoc = Lex.getLoc();
Chris Lattnerf4601652007-11-22 20:49:04 +0000383 Lex.Lex(); // eat the '{'
384
385 // Parse the range list.
386 Ranges = ParseRangeList();
387 if (Ranges.empty()) return true;
388
389 if (Lex.getCode() != tgtok::r_brace) {
390 TokError("expected '}' at end of bit list");
391 return Error(StartLoc, "to match this '{'");
392 }
393 Lex.Lex(); // eat the '}'.
394 return false;
395}
396
397
398/// ParseType - Parse and return a tblgen type. This returns null on error.
399///
400/// Type ::= STRING // string type
401/// Type ::= BIT // bit type
402/// Type ::= BITS '<' INTVAL '>' // bits<x> type
403/// Type ::= INT // int type
404/// Type ::= LIST '<' Type '>' // list<x> type
405/// Type ::= CODE // code type
406/// Type ::= DAG // dag type
407/// Type ::= ClassID // Record Type
408///
409RecTy *TGParser::ParseType() {
410 switch (Lex.getCode()) {
411 default: TokError("Unknown token when expecting a type"); return 0;
412 case tgtok::String: Lex.Lex(); return new StringRecTy();
413 case tgtok::Bit: Lex.Lex(); return new BitRecTy();
414 case tgtok::Int: Lex.Lex(); return new IntRecTy();
415 case tgtok::Code: Lex.Lex(); return new CodeRecTy();
416 case tgtok::Dag: Lex.Lex(); return new DagRecTy();
417 case tgtok::Id:
418 if (Record *R = ParseClassID()) return new RecordRecTy(R);
419 return 0;
420 case tgtok::Bits: {
421 if (Lex.Lex() != tgtok::less) { // Eat 'bits'
422 TokError("expected '<' after bits type");
423 return 0;
424 }
425 if (Lex.Lex() != tgtok::IntVal) { // Eat '<'
426 TokError("expected integer in bits<n> type");
427 return 0;
428 }
Dan Gohman63f97202008-10-17 01:33:43 +0000429 uint64_t Val = Lex.getCurIntVal();
Chris Lattnerf4601652007-11-22 20:49:04 +0000430 if (Lex.Lex() != tgtok::greater) { // Eat count.
431 TokError("expected '>' at end of bits<n> type");
432 return 0;
433 }
434 Lex.Lex(); // Eat '>'
435 return new BitsRecTy(Val);
436 }
437 case tgtok::List: {
438 if (Lex.Lex() != tgtok::less) { // Eat 'bits'
439 TokError("expected '<' after list type");
440 return 0;
441 }
442 Lex.Lex(); // Eat '<'
443 RecTy *SubType = ParseType();
444 if (SubType == 0) return 0;
445
446 if (Lex.getCode() != tgtok::greater) {
447 TokError("expected '>' at end of list<ty> type");
448 return 0;
449 }
450 Lex.Lex(); // Eat '>'
451 return new ListRecTy(SubType);
452 }
453 }
454}
455
456/// ParseIDValue - Parse an ID as a value and decode what it means.
457///
458/// IDValue ::= ID [def local value]
459/// IDValue ::= ID [def template arg]
460/// IDValue ::= ID [multiclass local value]
461/// IDValue ::= ID [multiclass template argument]
462/// IDValue ::= ID [def name]
463///
464Init *TGParser::ParseIDValue(Record *CurRec) {
465 assert(Lex.getCode() == tgtok::Id && "Expected ID in ParseIDValue");
466 std::string Name = Lex.getCurStrVal();
Chris Lattner1c8ae592009-03-13 16:01:53 +0000467 TGLoc Loc = Lex.getLoc();
Chris Lattnerf4601652007-11-22 20:49:04 +0000468 Lex.Lex();
469 return ParseIDValue(CurRec, Name, Loc);
470}
471
472/// ParseIDValue - This is just like ParseIDValue above, but it assumes the ID
473/// has already been read.
474Init *TGParser::ParseIDValue(Record *CurRec,
Chris Lattner1c8ae592009-03-13 16:01:53 +0000475 const std::string &Name, TGLoc NameLoc) {
Chris Lattnerf4601652007-11-22 20:49:04 +0000476 if (CurRec) {
477 if (const RecordVal *RV = CurRec->getValue(Name))
478 return new VarInit(Name, RV->getType());
479
480 std::string TemplateArgName = CurRec->getName()+":"+Name;
481 if (CurRec->isTemplateArg(TemplateArgName)) {
482 const RecordVal *RV = CurRec->getValue(TemplateArgName);
483 assert(RV && "Template arg doesn't exist??");
484 return new VarInit(TemplateArgName, RV->getType());
485 }
486 }
487
488 if (CurMultiClass) {
489 std::string MCName = CurMultiClass->Rec.getName()+"::"+Name;
490 if (CurMultiClass->Rec.isTemplateArg(MCName)) {
491 const RecordVal *RV = CurMultiClass->Rec.getValue(MCName);
492 assert(RV && "Template arg doesn't exist??");
493 return new VarInit(MCName, RV->getType());
494 }
495 }
496
497 if (Record *D = Records.getDef(Name))
498 return new DefInit(D);
499
500 Error(NameLoc, "Variable not defined: '" + Name + "'");
501 return 0;
502}
503
504/// ParseSimpleValue - Parse a tblgen value. This returns null on error.
505///
506/// SimpleValue ::= IDValue
507/// SimpleValue ::= INTVAL
Chris Lattnerd7a50cf2009-03-11 17:08:13 +0000508/// SimpleValue ::= STRVAL+
Chris Lattnerf4601652007-11-22 20:49:04 +0000509/// SimpleValue ::= CODEFRAGMENT
510/// SimpleValue ::= '?'
511/// SimpleValue ::= '{' ValueList '}'
512/// SimpleValue ::= ID '<' ValueListNE '>'
513/// SimpleValue ::= '[' ValueList ']'
514/// SimpleValue ::= '(' IDValue DagArgList ')'
515/// SimpleValue ::= CONCATTOK '(' Value ',' Value ')'
516/// SimpleValue ::= SHLTOK '(' Value ',' Value ')'
517/// SimpleValue ::= SRATOK '(' Value ',' Value ')'
518/// SimpleValue ::= SRLTOK '(' Value ',' Value ')'
519/// SimpleValue ::= STRCONCATTOK '(' Value ',' Value ')'
520///
521Init *TGParser::ParseSimpleValue(Record *CurRec) {
522 Init *R = 0;
523 switch (Lex.getCode()) {
524 default: TokError("Unknown token when parsing a value"); break;
525 case tgtok::IntVal: R = new IntInit(Lex.getCurIntVal()); Lex.Lex(); break;
Chris Lattnerd7a50cf2009-03-11 17:08:13 +0000526 case tgtok::StrVal: {
527 std::string Val = Lex.getCurStrVal();
528 Lex.Lex();
529
530 // Handle multiple consequtive concatenated strings.
531 while (Lex.getCode() == tgtok::StrVal) {
532 Val += Lex.getCurStrVal();
533 Lex.Lex();
534 }
535
536 R = new StringInit(Val);
537 break;
538 }
Chris Lattnerf4601652007-11-22 20:49:04 +0000539 case tgtok::CodeFragment:
540 R = new CodeInit(Lex.getCurStrVal()); Lex.Lex(); break;
541 case tgtok::question: R = new UnsetInit(); Lex.Lex(); break;
542 case tgtok::Id: {
Chris Lattner1c8ae592009-03-13 16:01:53 +0000543 TGLoc NameLoc = Lex.getLoc();
Chris Lattnerf4601652007-11-22 20:49:04 +0000544 std::string Name = Lex.getCurStrVal();
545 if (Lex.Lex() != tgtok::less) // consume the Id.
546 return ParseIDValue(CurRec, Name, NameLoc); // Value ::= IDValue
547
548 // Value ::= ID '<' ValueListNE '>'
549 if (Lex.Lex() == tgtok::greater) {
550 TokError("expected non-empty value list");
551 return 0;
552 }
553 std::vector<Init*> ValueList = ParseValueList(CurRec);
554 if (ValueList.empty()) return 0;
555
556 if (Lex.getCode() != tgtok::greater) {
557 TokError("expected '>' at end of value list");
558 return 0;
559 }
560 Lex.Lex(); // eat the '>'
561
562 // This is a CLASS<initvalslist> expression. This is supposed to synthesize
563 // a new anonymous definition, deriving from CLASS<initvalslist> with no
564 // body.
565 Record *Class = Records.getClass(Name);
566 if (!Class) {
567 Error(NameLoc, "Expected a class name, got '" + Name + "'");
568 return 0;
569 }
570
571 // Create the new record, set it as CurRec temporarily.
572 static unsigned AnonCounter = 0;
Chris Lattner7b9ffe42009-03-13 16:09:24 +0000573 Record *NewRec = new Record("anonymous.val."+utostr(AnonCounter++),NameLoc);
Chris Lattnerf4601652007-11-22 20:49:04 +0000574 SubClassReference SCRef;
575 SCRef.RefLoc = NameLoc;
576 SCRef.Rec = Class;
577 SCRef.TemplateArgs = ValueList;
578 // Add info about the subclass to NewRec.
579 if (AddSubClass(NewRec, SCRef))
580 return 0;
581 NewRec->resolveReferences();
582 Records.addDef(NewRec);
583
584 // The result of the expression is a reference to the new record.
585 return new DefInit(NewRec);
586 }
587 case tgtok::l_brace: { // Value ::= '{' ValueList '}'
Chris Lattner1c8ae592009-03-13 16:01:53 +0000588 TGLoc BraceLoc = Lex.getLoc();
Chris Lattnerf4601652007-11-22 20:49:04 +0000589 Lex.Lex(); // eat the '{'
590 std::vector<Init*> Vals;
591
592 if (Lex.getCode() != tgtok::r_brace) {
593 Vals = ParseValueList(CurRec);
594 if (Vals.empty()) return 0;
595 }
596 if (Lex.getCode() != tgtok::r_brace) {
597 TokError("expected '}' at end of bit list value");
598 return 0;
599 }
600 Lex.Lex(); // eat the '}'
601
602 BitsInit *Result = new BitsInit(Vals.size());
603 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
604 Init *Bit = Vals[i]->convertInitializerTo(new BitRecTy());
605 if (Bit == 0) {
Chris Lattner5d814862007-11-22 21:06:59 +0000606 Error(BraceLoc, "Element #" + utostr(i) + " (" + Vals[i]->getAsString()+
607 ") is not convertable to a bit");
Chris Lattnerf4601652007-11-22 20:49:04 +0000608 return 0;
609 }
610 Result->setBit(Vals.size()-i-1, Bit);
611 }
612 return Result;
613 }
614 case tgtok::l_square: { // Value ::= '[' ValueList ']'
615 Lex.Lex(); // eat the '['
616 std::vector<Init*> Vals;
617
618 if (Lex.getCode() != tgtok::r_square) {
619 Vals = ParseValueList(CurRec);
620 if (Vals.empty()) return 0;
621 }
622 if (Lex.getCode() != tgtok::r_square) {
623 TokError("expected ']' at end of list value");
624 return 0;
625 }
626 Lex.Lex(); // eat the ']'
627 return new ListInit(Vals);
628 }
629 case tgtok::l_paren: { // Value ::= '(' IDValue DagArgList ')'
630 Lex.Lex(); // eat the '('
Chris Lattner3dc2e962008-04-10 04:48:34 +0000631 if (Lex.getCode() != tgtok::Id) {
632 TokError("expected identifier in dag init");
633 return 0;
634 }
635
Chris Lattnerf4601652007-11-22 20:49:04 +0000636 Init *Operator = ParseIDValue(CurRec);
637 if (Operator == 0) return 0;
638
Nate Begeman7cee8172009-03-19 05:21:56 +0000639 // If the operator name is present, parse it.
640 std::string OperatorName;
641 if (Lex.getCode() == tgtok::colon) {
642 if (Lex.Lex() != tgtok::VarName) { // eat the ':'
643 TokError("expected variable name in dag operator");
644 return 0;
645 }
646 OperatorName = Lex.getCurStrVal();
647 Lex.Lex(); // eat the VarName.
648 }
649
650
Chris Lattnerf4601652007-11-22 20:49:04 +0000651 std::vector<std::pair<llvm::Init*, std::string> > DagArgs;
652 if (Lex.getCode() != tgtok::r_paren) {
653 DagArgs = ParseDagArgList(CurRec);
654 if (DagArgs.empty()) return 0;
655 }
656
657 if (Lex.getCode() != tgtok::r_paren) {
658 TokError("expected ')' in dag init");
659 return 0;
660 }
661 Lex.Lex(); // eat the ')'
662
Nate Begeman7cee8172009-03-19 05:21:56 +0000663 return new DagInit(Operator, OperatorName, DagArgs);
Chris Lattnerf4601652007-11-22 20:49:04 +0000664 }
665 case tgtok::XConcat:
666 case tgtok::XSRA:
667 case tgtok::XSRL:
668 case tgtok::XSHL:
669 case tgtok::XStrConcat: { // Value ::= !binop '(' Value ',' Value ')'
670 BinOpInit::BinaryOp Code;
671 switch (Lex.getCode()) {
672 default: assert(0 && "Unhandled code!");
673 case tgtok::XConcat: Code = BinOpInit::CONCAT; break;
674 case tgtok::XSRA: Code = BinOpInit::SRA; break;
675 case tgtok::XSRL: Code = BinOpInit::SRL; break;
676 case tgtok::XSHL: Code = BinOpInit::SHL; break;
677 case tgtok::XStrConcat: Code = BinOpInit::STRCONCAT; break;
678 }
679 Lex.Lex(); // eat the operation
680 if (Lex.getCode() != tgtok::l_paren) {
681 TokError("expected '(' after binary operator");
682 return 0;
683 }
684 Lex.Lex(); // eat the '('
685
686 Init *LHS = ParseValue(CurRec);
687 if (LHS == 0) return 0;
688
689 if (Lex.getCode() != tgtok::comma) {
690 TokError("expected ',' in binary operator");
691 return 0;
692 }
693 Lex.Lex(); // eat the ','
694
695 Init *RHS = ParseValue(CurRec);
696 if (RHS == 0) return 0;
697
698 if (Lex.getCode() != tgtok::r_paren) {
699 TokError("expected ')' in binary operator");
700 return 0;
701 }
702 Lex.Lex(); // eat the ')'
703 return (new BinOpInit(Code, LHS, RHS))->Fold();
704 }
705 }
706
707 return R;
708}
709
710/// ParseValue - Parse a tblgen value. This returns null on error.
711///
712/// Value ::= SimpleValue ValueSuffix*
713/// ValueSuffix ::= '{' BitList '}'
714/// ValueSuffix ::= '[' BitList ']'
715/// ValueSuffix ::= '.' ID
716///
717Init *TGParser::ParseValue(Record *CurRec) {
718 Init *Result = ParseSimpleValue(CurRec);
719 if (Result == 0) return 0;
720
721 // Parse the suffixes now if present.
722 while (1) {
723 switch (Lex.getCode()) {
724 default: return Result;
725 case tgtok::l_brace: {
Chris Lattner1c8ae592009-03-13 16:01:53 +0000726 TGLoc CurlyLoc = Lex.getLoc();
Chris Lattnerf4601652007-11-22 20:49:04 +0000727 Lex.Lex(); // eat the '{'
728 std::vector<unsigned> Ranges = ParseRangeList();
729 if (Ranges.empty()) return 0;
730
731 // Reverse the bitlist.
732 std::reverse(Ranges.begin(), Ranges.end());
733 Result = Result->convertInitializerBitRange(Ranges);
734 if (Result == 0) {
735 Error(CurlyLoc, "Invalid bit range for value");
736 return 0;
737 }
738
739 // Eat the '}'.
740 if (Lex.getCode() != tgtok::r_brace) {
741 TokError("expected '}' at end of bit range list");
742 return 0;
743 }
744 Lex.Lex();
745 break;
746 }
747 case tgtok::l_square: {
Chris Lattner1c8ae592009-03-13 16:01:53 +0000748 TGLoc SquareLoc = Lex.getLoc();
Chris Lattnerf4601652007-11-22 20:49:04 +0000749 Lex.Lex(); // eat the '['
750 std::vector<unsigned> Ranges = ParseRangeList();
751 if (Ranges.empty()) return 0;
752
753 Result = Result->convertInitListSlice(Ranges);
754 if (Result == 0) {
755 Error(SquareLoc, "Invalid range for list slice");
756 return 0;
757 }
758
759 // Eat the ']'.
760 if (Lex.getCode() != tgtok::r_square) {
761 TokError("expected ']' at end of list slice");
762 return 0;
763 }
764 Lex.Lex();
765 break;
766 }
767 case tgtok::period:
768 if (Lex.Lex() != tgtok::Id) { // eat the .
769 TokError("expected field identifier after '.'");
770 return 0;
771 }
772 if (!Result->getFieldType(Lex.getCurStrVal())) {
Chris Lattnerf4601652007-11-22 20:49:04 +0000773 TokError("Cannot access field '" + Lex.getCurStrVal() + "' of value '" +
Chris Lattner5d814862007-11-22 21:06:59 +0000774 Result->getAsString() + "'");
Chris Lattnerf4601652007-11-22 20:49:04 +0000775 return 0;
776 }
777 Result = new FieldInit(Result, Lex.getCurStrVal());
778 Lex.Lex(); // eat field name
779 break;
780 }
781 }
782}
783
784/// ParseDagArgList - Parse the argument list for a dag literal expression.
785///
786/// ParseDagArgList ::= Value (':' VARNAME)?
787/// ParseDagArgList ::= ParseDagArgList ',' Value (':' VARNAME)?
788std::vector<std::pair<llvm::Init*, std::string> >
789TGParser::ParseDagArgList(Record *CurRec) {
790 std::vector<std::pair<llvm::Init*, std::string> > Result;
791
792 while (1) {
793 Init *Val = ParseValue(CurRec);
794 if (Val == 0) return std::vector<std::pair<llvm::Init*, std::string> >();
795
796 // If the variable name is present, add it.
797 std::string VarName;
798 if (Lex.getCode() == tgtok::colon) {
799 if (Lex.Lex() != tgtok::VarName) { // eat the ':'
800 TokError("expected variable name in dag literal");
801 return std::vector<std::pair<llvm::Init*, std::string> >();
802 }
803 VarName = Lex.getCurStrVal();
804 Lex.Lex(); // eat the VarName.
805 }
806
807 Result.push_back(std::make_pair(Val, VarName));
808
809 if (Lex.getCode() != tgtok::comma) break;
810 Lex.Lex(); // eat the ','
811 }
812
813 return Result;
814}
815
816
817/// ParseValueList - Parse a comma separated list of values, returning them as a
818/// vector. Note that this always expects to be able to parse at least one
819/// value. It returns an empty list if this is not possible.
820///
821/// ValueList ::= Value (',' Value)
822///
823std::vector<Init*> TGParser::ParseValueList(Record *CurRec) {
824 std::vector<Init*> Result;
825 Result.push_back(ParseValue(CurRec));
826 if (Result.back() == 0) return std::vector<Init*>();
827
828 while (Lex.getCode() == tgtok::comma) {
829 Lex.Lex(); // Eat the comma
830
831 Result.push_back(ParseValue(CurRec));
832 if (Result.back() == 0) return std::vector<Init*>();
833 }
834
835 return Result;
836}
837
838
839
840/// ParseDeclaration - Read a declaration, returning the name of field ID, or an
841/// empty string on error. This can happen in a number of different context's,
842/// including within a def or in the template args for a def (which which case
843/// CurRec will be non-null) and within the template args for a multiclass (in
844/// which case CurRec will be null, but CurMultiClass will be set). This can
845/// also happen within a def that is within a multiclass, which will set both
846/// CurRec and CurMultiClass.
847///
848/// Declaration ::= FIELD? Type ID ('=' Value)?
849///
850std::string TGParser::ParseDeclaration(Record *CurRec,
851 bool ParsingTemplateArgs) {
852 // Read the field prefix if present.
853 bool HasField = Lex.getCode() == tgtok::Field;
854 if (HasField) Lex.Lex();
855
856 RecTy *Type = ParseType();
857 if (Type == 0) return "";
858
859 if (Lex.getCode() != tgtok::Id) {
860 TokError("Expected identifier in declaration");
861 return "";
862 }
863
Chris Lattner1c8ae592009-03-13 16:01:53 +0000864 TGLoc IdLoc = Lex.getLoc();
Chris Lattnerf4601652007-11-22 20:49:04 +0000865 std::string DeclName = Lex.getCurStrVal();
866 Lex.Lex();
867
868 if (ParsingTemplateArgs) {
869 if (CurRec) {
870 DeclName = CurRec->getName() + ":" + DeclName;
871 } else {
872 assert(CurMultiClass);
873 }
874 if (CurMultiClass)
875 DeclName = CurMultiClass->Rec.getName() + "::" + DeclName;
876 }
877
878 // Add the value.
879 if (AddValue(CurRec, IdLoc, RecordVal(DeclName, Type, HasField)))
880 return "";
881
882 // If a value is present, parse it.
883 if (Lex.getCode() == tgtok::equal) {
884 Lex.Lex();
Chris Lattner1c8ae592009-03-13 16:01:53 +0000885 TGLoc ValLoc = Lex.getLoc();
Chris Lattnerf4601652007-11-22 20:49:04 +0000886 Init *Val = ParseValue(CurRec);
887 if (Val == 0 ||
888 SetValue(CurRec, ValLoc, DeclName, std::vector<unsigned>(), Val))
889 return "";
890 }
891
892 return DeclName;
893}
894
895/// ParseTemplateArgList - Read a template argument list, which is a non-empty
896/// sequence of template-declarations in <>'s. If CurRec is non-null, these are
897/// template args for a def, which may or may not be in a multiclass. If null,
898/// these are the template args for a multiclass.
899///
900/// TemplateArgList ::= '<' Declaration (',' Declaration)* '>'
901///
902bool TGParser::ParseTemplateArgList(Record *CurRec) {
903 assert(Lex.getCode() == tgtok::less && "Not a template arg list!");
904 Lex.Lex(); // eat the '<'
905
906 Record *TheRecToAddTo = CurRec ? CurRec : &CurMultiClass->Rec;
907
908 // Read the first declaration.
909 std::string TemplArg = ParseDeclaration(CurRec, true/*templateargs*/);
910 if (TemplArg.empty())
911 return true;
912
913 TheRecToAddTo->addTemplateArg(TemplArg);
914
915 while (Lex.getCode() == tgtok::comma) {
916 Lex.Lex(); // eat the ','
917
918 // Read the following declarations.
919 TemplArg = ParseDeclaration(CurRec, true/*templateargs*/);
920 if (TemplArg.empty())
921 return true;
922 TheRecToAddTo->addTemplateArg(TemplArg);
923 }
924
925 if (Lex.getCode() != tgtok::greater)
926 return TokError("expected '>' at end of template argument list");
927 Lex.Lex(); // eat the '>'.
928 return false;
929}
930
931
932/// ParseBodyItem - Parse a single item at within the body of a def or class.
933///
934/// BodyItem ::= Declaration ';'
935/// BodyItem ::= LET ID OptionalBitList '=' Value ';'
936bool TGParser::ParseBodyItem(Record *CurRec) {
937 if (Lex.getCode() != tgtok::Let) {
938 if (ParseDeclaration(CurRec, false).empty())
939 return true;
940
941 if (Lex.getCode() != tgtok::semi)
942 return TokError("expected ';' after declaration");
943 Lex.Lex();
944 return false;
945 }
946
947 // LET ID OptionalRangeList '=' Value ';'
948 if (Lex.Lex() != tgtok::Id)
949 return TokError("expected field identifier after let");
950
Chris Lattner1c8ae592009-03-13 16:01:53 +0000951 TGLoc IdLoc = Lex.getLoc();
Chris Lattnerf4601652007-11-22 20:49:04 +0000952 std::string FieldName = Lex.getCurStrVal();
953 Lex.Lex(); // eat the field name.
954
955 std::vector<unsigned> BitList;
956 if (ParseOptionalBitList(BitList))
957 return true;
958 std::reverse(BitList.begin(), BitList.end());
959
960 if (Lex.getCode() != tgtok::equal)
961 return TokError("expected '=' in let expression");
962 Lex.Lex(); // eat the '='.
963
964 Init *Val = ParseValue(CurRec);
965 if (Val == 0) return true;
966
967 if (Lex.getCode() != tgtok::semi)
968 return TokError("expected ';' after let expression");
969 Lex.Lex();
970
971 return SetValue(CurRec, IdLoc, FieldName, BitList, Val);
972}
973
974/// ParseBody - Read the body of a class or def. Return true on error, false on
975/// success.
976///
977/// Body ::= ';'
978/// Body ::= '{' BodyList '}'
979/// BodyList BodyItem*
980///
981bool TGParser::ParseBody(Record *CurRec) {
982 // If this is a null definition, just eat the semi and return.
983 if (Lex.getCode() == tgtok::semi) {
984 Lex.Lex();
985 return false;
986 }
987
988 if (Lex.getCode() != tgtok::l_brace)
989 return TokError("Expected ';' or '{' to start body");
990 // Eat the '{'.
991 Lex.Lex();
992
993 while (Lex.getCode() != tgtok::r_brace)
994 if (ParseBodyItem(CurRec))
995 return true;
996
997 // Eat the '}'.
998 Lex.Lex();
999 return false;
1000}
1001
1002/// ParseObjectBody - Parse the body of a def or class. This consists of an
1003/// optional ClassList followed by a Body. CurRec is the current def or class
1004/// that is being parsed.
1005///
1006/// ObjectBody ::= BaseClassList Body
1007/// BaseClassList ::= /*empty*/
1008/// BaseClassList ::= ':' BaseClassListNE
1009/// BaseClassListNE ::= SubClassRef (',' SubClassRef)*
1010///
1011bool TGParser::ParseObjectBody(Record *CurRec) {
1012 // If there is a baseclass list, read it.
1013 if (Lex.getCode() == tgtok::colon) {
1014 Lex.Lex();
1015
1016 // Read all of the subclasses.
1017 SubClassReference SubClass = ParseSubClassReference(CurRec, false);
1018 while (1) {
1019 // Check for error.
1020 if (SubClass.Rec == 0) return true;
1021
1022 // Add it.
1023 if (AddSubClass(CurRec, SubClass))
1024 return true;
1025
1026 if (Lex.getCode() != tgtok::comma) break;
1027 Lex.Lex(); // eat ','.
1028 SubClass = ParseSubClassReference(CurRec, false);
1029 }
1030 }
1031
1032 // Process any variables on the let stack.
1033 for (unsigned i = 0, e = LetStack.size(); i != e; ++i)
1034 for (unsigned j = 0, e = LetStack[i].size(); j != e; ++j)
1035 if (SetValue(CurRec, LetStack[i][j].Loc, LetStack[i][j].Name,
1036 LetStack[i][j].Bits, LetStack[i][j].Value))
1037 return true;
1038
1039 return ParseBody(CurRec);
1040}
1041
1042
1043/// ParseDef - Parse and return a top level or multiclass def, return the record
1044/// corresponding to it. This returns null on error.
1045///
1046/// DefInst ::= DEF ObjectName ObjectBody
1047///
1048llvm::Record *TGParser::ParseDef(MultiClass *CurMultiClass) {
Chris Lattner1c8ae592009-03-13 16:01:53 +00001049 TGLoc DefLoc = Lex.getLoc();
Chris Lattnerf4601652007-11-22 20:49:04 +00001050 assert(Lex.getCode() == tgtok::Def && "Unknown tok");
1051 Lex.Lex(); // Eat the 'def' token.
1052
1053 // Parse ObjectName and make a record for it.
Chris Lattner7b9ffe42009-03-13 16:09:24 +00001054 Record *CurRec = new Record(ParseObjectName(), DefLoc);
Chris Lattnerf4601652007-11-22 20:49:04 +00001055
1056 if (!CurMultiClass) {
1057 // Top-level def definition.
1058
1059 // Ensure redefinition doesn't happen.
1060 if (Records.getDef(CurRec->getName())) {
1061 Error(DefLoc, "def '" + CurRec->getName() + "' already defined");
1062 return 0;
1063 }
1064 Records.addDef(CurRec);
1065 } else {
1066 // Otherwise, a def inside a multiclass, add it to the multiclass.
1067 for (unsigned i = 0, e = CurMultiClass->DefPrototypes.size(); i != e; ++i)
1068 if (CurMultiClass->DefPrototypes[i]->getName() == CurRec->getName()) {
1069 Error(DefLoc, "def '" + CurRec->getName() +
1070 "' already defined in this multiclass!");
1071 return 0;
1072 }
1073 CurMultiClass->DefPrototypes.push_back(CurRec);
1074 }
1075
1076 if (ParseObjectBody(CurRec))
1077 return 0;
1078
1079 if (CurMultiClass == 0) // Def's in multiclasses aren't really defs.
1080 CurRec->resolveReferences();
1081
1082 // If ObjectBody has template arguments, it's an error.
1083 assert(CurRec->getTemplateArgs().empty() && "How'd this get template args?");
1084 return CurRec;
1085}
1086
1087
1088/// ParseClass - Parse a tblgen class definition.
1089///
1090/// ClassInst ::= CLASS ID TemplateArgList? ObjectBody
1091///
1092bool TGParser::ParseClass() {
1093 assert(Lex.getCode() == tgtok::Class && "Unexpected token!");
1094 Lex.Lex();
1095
1096 if (Lex.getCode() != tgtok::Id)
1097 return TokError("expected class name after 'class' keyword");
1098
1099 Record *CurRec = Records.getClass(Lex.getCurStrVal());
1100 if (CurRec) {
1101 // If the body was previously defined, this is an error.
1102 if (!CurRec->getValues().empty() ||
1103 !CurRec->getSuperClasses().empty() ||
1104 !CurRec->getTemplateArgs().empty())
1105 return TokError("Class '" + CurRec->getName() + "' already defined");
1106 } else {
1107 // If this is the first reference to this class, create and add it.
Chris Lattner7b9ffe42009-03-13 16:09:24 +00001108 CurRec = new Record(Lex.getCurStrVal(), Lex.getLoc());
Chris Lattnerf4601652007-11-22 20:49:04 +00001109 Records.addClass(CurRec);
1110 }
1111 Lex.Lex(); // eat the name.
1112
1113 // If there are template args, parse them.
1114 if (Lex.getCode() == tgtok::less)
1115 if (ParseTemplateArgList(CurRec))
1116 return true;
1117
1118 // Finally, parse the object body.
1119 return ParseObjectBody(CurRec);
1120}
1121
1122/// ParseLetList - Parse a non-empty list of assignment expressions into a list
1123/// of LetRecords.
1124///
1125/// LetList ::= LetItem (',' LetItem)*
1126/// LetItem ::= ID OptionalRangeList '=' Value
1127///
1128std::vector<LetRecord> TGParser::ParseLetList() {
1129 std::vector<LetRecord> Result;
1130
1131 while (1) {
1132 if (Lex.getCode() != tgtok::Id) {
1133 TokError("expected identifier in let definition");
1134 return std::vector<LetRecord>();
1135 }
1136 std::string Name = Lex.getCurStrVal();
Chris Lattner1c8ae592009-03-13 16:01:53 +00001137 TGLoc NameLoc = Lex.getLoc();
Chris Lattnerf4601652007-11-22 20:49:04 +00001138 Lex.Lex(); // Eat the identifier.
1139
1140 // Check for an optional RangeList.
1141 std::vector<unsigned> Bits;
1142 if (ParseOptionalRangeList(Bits))
1143 return std::vector<LetRecord>();
1144 std::reverse(Bits.begin(), Bits.end());
1145
1146 if (Lex.getCode() != tgtok::equal) {
1147 TokError("expected '=' in let expression");
1148 return std::vector<LetRecord>();
1149 }
1150 Lex.Lex(); // eat the '='.
1151
1152 Init *Val = ParseValue(0);
1153 if (Val == 0) return std::vector<LetRecord>();
1154
1155 // Now that we have everything, add the record.
1156 Result.push_back(LetRecord(Name, Bits, Val, NameLoc));
1157
1158 if (Lex.getCode() != tgtok::comma)
1159 return Result;
1160 Lex.Lex(); // eat the comma.
1161 }
1162}
1163
1164/// ParseTopLevelLet - Parse a 'let' at top level. This can be a couple of
1165/// different related productions.
1166///
1167/// Object ::= LET LetList IN '{' ObjectList '}'
1168/// Object ::= LET LetList IN Object
1169///
1170bool TGParser::ParseTopLevelLet() {
1171 assert(Lex.getCode() == tgtok::Let && "Unexpected token");
1172 Lex.Lex();
1173
1174 // Add this entry to the let stack.
1175 std::vector<LetRecord> LetInfo = ParseLetList();
1176 if (LetInfo.empty()) return true;
1177 LetStack.push_back(LetInfo);
1178
1179 if (Lex.getCode() != tgtok::In)
1180 return TokError("expected 'in' at end of top-level 'let'");
1181 Lex.Lex();
1182
1183 // If this is a scalar let, just handle it now
1184 if (Lex.getCode() != tgtok::l_brace) {
1185 // LET LetList IN Object
1186 if (ParseObject())
1187 return true;
1188 } else { // Object ::= LETCommand '{' ObjectList '}'
Chris Lattner1c8ae592009-03-13 16:01:53 +00001189 TGLoc BraceLoc = Lex.getLoc();
Chris Lattnerf4601652007-11-22 20:49:04 +00001190 // Otherwise, this is a group let.
1191 Lex.Lex(); // eat the '{'.
1192
1193 // Parse the object list.
1194 if (ParseObjectList())
1195 return true;
1196
1197 if (Lex.getCode() != tgtok::r_brace) {
1198 TokError("expected '}' at end of top level let command");
1199 return Error(BraceLoc, "to match this '{'");
1200 }
1201 Lex.Lex();
1202 }
1203
1204 // Outside this let scope, this let block is not active.
1205 LetStack.pop_back();
1206 return false;
1207}
1208
1209/// ParseMultiClassDef - Parse a def in a multiclass context.
1210///
1211/// MultiClassDef ::= DefInst
1212///
1213bool TGParser::ParseMultiClassDef(MultiClass *CurMC) {
1214 if (Lex.getCode() != tgtok::Def)
1215 return TokError("expected 'def' in multiclass body");
1216
1217 Record *D = ParseDef(CurMC);
1218 if (D == 0) return true;
1219
1220 // Copy the template arguments for the multiclass into the def.
1221 const std::vector<std::string> &TArgs = CurMC->Rec.getTemplateArgs();
1222
1223 for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
1224 const RecordVal *RV = CurMC->Rec.getValue(TArgs[i]);
1225 assert(RV && "Template arg doesn't exist?");
1226 D->addValue(*RV);
1227 }
1228
1229 return false;
1230}
1231
1232/// ParseMultiClass - Parse a multiclass definition.
1233///
1234/// MultiClassInst ::= MULTICLASS ID TemplateArgList? '{' MultiClassDef+ '}'
1235///
1236bool TGParser::ParseMultiClass() {
1237 assert(Lex.getCode() == tgtok::MultiClass && "Unexpected token");
1238 Lex.Lex(); // Eat the multiclass token.
1239
1240 if (Lex.getCode() != tgtok::Id)
1241 return TokError("expected identifier after multiclass for name");
1242 std::string Name = Lex.getCurStrVal();
1243
1244 if (MultiClasses.count(Name))
1245 return TokError("multiclass '" + Name + "' already defined");
1246
Chris Lattner7b9ffe42009-03-13 16:09:24 +00001247 CurMultiClass = MultiClasses[Name] = new MultiClass(Name, Lex.getLoc());
Chris Lattnerf4601652007-11-22 20:49:04 +00001248 Lex.Lex(); // Eat the identifier.
1249
1250 // If there are template args, parse them.
1251 if (Lex.getCode() == tgtok::less)
1252 if (ParseTemplateArgList(0))
1253 return true;
1254
1255 if (Lex.getCode() != tgtok::l_brace)
1256 return TokError("expected '{' in multiclass definition");
1257
1258 if (Lex.Lex() == tgtok::r_brace) // eat the '{'.
1259 return TokError("multiclass must contain at least one def");
1260
1261 while (Lex.getCode() != tgtok::r_brace)
1262 if (ParseMultiClassDef(CurMultiClass))
1263 return true;
1264
1265 Lex.Lex(); // eat the '}'.
1266
1267 CurMultiClass = 0;
1268 return false;
1269}
1270
1271/// ParseDefm - Parse the instantiation of a multiclass.
1272///
1273/// DefMInst ::= DEFM ID ':' DefmSubClassRef ';'
1274///
1275bool TGParser::ParseDefm() {
1276 assert(Lex.getCode() == tgtok::Defm && "Unexpected token!");
1277 if (Lex.Lex() != tgtok::Id) // eat the defm.
1278 return TokError("expected identifier after defm");
1279
Chris Lattner1c8ae592009-03-13 16:01:53 +00001280 TGLoc DefmPrefixLoc = Lex.getLoc();
Chris Lattnerf4601652007-11-22 20:49:04 +00001281 std::string DefmPrefix = Lex.getCurStrVal();
1282 if (Lex.Lex() != tgtok::colon)
1283 return TokError("expected ':' after defm identifier");
1284
1285 // eat the colon.
1286 Lex.Lex();
1287
Chris Lattner1c8ae592009-03-13 16:01:53 +00001288 TGLoc SubClassLoc = Lex.getLoc();
Chris Lattnerf4601652007-11-22 20:49:04 +00001289 SubClassReference Ref = ParseSubClassReference(0, true);
1290 if (Ref.Rec == 0) return true;
1291
1292 if (Lex.getCode() != tgtok::semi)
1293 return TokError("expected ';' at end of defm");
1294 Lex.Lex();
1295
1296 // To instantiate a multiclass, we need to first get the multiclass, then
1297 // instantiate each def contained in the multiclass with the SubClassRef
1298 // template parameters.
1299 MultiClass *MC = MultiClasses[Ref.Rec->getName()];
1300 assert(MC && "Didn't lookup multiclass correctly?");
1301 std::vector<Init*> &TemplateVals = Ref.TemplateArgs;
1302
1303 // Verify that the correct number of template arguments were specified.
1304 const std::vector<std::string> &TArgs = MC->Rec.getTemplateArgs();
1305 if (TArgs.size() < TemplateVals.size())
1306 return Error(SubClassLoc,
1307 "more template args specified than multiclass expects");
1308
1309 // Loop over all the def's in the multiclass, instantiating each one.
1310 for (unsigned i = 0, e = MC->DefPrototypes.size(); i != e; ++i) {
1311 Record *DefProto = MC->DefPrototypes[i];
1312
1313 // Add the suffix to the defm name to get the new name.
Chris Lattner7b9ffe42009-03-13 16:09:24 +00001314 Record *CurRec = new Record(DefmPrefix + DefProto->getName(),DefmPrefixLoc);
Chris Lattnerf4601652007-11-22 20:49:04 +00001315
1316 SubClassReference Ref;
1317 Ref.RefLoc = DefmPrefixLoc;
1318 Ref.Rec = DefProto;
1319 AddSubClass(CurRec, Ref);
1320
1321 // Loop over all of the template arguments, setting them to the specified
1322 // value or leaving them as the default if necessary.
1323 for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
1324 if (i < TemplateVals.size()) { // A value is specified for this temp-arg?
1325 // Set it now.
1326 if (SetValue(CurRec, DefmPrefixLoc, TArgs[i], std::vector<unsigned>(),
1327 TemplateVals[i]))
1328 return true;
1329
1330 // Resolve it next.
1331 CurRec->resolveReferencesTo(CurRec->getValue(TArgs[i]));
1332
1333 // Now remove it.
1334 CurRec->removeValue(TArgs[i]);
1335
1336 } else if (!CurRec->getValue(TArgs[i])->getValue()->isComplete()) {
1337 return Error(SubClassLoc, "value not specified for template argument #"+
1338 utostr(i) + " (" + TArgs[i] + ") of multiclassclass '" +
1339 MC->Rec.getName() + "'");
1340 }
1341 }
1342
1343 // If the mdef is inside a 'let' expression, add to each def.
1344 for (unsigned i = 0, e = LetStack.size(); i != e; ++i)
1345 for (unsigned j = 0, e = LetStack[i].size(); j != e; ++j)
1346 if (SetValue(CurRec, LetStack[i][j].Loc, LetStack[i][j].Name,
1347 LetStack[i][j].Bits, LetStack[i][j].Value)) {
1348 Error(DefmPrefixLoc, "when instantiating this defm");
1349 return true;
1350 }
1351
1352
1353 // Ensure redefinition doesn't happen.
1354 if (Records.getDef(CurRec->getName()))
1355 return Error(DefmPrefixLoc, "def '" + CurRec->getName() +
1356 "' already defined, instantiating defm with subdef '" +
1357 DefProto->getName() + "'");
1358 Records.addDef(CurRec);
1359 CurRec->resolveReferences();
1360 }
1361
1362 return false;
1363}
1364
1365/// ParseObject
1366/// Object ::= ClassInst
1367/// Object ::= DefInst
1368/// Object ::= MultiClassInst
1369/// Object ::= DefMInst
1370/// Object ::= LETCommand '{' ObjectList '}'
1371/// Object ::= LETCommand Object
1372bool TGParser::ParseObject() {
1373 switch (Lex.getCode()) {
1374 default: assert(0 && "This is not an object");
1375 case tgtok::Let: return ParseTopLevelLet();
1376 case tgtok::Def: return ParseDef(0) == 0;
1377 case tgtok::Defm: return ParseDefm();
1378 case tgtok::Class: return ParseClass();
1379 case tgtok::MultiClass: return ParseMultiClass();
1380 }
1381}
1382
1383/// ParseObjectList
1384/// ObjectList :== Object*
1385bool TGParser::ParseObjectList() {
1386 while (isObjectStart(Lex.getCode())) {
1387 if (ParseObject())
1388 return true;
1389 }
1390 return false;
1391}
1392
1393
1394bool TGParser::ParseFile() {
1395 Lex.Lex(); // Prime the lexer.
1396 if (ParseObjectList()) return true;
1397
1398 // If we have unread input at the end of the file, report it.
1399 if (Lex.getCode() == tgtok::Eof)
1400 return false;
1401
1402 return TokError("Unexpected input at top level");
1403}
1404