forked from llvm/llvm-project
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTGParser.cpp
3801 lines (3276 loc) · 114 KB
/
TGParser.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//===- TGParser.cpp - Parser for TableGen Files ---------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// Implement the Parser for TableGen.
//
//===----------------------------------------------------------------------===//
#include "TGParser.h"
#include "llvm/ADT/DenseMapInfo.h"
#include "llvm/ADT/None.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/ADT/Twine.h"
#include "llvm/Config/llvm-config.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/raw_ostream.h"
#include <algorithm>
#include <cassert>
#include <cstdint>
#include <limits>
using namespace llvm;
//===----------------------------------------------------------------------===//
// Support Code for the Semantic Actions.
//===----------------------------------------------------------------------===//
namespace llvm {
struct SubClassReference {
SMRange RefRange;
Record *Rec;
SmallVector<Init*, 4> TemplateArgs;
SubClassReference() : Rec(nullptr) {}
bool isInvalid() const { return Rec == nullptr; }
};
struct SubMultiClassReference {
SMRange RefRange;
MultiClass *MC;
SmallVector<Init*, 4> TemplateArgs;
SubMultiClassReference() : MC(nullptr) {}
bool isInvalid() const { return MC == nullptr; }
void dump() const;
};
#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
LLVM_DUMP_METHOD void SubMultiClassReference::dump() const {
errs() << "Multiclass:\n";
MC->dump();
errs() << "Template args:\n";
for (Init *TA : TemplateArgs)
TA->dump();
}
#endif
} // end namespace llvm
static bool checkBitsConcrete(Record &R, const RecordVal &RV) {
BitsInit *BV = cast<BitsInit>(RV.getValue());
for (unsigned i = 0, e = BV->getNumBits(); i != e; ++i) {
Init *Bit = BV->getBit(i);
bool IsReference = false;
if (auto VBI = dyn_cast<VarBitInit>(Bit)) {
if (auto VI = dyn_cast<VarInit>(VBI->getBitVar())) {
if (R.getValue(VI->getName()))
IsReference = true;
}
} else if (isa<VarInit>(Bit)) {
IsReference = true;
}
if (!(IsReference || Bit->isConcrete()))
return false;
}
return true;
}
static void checkConcrete(Record &R) {
for (const RecordVal &RV : R.getValues()) {
// HACK: Disable this check for variables declared with 'field'. This is
// done merely because existing targets have legitimate cases of
// non-concrete variables in helper defs. Ideally, we'd introduce a
// 'maybe' or 'optional' modifier instead of this.
if (RV.isNonconcreteOK())
continue;
if (Init *V = RV.getValue()) {
bool Ok = isa<BitsInit>(V) ? checkBitsConcrete(R, RV) : V->isConcrete();
if (!Ok) {
PrintError(R.getLoc(),
Twine("Initializer of '") + RV.getNameInitAsString() +
"' in '" + R.getNameInitAsString() +
"' could not be fully resolved: " +
RV.getValue()->getAsString());
}
}
}
}
/// Return an Init with a qualifier prefix referring
/// to CurRec's name.
static Init *QualifyName(Record &CurRec, MultiClass *CurMultiClass,
Init *Name, StringRef Scoper) {
Init *NewName =
BinOpInit::getStrConcat(CurRec.getNameInit(), StringInit::get(Scoper));
NewName = BinOpInit::getStrConcat(NewName, Name);
if (CurMultiClass && Scoper != "::") {
Init *Prefix = BinOpInit::getStrConcat(CurMultiClass->Rec.getNameInit(),
StringInit::get("::"));
NewName = BinOpInit::getStrConcat(Prefix, NewName);
}
if (BinOpInit *BinOp = dyn_cast<BinOpInit>(NewName))
NewName = BinOp->Fold(&CurRec);
return NewName;
}
/// Return the qualified version of the implicit 'NAME' template argument.
static Init *QualifiedNameOfImplicitName(Record &Rec,
MultiClass *MC = nullptr) {
return QualifyName(Rec, MC, StringInit::get("NAME"), MC ? "::" : ":");
}
static Init *QualifiedNameOfImplicitName(MultiClass *MC) {
return QualifiedNameOfImplicitName(MC->Rec, MC);
}
bool TGParser::AddValue(Record *CurRec, SMLoc Loc, const RecordVal &RV) {
if (!CurRec)
CurRec = &CurMultiClass->Rec;
if (RecordVal *ERV = CurRec->getValue(RV.getNameInit())) {
// The value already exists in the class, treat this as a set.
if (ERV->setValue(RV.getValue()))
return Error(Loc, "New definition of '" + RV.getName() + "' of type '" +
RV.getType()->getAsString() + "' is incompatible with " +
"previous definition of type '" +
ERV->getType()->getAsString() + "'");
} else {
CurRec->addValue(RV);
}
return false;
}
/// SetValue -
/// Return true on error, false on success.
bool TGParser::SetValue(Record *CurRec, SMLoc Loc, Init *ValName,
ArrayRef<unsigned> BitList, Init *V,
bool AllowSelfAssignment) {
if (!V) return false;
if (!CurRec) CurRec = &CurMultiClass->Rec;
RecordVal *RV = CurRec->getValue(ValName);
if (!RV)
return Error(Loc, "Value '" + ValName->getAsUnquotedString() +
"' unknown!");
// Do not allow assignments like 'X = X'. This will just cause infinite loops
// in the resolution machinery.
if (BitList.empty())
if (VarInit *VI = dyn_cast<VarInit>(V))
if (VI->getNameInit() == ValName && !AllowSelfAssignment)
return Error(Loc, "Recursion / self-assignment forbidden");
// If we are assigning to a subset of the bits in the value... then we must be
// assigning to a field of BitsRecTy, which must have a BitsInit
// initializer.
//
if (!BitList.empty()) {
BitsInit *CurVal = dyn_cast<BitsInit>(RV->getValue());
if (!CurVal)
return Error(Loc, "Value '" + ValName->getAsUnquotedString() +
"' is not a bits type");
// Convert the incoming value to a bits type of the appropriate size...
Init *BI = V->getCastTo(BitsRecTy::get(BitList.size()));
if (!BI)
return Error(Loc, "Initializer is not compatible with bit range");
SmallVector<Init *, 16> NewBits(CurVal->getNumBits());
// Loop over bits, assigning values as appropriate.
for (unsigned i = 0, e = BitList.size(); i != e; ++i) {
unsigned Bit = BitList[i];
if (NewBits[Bit])
return Error(Loc, "Cannot set bit #" + Twine(Bit) + " of value '" +
ValName->getAsUnquotedString() + "' more than once");
NewBits[Bit] = BI->getBit(i);
}
for (unsigned i = 0, e = CurVal->getNumBits(); i != e; ++i)
if (!NewBits[i])
NewBits[i] = CurVal->getBit(i);
V = BitsInit::get(NewBits);
}
if (RV->setValue(V, Loc)) {
std::string InitType;
if (BitsInit *BI = dyn_cast<BitsInit>(V))
InitType = (Twine("' of type bit initializer with length ") +
Twine(BI->getNumBits())).str();
else if (TypedInit *TI = dyn_cast<TypedInit>(V))
InitType = (Twine("' of type '") + TI->getType()->getAsString()).str();
return Error(Loc, "Field '" + ValName->getAsUnquotedString() +
"' of type '" + RV->getType()->getAsString() +
"' is incompatible with value '" +
V->getAsString() + InitType + "'");
}
return false;
}
/// AddSubClass - Add SubClass as a subclass to CurRec, resolving its template
/// args as SubClass's template arguments.
bool TGParser::AddSubClass(Record *CurRec, SubClassReference &SubClass) {
Record *SC = SubClass.Rec;
MapResolver R(CurRec);
// Loop over all the subclass record's fields. Add template arguments
// to the resolver map. Add regular fields to the new record.
for (const RecordVal &Field : SC->getValues()) {
if (Field.isTemplateArg()) {
R.set(Field.getNameInit(), Field.getValue());
} else {
if (AddValue(CurRec, SubClass.RefRange.Start, Field))
return true;
}
}
ArrayRef<Init *> TArgs = SC->getTemplateArgs();
assert(SubClass.TemplateArgs.size() <= TArgs.size() &&
"Too many template arguments allowed");
// Loop over the template argument names. If a value was specified,
// reset the map value. If not and there was no default, complain.
for (unsigned I = 0, E = TArgs.size(); I != E; ++I) {
if (I < SubClass.TemplateArgs.size())
R.set(TArgs[I], SubClass.TemplateArgs[I]);
else if (!R.isComplete(TArgs[I]))
return Error(SubClass.RefRange.Start,
"Value not specified for template argument '" +
TArgs[I]->getAsUnquotedString() + "' (#" + Twine(I) +
") of parent class '" + SC->getNameInitAsString() + "'");
}
// Copy the subclass record's assertions to the new record.
CurRec->appendAssertions(SC);
Init *Name;
if (CurRec->isClass())
Name =
VarInit::get(QualifiedNameOfImplicitName(*CurRec), StringRecTy::get());
else
Name = CurRec->getNameInit();
R.set(QualifiedNameOfImplicitName(*SC), Name);
CurRec->resolveReferences(R);
// Since everything went well, we can now set the "superclass" list for the
// current record.
ArrayRef<std::pair<Record *, SMRange>> SCs = SC->getSuperClasses();
for (const auto &SCPair : SCs) {
if (CurRec->isSubClassOf(SCPair.first))
return Error(SubClass.RefRange.Start,
"Already subclass of '" + SCPair.first->getName() + "'!\n");
CurRec->addSuperClass(SCPair.first, SCPair.second);
}
if (CurRec->isSubClassOf(SC))
return Error(SubClass.RefRange.Start,
"Already subclass of '" + SC->getName() + "'!\n");
CurRec->addSuperClass(SC, SubClass.RefRange);
return false;
}
bool TGParser::AddSubClass(RecordsEntry &Entry, SubClassReference &SubClass) {
if (Entry.Rec)
return AddSubClass(Entry.Rec.get(), SubClass);
if (Entry.Assertion)
return false;
for (auto &E : Entry.Loop->Entries) {
if (AddSubClass(E, SubClass))
return true;
}
return false;
}
/// AddSubMultiClass - Add SubMultiClass as a subclass to
/// CurMC, resolving its template args as SubMultiClass's
/// template arguments.
bool TGParser::AddSubMultiClass(MultiClass *CurMC,
SubMultiClassReference &SubMultiClass) {
MultiClass *SMC = SubMultiClass.MC;
ArrayRef<Init *> SMCTArgs = SMC->Rec.getTemplateArgs();
if (SMCTArgs.size() < SubMultiClass.TemplateArgs.size())
return Error(SubMultiClass.RefRange.Start,
"More template args specified than expected");
// Prepare the mapping of template argument name to value, filling in default
// values if necessary.
SubstStack TemplateArgs;
for (unsigned i = 0, e = SMCTArgs.size(); i != e; ++i) {
if (i < SubMultiClass.TemplateArgs.size()) {
TemplateArgs.emplace_back(SMCTArgs[i], SubMultiClass.TemplateArgs[i]);
} else {
Init *Default = SMC->Rec.getValue(SMCTArgs[i])->getValue();
if (!Default->isComplete()) {
return Error(SubMultiClass.RefRange.Start,
"value not specified for template argument #" + Twine(i) +
" (" + SMCTArgs[i]->getAsUnquotedString() +
") of multiclass '" + SMC->Rec.getNameInitAsString() +
"'");
}
TemplateArgs.emplace_back(SMCTArgs[i], Default);
}
}
TemplateArgs.emplace_back(
QualifiedNameOfImplicitName(SMC),
VarInit::get(QualifiedNameOfImplicitName(CurMC), StringRecTy::get()));
// Add all of the defs in the subclass into the current multiclass.
return resolve(SMC->Entries, TemplateArgs, false, &CurMC->Entries);
}
/// Add a record, foreach loop, or assertion to the current context.
bool TGParser::addEntry(RecordsEntry E) {
assert((!!E.Rec + !!E.Loop + !!E.Assertion) == 1 &&
"RecordsEntry has invalid number of items");
// If we are parsing a loop, add it to the loop's entries.
if (!Loops.empty()) {
Loops.back()->Entries.push_back(std::move(E));
return false;
}
// If it is a loop, then resolve and perform the loop.
if (E.Loop) {
SubstStack Stack;
return resolve(*E.Loop, Stack, CurMultiClass == nullptr,
CurMultiClass ? &CurMultiClass->Entries : nullptr);
}
// If we are parsing a multiclass, add it to the multiclass's entries.
if (CurMultiClass) {
CurMultiClass->Entries.push_back(std::move(E));
return false;
}
// If it is an assertion, then it's a top-level one, so check it.
if (E.Assertion) {
CheckAssert(E.Assertion->Loc, E.Assertion->Condition, E.Assertion->Message);
return false;
}
// It must be a record, so finish it off.
return addDefOne(std::move(E.Rec));
}
/// Resolve the entries in \p Loop, going over inner loops recursively
/// and making the given subsitutions of (name, value) pairs.
///
/// The resulting records are stored in \p Dest if non-null. Otherwise, they
/// are added to the global record keeper.
bool TGParser::resolve(const ForeachLoop &Loop, SubstStack &Substs,
bool Final, std::vector<RecordsEntry> *Dest,
SMLoc *Loc) {
MapResolver R;
for (const auto &S : Substs)
R.set(S.first, S.second);
Init *List = Loop.ListValue->resolveReferences(R);
auto LI = dyn_cast<ListInit>(List);
if (!LI) {
if (!Final) {
Dest->emplace_back(std::make_unique<ForeachLoop>(Loop.Loc, Loop.IterVar,
List));
return resolve(Loop.Entries, Substs, Final, &Dest->back().Loop->Entries,
Loc);
}
PrintError(Loop.Loc, Twine("attempting to loop over '") +
List->getAsString() + "', expected a list");
return true;
}
bool Error = false;
for (auto Elt : *LI) {
if (Loop.IterVar)
Substs.emplace_back(Loop.IterVar->getNameInit(), Elt);
Error = resolve(Loop.Entries, Substs, Final, Dest);
if (Loop.IterVar)
Substs.pop_back();
if (Error)
break;
}
return Error;
}
/// Resolve the entries in \p Source, going over loops recursively and
/// making the given substitutions of (name, value) pairs.
///
/// The resulting records are stored in \p Dest if non-null. Otherwise, they
/// are added to the global record keeper.
bool TGParser::resolve(const std::vector<RecordsEntry> &Source,
SubstStack &Substs, bool Final,
std::vector<RecordsEntry> *Dest, SMLoc *Loc) {
bool Error = false;
for (auto &E : Source) {
if (E.Loop) {
Error = resolve(*E.Loop, Substs, Final, Dest);
} else if (E.Assertion) {
MapResolver R;
for (const auto &S : Substs)
R.set(S.first, S.second);
Init *Condition = E.Assertion->Condition->resolveReferences(R);
Init *Message = E.Assertion->Message->resolveReferences(R);
if (Dest)
Dest->push_back(std::make_unique<Record::AssertionInfo>(
E.Assertion->Loc, Condition, Message));
else
CheckAssert(E.Assertion->Loc, Condition, Message);
} else {
auto Rec = std::make_unique<Record>(*E.Rec);
if (Loc)
Rec->appendLoc(*Loc);
MapResolver R(Rec.get());
for (const auto &S : Substs)
R.set(S.first, S.second);
Rec->resolveReferences(R);
if (Dest)
Dest->push_back(std::move(Rec));
else
Error = addDefOne(std::move(Rec));
}
if (Error)
break;
}
return Error;
}
/// Resolve the record fully and add it to the record keeper.
bool TGParser::addDefOne(std::unique_ptr<Record> Rec) {
Init *NewName = nullptr;
if (Record *Prev = Records.getDef(Rec->getNameInitAsString())) {
if (!Rec->isAnonymous()) {
PrintError(Rec->getLoc(),
"def already exists: " + Rec->getNameInitAsString());
PrintNote(Prev->getLoc(), "location of previous definition");
return true;
}
NewName = Records.getNewAnonymousName();
}
Rec->resolveReferences(NewName);
checkConcrete(*Rec);
if (!isa<StringInit>(Rec->getNameInit())) {
PrintError(Rec->getLoc(), Twine("record name '") +
Rec->getNameInit()->getAsString() +
"' could not be fully resolved");
return true;
}
// Check the assertions.
Rec->checkRecordAssertions();
// If ObjectBody has template arguments, it's an error.
assert(Rec->getTemplateArgs().empty() && "How'd this get template args?");
for (DefsetRecord *Defset : Defsets) {
DefInit *I = Rec->getDefInit();
if (!I->getType()->typeIsA(Defset->EltTy)) {
PrintError(Rec->getLoc(), Twine("adding record of incompatible type '") +
I->getType()->getAsString() +
"' to defset");
PrintNote(Defset->Loc, "location of defset declaration");
return true;
}
Defset->Elements.push_back(I);
}
Records.addDef(std::move(Rec));
return false;
}
//===----------------------------------------------------------------------===//
// Parser Code
//===----------------------------------------------------------------------===//
/// isObjectStart - Return true if this is a valid first token for a statement.
static bool isObjectStart(tgtok::TokKind K) {
return K == tgtok::Assert || K == tgtok::Class || K == tgtok::Def ||
K == tgtok::Defm || K == tgtok::Defset || K == tgtok::Defvar ||
K == tgtok::Foreach || K == tgtok::If || K == tgtok::Let ||
K == tgtok::MultiClass;
}
bool TGParser::consume(tgtok::TokKind K) {
if (Lex.getCode() == K) {
Lex.Lex();
return true;
}
return false;
}
/// ParseObjectName - If a valid object name is specified, return it. If no
/// name is specified, return the unset initializer. Return nullptr on parse
/// error.
/// ObjectName ::= Value [ '#' Value ]*
/// ObjectName ::= /*empty*/
///
Init *TGParser::ParseObjectName(MultiClass *CurMultiClass) {
switch (Lex.getCode()) {
case tgtok::colon:
case tgtok::semi:
case tgtok::l_brace:
// These are all of the tokens that can begin an object body.
// Some of these can also begin values but we disallow those cases
// because they are unlikely to be useful.
return UnsetInit::get();
default:
break;
}
Record *CurRec = nullptr;
if (CurMultiClass)
CurRec = &CurMultiClass->Rec;
Init *Name = ParseValue(CurRec, StringRecTy::get(), ParseNameMode);
if (!Name)
return nullptr;
if (CurMultiClass) {
Init *NameStr = QualifiedNameOfImplicitName(CurMultiClass);
HasReferenceResolver R(NameStr);
Name->resolveReferences(R);
if (!R.found())
Name = BinOpInit::getStrConcat(VarInit::get(NameStr, StringRecTy::get()),
Name);
}
return Name;
}
/// ParseClassID - Parse and resolve a reference to a class name. This returns
/// null on error.
///
/// ClassID ::= ID
///
Record *TGParser::ParseClassID() {
if (Lex.getCode() != tgtok::Id) {
TokError("expected name for ClassID");
return nullptr;
}
Record *Result = Records.getClass(Lex.getCurStrVal());
if (!Result) {
std::string Msg("Couldn't find class '" + Lex.getCurStrVal() + "'");
if (MultiClasses[Lex.getCurStrVal()].get())
TokError(Msg + ". Use 'defm' if you meant to use multiclass '" +
Lex.getCurStrVal() + "'");
else
TokError(Msg);
}
Lex.Lex();
return Result;
}
/// ParseMultiClassID - Parse and resolve a reference to a multiclass name.
/// This returns null on error.
///
/// MultiClassID ::= ID
///
MultiClass *TGParser::ParseMultiClassID() {
if (Lex.getCode() != tgtok::Id) {
TokError("expected name for MultiClassID");
return nullptr;
}
MultiClass *Result = MultiClasses[Lex.getCurStrVal()].get();
if (!Result)
TokError("Couldn't find multiclass '" + Lex.getCurStrVal() + "'");
Lex.Lex();
return Result;
}
/// ParseSubClassReference - Parse a reference to a subclass or a
/// multiclass. This returns a SubClassRefTy with a null Record* on error.
///
/// SubClassRef ::= ClassID
/// SubClassRef ::= ClassID '<' ValueList '>'
///
SubClassReference TGParser::
ParseSubClassReference(Record *CurRec, bool isDefm) {
SubClassReference Result;
Result.RefRange.Start = Lex.getLoc();
if (isDefm) {
if (MultiClass *MC = ParseMultiClassID())
Result.Rec = &MC->Rec;
} else {
Result.Rec = ParseClassID();
}
if (!Result.Rec) return Result;
// If there is no template arg list, we're done.
if (!consume(tgtok::less)) {
Result.RefRange.End = Lex.getLoc();
return Result;
}
if (ParseTemplateArgValueList(Result.TemplateArgs, CurRec, Result.Rec)) {
Result.Rec = nullptr; // Error parsing value list.
return Result;
}
if (CheckTemplateArgValues(Result.TemplateArgs, Result.RefRange.Start,
Result.Rec)) {
Result.Rec = nullptr; // Error checking value list.
return Result;
}
Result.RefRange.End = Lex.getLoc();
return Result;
}
/// ParseSubMultiClassReference - Parse a reference to a subclass or to a
/// templated submulticlass. This returns a SubMultiClassRefTy with a null
/// Record* on error.
///
/// SubMultiClassRef ::= MultiClassID
/// SubMultiClassRef ::= MultiClassID '<' ValueList '>'
///
SubMultiClassReference TGParser::
ParseSubMultiClassReference(MultiClass *CurMC) {
SubMultiClassReference Result;
Result.RefRange.Start = Lex.getLoc();
Result.MC = ParseMultiClassID();
if (!Result.MC) return Result;
// If there is no template arg list, we're done.
if (!consume(tgtok::less)) {
Result.RefRange.End = Lex.getLoc();
return Result;
}
if (ParseTemplateArgValueList(Result.TemplateArgs, &CurMC->Rec,
&Result.MC->Rec)) {
Result.MC = nullptr; // Error parsing value list.
return Result;
}
Result.RefRange.End = Lex.getLoc();
return Result;
}
/// ParseRangePiece - Parse a bit/value range.
/// RangePiece ::= INTVAL
/// RangePiece ::= INTVAL '...' INTVAL
/// RangePiece ::= INTVAL '-' INTVAL
/// RangePiece ::= INTVAL INTVAL
// The last two forms are deprecated.
bool TGParser::ParseRangePiece(SmallVectorImpl<unsigned> &Ranges,
TypedInit *FirstItem) {
Init *CurVal = FirstItem;
if (!CurVal)
CurVal = ParseValue(nullptr);
IntInit *II = dyn_cast_or_null<IntInit>(CurVal);
if (!II)
return TokError("expected integer or bitrange");
int64_t Start = II->getValue();
int64_t End;
if (Start < 0)
return TokError("invalid range, cannot be negative");
switch (Lex.getCode()) {
default:
Ranges.push_back(Start);
return false;
case tgtok::dotdotdot:
case tgtok::minus: {
Lex.Lex(); // eat
Init *I_End = ParseValue(nullptr);
IntInit *II_End = dyn_cast_or_null<IntInit>(I_End);
if (!II_End) {
TokError("expected integer value as end of range");
return true;
}
End = II_End->getValue();
break;
}
case tgtok::IntVal: {
End = -Lex.getCurIntVal();
Lex.Lex();
break;
}
}
if (End < 0)
return TokError("invalid range, cannot be negative");
// Add to the range.
if (Start < End)
for (; Start <= End; ++Start)
Ranges.push_back(Start);
else
for (; Start >= End; --Start)
Ranges.push_back(Start);
return false;
}
/// ParseRangeList - Parse a list of scalars and ranges into scalar values.
///
/// RangeList ::= RangePiece (',' RangePiece)*
///
void TGParser::ParseRangeList(SmallVectorImpl<unsigned> &Result) {
// Parse the first piece.
if (ParseRangePiece(Result)) {
Result.clear();
return;
}
while (consume(tgtok::comma))
// Parse the next range piece.
if (ParseRangePiece(Result)) {
Result.clear();
return;
}
}
/// ParseOptionalRangeList - Parse either a range list in <>'s or nothing.
/// OptionalRangeList ::= '<' RangeList '>'
/// OptionalRangeList ::= /*empty*/
bool TGParser::ParseOptionalRangeList(SmallVectorImpl<unsigned> &Ranges) {
SMLoc StartLoc = Lex.getLoc();
if (!consume(tgtok::less))
return false;
// Parse the range list.
ParseRangeList(Ranges);
if (Ranges.empty()) return true;
if (!consume(tgtok::greater)) {
TokError("expected '>' at end of range list");
return Error(StartLoc, "to match this '<'");
}
return false;
}
/// ParseOptionalBitList - Parse either a bit list in {}'s or nothing.
/// OptionalBitList ::= '{' RangeList '}'
/// OptionalBitList ::= /*empty*/
bool TGParser::ParseOptionalBitList(SmallVectorImpl<unsigned> &Ranges) {
SMLoc StartLoc = Lex.getLoc();
if (!consume(tgtok::l_brace))
return false;
// Parse the range list.
ParseRangeList(Ranges);
if (Ranges.empty()) return true;
if (!consume(tgtok::r_brace)) {
TokError("expected '}' at end of bit list");
return Error(StartLoc, "to match this '{'");
}
return false;
}
/// ParseType - Parse and return a tblgen type. This returns null on error.
///
/// Type ::= STRING // string type
/// Type ::= CODE // code type
/// Type ::= BIT // bit type
/// Type ::= BITS '<' INTVAL '>' // bits<x> type
/// Type ::= INT // int type
/// Type ::= LIST '<' Type '>' // list<x> type
/// Type ::= DAG // dag type
/// Type ::= ClassID // Record Type
///
RecTy *TGParser::ParseType() {
switch (Lex.getCode()) {
default: TokError("Unknown token when expecting a type"); return nullptr;
case tgtok::String:
case tgtok::Code: Lex.Lex(); return StringRecTy::get();
case tgtok::Bit: Lex.Lex(); return BitRecTy::get();
case tgtok::Int: Lex.Lex(); return IntRecTy::get();
case tgtok::Dag: Lex.Lex(); return DagRecTy::get();
case tgtok::Id:
if (Record *R = ParseClassID()) return RecordRecTy::get(R);
TokError("unknown class name");
return nullptr;
case tgtok::Bits: {
if (Lex.Lex() != tgtok::less) { // Eat 'bits'
TokError("expected '<' after bits type");
return nullptr;
}
if (Lex.Lex() != tgtok::IntVal) { // Eat '<'
TokError("expected integer in bits<n> type");
return nullptr;
}
uint64_t Val = Lex.getCurIntVal();
if (Lex.Lex() != tgtok::greater) { // Eat count.
TokError("expected '>' at end of bits<n> type");
return nullptr;
}
Lex.Lex(); // Eat '>'
return BitsRecTy::get(Val);
}
case tgtok::List: {
if (Lex.Lex() != tgtok::less) { // Eat 'bits'
TokError("expected '<' after list type");
return nullptr;
}
Lex.Lex(); // Eat '<'
RecTy *SubType = ParseType();
if (!SubType) return nullptr;
if (!consume(tgtok::greater)) {
TokError("expected '>' at end of list<ty> type");
return nullptr;
}
return ListRecTy::get(SubType);
}
}
}
/// ParseIDValue
Init *TGParser::ParseIDValue(Record *CurRec, StringInit *Name, SMLoc NameLoc,
IDParseMode Mode) {
if (CurRec) {
if (const RecordVal *RV = CurRec->getValue(Name))
return VarInit::get(Name, RV->getType());
}
if ((CurRec && CurRec->isClass()) || CurMultiClass) {
Init *TemplateArgName;
if (CurMultiClass) {
TemplateArgName =
QualifyName(CurMultiClass->Rec, CurMultiClass, Name, "::");
} else
TemplateArgName = QualifyName(*CurRec, CurMultiClass, Name, ":");
Record *TemplateRec = CurMultiClass ? &CurMultiClass->Rec : CurRec;
if (TemplateRec->isTemplateArg(TemplateArgName)) {
RecordVal *RV = TemplateRec->getValue(TemplateArgName);
assert(RV && "Template arg doesn't exist??");
RV->setUsed(true);
return VarInit::get(TemplateArgName, RV->getType());
} else if (Name->getValue() == "NAME") {
return VarInit::get(TemplateArgName, StringRecTy::get());
}
}
if (CurLocalScope)
if (Init *I = CurLocalScope->getVar(Name->getValue()))
return I;
// If this is in a foreach loop, make sure it's not a loop iterator
for (const auto &L : Loops) {
if (L->IterVar) {
VarInit *IterVar = dyn_cast<VarInit>(L->IterVar);
if (IterVar && IterVar->getNameInit() == Name)
return IterVar;
}
}
if (Mode == ParseNameMode)
return Name;
if (Init *I = Records.getGlobal(Name->getValue()))
return I;
// Allow self-references of concrete defs, but delay the lookup so that we
// get the correct type.
if (CurRec && !CurRec->isClass() && !CurMultiClass &&
CurRec->getNameInit() == Name)
return UnOpInit::get(UnOpInit::CAST, Name, CurRec->getType());
Error(NameLoc, "Variable not defined: '" + Name->getValue() + "'");
return nullptr;
}
/// ParseOperation - Parse an operator. This returns null on error.
///
/// Operation ::= XOperator ['<' Type '>'] '(' Args ')'
///
Init *TGParser::ParseOperation(Record *CurRec, RecTy *ItemType) {
switch (Lex.getCode()) {
default:
TokError("unknown bang operator");
return nullptr;
case tgtok::XNOT:
case tgtok::XHead:
case tgtok::XTail:
case tgtok::XSize:
case tgtok::XEmpty:
case tgtok::XCast:
case tgtok::XGetDagOp: { // Value ::= !unop '(' Value ')'
UnOpInit::UnaryOp Code;
RecTy *Type = nullptr;
switch (Lex.getCode()) {
default: llvm_unreachable("Unhandled code!");
case tgtok::XCast:
Lex.Lex(); // eat the operation
Code = UnOpInit::CAST;
Type = ParseOperatorType();
if (!Type) {
TokError("did not get type for unary operator");
return nullptr;
}
break;
case tgtok::XNOT:
Lex.Lex(); // eat the operation
Code = UnOpInit::NOT;
Type = IntRecTy::get();
break;
case tgtok::XHead:
Lex.Lex(); // eat the operation
Code = UnOpInit::HEAD;
break;
case tgtok::XTail:
Lex.Lex(); // eat the operation
Code = UnOpInit::TAIL;
break;
case tgtok::XSize:
Lex.Lex();
Code = UnOpInit::SIZE;
Type = IntRecTy::get();
break;
case tgtok::XEmpty:
Lex.Lex(); // eat the operation
Code = UnOpInit::EMPTY;
Type = IntRecTy::get();
break;
case tgtok::XGetDagOp:
Lex.Lex(); // eat the operation
if (Lex.getCode() == tgtok::less) {
// Parse an optional type suffix, so that you can say
// !getdagop<BaseClass>(someDag) as a shorthand for
// !cast<BaseClass>(!getdagop(someDag)).
Type = ParseOperatorType();
if (!Type) {
TokError("did not get type for unary operator");
return nullptr;
}
if (!isa<RecordRecTy>(Type)) {
TokError("type for !getdagop must be a record type");
// but keep parsing, to consume the operand
}
} else {
Type = RecordRecTy::get({});
}
Code = UnOpInit::GETDAGOP;
break;
}
if (!consume(tgtok::l_paren)) {
TokError("expected '(' after unary operator");
return nullptr;
}
Init *LHS = ParseValue(CurRec);
if (!LHS) return nullptr;