LLVM 24.0.0git
Record.cpp
Go to the documentation of this file.
1//===- Record.cpp - Record implementation ---------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// Implement the tablegen record classes.
10//
11//===----------------------------------------------------------------------===//
12
14#include "llvm/ADT/ArrayRef.h"
15#include "llvm/ADT/DenseMap.h"
16#include "llvm/ADT/FoldingSet.h"
20#include "llvm/ADT/StringMap.h"
21#include "llvm/ADT/StringRef.h"
22#include "llvm/Config/llvm-config.h"
28#include "llvm/Support/Regex.h"
29#include "llvm/Support/SMLoc.h"
31#include "llvm/TableGen/Error.h"
33#include <cassert>
34#include <cstdint>
35#include <memory>
36#include <string>
37#include <utility>
38#include <vector>
39
40using namespace llvm;
41
42#define DEBUG_TYPE "tblgen-records"
43
44//===----------------------------------------------------------------------===//
45// Context
46//===----------------------------------------------------------------------===//
47
48/// This class represents the internal implementation of the RecordKeeper.
49/// It contains all of the contextual static state of the Record classes. It is
50/// kept out-of-line to simplify dependencies, and also make it easier for
51/// internal classes to access the uniquer state of the keeper.
59
61 std::vector<BitsRecTy *> SharedBitsRecTys;
66
71
94
95 unsigned AnonCounter;
96 unsigned LastRecordID;
97
98 void dumpAllocationStats(raw_ostream &OS) const;
99};
100
102 // Dump memory allocation related stats.
103 OS << "TheArgumentInitPool size = " << TheArgumentInitPool.size() << '\n';
104 OS << "TheBitsInitPool size = " << TheBitsInitPool.size() << '\n';
105 OS << "TheIntInitPool size = " << TheIntInitPool.size() << '\n';
106 OS << "StringInitStringPool size = " << StringInitStringPool.size() << '\n';
107 OS << "StringInitCodePool size = " << StringInitCodePool.size() << '\n';
108 OS << "TheListInitPool size = " << TheListInitPool.size() << '\n';
109 OS << "TheUnOpInitPool size = " << TheUnOpInitPool.size() << '\n';
110 OS << "TheBinOpInitPool size = " << TheBinOpInitPool.size() << '\n';
111 OS << "TheTernOpInitPool size = " << TheTernOpInitPool.size() << '\n';
112 OS << "TheFoldOpInitPool size = " << TheFoldOpInitPool.size() << '\n';
113 OS << "TheIsAOpInitPool size = " << TheIsAOpInitPool.size() << '\n';
114 OS << "TheExistsOpInitPool size = " << TheExistsOpInitPool.size() << '\n';
115 OS << "TheCondOpInitPool size = " << TheCondOpInitPool.size() << '\n';
116 OS << "TheDagInitPool size = " << TheDagInitPool.size() << '\n';
117 OS << "RecordTypePool size = " << RecordTypePool.size() << '\n';
118 OS << "TheVarInitPool size = " << TheVarInitPool.size() << '\n';
119 OS << "TheVarBitInitPool size = " << TheVarBitInitPool.size() << '\n';
120 OS << "TheVarDefInitPool size = " << TheVarDefInitPool.size() << '\n';
121 OS << "TheFieldInitPool size = " << TheFieldInitPool.size() << '\n';
122 OS << "Total allocator memory = " << Allocator.getTotalMemory() << "\n\n";
123
124 OS << "Number of records instantiated = " << LastRecordID << '\n';
125 OS << "Number of anonymous records = " << AnonCounter << '\n';
126}
127
128//===----------------------------------------------------------------------===//
129// Type implementations
130//===----------------------------------------------------------------------===//
131
132#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
134#endif
135
137 if (!ListTy)
138 ListTy = new (RK.getImpl().Allocator) ListRecTy(this);
139 return ListTy;
140}
141
142bool RecTy::typeIsConvertibleTo(const RecTy *RHS) const {
143 assert(RHS && "NULL pointer");
144 return Kind == RHS->getRecTyKind();
145}
146
147bool RecTy::typeIsA(const RecTy *RHS) const { return this == RHS; }
148
149const BitRecTy *BitRecTy::get(RecordKeeper &RK) {
150 return &RK.getImpl().SharedBitRecTy;
151}
152
154 if (RecTy::typeIsConvertibleTo(RHS) || RHS->getRecTyKind() == IntRecTyKind)
155 return true;
156 if (const auto *BitsTy = dyn_cast<BitsRecTy>(RHS))
157 return BitsTy->getNumBits() == 1;
158 return false;
159}
160
161const BitsRecTy *BitsRecTy::get(RecordKeeper &RK, unsigned Sz) {
162 detail::RecordKeeperImpl &RKImpl = RK.getImpl();
163 if (Sz >= RKImpl.SharedBitsRecTys.size())
164 RKImpl.SharedBitsRecTys.resize(Sz + 1);
165 BitsRecTy *&Ty = RKImpl.SharedBitsRecTys[Sz];
166 if (!Ty)
167 Ty = new (RKImpl.Allocator) BitsRecTy(RK, Sz);
168 return Ty;
169}
170
171std::string BitsRecTy::getAsString() const {
172 return "bits<" + utostr(Size) + ">";
173}
174
175bool BitsRecTy::typeIsConvertibleTo(const RecTy *RHS) const {
176 if (RecTy::typeIsConvertibleTo(RHS)) //argument and the sender are same type
177 return cast<BitsRecTy>(RHS)->Size == Size;
178 RecTyKind kind = RHS->getRecTyKind();
179 return (kind == BitRecTyKind && Size == 1) || (kind == IntRecTyKind);
180}
181
182const IntRecTy *IntRecTy::get(RecordKeeper &RK) {
183 return &RK.getImpl().SharedIntRecTy;
184}
185
186bool IntRecTy::typeIsConvertibleTo(const RecTy *RHS) const {
187 RecTyKind kind = RHS->getRecTyKind();
188 return kind==BitRecTyKind || kind==BitsRecTyKind || kind==IntRecTyKind;
189}
190
191const StringRecTy *StringRecTy::get(RecordKeeper &RK) {
192 return &RK.getImpl().SharedStringRecTy;
193}
194
195std::string StringRecTy::getAsString() const {
196 return "string";
197}
198
200 RecTyKind Kind = RHS->getRecTyKind();
201 return Kind == StringRecTyKind;
202}
203
204std::string ListRecTy::getAsString() const {
205 return "list<" + ElementTy->getAsString() + ">";
206}
207
208bool ListRecTy::typeIsConvertibleTo(const RecTy *RHS) const {
209 if (const auto *ListTy = dyn_cast<ListRecTy>(RHS))
210 return ElementTy->typeIsConvertibleTo(ListTy->getElementType());
211 return false;
212}
213
214bool ListRecTy::typeIsA(const RecTy *RHS) const {
215 if (const auto *RHSl = dyn_cast<ListRecTy>(RHS))
216 return getElementType()->typeIsA(RHSl->getElementType());
217 return false;
218}
219
220const DagRecTy *DagRecTy::get(RecordKeeper &RK) {
221 return &RK.getImpl().SharedDagRecTy;
222}
223
224std::string DagRecTy::getAsString() const {
225 return "dag";
226}
227
228RecordRecTy::RecordRecTy(RecordKeeper &RK, ArrayRef<const Record *> Classes)
229 : RecTy(RecordRecTyKind, RK), NumClasses(Classes.size()) {
230 llvm::uninitialized_copy(Classes, getTrailingObjects());
231}
232
233const RecordRecTy *RecordRecTy::get(RecordKeeper &RK,
234 ArrayRef<const Record *> UnsortedClasses) {
235 detail::RecordKeeperImpl &RKImpl = RK.getImpl();
236 if (UnsortedClasses.empty())
237 return &RKImpl.AnyRecord;
238
240
241 SmallVector<const Record *, 4> Classes(UnsortedClasses);
242 llvm::sort(Classes, [](const Record *LHS, const Record *RHS) {
243 return LHS->getNameInitAsString() < RHS->getNameInitAsString();
244 });
245
247 if (RecordRecTy *Ty = ThePool.lookup(Classes, Token))
248 return Ty;
249
250#ifndef NDEBUG
251 // Check for redundancy.
252 for (unsigned i = 0; i < Classes.size(); ++i) {
253 for (unsigned j = 0; j < Classes.size(); ++j) {
254 assert(i == j || !Classes[i]->isSubClassOf(Classes[j]));
255 }
256 assert(&Classes[0]->getRecords() == &Classes[i]->getRecords());
257 }
258#endif
259
260 void *Mem = RKImpl.Allocator.Allocate(
261 totalSizeToAlloc<const Record *>(Classes.size()), alignof(RecordRecTy));
262 RecordRecTy *Ty = new (Mem) RecordRecTy(RK, Classes);
263 ThePool.insert(Ty, Token);
264 return Ty;
265}
266
267const RecordRecTy *RecordRecTy::get(const Record *Class) {
268 assert(Class && "unexpected null class");
269 return get(Class->getRecords(), {Class});
270}
271
272std::string RecordRecTy::getAsString() const {
273 if (NumClasses == 1)
274 return getClasses()[0]->getNameInitAsString();
275
276 std::string Str = "{";
277 ListSeparator LS;
278 for (const Record *R : getClasses()) {
279 Str += LS;
280 Str += R->getNameInitAsString();
281 }
282 Str += "}";
283 return Str;
284}
285
286bool RecordRecTy::isSubClassOf(const Record *Class) const {
287 return llvm::any_of(getClasses(), [Class](const Record *MySuperClass) {
288 return MySuperClass == Class || MySuperClass->isSubClassOf(Class);
289 });
290}
291
293 if (this == RHS)
294 return true;
295
296 const auto *RTy = dyn_cast<RecordRecTy>(RHS);
297 if (!RTy)
298 return false;
299
300 return llvm::all_of(RTy->getClasses(), [this](const Record *TargetClass) {
301 return isSubClassOf(TargetClass);
302 });
303}
304
305bool RecordRecTy::typeIsA(const RecTy *RHS) const {
306 return typeIsConvertibleTo(RHS);
307}
308
310 const RecordRecTy *T2) {
311 SmallVector<const Record *, 4> CommonSuperClasses;
312 SmallVector<const Record *, 4> Stack(T1->getClasses());
313
314 while (!Stack.empty()) {
315 const Record *R = Stack.pop_back_val();
316
317 if (T2->isSubClassOf(R))
318 CommonSuperClasses.push_back(R);
319 else
320 llvm::append_range(Stack, make_first_range(R->getDirectSuperClasses()));
321 }
322
323 return RecordRecTy::get(T1->getRecordKeeper(), CommonSuperClasses);
324}
325
326const RecTy *llvm::resolveTypes(const RecTy *T1, const RecTy *T2) {
327 if (T1 == T2)
328 return T1;
329
330 if (const auto *RecTy1 = dyn_cast<RecordRecTy>(T1)) {
331 if (const auto *RecTy2 = dyn_cast<RecordRecTy>(T2))
332 return resolveRecordTypes(RecTy1, RecTy2);
333 }
334
335 assert(T1 != nullptr && "Invalid record type");
336 if (T1->typeIsConvertibleTo(T2))
337 return T2;
338
339 assert(T2 != nullptr && "Invalid record type");
340 if (T2->typeIsConvertibleTo(T1))
341 return T1;
342
343 if (const auto *ListTy1 = dyn_cast<ListRecTy>(T1)) {
344 if (const auto *ListTy2 = dyn_cast<ListRecTy>(T2)) {
345 const RecTy *NewType =
346 resolveTypes(ListTy1->getElementType(), ListTy2->getElementType());
347 if (NewType)
348 return NewType->getListTy();
349 }
350 }
351
352 return nullptr;
353}
354
355//===----------------------------------------------------------------------===//
356// Initializer implementations
357//===----------------------------------------------------------------------===//
358
359void Init::anchor() {}
360
361#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
362LLVM_DUMP_METHOD void Init::dump() const { return print(errs()); }
363#endif
364
366 if (auto *TyInit = dyn_cast<TypedInit>(this))
367 return TyInit->getType()->getRecordKeeper();
368 if (auto *ArgInit = dyn_cast<ArgumentInit>(this))
369 return ArgInit->getRecordKeeper();
370 return cast<UnsetInit>(this)->getRecordKeeper();
371}
372
374 return &RK.getImpl().TheUnsetInit;
375}
376
377const Init *UnsetInit::getCastTo(const RecTy *Ty) const { return this; }
378
380 return this;
381}
382
384 detail::RecordKeeperImpl &RK = Value->getRecordKeeper().getImpl();
386 if (const ArgumentInit *I =
387 RK.TheArgumentInitPool.lookup({Value, Aux}, Token))
388 return I;
389
390 ArgumentInit *I = new (RK.Allocator) ArgumentInit(Value, Aux);
391 RK.TheArgumentInitPool.insert(I, Token);
392 return I;
393}
394
397 return this;
398
399 const Init *NewValue = Value->resolveReferences(R);
400 if (NewValue != Value)
401 return cloneWithValue(NewValue);
402
403 return this;
404}
405
406BitInit *BitInit::get(RecordKeeper &RK, bool V) {
407 return V ? &RK.getImpl().TrueBitInit : &RK.getImpl().FalseBitInit;
408}
409
410const Init *BitInit::convertInitializerTo(const RecTy *Ty) const {
411 if (isa<BitRecTy>(Ty))
412 return this;
413
414 if (isa<IntRecTy>(Ty))
416
417 if (auto *BRT = dyn_cast<BitsRecTy>(Ty)) {
418 // Can only convert single bit.
419 if (BRT->getNumBits() == 1)
420 return BitsInit::get(getRecordKeeper(), this);
421 }
422
423 return nullptr;
424}
425
426BitsInit::BitsInit(RecordKeeper &RK, ArrayRef<const Init *> Bits)
427 : TypedInit(IK_BitsInit, BitsRecTy::get(RK, Bits.size())),
428 NumBits(Bits.size()) {
429 llvm::uninitialized_copy(Bits, getTrailingObjects());
430 // Other values are converted to a bit when resolved.
432}
433
435 detail::RecordKeeperImpl &RKImpl = RK.getImpl();
437 if (BitsInit *I = RKImpl.TheBitsInitPool.lookup(Bits, Token))
438 return I;
439
440 void *Mem = RKImpl.Allocator.Allocate(
441 totalSizeToAlloc<const Init *>(Bits.size()), alignof(BitsInit));
442 BitsInit *I = new (Mem) BitsInit(RK, Bits);
443 RKImpl.TheBitsInitPool.insert(I, Token);
444 return I;
445}
446
448 if (isa<BitRecTy>(Ty)) {
449 if (getNumBits() != 1) return nullptr; // Only accept if just one bit!
450 return getBit(0);
451 }
452
453 if (auto *BRT = dyn_cast<BitsRecTy>(Ty)) {
454 // If the number of bits is right, return it. Otherwise we need to expand
455 // or truncate.
456 if (getNumBits() != BRT->getNumBits()) return nullptr;
457 return this;
458 }
459
460 if (isa<IntRecTy>(Ty)) {
461 std::optional<int64_t> Result = convertInitializerToInt();
462 if (Result)
463 return IntInit::get(getRecordKeeper(), *Result);
464 }
465
466 return nullptr;
467}
468
469std::optional<int64_t> BitsInit::convertInitializerToInt() const {
470 int64_t Result = 0;
471 for (auto [Idx, InitV] : enumerate(getBits()))
472 if (auto *Bit = dyn_cast<BitInit>(InitV))
473 Result |= static_cast<int64_t>(Bit->getValue()) << Idx;
474 else
475 return std::nullopt;
476 return Result;
477}
478
480 uint64_t Result = 0;
481 for (auto [Idx, InitV] : enumerate(getBits()))
482 if (auto *Bit = dyn_cast<BitInit>(InitV))
483 Result |= static_cast<int64_t>(Bit->getValue()) << Idx;
484 return Result;
485}
486
487const Init *
489 SmallVector<const Init *, 16> NewBits(Bits.size());
490
491 for (auto [Bit, NewBit] : zip_equal(Bits, NewBits)) {
492 if (Bit >= getNumBits())
493 return nullptr;
494 NewBit = getBit(Bit);
495 }
496 return BitsInit::get(getRecordKeeper(), NewBits);
497}
498
500 return all_of(getBits(), [](const Init *Bit) { return Bit->isComplete(); });
501}
503 return all_of(getBits(), [](const Init *Bit) { return !Bit->isComplete(); });
504}
506 return all_of(getBits(), [](const Init *Bit) { return Bit->isConcrete(); });
507}
508
509std::string BitsInit::getAsString() const {
510 std::string Result = "{ ";
511 ListSeparator LS;
512 for (const Init *Bit : reverse(getBits())) {
513 Result += LS;
514 if (Bit)
515 Result += Bit->getAsString();
516 else
517 Result += "*";
518 }
519 return Result + " }";
520}
521
522// resolveReferences - If there are any field references that refer to fields
523// that have been filled in, we can propagate the values now.
526 return this;
527
528 bool Changed = false;
530
531 const Init *CachedBitVarRef = nullptr;
532 const Init *CachedBitVarResolved = nullptr;
533
534 for (auto [CurBit, NewBit] : zip_equal(getBits(), NewBits)) {
535 NewBit = CurBit;
536
537 if (const auto *CurBitVar = dyn_cast<VarBitInit>(CurBit)) {
538 if (CurBitVar->getBitVar() != CachedBitVarRef) {
539 CachedBitVarRef = CurBitVar->getBitVar();
540 CachedBitVarResolved = CachedBitVarRef->resolveReferences(R);
541 }
542 assert(CachedBitVarResolved && "Unresolved bitvar reference");
543 NewBit = CachedBitVarResolved->getBit(CurBitVar->getBitNum());
544 } else {
545 // getBit(0) implicitly converts int and bits<1> values to bit.
546 NewBit = CurBit->resolveReferences(R)->getBit(0);
547 }
548
549 if (isa<UnsetInit>(NewBit) && R.keepUnsetBits())
550 NewBit = CurBit;
551 Changed |= CurBit != NewBit;
552 }
553
554 if (Changed)
555 return BitsInit::get(getRecordKeeper(), NewBits);
556
557 return this;
558}
559
560IntInit *IntInit::get(RecordKeeper &RK, int64_t V) {
561 IntInit *&I = RK.getImpl().TheIntInitPool[V];
562 if (!I)
563 I = new (RK.getImpl().Allocator) IntInit(RK, V);
564 return I;
565}
566
567std::string IntInit::getAsString() const {
568 return itostr(Value);
569}
570
571static bool canFitInBitfield(int64_t Value, unsigned NumBits) {
572 // For example, with NumBits == 4, we permit Values from [-7 .. 15].
573 return (NumBits >= sizeof(Value) * 8) ||
574 (Value >> NumBits == 0) || (Value >> (NumBits-1) == -1);
575}
576
577const Init *IntInit::convertInitializerTo(const RecTy *Ty) const {
578 if (isa<IntRecTy>(Ty))
579 return this;
580
581 if (isa<BitRecTy>(Ty)) {
582 int64_t Val = getValue();
583 if (Val != 0 && Val != 1) return nullptr; // Only accept 0 or 1 for a bit!
584 return BitInit::get(getRecordKeeper(), Val != 0);
585 }
586
587 if (const auto *BRT = dyn_cast<BitsRecTy>(Ty)) {
588 int64_t Value = getValue();
589 // Make sure this bitfield is large enough to hold the integer value.
590 if (!canFitInBitfield(Value, BRT->getNumBits()))
591 return nullptr;
592
593 SmallVector<const Init *, 16> NewBits(BRT->getNumBits());
594 for (unsigned i = 0; i != BRT->getNumBits(); ++i)
595 NewBits[i] =
596 BitInit::get(getRecordKeeper(), Value & ((i < 64) ? (1LL << i) : 0));
597
598 return BitsInit::get(getRecordKeeper(), NewBits);
599 }
600
601 return nullptr;
602}
603
605 SmallVector<const Init *, 16> NewBits(Bits.size());
606
607 for (auto [Bit, NewBit] : zip_equal(Bits, NewBits)) {
608 if (Bit >= 64)
609 return nullptr;
610
611 NewBit = BitInit::get(getRecordKeeper(), Value & (INT64_C(1) << Bit));
612 }
613 return BitsInit::get(getRecordKeeper(), NewBits);
614}
615
616AnonymousNameInit *AnonymousNameInit::get(RecordKeeper &RK, unsigned V) {
617 return new (RK.getImpl().Allocator) AnonymousNameInit(RK, V);
618}
619
623
625 return "anonymous_" + utostr(Value);
626}
627
629 auto *Old = this;
630 auto *New = R.resolve(Old);
631 New = New ? New : Old;
632 if (R.isFinal())
633 if (const auto *Anonymous = dyn_cast<AnonymousNameInit>(New))
634 return Anonymous->getNameInit();
635 return New;
636}
637
638const StringInit *StringInit::get(RecordKeeper &RK, StringRef V,
639 StringFormat Fmt) {
640 detail::RecordKeeperImpl &RKImpl = RK.getImpl();
641 auto &InitMap = Fmt == SF_String ? RKImpl.StringInitStringPool
642 : RKImpl.StringInitCodePool;
643 auto &Entry = *InitMap.try_emplace(V, nullptr).first;
644 if (!Entry.second)
645 Entry.second = new (RKImpl.Allocator) StringInit(RK, Entry.getKey(), Fmt);
646 return Entry.second;
647}
648
650 if (isa<StringRecTy>(Ty))
651 return this;
652
653 return nullptr;
654}
655
656ListInit::ListInit(ArrayRef<const Init *> Elements, const RecTy *EltTy)
657 : TypedInit(IK_ListInit, ListRecTy::get(EltTy)),
658 NumElements(Elements.size()) {
659 llvm::uninitialized_copy(Elements, getTrailingObjects());
661 Elements, [](const Init *Elt) { return Elt->isTriviallyResolved(); });
662}
663
664const ListInit *ListInit::get(ArrayRef<const Init *> Elements,
665 const RecTy *EltTy) {
668 if (const ListInit *I = RK.TheListInitPool.lookup({Elements, EltTy}, Token))
669 return I;
670
671 assert(Elements.empty() || !isa<TypedInit>(Elements[0]) ||
672 cast<TypedInit>(Elements[0])->getType()->typeIsConvertibleTo(EltTy));
673
674 void *Mem = RK.Allocator.Allocate(
675 totalSizeToAlloc<const Init *>(Elements.size()), alignof(ListInit));
676 ListInit *I = new (Mem) ListInit(Elements, EltTy);
677 RK.TheListInitPool.insert(I, Token);
678 return I;
679}
680
682 if (getType() == Ty)
683 return this;
684
685 if (const auto *LRT = dyn_cast<ListRecTy>(Ty)) {
687 Elements.reserve(size());
688
689 // Verify that all of the elements of the list are subclasses of the
690 // appropriate class!
691 bool Changed = false;
692 const RecTy *ElementType = LRT->getElementType();
693 for (const Init *I : getElements())
694 if (const Init *CI = I->convertInitializerTo(ElementType)) {
695 Elements.push_back(CI);
696 if (CI != I)
697 Changed = true;
698 } else {
699 return nullptr;
700 }
701
702 if (!Changed)
703 return this;
704 return ListInit::get(Elements, ElementType);
705 }
706
707 return nullptr;
708}
709
710const Record *ListInit::getElementAsRecord(unsigned Idx) const {
711 const auto *DI = dyn_cast<DefInit>(getElement(Idx));
712 if (!DI)
713 PrintFatalError("expected record type for the element with index " +
714 Twine(Idx) + " in list " + getAsString());
715 return DI->getDef();
716}
717
720 return this;
721
723 Resolved.reserve(size());
724 bool Changed = false;
725
726 for (const Init *CurElt : getElements()) {
727 const Init *E = CurElt->resolveReferences(R);
728 Changed |= E != CurElt;
729 Resolved.push_back(E);
730 }
731
732 if (Changed)
733 return ListInit::get(Resolved, getElementType());
734 return this;
735}
736
738 return all_of(*this,
739 [](const Init *Element) { return Element->isComplete(); });
740}
741
743 return all_of(*this,
744 [](const Init *Element) { return Element->isConcrete(); });
745}
746
747std::string ListInit::getAsString() const {
748 std::string Result = "[";
749 ListSeparator LS;
750 for (const Init *Element : *this) {
751 Result += LS;
752 Result += Element->getAsString();
753 }
754 return Result + "]";
755}
756
757const Init *OpInit::getBit(unsigned Bit) const {
758 if (isa<BitRecTy>(getType()))
759 return this;
760 return VarBitInit::get(this, Bit);
761}
762
763const UnOpInit *UnOpInit::get(UnaryOp Opc, const Init *LHS, const RecTy *Type) {
764 detail::RecordKeeperImpl &RK = Type->getRecordKeeper().getImpl();
766 if (const UnOpInit *I = RK.TheUnOpInitPool.lookup({Opc, LHS, Type}, Token))
767 return I;
768
769 UnOpInit *I = new (RK.Allocator) UnOpInit(Opc, LHS, Type);
770 RK.TheUnOpInitPool.insert(I, Token);
771 return I;
772}
773
774const Init *UnOpInit::Fold(const Record *CurRec, bool IsFinal) const {
776 switch (getOpcode()) {
777 case REPR:
778 if (LHS->isConcrete()) {
779 // If it is a Record, print the full content.
780 if (const auto *Def = dyn_cast<DefInit>(LHS)) {
781 std::string S;
782 raw_string_ostream OS(S);
783 OS << *Def->getDef();
784 return StringInit::get(RK, S);
785 } else {
786 // Otherwise, print the value of the variable.
787 //
788 // NOTE: we could recursively !repr the elements of a list,
789 // but that could produce a lot of output when printing a
790 // defset.
791 return StringInit::get(RK, LHS->getAsString());
792 }
793 }
794 break;
795 case TOLOWER:
796 if (const auto *LHSs = dyn_cast<StringInit>(LHS))
797 return StringInit::get(RK, LHSs->getValue().lower());
798 break;
799 case TOUPPER:
800 if (const auto *LHSs = dyn_cast<StringInit>(LHS))
801 return StringInit::get(RK, LHSs->getValue().upper());
802 break;
803 case CAST:
804 if (isa<StringRecTy>(getType())) {
805 if (const auto *LHSs = dyn_cast<StringInit>(LHS))
806 return LHSs;
807
808 if (const auto *LHSd = dyn_cast<DefInit>(LHS))
809 return StringInit::get(RK, LHSd->getAsString());
810
811 if (const auto *LHSi = dyn_cast_or_null<IntInit>(
812 LHS->convertInitializerTo(IntRecTy::get(RK))))
813 return StringInit::get(RK, LHSi->getAsString());
814
815 } else if (isa<RecordRecTy>(getType())) {
816 if (const auto *Name = dyn_cast<StringInit>(LHS)) {
817 const Record *D = RK.getDef(Name->getValue());
818 if (!D && CurRec) {
819 // Self-references are allowed, but their resolution is delayed until
820 // the final resolve to ensure that we get the correct type for them.
821 auto *Anonymous = dyn_cast<AnonymousNameInit>(CurRec->getNameInit());
822 if (Name == CurRec->getNameInit() ||
823 (Anonymous && Name == Anonymous->getNameInit())) {
824 if (!IsFinal)
825 break;
826 D = CurRec;
827 }
828 }
829
830 auto PrintFatalErrorHelper = [CurRec](const Twine &T) {
831 if (CurRec)
832 PrintFatalError(CurRec->getLoc(), T);
833 else
835 };
836
837 if (!D) {
838 if (IsFinal) {
839 PrintFatalErrorHelper(Twine("Undefined reference to record: '") +
840 Name->getValue() + "'\n");
841 }
842 break;
843 }
844
845 DefInit *DI = D->getDefInit();
846 if (!DI->getType()->typeIsA(getType())) {
847 PrintFatalErrorHelper(Twine("Expected type '") +
848 getType()->getAsString() + "', got '" +
849 DI->getType()->getAsString() + "' in: " +
850 getAsString() + "\n");
851 }
852 return DI;
853 }
854 }
855
856 if (const Init *NewInit = LHS->convertInitializerTo(getType()))
857 return NewInit;
858 break;
859
860 case INITIALIZED:
861 if (isa<UnsetInit>(LHS))
862 return IntInit::get(RK, 0);
863 if (LHS->isConcrete())
864 return IntInit::get(RK, 1);
865 break;
866
867 case NOT:
868 if (const auto *LHSi = dyn_cast_or_null<IntInit>(
869 LHS->convertInitializerTo(IntRecTy::get(RK))))
870 return IntInit::get(RK, LHSi->getValue() ? 0 : 1);
871 break;
872
873 case HEAD:
874 if (const auto *LHSl = dyn_cast<ListInit>(LHS)) {
875 assert(!LHSl->empty() && "Empty list in head");
876 return LHSl->getElement(0);
877 }
878 break;
879
880 case TAIL:
881 if (const auto *LHSl = dyn_cast<ListInit>(LHS)) {
882 assert(!LHSl->empty() && "Empty list in tail");
883 // Note the slice(1). We can't just pass the result of getElements()
884 // directly.
885 return ListInit::get(LHSl->getElements().slice(1),
886 LHSl->getElementType());
887 }
888 break;
889
890 case SIZE:
891 if (const auto *LHSl = dyn_cast<ListInit>(LHS))
892 return IntInit::get(RK, LHSl->size());
893 if (const auto *LHSd = dyn_cast<DagInit>(LHS))
894 return IntInit::get(RK, LHSd->arg_size());
895 if (const auto *LHSs = dyn_cast<StringInit>(LHS))
896 return IntInit::get(RK, LHSs->getValue().size());
897 break;
898
899 case EMPTY:
900 if (const auto *LHSl = dyn_cast<ListInit>(LHS))
901 return IntInit::get(RK, LHSl->empty());
902 if (const auto *LHSd = dyn_cast<DagInit>(LHS))
903 return IntInit::get(RK, LHSd->arg_empty());
904 if (const auto *LHSs = dyn_cast<StringInit>(LHS))
905 return IntInit::get(RK, LHSs->getValue().empty());
906 break;
907
908 case GETDAGOP:
909 if (const auto *Dag = dyn_cast<DagInit>(LHS)) {
910 // TI is not necessarily a def due to the late resolution in multiclasses,
911 // but has to be a TypedInit.
912 auto *TI = cast<TypedInit>(Dag->getOperator());
913 if (!TI->getType()->typeIsA(getType())) {
914 PrintFatalError(CurRec->getLoc(),
915 Twine("Expected type '") + getType()->getAsString() +
916 "', got '" + TI->getType()->getAsString() +
917 "' in: " + getAsString() + "\n");
918 } else {
919 return Dag->getOperator();
920 }
921 }
922 break;
923
924 case GETDAGOPNAME:
925 if (const auto *Dag = dyn_cast<DagInit>(LHS)) {
926 return Dag->getName();
927 }
928 break;
929
930 case LOG2:
931 if (const auto *LHSi = dyn_cast_or_null<IntInit>(
932 LHS->convertInitializerTo(IntRecTy::get(RK)))) {
933 int64_t LHSv = LHSi->getValue();
934 if (LHSv <= 0) {
935 PrintFatalError(CurRec->getLoc(),
936 "Illegal operation: logtwo is undefined "
937 "on arguments less than or equal to 0");
938 } else {
939 uint64_t Log = Log2_64(LHSv);
940 assert(Log <= INT64_MAX &&
941 "Log of an int64_t must be smaller than INT64_MAX");
942 return IntInit::get(RK, static_cast<int64_t>(Log));
943 }
944 }
945 break;
946
947 case LISTFLATTEN:
948 if (const auto *LHSList = dyn_cast<ListInit>(LHS)) {
949 const auto *InnerListTy = dyn_cast<ListRecTy>(LHSList->getElementType());
950 // list of non-lists, !listflatten() is a NOP.
951 if (!InnerListTy)
952 return LHS;
953
954 auto Flatten =
955 [](const ListInit *List) -> std::optional<std::vector<const Init *>> {
956 std::vector<const Init *> Flattened;
957 // Concatenate elements of all the inner lists.
958 for (const Init *InnerInit : List->getElements()) {
959 const auto *InnerList = dyn_cast<ListInit>(InnerInit);
960 if (!InnerList)
961 return std::nullopt;
962 llvm::append_range(Flattened, InnerList->getElements());
963 };
964 return Flattened;
965 };
966
967 auto Flattened = Flatten(LHSList);
968 if (Flattened)
969 return ListInit::get(*Flattened, InnerListTy->getElementType());
970 }
971 break;
972 }
973 return this;
974}
975
977 const Init *lhs = LHS->resolveReferences(R);
978
979 if (LHS != lhs || (R.isFinal() && getOpcode() == CAST))
980 return (UnOpInit::get(getOpcode(), lhs, getType()))
981 ->Fold(R.getCurrentRecord(), R.isFinal());
982 return this;
983}
984
985std::string UnOpInit::getAsString() const {
986 std::string Result;
987 switch (getOpcode()) {
988 case CAST: Result = "!cast<" + getType()->getAsString() + ">"; break;
989 case NOT: Result = "!not"; break;
990 case HEAD: Result = "!head"; break;
991 case TAIL: Result = "!tail"; break;
992 case SIZE: Result = "!size"; break;
993 case EMPTY: Result = "!empty"; break;
994 case GETDAGOP: Result = "!getdagop"; break;
995 case GETDAGOPNAME:
996 Result = "!getdagopname";
997 break;
998 case LOG2 : Result = "!logtwo"; break;
999 case LISTFLATTEN:
1000 Result = "!listflatten";
1001 break;
1002 case REPR:
1003 Result = "!repr";
1004 break;
1005 case TOLOWER:
1006 Result = "!tolower";
1007 break;
1008 case TOUPPER:
1009 Result = "!toupper";
1010 break;
1011 case INITIALIZED:
1012 Result = "!initialized";
1013 break;
1014 }
1015 return Result + "(" + LHS->getAsString() + ")";
1016}
1017
1018const BinOpInit *BinOpInit::get(BinaryOp Opc, const Init *LHS, const Init *RHS,
1019 const RecTy *Type) {
1020 detail::RecordKeeperImpl &RK = LHS->getRecordKeeper().getImpl();
1022 if (const BinOpInit *I =
1023 RK.TheBinOpInitPool.lookup({Opc, LHS, RHS, Type}, Token))
1024 return I;
1025
1026 BinOpInit *I = new (RK.Allocator) BinOpInit(Opc, LHS, RHS, Type);
1027 RK.TheBinOpInitPool.insert(I, Token);
1028 return I;
1029}
1030
1032 const StringInit *I1) {
1034 Concat.append(I1->getValue());
1035 return StringInit::get(
1036 I0->getRecordKeeper(), Concat,
1037 StringInit::determineFormat(I0->getFormat(), I1->getFormat()));
1038}
1039
1040static const StringInit *interleaveStringList(const ListInit *List,
1041 const StringInit *Delim) {
1042 if (List->size() == 0)
1043 return StringInit::get(List->getRecordKeeper(), "");
1044 const auto *Element = dyn_cast<StringInit>(List->getElement(0));
1045 if (!Element)
1046 return nullptr;
1047 SmallString<80> Result(Element->getValue());
1049
1050 for (const Init *Elem : List->getElements().drop_front()) {
1051 Result.append(Delim->getValue());
1052 const auto *Element = dyn_cast<StringInit>(Elem);
1053 if (!Element)
1054 return nullptr;
1055 Result.append(Element->getValue());
1056 Fmt = StringInit::determineFormat(Fmt, Element->getFormat());
1057 }
1058 return StringInit::get(List->getRecordKeeper(), Result, Fmt);
1059}
1060
1061static const StringInit *interleaveIntList(const ListInit *List,
1062 const StringInit *Delim) {
1063 RecordKeeper &RK = List->getRecordKeeper();
1064 if (List->size() == 0)
1065 return StringInit::get(RK, "");
1066 const auto *Element = dyn_cast_or_null<IntInit>(
1067 List->getElement(0)->convertInitializerTo(IntRecTy::get(RK)));
1068 if (!Element)
1069 return nullptr;
1070 SmallString<80> Result(Element->getAsString());
1071
1072 for (const Init *Elem : List->getElements().drop_front()) {
1073 Result.append(Delim->getValue());
1074 const auto *Element = dyn_cast_or_null<IntInit>(
1075 Elem->convertInitializerTo(IntRecTy::get(RK)));
1076 if (!Element)
1077 return nullptr;
1078 Result.append(Element->getAsString());
1079 }
1080 return StringInit::get(RK, Result);
1081}
1082
1083const Init *BinOpInit::getStrConcat(const Init *I0, const Init *I1) {
1084 // Shortcut for the common case of concatenating two strings.
1085 if (const auto *I0s = dyn_cast<StringInit>(I0))
1086 if (const auto *I1s = dyn_cast<StringInit>(I1))
1087 return ConcatStringInits(I0s, I1s);
1088 return BinOpInit::get(BinOpInit::STRCONCAT, I0, I1,
1090}
1091
1093 const ListInit *RHS) {
1095 llvm::append_range(Args, *LHS);
1096 llvm::append_range(Args, *RHS);
1097 return ListInit::get(Args, LHS->getElementType());
1098}
1099
1100const Init *BinOpInit::getListConcat(const TypedInit *LHS, const Init *RHS) {
1101 assert(isa<ListRecTy>(LHS->getType()) && "First arg must be a list");
1102
1103 // Shortcut for the common case of concatenating two lists.
1104 if (const auto *LHSList = dyn_cast<ListInit>(LHS))
1105 if (const auto *RHSList = dyn_cast<ListInit>(RHS))
1106 return ConcatListInits(LHSList, RHSList);
1107 return BinOpInit::get(BinOpInit::LISTCONCAT, LHS, RHS, LHS->getType());
1108}
1109
1110std::optional<bool> BinOpInit::CompareInit(unsigned Opc, const Init *LHS,
1111 const Init *RHS) const {
1112 // First see if we have two bit, bits, or int.
1113 const auto *LHSi = dyn_cast_or_null<IntInit>(
1114 LHS->convertInitializerTo(IntRecTy::get(getRecordKeeper())));
1115 const auto *RHSi = dyn_cast_or_null<IntInit>(
1116 RHS->convertInitializerTo(IntRecTy::get(getRecordKeeper())));
1117
1118 if (LHSi && RHSi) {
1119 bool Result;
1120 switch (Opc) {
1121 case EQ:
1122 Result = LHSi->getValue() == RHSi->getValue();
1123 break;
1124 case NE:
1125 Result = LHSi->getValue() != RHSi->getValue();
1126 break;
1127 case LE:
1128 Result = LHSi->getValue() <= RHSi->getValue();
1129 break;
1130 case LT:
1131 Result = LHSi->getValue() < RHSi->getValue();
1132 break;
1133 case GE:
1134 Result = LHSi->getValue() >= RHSi->getValue();
1135 break;
1136 case GT:
1137 Result = LHSi->getValue() > RHSi->getValue();
1138 break;
1139 default:
1140 llvm_unreachable("unhandled comparison");
1141 }
1142 return Result;
1143 }
1144
1145 // Next try strings.
1146 const auto *LHSs = dyn_cast<StringInit>(LHS);
1147 const auto *RHSs = dyn_cast<StringInit>(RHS);
1148
1149 if (LHSs && RHSs) {
1150 bool Result;
1151 switch (Opc) {
1152 case EQ:
1153 Result = LHSs->getValue() == RHSs->getValue();
1154 break;
1155 case NE:
1156 Result = LHSs->getValue() != RHSs->getValue();
1157 break;
1158 case LE:
1159 Result = LHSs->getValue() <= RHSs->getValue();
1160 break;
1161 case LT:
1162 Result = LHSs->getValue() < RHSs->getValue();
1163 break;
1164 case GE:
1165 Result = LHSs->getValue() >= RHSs->getValue();
1166 break;
1167 case GT:
1168 Result = LHSs->getValue() > RHSs->getValue();
1169 break;
1170 default:
1171 llvm_unreachable("unhandled comparison");
1172 }
1173 return Result;
1174 }
1175
1176 // Finally, !eq and !ne can be used with records.
1177 if (Opc == EQ || Opc == NE) {
1178 const auto *LHSd = dyn_cast<DefInit>(LHS);
1179 const auto *RHSd = dyn_cast<DefInit>(RHS);
1180 if (LHSd && RHSd)
1181 return (Opc == EQ) ? LHSd == RHSd : LHSd != RHSd;
1182 }
1183
1184 return std::nullopt;
1185}
1186
1187static std::optional<unsigned>
1188getDagArgNoByKey(const DagInit *Dag, const Init *Key, std::string &Error) {
1189 // Accessor by index
1190 if (const auto *Idx = dyn_cast<IntInit>(Key)) {
1191 int64_t Pos = Idx->getValue();
1192 if (Pos < 0) {
1193 // The index is negative.
1194 Error =
1195 (Twine("index ") + std::to_string(Pos) + Twine(" is negative")).str();
1196 return std::nullopt;
1197 }
1198 if (Pos >= Dag->getNumArgs()) {
1199 // The index is out-of-range.
1200 Error = (Twine("index ") + std::to_string(Pos) +
1201 " is out of range (dag has " +
1202 std::to_string(Dag->getNumArgs()) + " arguments)")
1203 .str();
1204 return std::nullopt;
1205 }
1206 return Pos;
1207 }
1209 // Accessor by name
1210 const auto *Name = dyn_cast<StringInit>(Key);
1211 auto ArgNo = Dag->getArgNo(Name->getValue());
1212 if (!ArgNo) {
1213 // The key is not found.
1214 Error = (Twine("key '") + Name->getValue() + Twine("' is not found")).str();
1215 return std::nullopt;
1216 }
1217 return *ArgNo;
1218}
1219
1220const Init *BinOpInit::Fold(const Record *CurRec) const {
1221 switch (getOpcode()) {
1222 case CONCAT: {
1223 const auto *LHSs = dyn_cast<DagInit>(LHS);
1224 const auto *RHSs = dyn_cast<DagInit>(RHS);
1225 if (LHSs && RHSs) {
1226 const auto *LOp = dyn_cast<DefInit>(LHSs->getOperator());
1227 const auto *ROp = dyn_cast<DefInit>(RHSs->getOperator());
1228 if ((!LOp && !isa<UnsetInit>(LHSs->getOperator())) ||
1229 (!ROp && !isa<UnsetInit>(RHSs->getOperator())))
1230 break;
1231 if (LOp && ROp && LOp->getDef() != ROp->getDef()) {
1232 PrintFatalError(Twine("Concatenated Dag operators do not match: '") +
1233 LHSs->getAsString() + "' vs. '" + RHSs->getAsString() +
1234 "'");
1235 }
1236 const Init *Op = LOp ? LOp : ROp;
1237 if (!Op)
1239
1241 llvm::append_range(Args, LHSs->getArgAndNames());
1242 llvm::append_range(Args, RHSs->getArgAndNames());
1243 // Use the name of the LHS DAG if it's set, otherwise the name of the RHS.
1244 const auto *NameInit = LHSs->getName();
1245 if (!NameInit)
1246 NameInit = RHSs->getName();
1247 return DagInit::get(Op, NameInit, Args);
1248 }
1249 break;
1250 }
1251 case MATCH: {
1252 const auto *StrInit = dyn_cast<StringInit>(LHS);
1253 if (!StrInit)
1254 return this;
1255
1256 const auto *RegexInit = dyn_cast<StringInit>(RHS);
1257 if (!RegexInit)
1258 return this;
1259
1260 StringRef RegexStr = RegexInit->getValue();
1261 llvm::Regex Matcher(RegexStr);
1262 if (!Matcher.isValid())
1263 PrintFatalError(Twine("invalid regex '") + RegexStr + Twine("'"));
1264
1265 return BitInit::get(LHS->getRecordKeeper(),
1266 Matcher.match(StrInit->getValue()));
1267 }
1268 case LISTCONCAT: {
1269 const auto *LHSs = dyn_cast<ListInit>(LHS);
1270 const auto *RHSs = dyn_cast<ListInit>(RHS);
1271 if (LHSs && RHSs) {
1273 llvm::append_range(Args, *LHSs);
1274 llvm::append_range(Args, *RHSs);
1275 return ListInit::get(Args, LHSs->getElementType());
1276 }
1277 break;
1278 }
1279 case LISTSPLAT: {
1280 const auto *Value = dyn_cast<TypedInit>(LHS);
1281 const auto *Count = dyn_cast<IntInit>(RHS);
1282 if (Value && Count) {
1283 if (Count->getValue() < 0)
1284 PrintFatalError(Twine("!listsplat count ") + Count->getAsString() +
1285 " is negative");
1286 SmallVector<const Init *, 8> Args(Count->getValue(), Value);
1287 return ListInit::get(Args, Value->getType());
1288 }
1289 break;
1290 }
1291 case LISTREMOVE: {
1292 const auto *LHSs = dyn_cast<ListInit>(LHS);
1293 const auto *RHSs = dyn_cast<ListInit>(RHS);
1294 if (LHSs && RHSs) {
1296 for (const Init *EltLHS : *LHSs) {
1297 bool Found = false;
1298 for (const Init *EltRHS : *RHSs) {
1299 if (std::optional<bool> Result = CompareInit(EQ, EltLHS, EltRHS)) {
1300 if (*Result) {
1301 Found = true;
1302 break;
1303 }
1304 }
1305 }
1306 if (!Found)
1307 Args.push_back(EltLHS);
1308 }
1309 return ListInit::get(Args, LHSs->getElementType());
1310 }
1311 break;
1312 }
1313 case LISTELEM: {
1314 const auto *TheList = dyn_cast<ListInit>(LHS);
1315 const auto *Idx = dyn_cast<IntInit>(RHS);
1316 if (!TheList || !Idx)
1317 break;
1318 auto i = Idx->getValue();
1319 if (i < 0 || i >= (ssize_t)TheList->size())
1320 break;
1321 return TheList->getElement(i);
1322 }
1323 case LISTSLICE: {
1324 const auto *TheList = dyn_cast<ListInit>(LHS);
1325 const auto *SliceIdxs = dyn_cast<ListInit>(RHS);
1326 if (!TheList || !SliceIdxs)
1327 break;
1329 Args.reserve(SliceIdxs->size());
1330 for (auto *I : *SliceIdxs) {
1331 auto *II = dyn_cast<IntInit>(I);
1332 if (!II)
1333 goto unresolved;
1334 auto i = II->getValue();
1335 if (i < 0 || i >= (ssize_t)TheList->size())
1336 goto unresolved;
1337 Args.push_back(TheList->getElement(i));
1338 }
1339 return ListInit::get(Args, TheList->getElementType());
1340 }
1341 case RANGEC: {
1342 const auto *LHSi = dyn_cast<IntInit>(LHS);
1343 const auto *RHSi = dyn_cast<IntInit>(RHS);
1344 if (!LHSi || !RHSi)
1345 break;
1346
1347 int64_t Start = LHSi->getValue();
1348 int64_t End = RHSi->getValue();
1350 if (getOpcode() == RANGEC) {
1351 // Closed interval
1352 if (Start <= End) {
1353 // Ascending order
1354 Args.reserve(End - Start + 1);
1355 for (auto i = Start; i <= End; ++i)
1356 Args.push_back(IntInit::get(getRecordKeeper(), i));
1357 } else {
1358 // Descending order
1359 Args.reserve(Start - End + 1);
1360 for (auto i = Start; i >= End; --i)
1361 Args.push_back(IntInit::get(getRecordKeeper(), i));
1362 }
1363 } else if (Start < End) {
1364 // Half-open interval (excludes `End`)
1365 Args.reserve(End - Start);
1366 for (auto i = Start; i < End; ++i)
1367 Args.push_back(IntInit::get(getRecordKeeper(), i));
1368 } else {
1369 // Empty set
1370 }
1371 return ListInit::get(Args, LHSi->getType());
1372 }
1373 case STRCONCAT: {
1374 const auto *LHSs = dyn_cast<StringInit>(LHS);
1375 const auto *RHSs = dyn_cast<StringInit>(RHS);
1376 if (LHSs && RHSs)
1377 return ConcatStringInits(LHSs, RHSs);
1378 break;
1379 }
1380 case INTERLEAVE: {
1381 const auto *List = dyn_cast<ListInit>(LHS);
1382 const auto *Delim = dyn_cast<StringInit>(RHS);
1383 if (List && Delim) {
1384 const StringInit *Result;
1385 if (isa<StringRecTy>(List->getElementType()))
1386 Result = interleaveStringList(List, Delim);
1387 else
1388 Result = interleaveIntList(List, Delim);
1389 if (Result)
1390 return Result;
1391 }
1392 break;
1393 }
1394 case EQ:
1395 case NE:
1396 case LE:
1397 case LT:
1398 case GE:
1399 case GT: {
1400 if (std::optional<bool> Result = CompareInit(getOpcode(), LHS, RHS))
1401 return BitInit::get(getRecordKeeper(), *Result);
1402 break;
1403 }
1404 case GETDAGARG: {
1405 const auto *Dag = dyn_cast<DagInit>(LHS);
1406 if (Dag && isa<IntInit, StringInit>(RHS)) {
1407 std::string Error;
1408 auto ArgNo = getDagArgNoByKey(Dag, RHS, Error);
1409 if (!ArgNo)
1410 PrintFatalError(CurRec->getLoc(), "!getdagarg " + Error);
1411
1412 assert(*ArgNo < Dag->getNumArgs());
1413
1414 const Init *Arg = Dag->getArg(*ArgNo);
1415 if (const auto *TI = dyn_cast<TypedInit>(Arg))
1416 if (!TI->getType()->typeIsConvertibleTo(getType()))
1417 return UnsetInit::get(Dag->getRecordKeeper());
1418 return Arg;
1419 }
1420 break;
1421 }
1422 case GETDAGNAME: {
1423 const auto *Dag = dyn_cast<DagInit>(LHS);
1424 const auto *Idx = dyn_cast<IntInit>(RHS);
1425 if (Dag && Idx) {
1426 int64_t Pos = Idx->getValue();
1427 if (Pos < 0 || Pos >= Dag->getNumArgs()) {
1428 // The index is out-of-range.
1429 PrintError(CurRec->getLoc(),
1430 Twine("!getdagname index is out of range 0...") +
1431 std::to_string(Dag->getNumArgs() - 1) + ": " +
1432 std::to_string(Pos));
1433 }
1434 const Init *ArgName = Dag->getArgName(Pos);
1435 if (!ArgName)
1437 return ArgName;
1438 }
1439 break;
1440 }
1441 case SETDAGOP: {
1442 const auto *Dag = dyn_cast<DagInit>(LHS);
1443 const auto *Op = dyn_cast<DefInit>(RHS);
1444 if (Dag && Op)
1445 return DagInit::get(Op, Dag->getArgs(), Dag->getArgNames());
1446 break;
1447 }
1448 case SETDAGOPNAME: {
1449 const auto *Dag = dyn_cast<DagInit>(LHS);
1450 const auto *Op = dyn_cast<StringInit>(RHS);
1451 if (Dag && Op)
1452 return DagInit::get(Dag->getOperator(), Op, Dag->getArgs(),
1453 Dag->getArgNames());
1454 break;
1455 }
1456 case ADD:
1457 case SUB:
1458 case MUL:
1459 case DIV:
1460 case AND:
1461 case OR:
1462 case XOR:
1463 case SHL:
1464 case SRA:
1465 case SRL: {
1466 const auto *LHSi = dyn_cast_or_null<IntInit>(
1467 LHS->convertInitializerTo(IntRecTy::get(getRecordKeeper())));
1468 const auto *RHSi = dyn_cast_or_null<IntInit>(
1469 RHS->convertInitializerTo(IntRecTy::get(getRecordKeeper())));
1470 if (LHSi && RHSi) {
1471 int64_t LHSv = LHSi->getValue(), RHSv = RHSi->getValue();
1472 int64_t Result;
1473 switch (getOpcode()) {
1474 default: llvm_unreachable("Bad opcode!");
1475 case ADD: Result = LHSv + RHSv; break;
1476 case SUB: Result = LHSv - RHSv; break;
1477 case MUL: Result = LHSv * RHSv; break;
1478 case DIV:
1479 if (RHSv == 0)
1480 PrintFatalError(CurRec->getLoc(),
1481 "Illegal operation: division by zero");
1482 else if (LHSv == INT64_MIN && RHSv == -1)
1483 PrintFatalError(CurRec->getLoc(),
1484 "Illegal operation: INT64_MIN / -1");
1485 else
1486 Result = LHSv / RHSv;
1487 break;
1488 case AND: Result = LHSv & RHSv; break;
1489 case OR: Result = LHSv | RHSv; break;
1490 case XOR: Result = LHSv ^ RHSv; break;
1491 case SHL:
1492 if (RHSv < 0 || RHSv >= 64)
1493 PrintFatalError(CurRec->getLoc(),
1494 "Illegal operation: out of bounds shift");
1495 Result = (uint64_t)LHSv << (uint64_t)RHSv;
1496 break;
1497 case SRA:
1498 if (RHSv < 0 || RHSv >= 64)
1499 PrintFatalError(CurRec->getLoc(),
1500 "Illegal operation: out of bounds shift");
1501 Result = LHSv >> (uint64_t)RHSv;
1502 break;
1503 case SRL:
1504 if (RHSv < 0 || RHSv >= 64)
1505 PrintFatalError(CurRec->getLoc(),
1506 "Illegal operation: out of bounds shift");
1507 Result = (uint64_t)LHSv >> (uint64_t)RHSv;
1508 break;
1509 }
1510 return IntInit::get(getRecordKeeper(), Result);
1511 }
1512 break;
1513 }
1514 }
1515unresolved:
1516 return this;
1517}
1518
1520 const Init *NewLHS = LHS->resolveReferences(R);
1521
1522 unsigned Opc = getOpcode();
1523 if (Opc == AND || Opc == OR) {
1524 // Short-circuit. Regardless whether this is a logical or bitwise
1525 // AND/OR.
1526 // Ideally we could also short-circuit `!or(true, ...)`, but it's
1527 // difficult to do it right without knowing if rest of the operands
1528 // are all `bit` or not. Therefore, we're only implementing a relatively
1529 // limited version of short-circuit against all ones (`true` is casted
1530 // to 1 rather than all ones before we evaluate `!or`).
1531 if (const auto *LHSi = dyn_cast_or_null<IntInit>(
1533 if ((Opc == AND && !LHSi->getValue()) ||
1534 (Opc == OR && LHSi->getValue() == -1))
1535 return LHSi;
1536 }
1537 }
1538
1539 const Init *NewRHS = RHS->resolveReferences(R);
1540
1541 if (LHS != NewLHS || RHS != NewRHS)
1542 return (BinOpInit::get(getOpcode(), NewLHS, NewRHS, getType()))
1543 ->Fold(R.getCurrentRecord());
1544 return this;
1545}
1546
1547std::string BinOpInit::getAsString() const {
1548 std::string Result;
1549 switch (getOpcode()) {
1550 case LISTELEM:
1551 case LISTSLICE:
1552 return LHS->getAsString() + "[" + RHS->getAsString() + "]";
1553 case RANGEC:
1554 return LHS->getAsString() + "..." + RHS->getAsString();
1555 case CONCAT: Result = "!con"; break;
1556 case MATCH:
1557 Result = "!match";
1558 break;
1559 case ADD: Result = "!add"; break;
1560 case SUB: Result = "!sub"; break;
1561 case MUL: Result = "!mul"; break;
1562 case DIV: Result = "!div"; break;
1563 case AND: Result = "!and"; break;
1564 case OR: Result = "!or"; break;
1565 case XOR: Result = "!xor"; break;
1566 case SHL: Result = "!shl"; break;
1567 case SRA: Result = "!sra"; break;
1568 case SRL: Result = "!srl"; break;
1569 case EQ: Result = "!eq"; break;
1570 case NE: Result = "!ne"; break;
1571 case LE: Result = "!le"; break;
1572 case LT: Result = "!lt"; break;
1573 case GE: Result = "!ge"; break;
1574 case GT: Result = "!gt"; break;
1575 case LISTCONCAT: Result = "!listconcat"; break;
1576 case LISTSPLAT: Result = "!listsplat"; break;
1577 case LISTREMOVE:
1578 Result = "!listremove";
1579 break;
1580 case STRCONCAT: Result = "!strconcat"; break;
1581 case INTERLEAVE: Result = "!interleave"; break;
1582 case SETDAGOP: Result = "!setdagop"; break;
1583 case SETDAGOPNAME:
1584 Result = "!setdagopname";
1585 break;
1586 case GETDAGARG:
1587 Result = "!getdagarg<" + getType()->getAsString() + ">";
1588 break;
1589 case GETDAGNAME:
1590 Result = "!getdagname";
1591 break;
1592 }
1593 return Result + "(" + LHS->getAsString() + ", " + RHS->getAsString() + ")";
1594}
1595
1596const TernOpInit *TernOpInit::get(TernaryOp Opc, const Init *LHS,
1597 const Init *MHS, const Init *RHS,
1598 const RecTy *Type) {
1599 detail::RecordKeeperImpl &RK = LHS->getRecordKeeper().getImpl();
1601 if (TernOpInit *I =
1602 RK.TheTernOpInitPool.lookup({Opc, LHS, MHS, RHS, Type}, Token))
1603 return I;
1604
1605 TernOpInit *I = new (RK.Allocator) TernOpInit(Opc, LHS, MHS, RHS, Type);
1606 RK.TheTernOpInitPool.insert(I, Token);
1607 return I;
1608}
1609
1610static const Init *ItemApply(const Init *LHS, const Init *MHSe, const Init *RHS,
1611 const Record *CurRec) {
1612 MapResolver R(CurRec);
1613 R.set(LHS, MHSe);
1614 return RHS->resolveReferences(R);
1615}
1616
1617static const Init *ForeachDagApply(const Init *LHS, const DagInit *MHSd,
1618 const Init *RHS, const Record *CurRec) {
1619 bool Change = false;
1620 const Init *Val = ItemApply(LHS, MHSd->getOperator(), RHS, CurRec);
1621 if (Val != MHSd->getOperator())
1622 Change = true;
1623
1625 for (auto [Arg, ArgName] : MHSd->getArgAndNames()) {
1626 const Init *NewArg;
1627
1628 if (const auto *Argd = dyn_cast<DagInit>(Arg))
1629 NewArg = ForeachDagApply(LHS, Argd, RHS, CurRec);
1630 else
1631 NewArg = ItemApply(LHS, Arg, RHS, CurRec);
1632
1633 NewArgs.emplace_back(NewArg, ArgName);
1634 if (Arg != NewArg)
1635 Change = true;
1636 }
1637
1638 if (Change)
1639 return DagInit::get(Val, MHSd->getName(), NewArgs);
1640 return MHSd;
1641}
1642
1643// Applies RHS to all elements of MHS, using LHS as a temp variable.
1644static const Init *ForeachHelper(const Init *LHS, const Init *MHS,
1645 const Init *RHS, const RecTy *Type,
1646 const Record *CurRec) {
1647 if (const auto *MHSd = dyn_cast<DagInit>(MHS))
1648 return ForeachDagApply(LHS, MHSd, RHS, CurRec);
1649
1650 if (const auto *MHSl = dyn_cast<ListInit>(MHS)) {
1651 SmallVector<const Init *, 8> NewList(MHSl->begin(), MHSl->end());
1652
1653 for (const Init *&Item : NewList) {
1654 const Init *NewItem = ItemApply(LHS, Item, RHS, CurRec);
1655 if (NewItem != Item)
1656 Item = NewItem;
1657 }
1658 return ListInit::get(NewList, cast<ListRecTy>(Type)->getElementType());
1659 }
1660
1661 return nullptr;
1662}
1663
1664// Evaluates RHS for all elements of MHS, using LHS as a temp variable.
1665// Creates a new list with the elements that evaluated to true.
1666static const Init *FilterHelper(const Init *LHS, const Init *MHS,
1667 const Init *RHS, const RecTy *Type,
1668 const Record *CurRec) {
1669 if (const auto *MHSl = dyn_cast<ListInit>(MHS)) {
1671
1672 for (const Init *Item : MHSl->getElements()) {
1673 const Init *Include = ItemApply(LHS, Item, RHS, CurRec);
1674 if (!Include)
1675 return nullptr;
1676 if (const auto *IncludeInt =
1677 dyn_cast_or_null<IntInit>(Include->convertInitializerTo(
1678 IntRecTy::get(LHS->getRecordKeeper())))) {
1679 if (IncludeInt->getValue())
1680 NewList.push_back(Item);
1681 } else {
1682 return nullptr;
1683 }
1684 }
1685 return ListInit::get(NewList, cast<ListRecTy>(Type)->getElementType());
1686 }
1687
1688 return nullptr;
1689}
1690
1691static const Init *SortHelper(const Init *LHS, const Init *MHS, const Init *RHS,
1692 const RecTy *Type, const Record *CurRec) {
1693 const auto *MHSl = dyn_cast<ListInit>(MHS);
1694 if (!MHSl)
1695 return nullptr;
1696
1697 RecordKeeper &RK = LHS->getRecordKeeper();
1698 using KV = std::pair<const Init *, const Init *>;
1699 SmallVector<KV, 8> KeyedList;
1700
1701 for (const Init *Item : MHSl->getElements()) {
1702 const Init *Key = ItemApply(LHS, Item, RHS, CurRec);
1703 if (!Key)
1704 return nullptr;
1705 KeyedList.emplace_back(Key, Item);
1706 }
1707
1708 if (KeyedList.empty())
1709 return ListInit::get({}, cast<ListRecTy>(Type)->getElementType());
1710
1711 // Determine key type from the first element; all keys must agree.
1712 bool UseInt =
1713 dyn_cast_or_null<IntInit>(KeyedList[0].first->convertInitializerTo(
1714 IntRecTy::get(RK))) != nullptr;
1715 for (auto &[Key, Item] : KeyedList) {
1716 if (UseInt) {
1718 Key->convertInitializerTo(IntRecTy::get(RK))))
1719 return nullptr;
1720 } else {
1721 if (!isa<StringInit>(Key))
1722 return nullptr;
1723 }
1724 }
1725
1726 llvm::stable_sort(KeyedList, [&RK, UseInt](const KV &A, const KV &B) {
1727 if (UseInt)
1728 return cast<IntInit>(A.first->convertInitializerTo(IntRecTy::get(RK)))
1729 ->getValue() <
1730 cast<IntInit>(B.first->convertInitializerTo(IntRecTy::get(RK)))
1731 ->getValue();
1732 return cast<StringInit>(A.first)->getValue() <
1733 cast<StringInit>(B.first)->getValue();
1734 });
1735
1737 for (auto &[Key, Item] : KeyedList)
1738 Result.push_back(Item);
1739 return ListInit::get(Result, cast<ListRecTy>(Type)->getElementType());
1740}
1741
1742const Init *TernOpInit::Fold(const Record *CurRec) const {
1744 switch (getOpcode()) {
1745 case SUBST: {
1746 const auto *LHSd = dyn_cast<DefInit>(LHS);
1747 const auto *LHSv = dyn_cast<VarInit>(LHS);
1748 const auto *LHSs = dyn_cast<StringInit>(LHS);
1749
1750 const auto *MHSd = dyn_cast<DefInit>(MHS);
1751 const auto *MHSv = dyn_cast<VarInit>(MHS);
1752 const auto *MHSs = dyn_cast<StringInit>(MHS);
1753
1754 const auto *RHSd = dyn_cast<DefInit>(RHS);
1755 const auto *RHSv = dyn_cast<VarInit>(RHS);
1756 const auto *RHSs = dyn_cast<StringInit>(RHS);
1757
1758 if (LHSd && MHSd && RHSd) {
1759 const Record *Val = RHSd->getDef();
1760 if (LHSd->getAsString() == RHSd->getAsString())
1761 Val = MHSd->getDef();
1762 return Val->getDefInit();
1763 }
1764 if (LHSv && MHSv && RHSv) {
1765 std::string Val = RHSv->getName().str();
1766 if (LHSv->getAsString() == RHSv->getAsString())
1767 Val = MHSv->getName().str();
1768 return VarInit::get(Val, getType());
1769 }
1770 if (LHSs && MHSs && RHSs) {
1771 std::string Val = RHSs->getValue().str();
1772
1773 std::string::size_type Idx = 0;
1774 while (true) {
1775 std::string::size_type Found = Val.find(LHSs->getValue(), Idx);
1776 if (Found == std::string::npos)
1777 break;
1778 Val.replace(Found, LHSs->getValue().size(), MHSs->getValue().str());
1779 Idx = Found + MHSs->getValue().size();
1780 }
1781
1782 return StringInit::get(RK, Val);
1783 }
1784 break;
1785 }
1786
1787 case FOREACH: {
1788 if (const Init *Result = ForeachHelper(LHS, MHS, RHS, getType(), CurRec))
1789 return Result;
1790 break;
1791 }
1792
1793 case FILTER: {
1794 if (const Init *Result = FilterHelper(LHS, MHS, RHS, getType(), CurRec))
1795 return Result;
1796 break;
1797 }
1798
1799 case SORT: {
1800 if (const Init *Result = SortHelper(LHS, MHS, RHS, getType(), CurRec))
1801 return Result;
1802 break;
1803 }
1804
1805 case IF: {
1806 if (const auto *LHSi = dyn_cast_or_null<IntInit>(
1807 LHS->convertInitializerTo(IntRecTy::get(RK)))) {
1808 if (LHSi->getValue())
1809 return MHS;
1810 return RHS;
1811 }
1812 break;
1813 }
1814
1815 case DAG: {
1816 const auto *MHSl = dyn_cast<ListInit>(MHS);
1817 const auto *RHSl = dyn_cast<ListInit>(RHS);
1818 bool MHSok = MHSl || isa<UnsetInit>(MHS);
1819 bool RHSok = RHSl || isa<UnsetInit>(RHS);
1820
1821 if (isa<UnsetInit>(MHS) && isa<UnsetInit>(RHS))
1822 break; // Typically prevented by the parser, but might happen with template args
1823
1824 if (MHSok && RHSok && (!MHSl || !RHSl || MHSl->size() == RHSl->size())) {
1826 unsigned Size = MHSl ? MHSl->size() : RHSl->size();
1827 for (unsigned i = 0; i != Size; ++i) {
1828 const Init *Node = MHSl ? MHSl->getElement(i) : UnsetInit::get(RK);
1829 const Init *Name = RHSl ? RHSl->getElement(i) : UnsetInit::get(RK);
1830 if (!isa<StringInit>(Name) && !isa<UnsetInit>(Name))
1831 return this;
1832 Children.emplace_back(Node, dyn_cast<StringInit>(Name));
1833 }
1834 return DagInit::get(LHS, Children);
1835 }
1836 break;
1837 }
1838
1839 case RANGE: {
1840 const auto *LHSi = dyn_cast<IntInit>(LHS);
1841 const auto *MHSi = dyn_cast<IntInit>(MHS);
1842 const auto *RHSi = dyn_cast<IntInit>(RHS);
1843 if (!LHSi || !MHSi || !RHSi)
1844 break;
1845
1846 auto Start = LHSi->getValue();
1847 auto End = MHSi->getValue();
1848 auto Step = RHSi->getValue();
1849 if (Step == 0)
1850 PrintError(CurRec->getLoc(), "Step of !range can't be 0");
1851
1853 if (Start < End && Step > 0) {
1854 Args.reserve((End - Start) / Step);
1855 for (auto I = Start; I < End; I += Step)
1856 Args.push_back(IntInit::get(getRecordKeeper(), I));
1857 } else if (Start > End && Step < 0) {
1858 Args.reserve((Start - End) / -Step);
1859 for (auto I = Start; I > End; I += Step)
1860 Args.push_back(IntInit::get(getRecordKeeper(), I));
1861 } else {
1862 // Empty set
1863 }
1864 return ListInit::get(Args, LHSi->getType());
1865 }
1866
1867 case SUBSTR: {
1868 const auto *LHSs = dyn_cast<StringInit>(LHS);
1869 const auto *MHSi = dyn_cast<IntInit>(MHS);
1870 const auto *RHSi = dyn_cast<IntInit>(RHS);
1871 if (LHSs && MHSi && RHSi) {
1872 int64_t StringSize = LHSs->getValue().size();
1873 int64_t Start = MHSi->getValue();
1874 int64_t Length = RHSi->getValue();
1875 if (Start < 0 || Start > StringSize)
1876 PrintError(CurRec->getLoc(),
1877 Twine("!substr start position is out of range 0...") +
1878 std::to_string(StringSize) + ": " +
1879 std::to_string(Start));
1880 if (Length < 0)
1881 PrintError(CurRec->getLoc(), "!substr length must be nonnegative");
1882 return StringInit::get(RK, LHSs->getValue().substr(Start, Length),
1883 LHSs->getFormat());
1884 }
1885 break;
1886 }
1887
1888 case FIND: {
1889 const auto *LHSs = dyn_cast<StringInit>(LHS);
1890 const auto *MHSs = dyn_cast<StringInit>(MHS);
1891 const auto *RHSi = dyn_cast<IntInit>(RHS);
1892 if (LHSs && MHSs && RHSi) {
1893 int64_t SourceSize = LHSs->getValue().size();
1894 int64_t Start = RHSi->getValue();
1895 if (Start < 0 || Start > SourceSize)
1896 PrintError(CurRec->getLoc(),
1897 Twine("!find start position is out of range 0...") +
1898 std::to_string(SourceSize) + ": " +
1899 std::to_string(Start));
1900 auto I = LHSs->getValue().find(MHSs->getValue(), Start);
1901 if (I == std::string::npos)
1902 return IntInit::get(RK, -1);
1903 return IntInit::get(RK, I);
1904 }
1905 break;
1906 }
1907
1908 case SETDAGARG: {
1909 const auto *Dag = dyn_cast<DagInit>(LHS);
1910 if (Dag && isa<IntInit, StringInit>(MHS)) {
1911 std::string Error;
1912 auto ArgNo = getDagArgNoByKey(Dag, MHS, Error);
1913 if (!ArgNo)
1914 PrintFatalError(CurRec->getLoc(), "!setdagarg " + Error);
1915
1916 assert(*ArgNo < Dag->getNumArgs());
1917
1918 SmallVector<const Init *, 8> Args(Dag->getArgs());
1919 Args[*ArgNo] = RHS;
1920 return DagInit::get(Dag->getOperator(), Dag->getName(), Args,
1921 Dag->getArgNames());
1922 }
1923 break;
1924 }
1925
1926 case SETDAGNAME: {
1927 const auto *Dag = dyn_cast<DagInit>(LHS);
1928 if (Dag && isa<IntInit, StringInit>(MHS)) {
1929 std::string Error;
1930 auto ArgNo = getDagArgNoByKey(Dag, MHS, Error);
1931 if (!ArgNo)
1932 PrintFatalError(CurRec->getLoc(), "!setdagname " + Error);
1933
1934 assert(*ArgNo < Dag->getNumArgs());
1935
1936 SmallVector<const StringInit *, 8> Names(Dag->getArgNames());
1937 Names[*ArgNo] = dyn_cast<StringInit>(RHS);
1938 return DagInit::get(Dag->getOperator(), Dag->getName(), Dag->getArgs(),
1939 Names);
1940 }
1941 break;
1942 }
1943 }
1944
1945 return this;
1946}
1947
1949 const Init *lhs = LHS->resolveReferences(R);
1950
1951 if (getOpcode() == IF && lhs != LHS) {
1952 if (const auto *Value = dyn_cast_or_null<IntInit>(
1954 // Short-circuit
1955 if (Value->getValue())
1956 return MHS->resolveReferences(R);
1957 return RHS->resolveReferences(R);
1958 }
1959 }
1960
1961 const Init *mhs = MHS->resolveReferences(R);
1962 const Init *rhs;
1963
1964 if (getOpcode() == FOREACH || getOpcode() == FILTER || getOpcode() == SORT) {
1965 ShadowResolver SR(R);
1966 SR.addShadow(lhs);
1967 rhs = RHS->resolveReferences(SR);
1968 } else {
1969 rhs = RHS->resolveReferences(R);
1970 }
1971
1972 if (LHS != lhs || MHS != mhs || RHS != rhs)
1973 return (TernOpInit::get(getOpcode(), lhs, mhs, rhs, getType()))
1974 ->Fold(R.getCurrentRecord());
1975 return this;
1976}
1977
1978std::string TernOpInit::getAsString() const {
1979 std::string Result;
1980 bool UnquotedLHS = false;
1981 switch (getOpcode()) {
1982 case DAG: Result = "!dag"; break;
1983 case FILTER: Result = "!filter"; UnquotedLHS = true; break;
1984 case FOREACH: Result = "!foreach"; UnquotedLHS = true; break;
1985 case SORT:
1986 Result = "!sort";
1987 UnquotedLHS = true;
1988 break;
1989 case IF: Result = "!if"; break;
1990 case RANGE:
1991 Result = "!range";
1992 break;
1993 case SUBST: Result = "!subst"; break;
1994 case SUBSTR: Result = "!substr"; break;
1995 case FIND: Result = "!find"; break;
1996 case SETDAGARG:
1997 Result = "!setdagarg";
1998 break;
1999 case SETDAGNAME:
2000 Result = "!setdagname";
2001 break;
2002 }
2003 return (Result + "(" +
2004 (UnquotedLHS ? LHS->getAsUnquotedString() : LHS->getAsString()) +
2005 ", " + MHS->getAsString() + ", " + RHS->getAsString() + ")");
2006}
2007
2008const FoldOpInit *FoldOpInit::get(const Init *Start, const Init *List,
2009 const Init *A, const Init *B,
2010 const Init *Expr, const RecTy *Type) {
2011 detail::RecordKeeperImpl &RK = Start->getRecordKeeper().getImpl();
2013 if (const FoldOpInit *I =
2014 RK.TheFoldOpInitPool.lookup({Start, List, A, B, Expr, Type}, Token))
2015 return I;
2016
2017 FoldOpInit *I = new (RK.Allocator) FoldOpInit(Start, List, A, B, Expr, Type);
2018 RK.TheFoldOpInitPool.insert(I, Token);
2019 return I;
2020}
2021
2022const Init *FoldOpInit::Fold(const Record *CurRec) const {
2023 if (const auto *LI = dyn_cast<ListInit>(List)) {
2024 const Init *Accum = Start;
2025 for (const Init *Elt : *LI) {
2026 MapResolver R(CurRec);
2027 R.set(A, Accum);
2028 R.set(B, Elt);
2029 Accum = Expr->resolveReferences(R);
2030 }
2031 return Accum;
2032 }
2033 return this;
2034}
2035
2037 const Init *NewStart = Start->resolveReferences(R);
2038 const Init *NewList = List->resolveReferences(R);
2039 ShadowResolver SR(R);
2040 SR.addShadow(A);
2041 SR.addShadow(B);
2042 const Init *NewExpr = Expr->resolveReferences(SR);
2043
2044 if (Start == NewStart && List == NewList && Expr == NewExpr)
2045 return this;
2046
2047 return get(NewStart, NewList, A, B, NewExpr, getType())
2048 ->Fold(R.getCurrentRecord());
2049}
2050
2051const Init *FoldOpInit::getBit(unsigned Bit) const {
2052 if (isa<BitRecTy>(getType()))
2053 return this;
2054 return VarBitInit::get(this, Bit);
2055}
2056
2057std::string FoldOpInit::getAsString() const {
2058 return (Twine("!foldl(") + Start->getAsString() + ", " + List->getAsString() +
2059 ", " + A->getAsUnquotedString() + ", " + B->getAsUnquotedString() +
2060 ", " + Expr->getAsString() + ")")
2061 .str();
2062}
2063
2064const IsAOpInit *IsAOpInit::get(const RecTy *CheckType, const Init *Expr) {
2065
2066 detail::RecordKeeperImpl &RK = Expr->getRecordKeeper().getImpl();
2068 if (const IsAOpInit *I = RK.TheIsAOpInitPool.lookup({CheckType, Expr}, Token))
2069 return I;
2070
2071 IsAOpInit *I = new (RK.Allocator) IsAOpInit(CheckType, Expr);
2072 RK.TheIsAOpInitPool.insert(I, Token);
2073 return I;
2074}
2075
2076const Init *IsAOpInit::Fold() const {
2077 if (const auto *TI = dyn_cast<TypedInit>(Expr)) {
2078 // Is the expression type known to be (a subclass of) the desired type?
2079 if (TI->getType()->typeIsConvertibleTo(CheckType))
2080 return IntInit::get(getRecordKeeper(), 1);
2081
2082 if (isa<RecordRecTy>(CheckType)) {
2083 // If the target type is not a subclass of the expression type once the
2084 // expression has been made concrete, or if the expression has fully
2085 // resolved to a record, we know that it can't be of the required type.
2086 if ((!CheckType->typeIsConvertibleTo(TI->getType()) &&
2087 Expr->isConcrete()) ||
2088 isa<DefInit>(Expr))
2089 return IntInit::get(getRecordKeeper(), 0);
2090 } else {
2091 // We treat non-record types as not castable.
2092 return IntInit::get(getRecordKeeper(), 0);
2093 }
2094 }
2095 return this;
2096}
2097
2099 const Init *NewExpr = Expr->resolveReferences(R);
2100 if (Expr != NewExpr)
2101 return get(CheckType, NewExpr)->Fold();
2102 return this;
2103}
2104
2105const Init *IsAOpInit::getBit(unsigned Bit) const {
2106 return VarBitInit::get(this, Bit);
2107}
2108
2109std::string IsAOpInit::getAsString() const {
2110 return (Twine("!isa<") + CheckType->getAsString() + ">(" +
2111 Expr->getAsString() + ")")
2112 .str();
2113}
2114
2115const ExistsOpInit *ExistsOpInit::get(const RecTy *CheckType,
2116 const Init *Expr) {
2117 detail::RecordKeeperImpl &RK = Expr->getRecordKeeper().getImpl();
2119 if (const ExistsOpInit *I =
2120 RK.TheExistsOpInitPool.lookup({CheckType, Expr}, Token))
2121 return I;
2122
2123 ExistsOpInit *I = new (RK.Allocator) ExistsOpInit(CheckType, Expr);
2124 RK.TheExistsOpInitPool.insert(I, Token);
2125 return I;
2126}
2127
2128const Init *ExistsOpInit::Fold(const Record *CurRec, bool IsFinal) const {
2129 if (const auto *Name = dyn_cast<StringInit>(Expr)) {
2130 // Look up all defined records to see if we can find one.
2131 const Record *D = CheckType->getRecordKeeper().getDef(Name->getValue());
2132 if (D) {
2133 // Check if types are compatible.
2135 D->getDefInit()->getType()->typeIsA(CheckType));
2136 }
2137
2138 if (CurRec) {
2139 // Self-references are allowed, but their resolution is delayed until
2140 // the final resolve to ensure that we get the correct type for them.
2141 auto *Anonymous = dyn_cast<AnonymousNameInit>(CurRec->getNameInit());
2142 if (Name == CurRec->getNameInit() ||
2143 (Anonymous && Name == Anonymous->getNameInit())) {
2144 if (!IsFinal)
2145 return this;
2146
2147 // No doubt that there exists a record, so we should check if types are
2148 // compatible.
2150 CurRec->getType()->typeIsA(CheckType));
2151 }
2152 }
2153
2154 if (IsFinal)
2155 return IntInit::get(getRecordKeeper(), 0);
2156 }
2157 return this;
2158}
2159
2161 const Init *NewExpr = Expr->resolveReferences(R);
2162 if (Expr != NewExpr || R.isFinal())
2163 return get(CheckType, NewExpr)->Fold(R.getCurrentRecord(), R.isFinal());
2164 return this;
2165}
2166
2167const Init *ExistsOpInit::getBit(unsigned Bit) const {
2168 return VarBitInit::get(this, Bit);
2169}
2170
2171std::string ExistsOpInit::getAsString() const {
2172 return (Twine("!exists<") + CheckType->getAsString() + ">(" +
2173 Expr->getAsString() + ")")
2174 .str();
2175}
2176
2177const InstancesOpInit *InstancesOpInit::get(const RecTy *Type,
2178 const Init *Regex) {
2179 detail::RecordKeeperImpl &RK = Regex->getRecordKeeper().getImpl();
2181 if (const InstancesOpInit *I =
2182 RK.TheInstancesOpInitPool.lookup({Type, Regex}, Token))
2183 return I;
2184
2185 InstancesOpInit *I = new (RK.Allocator) InstancesOpInit(Type, Regex);
2186 RK.TheInstancesOpInitPool.insert(I, Token);
2187 return I;
2188}
2189
2190const Init *InstancesOpInit::Fold(const Record *CurRec, bool IsFinal) const {
2191 if (CurRec && !IsFinal)
2192 return this;
2193
2194 const auto *RegexInit = dyn_cast<StringInit>(Regex);
2195 if (!RegexInit)
2196 return this;
2197
2198 StringRef RegexStr = RegexInit->getValue();
2199 llvm::Regex Matcher(RegexStr);
2200 if (!Matcher.isValid())
2201 PrintFatalError(Twine("invalid regex '") + RegexStr + Twine("'"));
2202
2203 const RecordKeeper &RK = Type->getRecordKeeper();
2204 SmallVector<Init *, 8> Selected;
2205 for (auto &Def : RK.getAllDerivedDefinitionsIfDefined(Type->getAsString()))
2206 if (Matcher.match(Def->getName()))
2207 Selected.push_back(Def->getDefInit());
2208
2209 return ListInit::get(Selected, Type);
2210}
2211
2213 const Init *NewRegex = Regex->resolveReferences(R);
2214 if (Regex != NewRegex || R.isFinal())
2215 return get(Type, NewRegex)->Fold(R.getCurrentRecord(), R.isFinal());
2216 return this;
2217}
2218
2219std::string InstancesOpInit::getAsString() const {
2220 return "!instances<" + Type->getAsString() + ">(" + Regex->getAsString() +
2221 ")";
2222}
2223
2224const RecTy *TypedInit::getFieldType(const StringInit *FieldName) const {
2225 if (const auto *RecordType = dyn_cast<RecordRecTy>(getType())) {
2226 for (const Record *Rec : RecordType->getClasses()) {
2227 if (const RecordVal *Field = Rec->getValue(FieldName))
2228 return Field->getType();
2229 }
2230 }
2231 return nullptr;
2232}
2233
2235 if (getType()->typeIsA(Ty))
2236 return this;
2237
2238 if (isa<BitRecTy>(getType()) && isa<BitsRecTy>(Ty) &&
2239 cast<BitsRecTy>(Ty)->getNumBits() == 1)
2240 return BitsInit::get(getRecordKeeper(), {this});
2241
2242 return nullptr;
2243}
2244
2245const Init *
2247 const auto *T = dyn_cast<BitsRecTy>(getType());
2248 if (!T) return nullptr; // Cannot subscript a non-bits variable.
2249 unsigned NumBits = T->getNumBits();
2250
2252 NewBits.reserve(Bits.size());
2253 for (unsigned Bit : Bits) {
2254 if (Bit >= NumBits)
2255 return nullptr;
2256
2257 NewBits.push_back(VarBitInit::get(this, Bit));
2258 }
2259 return BitsInit::get(getRecordKeeper(), NewBits);
2260}
2261
2262const Init *TypedInit::getCastTo(const RecTy *Ty) const {
2263 // Handle the common case quickly
2264 if (getType()->typeIsA(Ty))
2265 return this;
2266
2267 if (const Init *Converted = convertInitializerTo(Ty)) {
2268 assert(!isa<TypedInit>(Converted) ||
2269 cast<TypedInit>(Converted)->getType()->typeIsA(Ty));
2270 return Converted;
2271 }
2272
2273 if (!getType()->typeIsConvertibleTo(Ty))
2274 return nullptr;
2275
2276 return UnOpInit::get(UnOpInit::CAST, this, Ty)->Fold(nullptr);
2277}
2278
2279const VarInit *VarInit::get(StringRef VN, const RecTy *T) {
2280 const Init *Value = StringInit::get(T->getRecordKeeper(), VN);
2281 return VarInit::get(Value, T);
2282}
2283
2284const VarInit *VarInit::get(const Init *VN, const RecTy *T) {
2285 detail::RecordKeeperImpl &RK = T->getRecordKeeper().getImpl();
2286 VarInit *&I = RK.TheVarInitPool[{T, VN}];
2287 if (!I)
2288 I = new (RK.Allocator) VarInit(VN, T);
2289 return I;
2290}
2291
2293 const auto *NameString = cast<StringInit>(getNameInit());
2294 return NameString->getValue();
2295}
2296
2297const Init *VarInit::getBit(unsigned Bit) const {
2298 if (isa<BitRecTy>(getType()))
2299 return this;
2300 return VarBitInit::get(this, Bit);
2301}
2302
2304 if (const Init *Val = R.resolve(VarName))
2305 return Val;
2306 return this;
2307}
2308
2309const VarBitInit *VarBitInit::get(const TypedInit *T, unsigned B) {
2310 detail::RecordKeeperImpl &RK = T->getRecordKeeper().getImpl();
2311 VarBitInit *&I = RK.TheVarBitInitPool[{T, B}];
2312 if (!I)
2313 I = new (RK.Allocator) VarBitInit(T, B);
2314 return I;
2315}
2316
2317std::string VarBitInit::getAsString() const {
2318 return TI->getAsString() + "{" + utostr(Bit) + "}";
2319}
2320
2322 const Init *I = TI->resolveReferences(R);
2323 if (TI != I)
2324 return I->getBit(getBitNum());
2325
2326 return this;
2327}
2328
2329DefInit::DefInit(const Record *D)
2330 : TypedInit(IK_DefInit, D->getType()), Def(D) {}
2331
2333 if (auto *RRT = dyn_cast<RecordRecTy>(Ty))
2334 if (getType()->typeIsConvertibleTo(RRT))
2335 return this;
2336 return nullptr;
2337}
2338
2339const RecTy *DefInit::getFieldType(const StringInit *FieldName) const {
2340 if (const RecordVal *RV = Def->getValue(FieldName))
2341 return RV->getType();
2342 return nullptr;
2343}
2344
2345std::string DefInit::getAsString() const { return Def->getName().str(); }
2346
2347VarDefInit::VarDefInit(SMLoc Loc, const Record *Class,
2349 : TypedInit(IK_VarDefInit, RecordRecTy::get(Class)), Loc(Loc), Class(Class),
2350 NumArgs(Args.size()) {
2351 llvm::uninitialized_copy(Args, getTrailingObjects());
2352}
2353
2354const VarDefInit *VarDefInit::get(SMLoc Loc, const Record *Class,
2356 detail::RecordKeeperImpl &RK = Class->getRecords().getImpl();
2358 if (const VarDefInit *I = RK.TheVarDefInitPool.lookup({Class, Args}, Token))
2359 return I;
2360
2361 void *Mem = RK.Allocator.Allocate(
2362 totalSizeToAlloc<const ArgumentInit *>(Args.size()), alignof(VarDefInit));
2363 VarDefInit *I = new (Mem) VarDefInit(Loc, Class, Args);
2364 RK.TheVarDefInitPool.insert(I, Token);
2365 return I;
2366}
2367
2368const DefInit *VarDefInit::instantiate() {
2369 if (Def)
2370 return Def;
2371
2372 RecordKeeper &Records = Class->getRecords();
2373 auto NewRecOwner = std::make_unique<Record>(
2374 Records.getNewAnonymousName(), Loc, Records, Record::RK_AnonymousDef);
2375 Record *NewRec = NewRecOwner.get();
2376
2377 // Copy values from class to instance
2378 for (const RecordVal &Val : Class->getValues())
2379 NewRec->addValue(Val);
2380
2381 // Copy assertions from class to instance.
2382 NewRec->appendAssertions(Class);
2383
2384 // Copy dumps from class to instance.
2385 NewRec->appendDumps(Class);
2386
2387 // Substitute and resolve template arguments
2388 ArrayRef<const Init *> TArgs = Class->getTemplateArgs();
2389 MapResolver R(NewRec);
2390
2391 for (const Init *Arg : TArgs) {
2392 R.set(Arg, NewRec->getValue(Arg)->getValue());
2393 NewRec->removeValue(Arg);
2394 }
2395
2396 for (auto *Arg : args()) {
2397 if (Arg->isPositional())
2398 R.set(TArgs[Arg->getIndex()], Arg->getValue());
2399 if (Arg->isNamed())
2400 R.set(Arg->getName(), Arg->getValue());
2401 }
2402
2403 NewRec->resolveReferences(R);
2404
2405 // Add superclass.
2406 NewRec->addDirectSuperClass(
2407 Class, SMRange(Class->getLoc().back(), Class->getLoc().back()));
2408
2409 // Resolve internal references and store in record keeper
2410 NewRec->resolveReferences();
2411 Records.addDef(std::move(NewRecOwner));
2412
2413 // Check the assertions.
2414 NewRec->checkRecordAssertions();
2415
2416 // Check the assertions.
2417 NewRec->emitRecordDumps();
2418
2419 return Def = NewRec->getDefInit();
2420}
2421
2424 bool Changed = false;
2426 NewArgs.reserve(args_size());
2427
2428 for (const ArgumentInit *Arg : args()) {
2429 const auto *NewArg = cast<ArgumentInit>(Arg->resolveReferences(UR));
2430 NewArgs.push_back(NewArg);
2431 Changed |= NewArg != Arg;
2432 }
2433
2434 if (Changed) {
2435 auto *New = VarDefInit::get(Loc, Class, NewArgs);
2436 if (!UR.foundUnresolved())
2437 return const_cast<VarDefInit *>(New)->instantiate();
2438 return New;
2439 }
2440 return this;
2441}
2442
2443const Init *VarDefInit::Fold() const {
2444 if (Def)
2445 return Def;
2446
2448 for (const Init *Arg : args())
2449 Arg->resolveReferences(R);
2450
2451 if (!R.foundUnresolved())
2452 return const_cast<VarDefInit *>(this)->instantiate();
2453 return this;
2454}
2455
2456std::string VarDefInit::getAsString() const {
2457 std::string Result = Class->getNameInitAsString() + "<";
2458 ListSeparator LS;
2459 for (const Init *Arg : args()) {
2460 Result += LS;
2461 Result += Arg->getAsString();
2462 }
2463 return Result + ">";
2464}
2465
2466const FieldInit *FieldInit::get(const Init *R, const StringInit *FN) {
2467 detail::RecordKeeperImpl &RK = R->getRecordKeeper().getImpl();
2468 FieldInit *&I = RK.TheFieldInitPool[{R, FN}];
2469 if (!I)
2470 I = new (RK.Allocator) FieldInit(R, FN);
2471 return I;
2472}
2473
2474const Init *FieldInit::getBit(unsigned Bit) const {
2475 if (isa<BitRecTy>(getType()))
2476 return this;
2477 return VarBitInit::get(this, Bit);
2478}
2479
2481 const Init *NewRec = Rec->resolveReferences(R);
2482 if (NewRec != Rec)
2483 return FieldInit::get(NewRec, FieldName)->Fold(R.getCurrentRecord());
2484 return this;
2485}
2486
2487const Init *FieldInit::Fold(const Record *CurRec) const {
2488 if (const auto *DI = dyn_cast<DefInit>(Rec)) {
2489 const Record *Def = DI->getDef();
2490 if (Def == CurRec)
2491 PrintFatalError(CurRec->getLoc(),
2492 Twine("Attempting to access field '") +
2493 FieldName->getAsUnquotedString() + "' of '" +
2494 Rec->getAsString() + "' is a forbidden self-reference");
2495 const Init *FieldVal = Def->getValue(FieldName)->getValue();
2496 if (FieldVal->isConcrete())
2497 return FieldVal;
2498 }
2499 return this;
2500}
2501
2503 if (const auto *DI = dyn_cast<DefInit>(Rec)) {
2504 const Init *FieldVal = DI->getDef()->getValue(FieldName)->getValue();
2505 return FieldVal->isConcrete();
2506 }
2507 return false;
2508}
2509
2510CondOpInit::CondOpInit(ArrayRef<const Init *> Conds,
2512 : TypedInit(IK_CondOpInit, Type), NumConds(Conds.size()), ValType(Type) {
2513 const Init **TrailingObjects = getTrailingObjects();
2516}
2517
2520 const RecTy *Ty) {
2521 assert(Conds.size() == Values.size() &&
2522 "Number of conditions and values must match!");
2523
2524 detail::RecordKeeperImpl &RK = Ty->getRecordKeeper().getImpl();
2526 if (const CondOpInit *I =
2527 RK.TheCondOpInitPool.lookup({Ty, Conds, Values}, Token))
2528 return I;
2529
2530 void *Mem = RK.Allocator.Allocate(
2531 totalSizeToAlloc<const Init *>(2 * Conds.size()), alignof(CondOpInit));
2532 CondOpInit *I = new (Mem) CondOpInit(Conds, Values, Ty);
2533 RK.TheCondOpInitPool.insert(I, Token);
2534 return I;
2535}
2536
2540
2541 bool Changed = false;
2542 for (auto [Cond, Val] : getCondAndVals()) {
2543 const Init *NewCond = Cond->resolveReferences(R);
2544 NewConds.push_back(NewCond);
2545 Changed |= NewCond != Cond;
2546
2547 const Init *NewVal = Val->resolveReferences(R);
2548 NewVals.push_back(NewVal);
2549 Changed |= NewVal != Val;
2550
2551 // Short-circuit if this cond is true.
2552 if (auto *NewCondVal = dyn_cast_or_null<IntInit>(
2554 if (NewCondVal->getValue()) {
2555 Changed = true;
2556 // Don't push the rest of the conds and values.
2557 break;
2558 }
2559 }
2560 }
2561
2562 if (Changed)
2563 return (CondOpInit::get(NewConds, NewVals,
2564 getValType()))->Fold(R.getCurrentRecord());
2565
2566 return this;
2567}
2568
2569const Init *CondOpInit::Fold(const Record *CurRec) const {
2571 for (auto [Cond, Val] : getCondAndVals()) {
2572 if (const auto *CondI = dyn_cast_or_null<IntInit>(
2573 Cond->convertInitializerTo(IntRecTy::get(RK)))) {
2574 if (CondI->getValue())
2575 return Val->convertInitializerTo(getValType());
2576 } else {
2577 return this;
2578 }
2579 }
2580
2581 PrintFatalError(CurRec->getLoc(),
2582 CurRec->getNameInitAsString() +
2583 " does not have any true condition in:" +
2584 this->getAsString());
2585 return nullptr;
2586}
2587
2589 return all_of(getCondAndVals(), [](const auto &Pair) {
2590 return std::get<0>(Pair)->isConcrete() && std::get<1>(Pair)->isConcrete();
2591 });
2592}
2593
2595 return all_of(getCondAndVals(), [](const auto &Pair) {
2596 return std::get<0>(Pair)->isComplete() && std::get<1>(Pair)->isComplete();
2597 });
2598}
2599
2600std::string CondOpInit::getAsString() const {
2601 std::string Result = "!cond(";
2602 ListSeparator LS;
2603 for (auto [Cond, Val] : getCondAndVals()) {
2604 Result += LS;
2605 Result += Cond->getAsString() + ": ";
2606 Result += Val->getAsString();
2607 }
2608 return Result + ")";
2609}
2610
2611const Init *CondOpInit::getBit(unsigned Bit) const {
2612 if (isa<BitRecTy>(getType()))
2613 return this;
2614 return VarBitInit::get(this, Bit);
2615}
2616
2617DagInit::DagInit(const Init *V, const StringInit *VN,
2620 : TypedInit(IK_DagInit, DagRecTy::get(V->getRecordKeeper())), Val(V),
2621 ValName(VN), NumArgs(Args.size()) {
2625 V->isTriviallyResolved() &&
2626 all_of(Args, [](const Init *Arg) { return Arg->isTriviallyResolved(); });
2627}
2628
2629const DagInit *DagInit::get(const Init *V, const StringInit *VN,
2632 assert(Args.size() == ArgNames.size() &&
2633 "Number of DAG args and arg names must match!");
2634
2635 detail::RecordKeeperImpl &RK = V->getRecordKeeper().getImpl();
2637 if (const DagInit *I =
2638 RK.TheDagInitPool.lookup({V, VN, Args, ArgNames}, Token))
2639 return I;
2640
2641 void *Mem =
2643 Args.size(), ArgNames.size()),
2644 alignof(DagInit));
2645 DagInit *I = new (Mem) DagInit(V, VN, Args, ArgNames);
2646 RK.TheDagInitPool.insert(I, Token);
2647 return I;
2648}
2649
2650const DagInit *DagInit::get(
2651 const Init *V, const StringInit *VN,
2652 ArrayRef<std::pair<const Init *, const StringInit *>> ArgAndNames) {
2655 return DagInit::get(V, VN, Args, Names);
2656}
2657
2659 if (const auto *DefI = dyn_cast<DefInit>(Val))
2660 return DefI->getDef();
2661 PrintFatalError(Loc, "Expected record as operator");
2662 return nullptr;
2663}
2664
2665std::optional<unsigned> DagInit::getArgNo(StringRef Name) const {
2667 auto It = llvm::find_if(ArgNames, [Name](const StringInit *ArgName) {
2668 return ArgName && ArgName->getValue() == Name;
2669 });
2670 if (It == ArgNames.end())
2671 return std::nullopt;
2672 return std::distance(ArgNames.begin(), It);
2673}
2674
2676 if (isTriviallyResolved())
2677 return this;
2678
2680 NewArgs.reserve(arg_size());
2681 bool ArgsChanged = false;
2682 for (const Init *Arg : getArgs()) {
2683 const Init *NewArg = Arg->resolveReferences(R);
2684 NewArgs.push_back(NewArg);
2685 ArgsChanged |= NewArg != Arg;
2686 }
2687
2688 const Init *Op = Val->resolveReferences(R);
2689 if (Op != Val || ArgsChanged)
2690 return DagInit::get(Op, ValName, NewArgs, getArgNames());
2691
2692 return this;
2693}
2694
2696 if (!Val->isConcrete())
2697 return false;
2698 return all_of(getArgs(), [](const Init *Elt) { return Elt->isConcrete(); });
2699}
2700
2701std::string DagInit::getAsString() const {
2702 std::string Result = "(" + Val->getAsString();
2703 if (ValName)
2704 Result += ":$" + ValName->getAsUnquotedString();
2705 if (!arg_empty()) {
2706 Result += " ";
2707 ListSeparator LS;
2708 for (auto [Arg, Name] : getArgAndNames()) {
2709 Result += LS;
2710 Result += Arg->getAsString();
2711 if (Name)
2712 Result += ":$" + Name->getAsUnquotedString();
2713 }
2714 }
2715 return Result + ")";
2716}
2717
2718//===----------------------------------------------------------------------===//
2719// Other implementations
2720//===----------------------------------------------------------------------===//
2721
2723 : Name(N), TyAndFlags(T, K) {
2724 setValue(UnsetInit::get(N->getRecordKeeper()));
2725 assert(Value && "Cannot create unset value for current type!");
2726}
2727
2728// This constructor accepts the same arguments as the above, but also
2729// a source location.
2731 : Name(N), Loc(Loc), TyAndFlags(T, K) {
2732 setValue(UnsetInit::get(N->getRecordKeeper()));
2733 assert(Value && "Cannot create unset value for current type!");
2734}
2735
2737 return cast<StringInit>(getNameInit())->getValue();
2738}
2739
2740std::string RecordVal::getPrintType() const {
2741 if (isa<StringRecTy>(getType())) {
2742 if (const auto *StrInit = dyn_cast<StringInit>(Value)) {
2743 if (StrInit->hasCodeFormat())
2744 return "code";
2745 else
2746 return "string";
2747 } else {
2748 return "string";
2749 }
2750 } else {
2751 return getType()->getAsString();
2752 }
2753}
2754
2756 if (!V) {
2757 Value = nullptr;
2758 return false;
2759 }
2760
2761 const Init *NewValue = V->getCastTo(getType());
2762 if (!NewValue)
2763 return true;
2764
2765 Value = NewValue;
2766 assert(!isa<TypedInit>(Value) ||
2767 cast<TypedInit>(Value)->getType()->typeIsA(getType()));
2768 if (const auto *BTy = dyn_cast<BitsRecTy>(getType())) {
2769 if (isa<BitsInit>(Value))
2770 return false;
2771 SmallVector<const Init *, 64> Bits(BTy->getNumBits());
2772 for (unsigned I = 0, E = BTy->getNumBits(); I < E; ++I)
2773 Bits[I] = Value->getBit(I);
2774 Value = BitsInit::get(V->getRecordKeeper(), Bits);
2775 }
2776
2777 return false;
2778}
2779
2780// This version of setValue takes a source location and resets the
2781// location in the RecordVal.
2782bool RecordVal::setValue(const Init *V, SMLoc NewLoc) {
2783 Loc = NewLoc;
2784 return setValue(V);
2785}
2786
2787#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2788LLVM_DUMP_METHOD void RecordVal::dump() const { errs() << *this; }
2789#endif
2790
2791void RecordVal::print(raw_ostream &OS, bool PrintSem) const {
2792 if (isNonconcreteOK()) OS << "field ";
2793 OS << getPrintType() << " " << getNameInitAsString();
2794
2795 if (getValue())
2796 OS << " = " << *getValue();
2797
2798 if (PrintSem) OS << ";\n";
2799}
2800
2802 assert(Locs.size() == 1);
2803 ForwardDeclarationLocs.push_back(Locs.front());
2804
2805 Locs.clear();
2806 Locs.push_back(Loc);
2807}
2808
2809void Record::checkName() {
2810 // Ensure the record name has string type.
2811 const auto *TypedName = cast<const TypedInit>(Name);
2812 if (!isa<StringRecTy>(TypedName->getType()))
2813 PrintFatalError(getLoc(), Twine("Record name '") + Name->getAsString() +
2814 "' is not a string!");
2815}
2816
2820 return RecordRecTy::get(TrackedRecords, DirectSCs);
2821}
2822
2824 if (!CorrespondingDefInit) {
2825 CorrespondingDefInit =
2826 new (TrackedRecords.getImpl().Allocator) DefInit(this);
2827 }
2828 return CorrespondingDefInit;
2829}
2830
2832 return RK.getImpl().LastRecordID++;
2833}
2834
2835void Record::setName(const Init *NewName) {
2836 Name = NewName;
2837 checkName();
2838 // DO NOT resolve record values to the name at this point because
2839 // there might be default values for arguments of this def. Those
2840 // arguments might not have been resolved yet so we don't want to
2841 // prematurely assume values for those arguments were not passed to
2842 // this def.
2843 //
2844 // Nonetheless, it may be that some of this Record's values
2845 // reference the record name. Indeed, the reason for having the
2846 // record name be an Init is to provide this flexibility. The extra
2847 // resolve steps after completely instantiating defs takes care of
2848 // this. See TGParser::ParseDef and TGParser::ParseDefm.
2849}
2850
2852 const Init *OldName = getNameInit();
2853 const Init *NewName = Name->resolveReferences(R);
2854 if (NewName != OldName) {
2855 // Re-register with RecordKeeper.
2856 setName(NewName);
2857 }
2858
2859 // Resolve the field values.
2860 for (RecordVal &Value : Values) {
2861 if (SkipVal == &Value) // Skip resolve the same field as the given one
2862 continue;
2863 if (const Init *V = Value.getValue()) {
2864 const Init *VR = V->resolveReferences(R);
2865 if (Value.setValue(VR)) {
2866 std::string Type;
2867 if (const auto *VRT = dyn_cast<TypedInit>(VR))
2868 Type =
2869 (Twine("of type '") + VRT->getType()->getAsString() + "' ").str();
2871 getLoc(),
2872 Twine("Invalid value ") + Type + "found when setting field '" +
2873 Value.getNameInitAsString() + "' of type '" +
2874 Value.getType()->getAsString() +
2875 "' after resolving references: " + VR->getAsUnquotedString() +
2876 "\n");
2877 }
2878 }
2879 }
2880
2881 // Resolve the assertion expressions.
2882 for (AssertionInfo &Assertion : Assertions) {
2883 const Init *Value = Assertion.Condition->resolveReferences(R);
2884 Assertion.Condition = Value;
2885 Value = Assertion.Message->resolveReferences(R);
2886 Assertion.Message = Value;
2887 }
2888 // Resolve the dump expressions.
2889 for (DumpInfo &Dump : Dumps) {
2890 const Init *Value = Dump.Message->resolveReferences(R);
2891 Dump.Message = Value;
2892 }
2893}
2894
2895void Record::resolveReferences(const Init *NewName) {
2896 RecordResolver R(*this);
2897 R.setName(NewName);
2898 R.setFinal(true);
2900}
2901
2902#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2903LLVM_DUMP_METHOD void Record::dump() const { errs() << *this; }
2904#endif
2905
2907 OS << R.getNameInitAsString();
2908
2909 ArrayRef<const Init *> TArgs = R.getTemplateArgs();
2910 if (!TArgs.empty()) {
2911 OS << "<";
2912 ListSeparator LS;
2913 for (const Init *TA : TArgs) {
2914 const RecordVal *RV = R.getValue(TA);
2915 assert(RV && "Template argument record not found??");
2916 OS << LS;
2917 RV->print(OS, false);
2918 }
2919 OS << ">";
2920 }
2921
2922 OS << " {";
2923 std::vector<const Record *> SCs = R.getSuperClasses();
2924 if (!SCs.empty()) {
2925 OS << "\t//";
2926 for (const Record *SC : SCs)
2927 OS << " " << SC->getNameInitAsString();
2928 }
2929 OS << "\n";
2930
2931 for (const RecordVal &Val : R.getValues())
2932 if (Val.isNonconcreteOK() && !R.isTemplateArg(Val.getNameInit()))
2933 OS << Val;
2934 for (const RecordVal &Val : R.getValues())
2935 if (!Val.isNonconcreteOK() && !R.isTemplateArg(Val.getNameInit()))
2936 OS << Val;
2937
2938 return OS << "}\n";
2939}
2940
2942 const RecordVal *R = getValue(FieldName);
2943 if (!R)
2944 PrintFatalError(getLoc(), "Record `" + getName() +
2945 "' does not have a field named `" + FieldName + "'!\n");
2946 return R->getLoc();
2947}
2948
2949const Init *Record::getValueInit(StringRef FieldName) const {
2950 const RecordVal *R = getValue(FieldName);
2951 if (!R || !R->getValue())
2952 PrintFatalError(getLoc(), "Record `" + getName() +
2953 "' does not have a field named `" + FieldName + "'!\n");
2954 return R->getValue();
2955}
2956
2958 const Init *I = getValueInit(FieldName);
2959 if (const auto *SI = dyn_cast<StringInit>(I))
2960 return SI->getValue();
2961 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" + FieldName +
2962 "' exists but does not have a string value");
2963}
2964
2965std::optional<StringRef>
2967 const RecordVal *R = getValue(FieldName);
2968 if (!R || !R->getValue())
2969 return std::nullopt;
2970 if (isa<UnsetInit>(R->getValue()))
2971 return std::nullopt;
2972
2973 if (const auto *SI = dyn_cast<StringInit>(R->getValue()))
2974 return SI->getValue();
2975
2977 "Record `" + getName() + "', ` field `" + FieldName +
2978 "' exists but does not have a string initializer!");
2979}
2980
2982 const Init *I = getValueInit(FieldName);
2983 if (const auto *BI = dyn_cast<BitsInit>(I))
2984 return BI;
2985 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" + FieldName +
2986 "' exists but does not have a bits value");
2987}
2988
2990 const Init *I = getValueInit(FieldName);
2991 if (const auto *LI = dyn_cast<ListInit>(I))
2992 return LI;
2993 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" + FieldName +
2994 "' exists but does not have a list value");
2995}
2996
2997std::vector<const Record *>
2999 const ListInit *List = getValueAsListInit(FieldName);
3000 std::vector<const Record *> Defs;
3001 for (const Init *I : List->getElements()) {
3002 if (const auto *DI = dyn_cast<DefInit>(I))
3003 Defs.push_back(DI->getDef());
3004 else
3005 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
3006 FieldName +
3007 "' list is not entirely DefInit!");
3008 }
3009 return Defs;
3010}
3011
3012int64_t Record::getValueAsInt(StringRef FieldName) const {
3013 const Init *I = getValueInit(FieldName);
3014 if (const auto *II = dyn_cast<IntInit>(I))
3015 return II->getValue();
3017 getLoc(),
3018 Twine("Record `") + getName() + "', field `" + FieldName +
3019 "' exists but does not have an int value: " + I->getAsString());
3020}
3021
3022std::vector<int64_t>
3024 const ListInit *List = getValueAsListInit(FieldName);
3025 std::vector<int64_t> Ints;
3026 for (const Init *I : List->getElements()) {
3027 if (const auto *II = dyn_cast<IntInit>(I))
3028 Ints.push_back(II->getValue());
3029 else
3031 Twine("Record `") + getName() + "', field `" + FieldName +
3032 "' exists but does not have a list of ints value: " +
3033 I->getAsString());
3034 }
3035 return Ints;
3036}
3037
3038std::vector<StringRef>
3040 const ListInit *List = getValueAsListInit(FieldName);
3041 std::vector<StringRef> Strings;
3042 for (const Init *I : List->getElements()) {
3043 if (const auto *SI = dyn_cast<StringInit>(I))
3044 Strings.push_back(SI->getValue());
3045 else
3047 Twine("Record `") + getName() + "', field `" + FieldName +
3048 "' exists but does not have a list of strings value: " +
3049 I->getAsString());
3050 }
3051 return Strings;
3052}
3053
3054const Record *Record::getValueAsDef(StringRef FieldName) const {
3055 const Init *I = getValueInit(FieldName);
3056 if (const auto *DI = dyn_cast<DefInit>(I))
3057 return DI->getDef();
3058 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
3059 FieldName + "' does not have a def initializer!");
3060}
3061
3063 const Init *I = getValueInit(FieldName);
3064 if (const auto *DI = dyn_cast<DefInit>(I))
3065 return DI->getDef();
3066 if (isa<UnsetInit>(I))
3067 return nullptr;
3068 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
3069 FieldName + "' does not have either a def initializer or '?'!");
3070}
3071
3072bool Record::getValueAsBit(StringRef FieldName) const {
3073 const Init *I = getValueInit(FieldName);
3074 if (const auto *BI = dyn_cast<BitInit>(I))
3075 return BI->getValue();
3076 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
3077 FieldName + "' does not have a bit initializer!");
3078}
3079
3080bool Record::getValueAsBitOrUnset(StringRef FieldName, bool &Unset) const {
3081 const Init *I = getValueInit(FieldName);
3082 if (isa<UnsetInit>(I)) {
3083 Unset = true;
3084 return false;
3085 }
3086 Unset = false;
3087 if (const auto *BI = dyn_cast<BitInit>(I))
3088 return BI->getValue();
3089 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
3090 FieldName + "' does not have a bit initializer!");
3091}
3092
3093const DagInit *Record::getValueAsDag(StringRef FieldName) const {
3094 const Init *I = getValueInit(FieldName);
3095 if (const auto *DI = dyn_cast<DagInit>(I))
3096 return DI;
3097 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
3098 FieldName + "' does not have a dag initializer!");
3099}
3100
3101// Check all record assertions: For each one, resolve the condition
3102// and message, then call CheckAssert().
3103// Note: The condition and message are probably already resolved,
3104// but resolving again allows calls before records are resolved.
3106 RecordResolver R(*this);
3107 R.setFinal(true);
3108
3109 bool AnyFailed = false;
3110 for (const auto &Assertion : getAssertions()) {
3111 const Init *Condition = Assertion.Condition->resolveReferences(R);
3112 const Init *Message = Assertion.Message->resolveReferences(R);
3113 AnyFailed |= CheckAssert(Assertion.Loc, Condition, Message);
3114 }
3115
3116 if (!AnyFailed)
3117 return;
3118
3119 // If any of the record assertions failed, print some context that will
3120 // help see where the record that caused these assert failures is defined.
3121 PrintError(this, "assertion failed in this record");
3122}
3123
3125 RecordResolver R(*this);
3126 R.setFinal(true);
3127
3128 for (const DumpInfo &Dump : getDumps()) {
3129 const Init *Message = Dump.Message->resolveReferences(R);
3130 dumpMessage(Dump.Loc, Message);
3131 }
3132}
3133
3134// Report a warning if the record has unused template arguments.
3136 for (const Init *TA : getTemplateArgs()) {
3137 const RecordVal *Arg = getValue(TA);
3138 if (!Arg->isUsed())
3139 PrintWarning(Arg->getLoc(),
3140 "unused template argument: " + Twine(Arg->getName()));
3141 }
3142}
3143
3145 : Impl(std::make_unique<detail::RecordKeeperImpl>(*this)),
3146 Timer(std::make_unique<TGTimer>()) {}
3147
3148RecordKeeper::~RecordKeeper() = default;
3149
3150#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3151LLVM_DUMP_METHOD void RecordKeeper::dump() const { errs() << *this; }
3152#endif
3153
3155 OS << "------------- Classes -----------------\n";
3156 for (const auto &[_, C] : RK.getClasses())
3157 OS << "class " << *C;
3158
3159 OS << "------------- Defs -----------------\n";
3160 for (const auto &[_, D] : RK.getDefs())
3161 OS << "def " << *D;
3162 return OS;
3163}
3164
3165/// GetNewAnonymousName - Generate a unique anonymous name that can be used as
3166/// an identifier.
3168 return AnonymousNameInit::get(*this, getImpl().AnonCounter++);
3169}
3170
3173 // We cache the record vectors for single classes. Many backends request
3174 // the same vectors multiple times.
3175 auto [Iter, Inserted] = Cache.try_emplace(ClassName.str());
3176 if (Inserted)
3177 Iter->second = getAllDerivedDefinitions(ArrayRef(ClassName));
3178 return Iter->second;
3179}
3180
3181std::vector<const Record *>
3184 std::vector<const Record *> Defs;
3185
3186 assert(ClassNames.size() > 0 && "At least one class must be passed.");
3187 for (StringRef ClassName : ClassNames) {
3188 const Record *Class = getClass(ClassName);
3189 if (!Class)
3190 PrintFatalError("The class '" + ClassName + "' is not defined\n");
3191 ClassRecs.push_back(Class);
3192 }
3193
3194 for (const auto &OneDef : getDefs()) {
3195 if (all_of(ClassRecs, [&OneDef](const Record *Class) {
3196 return OneDef.second->isSubClassOf(Class);
3197 }))
3198 Defs.push_back(OneDef.second.get());
3199 }
3200 llvm::sort(Defs, LessRecord());
3201 return Defs;
3202}
3203
3206 if (getClass(ClassName))
3207 return getAllDerivedDefinitions(ClassName);
3208 return Cache[""];
3209}
3210
3212 Impl->dumpAllocationStats(OS);
3213}
3214
3215const Init *MapResolver::resolve(const Init *VarName) {
3216 auto It = Map.find(VarName);
3217 if (It == Map.end())
3218 return nullptr;
3219
3220 const Init *I = It->second.V;
3221
3222 if (!It->second.Resolved && Map.size() > 1) {
3223 // Resolve mutual references among the mapped variables, but prevent
3224 // infinite recursion.
3225 Map.erase(It);
3226 I = I->resolveReferences(*this);
3227 Map[VarName] = {I, true};
3228 }
3229
3230 return I;
3231}
3232
3233const Init *RecordResolver::resolve(const Init *VarName) {
3234 const Init *Val = Cache.lookup(VarName);
3235 if (Val)
3236 return Val;
3237
3238 if (llvm::is_contained(Stack, VarName))
3239 return nullptr; // prevent infinite recursion
3240
3241 if (const RecordVal *RV = getCurrentRecord()->getValue(VarName)) {
3242 if (!isa<UnsetInit>(RV->getValue())) {
3243 Val = RV->getValue();
3244 Stack.push_back(VarName);
3245 Val = Val->resolveReferences(*this);
3246 Stack.pop_back();
3247 }
3248 } else if (Name && VarName == getCurrentRecord()->getNameInit()) {
3249 Stack.push_back(VarName);
3250 Val = Name->resolveReferences(*this);
3251 Stack.pop_back();
3252 }
3253
3254 Cache[VarName] = Val;
3255 return Val;
3256}
3257
3259 const Init *I = nullptr;
3260
3261 if (R) {
3262 I = R->resolve(VarName);
3263 if (I && !FoundUnresolved) {
3264 // Do not recurse into the resolved initializer, as that would change
3265 // the behavior of the resolver we're delegating, but do check to see
3266 // if there are unresolved variables remaining.
3268 I->resolveReferences(Sub);
3269 FoundUnresolved |= Sub.FoundUnresolved;
3270 }
3271 }
3272
3273 if (!I)
3274 FoundUnresolved = true;
3275 return I;
3276}
3277
3279 if (VarName == VarNameToTrack)
3280 Found = true;
3281 return nullptr;
3282}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This file defines the StringMap class.
This file defines the BumpPtrAllocator interface.
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds.
Definition Compiler.h:686
This file defines the DenseMap class.
This file defines a hash set that can be used to remove duplication of nodes in a graph.
#define _
static constexpr Value * getValue(Ty &ValueOrUse)
#define I(x, y, z)
Definition MD5.cpp:57
#define T
#define T1
uint64_t IntrinsicInst * II
OptimizedStructLayoutField Field
const SmallVectorImpl< MachineOperand > & Cond
static const Init * SortHelper(const Init *LHS, const Init *MHS, const Init *RHS, const RecTy *Type, const Record *CurRec)
Definition Record.cpp:1691
static bool canFitInBitfield(int64_t Value, unsigned NumBits)
Definition Record.cpp:571
static std::optional< unsigned > getDagArgNoByKey(const DagInit *Dag, const Init *Key, std::string &Error)
Definition Record.cpp:1188
static const StringInit * ConcatStringInits(const StringInit *I0, const StringInit *I1)
Definition Record.cpp:1031
static const ListInit * ConcatListInits(const ListInit *LHS, const ListInit *RHS)
Definition Record.cpp:1092
static const StringInit * interleaveStringList(const ListInit *List, const StringInit *Delim)
Definition Record.cpp:1040
static const Init * ForeachDagApply(const Init *LHS, const DagInit *MHSd, const Init *RHS, const Record *CurRec)
Definition Record.cpp:1617
static const Init * FilterHelper(const Init *LHS, const Init *MHS, const Init *RHS, const RecTy *Type, const Record *CurRec)
Definition Record.cpp:1666
static const Init * ItemApply(const Init *LHS, const Init *MHSe, const Init *RHS, const Record *CurRec)
Definition Record.cpp:1610
static const RecordRecTy * resolveRecordTypes(const RecordRecTy *T1, const RecordRecTy *T2)
Definition Record.cpp:309
static const Init * ForeachHelper(const Init *LHS, const Init *MHS, const Init *RHS, const RecTy *Type, const Record *CurRec)
Definition Record.cpp:1644
static const StringInit * interleaveIntList(const ListInit *List, const StringInit *Delim)
Definition Record.cpp:1061
This file defines the SmallString class.
This file defines the SmallVector class.
FunctionLoweringInfo::StatepointRelocationRecord RecordType
This file contains some functions that are useful when dealing with strings.
static SymbolRef::Type getType(const Symbol *Sym)
Definition TapiFile.cpp:39
static constexpr int Concat[]
Value * RHS
Value * LHS
static AnonymousNameInit * get(RecordKeeper &RK, unsigned)
Definition Record.cpp:616
const StringInit * getNameInit() const
Definition Record.cpp:620
const Init * resolveReferences(Resolver &R) const override
This function is used by classes that refer to other variables which may not be defined at the time t...
Definition Record.cpp:628
std::string getAsString() const override
Convert this value to a literal form.
Definition Record.cpp:624
const ArgumentInit * cloneWithValue(const Init *Value) const
Definition Record.h:546
static const ArgumentInit * get(const Init *Value, ArgAuxType Aux)
Definition Record.cpp:383
ArgumentInit(const Init *Value, ArgAuxType Aux)
Definition Record.h:519
const Init * resolveReferences(Resolver &R) const override
This function is used by classes that refer to other variables which may not be defined at the time t...
Definition Record.cpp:395
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
iterator end() const
Definition ArrayRef.h:130
size_t size() const
Get the array size.
Definition ArrayRef.h:141
iterator begin() const
Definition ArrayRef.h:129
bool empty() const
Check if the array is empty.
Definition ArrayRef.h:136
static const BinOpInit * get(BinaryOp opc, const Init *lhs, const Init *rhs, const RecTy *Type)
Definition Record.cpp:1018
const Init * resolveReferences(Resolver &R) const override
This function is used by classes that refer to other variables which may not be defined at the time t...
Definition Record.cpp:1519
static const Init * getStrConcat(const Init *lhs, const Init *rhs)
Definition Record.cpp:1083
std::string getAsString() const override
Convert this value to a literal form.
Definition Record.cpp:1547
BinaryOp getOpcode() const
Definition Record.h:961
std::optional< bool > CompareInit(unsigned Opc, const Init *LHS, const Init *RHS) const
Definition Record.cpp:1110
static const Init * getListConcat(const TypedInit *lhs, const Init *rhs)
Definition Record.cpp:1100
const Init * Fold(const Record *CurRec) const
Definition Record.cpp:1220
'true'/'false' - Represent a concrete initializer for a bit.
Definition Record.h:574
static BitInit * get(RecordKeeper &RK, bool V)
Definition Record.cpp:406
bool getValue() const
Definition Record.h:592
const Init * convertInitializerTo(const RecTy *Ty) const override
Convert to a value whose type is Ty, or return null if this is not possible.
Definition Record.cpp:410
'bit' - Represent a single bit
Definition Record.h:115
static const BitRecTy * get(RecordKeeper &RK)
Definition Record.cpp:149
bool typeIsConvertibleTo(const RecTy *RHS) const override
Return true if all values of 'this' type can be converted to the specified type.
Definition Record.cpp:153
'{ a, b, c }' - Represents an initializer for a BitsRecTy value.
Definition Record.h:609
std::string getAsString() const override
Convert this value to a literal form.
Definition Record.cpp:509
bool isComplete() const override
Is this a complete value with no unset (uninitialized) subvalues?
Definition Record.cpp:499
unsigned getNumBits() const
Definition Record.h:630
std::optional< int64_t > convertInitializerToInt() const
Definition Record.cpp:469
const Init * getBit(unsigned Bit) const override
Get the Init value of the specified bit.
Definition Record.h:649
const Init * convertInitializerBitRange(ArrayRef< unsigned > Bits) const override
This function is used to implement the bit range selection operator.
Definition Record.cpp:488
const Init * resolveReferences(Resolver &R) const override
This function is used by classes that refer to other variables which may not be defined at the time t...
Definition Record.cpp:524
const Init * convertInitializerTo(const RecTy *Ty) const override
Convert to a value whose type is Ty, or return null if this is not possible.
Definition Record.cpp:447
ArrayRef< const Init * > getBits() const
Definition Record.h:647
uint64_t convertKnownBitsToInt() const
Definition Record.cpp:479
bool allInComplete() const
Definition Record.cpp:502
static BitsInit * get(RecordKeeper &RK, ArrayRef< const Init * > Range)
Definition Record.cpp:434
bool isConcrete() const override
Is this a concrete and fully resolved value without any references or stuck operations?
Definition Record.cpp:505
'bits<n>' - Represent a fixed number of bits
Definition Record.h:133
bool typeIsConvertibleTo(const RecTy *RHS) const override
Return true if all values of 'this' type can be converted to the specified type.
Definition Record.cpp:175
static const BitsRecTy * get(RecordKeeper &RK, unsigned Sz)
Definition Record.cpp:161
std::string getAsString() const override
Definition Record.cpp:171
const Init * Fold(const Record *CurRec) const
Definition Record.cpp:2569
auto getCondAndVals() const
Definition Record.h:1086
const Init * resolveReferences(Resolver &R) const override
This function is used by classes that refer to other variables which may not be defined at the time t...
Definition Record.cpp:2537
const Init * getBit(unsigned Bit) const override
Get the Init value of the specified bit.
Definition Record.cpp:2611
bool isConcrete() const override
Is this a concrete and fully resolved value without any references or stuck operations?
Definition Record.cpp:2588
std::string getAsString() const override
Convert this value to a literal form.
Definition Record.cpp:2600
static const CondOpInit * get(ArrayRef< const Init * > Conds, ArrayRef< const Init * > Values, const RecTy *Type)
Definition Record.cpp:2518
const RecTy * getValType() const
Definition Record.h:1070
bool isComplete() const override
Is this a complete value with no unset (uninitialized) subvalues?
Definition Record.cpp:2594
(v a, b) - Represent a DAG tree value.
Definition Record.h:1472
bool isConcrete() const override
Is this a concrete and fully resolved value without any references or stuck operations?
Definition Record.cpp:2695
std::optional< unsigned > getArgNo(StringRef Name) const
This method looks up the specified argument name and returns its argument number or std::nullopt if t...
Definition Record.cpp:2665
const StringInit * getName() const
Definition Record.h:1522
const Init * getOperator() const
Definition Record.h:1519
const Init * resolveReferences(Resolver &R) const override
This function is used by classes that refer to other variables which may not be defined at the time t...
Definition Record.cpp:2675
ArrayRef< const StringInit * > getArgNames() const
Definition Record.h:1549
static const DagInit * get(const Init *V, const StringInit *VN, ArrayRef< const Init * > Args, ArrayRef< const StringInit * > ArgNames)
Definition Record.cpp:2629
size_t arg_size() const
Definition Record.h:1574
bool arg_empty() const
Definition Record.h:1575
const Record * getOperatorAsDef(ArrayRef< SMLoc > Loc) const
Definition Record.cpp:2658
auto getArgAndNames() const
Definition Record.h:1554
ArrayRef< const Init * > getArgs() const
Definition Record.h:1545
std::string getAsString() const override
Convert this value to a literal form.
Definition Record.cpp:2701
'dag' - Represent a dag fragment
Definition Record.h:215
std::string getAsString() const override
Definition Record.cpp:224
static const DagRecTy * get(RecordKeeper &RK)
Definition Record.cpp:220
AL - Represent a reference to a 'def' in the description.
Definition Record.h:1338
std::string getAsString() const override
Convert this value to a literal form.
Definition Record.cpp:2345
const RecTy * getFieldType(const StringInit *FieldName) const override
This function is used to implement the FieldInit class.
Definition Record.cpp:2339
const Init * convertInitializerTo(const RecTy *Ty) const override
Convert to a value whose type is Ty, or return null if this is not possible.
Definition Record.cpp:2332
Lightweight error class with error context and mandatory checking.
Definition Error.h:159
static const ExistsOpInit * get(const RecTy *CheckType, const Init *Expr)
Definition Record.cpp:2115
std::string getAsString() const override
Convert this value to a literal form.
Definition Record.cpp:2171
const Init * resolveReferences(Resolver &R) const override
This function is used by classes that refer to other variables which may not be defined at the time t...
Definition Record.cpp:2160
const Init * Fold(const Record *CurRec, bool IsFinal=false) const
Definition Record.cpp:2128
const Init * getBit(unsigned Bit) const override
Get the Init value of the specified bit.
Definition Record.cpp:2167
X.Y - Represent a reference to a subfield of a variable.
Definition Record.h:1426
const Init * Fold(const Record *CurRec) const
Definition Record.cpp:2487
const Init * getBit(unsigned Bit) const override
Get the Init value of the specified bit.
Definition Record.cpp:2474
static const FieldInit * get(const Init *R, const StringInit *FN)
Definition Record.cpp:2466
const Init * resolveReferences(Resolver &R) const override
This function is used by classes that refer to other variables which may not be defined at the time t...
Definition Record.cpp:2480
bool isConcrete() const override
Is this a concrete and fully resolved value without any references or stuck operations?
Definition Record.cpp:2502
const Init * Fold(const Record *CurRec) const
Definition Record.cpp:2022
std::string getAsString() const override
Convert this value to a literal form.
Definition Record.cpp:2057
static const FoldOpInit * get(const Init *Start, const Init *List, const Init *A, const Init *B, const Init *Expr, const RecTy *Type)
Definition Record.cpp:2008
const Init * getBit(unsigned Bit) const override
Get the Init value of the specified bit.
Definition Record.cpp:2051
const Init * resolveReferences(Resolver &R) const override
This function is used by classes that refer to other variables which may not be defined at the time t...
Definition Record.cpp:2036
Insertion token: a failed lookup fills it in, the matching insert consumes it.
Definition FoldingSet.h:284
const Init * resolve(const Init *VarName) override
Return the initializer for the given variable name (should normally be a StringInit),...
Definition Record.cpp:3278
virtual const Init * resolveReferences(Resolver &R) const
This function is used by classes that refer to other variables which may not be defined at the time t...
Definition Record.h:422
uint8_t Opc
Definition Record.h:337
bool isTriviallyResolved() const
Return true if resolveReferences returns this value unchanged with any resolver.
Definition Record.h:357
virtual std::string getAsUnquotedString() const
Convert this value to a literal form, without adding quotes around a string.
Definition Record.h:386
void dump() const
Debugging method that may be called through a debugger; just invokes print on stderr.
Definition Record.cpp:362
void print(raw_ostream &OS) const
Print this value.
Definition Record.h:379
virtual std::string getAsString() const =0
Convert this value to a literal form.
virtual bool isConcrete() const
Is this a concrete and fully resolved value without any references or stuck operations?
Definition Record.h:376
virtual bool isComplete() const
Is this a complete value with no unset (uninitialized) subvalues?
Definition Record.h:372
virtual const Init * getBit(unsigned Bit) const =0
Get the Init value of the specified bit.
virtual const Init * convertInitializerTo(const RecTy *Ty) const =0
Convert to a value whose type is Ty, or return null if this is not possible.
bool TriviallyResolved
Set if resolveReferences returns this value unchanged with any resolver.
Definition Record.h:340
virtual const Init * getCastTo(const RecTy *Ty) const =0
If this value is convertible to type Ty, return a value whose type is Ty, generating a !...
RecordKeeper & getRecordKeeper() const
Get the record keeper that initialized this Init.
Definition Record.cpp:365
Init(InitKind K, uint8_t Opc=0)
Definition Record.h:363
const Init * Fold(const Record *CurRec, bool IsFinal=false) const
Definition Record.cpp:2190
const Init * resolveReferences(Resolver &R) const override
This function is used by classes that refer to other variables which may not be defined at the time t...
Definition Record.cpp:2212
std::string getAsString() const override
Convert this value to a literal form.
Definition Record.cpp:2219
static const InstancesOpInit * get(const RecTy *Type, const Init *Regex)
Definition Record.cpp:2177
static IntInit * get(RecordKeeper &RK, int64_t V)
Definition Record.cpp:560
const Init * convertInitializerBitRange(ArrayRef< unsigned > Bits) const override
This function is used to implement the bit range selection operator.
Definition Record.cpp:604
int64_t getValue() const
Definition Record.h:669
std::string getAsString() const override
Convert this value to a literal form.
Definition Record.cpp:567
const Init * convertInitializerTo(const RecTy *Ty) const override
Convert to a value whose type is Ty, or return null if this is not possible.
Definition Record.cpp:577
'int' - Represent an integer value of no particular size
Definition Record.h:154
static const IntRecTy * get(RecordKeeper &RK)
Definition Record.cpp:182
bool typeIsConvertibleTo(const RecTy *RHS) const override
Return true if all values of 'this' type can be converted to the specified type.
Definition Record.cpp:186
static const IsAOpInit * get(const RecTy *CheckType, const Init *Expr)
Definition Record.cpp:2064
const Init * resolveReferences(Resolver &R) const override
This function is used by classes that refer to other variables which may not be defined at the time t...
Definition Record.cpp:2098
std::string getAsString() const override
Convert this value to a literal form.
Definition Record.cpp:2109
const Init * getBit(unsigned Bit) const override
Get the Init value of the specified bit.
Definition Record.cpp:2105
const Init * Fold() const
Definition Record.cpp:2076
[AL, AH, CL] - Represent a list of defs
Definition Record.h:769
std::string getAsString() const override
Convert this value to a literal form.
Definition Record.cpp:747
const RecTy * getElementType() const
Definition Record.h:804
static const ListInit * get(ArrayRef< const Init * > Range, const RecTy *EltTy)
Definition Record.cpp:664
bool isConcrete() const override
Is this a concrete and fully resolved value without any references or stuck operations?
Definition Record.cpp:742
bool isComplete() const override
Is this a complete value with no unset (uninitialized) subvalues?
Definition Record.cpp:737
const Init * resolveReferences(Resolver &R) const override
This method is used by classes that refer to other variables which may not be defined at the time the...
Definition Record.cpp:718
size_t size() const
Definition Record.h:826
const Init * convertInitializerTo(const RecTy *Ty) const override
Convert to a value whose type is Ty, or return null if this is not possible.
Definition Record.cpp:681
const Record * getElementAsRecord(unsigned Idx) const
Definition Record.cpp:710
ArrayRef< const Init * > getElements() const
Definition Record.h:791
const Init * getElement(unsigned Idx) const
Definition Record.h:798
'list<Ty>' - Represent a list of element values, all of which must be of the specified type.
Definition Record.h:191
const RecTy * getElementType() const
Definition Record.h:205
bool typeIsA(const RecTy *RHS) const override
Return true if 'this' type is equal to or a subtype of RHS.
Definition Record.cpp:214
std::string getAsString() const override
Definition Record.cpp:204
bool typeIsConvertibleTo(const RecTy *RHS) const override
Return true if all values of 'this' type can be converted to the specified type.
Definition Record.cpp:208
A helper class to return the specified delimiter string after the first invocation of operator String...
Resolve arbitrary mappings.
Definition Record.h:2283
const Init * resolve(const Init *VarName) override
Return the initializer for the given variable name (should normally be a StringInit),...
Definition Record.cpp:3215
const Init * getBit(unsigned Bit) const final
Get the Init value of the specified bit.
Definition Record.cpp:757
RecordKeeper & getRecordKeeper() const
Return the RecordKeeper that uniqued this Type.
Definition Record.h:91
virtual bool typeIsA(const RecTy *RHS) const
Return true if 'this' type is equal to or a subtype of RHS.
Definition Record.cpp:147
virtual bool typeIsConvertibleTo(const RecTy *RHS) const
Return true if all values of 'this' type can be converted to the specified type.
Definition Record.cpp:142
RecTyKind
Subclass discriminator (for dyn_cast<> et al.)
Definition Record.h:66
@ BitsRecTyKind
Definition Record.h:68
@ IntRecTyKind
Definition Record.h:69
@ StringRecTyKind
Definition Record.h:70
@ BitRecTyKind
Definition Record.h:67
RecTy(RecTyKind K, RecordKeeper &RK)
Definition Record.h:85
virtual std::string getAsString() const =0
void dump() const
Definition Record.cpp:133
const ListRecTy * getListTy() const
Returns the type representing list<thistype>.
Definition Record.cpp:136
const Record * getClass(StringRef Name) const
Get the class with the specified name.
Definition Record.h:2057
const RecordMap & getClasses() const
Get the map of classes.
Definition Record.h:2048
const Init * getNewAnonymousName()
GetNewAnonymousName - Generate a unique anonymous name that can be used as an identifier.
Definition Record.cpp:3167
const RecordMap & getDefs() const
Get the map of records (defs).
Definition Record.h:2051
void dump() const
Definition Record.cpp:3151
detail::RecordKeeperImpl & getImpl()
Return the internal implementation of the RecordKeeper.
Definition Record.h:2042
void dumpAllocationStats(raw_ostream &OS) const
Definition Record.cpp:3211
ArrayRef< const Record * > getAllDerivedDefinitionsIfDefined(StringRef ClassName) const
Get all the concrete records that inherit from specified class, if the class is defined.
Definition Record.cpp:3205
const Record * getDef(StringRef Name) const
Get the concrete record with the specified name.
Definition Record.h:2063
ArrayRef< const Record * > getAllDerivedDefinitions(StringRef ClassName) const
Get all the concrete records that inherit from the one specified class.
Definition Record.cpp:3172
'[classname]' - Type of record values that have zero or more superclasses.
Definition Record.h:236
bool typeIsConvertibleTo(const RecTy *RHS) const override
Return true if all values of 'this' type can be converted to the specified type.
Definition Record.cpp:292
bool isSubClassOf(const Record *Class) const
Definition Record.cpp:286
ArrayRef< const Record * > getClasses() const
Definition Record.h:263
friend class Record
Definition Record.h:238
std::string getAsString() const override
Definition Record.cpp:272
bool typeIsA(const RecTy *RHS) const override
Return true if 'this' type is equal to or a subtype of RHS.
Definition Record.cpp:305
static const RecordRecTy * get(RecordKeeper &RK, ArrayRef< const Record * > Classes)
Get the record type with the given non-redundant list of superclasses.
Definition Record.cpp:233
Resolve all variables from a record except for unset variables.
Definition Record.h:2309
const Init * resolve(const Init *VarName) override
Return the initializer for the given variable name (should normally be a StringInit),...
Definition Record.cpp:3233
This class represents a field in a record, including its name, type, value, and source location.
Definition Record.h:1591
std::string getNameInitAsString() const
Get the name of the field as a std::string.
Definition Record.h:1632
bool isNonconcreteOK() const
Is this a field where nonconcrete values are okay?
Definition Record.h:1640
bool setValue(const Init *V)
Set the value of the field from an Init.
Definition Record.cpp:2755
SMLoc getLoc() const
Get the source location of the point where the field was defined.
Definition Record.h:1637
const Init * getValue() const
Get the value of the field as an Init.
Definition Record.h:1652
bool isUsed() const
Definition Record.h:1672
void dump() const
Definition Record.cpp:2788
StringRef getName() const
Get the name of the field as a StringRef.
Definition Record.cpp:2736
void print(raw_ostream &OS, bool PrintSem=true) const
Print the value to an output stream, possibly with a semicolon.
Definition Record.cpp:2791
RecordVal(const Init *N, const RecTy *T, FieldKind K)
Definition Record.cpp:2722
const Init * getNameInit() const
Get the name of the field as an Init.
Definition Record.h:1629
std::string getPrintType() const
Get the type of the field for printing purposes.
Definition Record.cpp:2740
const RecTy * getType() const
Get the type of the field value as a RecTy.
Definition Record.h:1646
std::vector< int64_t > getValueAsListOfInts(StringRef FieldName) const
This method looks up the specified field and returns its value as a vector of integers,...
Definition Record.cpp:3023
const RecordRecTy * getType() const
Definition Record.cpp:2817
const Init * getValueInit(StringRef FieldName) const
Return the initializer for a value with the specified name, or throw an exception if the field does n...
Definition Record.cpp:2949
bool getValueAsBitOrUnset(StringRef FieldName, bool &Unset) const
This method looks up the specified field and returns its value as a bit.
Definition Record.cpp:3080
bool getValueAsBit(StringRef FieldName) const
This method looks up the specified field and returns its value as a bit, throwing an exception if the...
Definition Record.cpp:3072
@ RK_AnonymousDef
Definition Record.h:1707
static unsigned getNewUID(RecordKeeper &RK)
Definition Record.cpp:2831
ArrayRef< SMLoc > getLoc() const
Definition Record.h:1776
void checkUnusedTemplateArgs()
Definition Record.cpp:3135
void emitRecordDumps()
Definition Record.cpp:3124
ArrayRef< DumpInfo > getDumps() const
Definition Record.h:1809
std::vector< const Record * > getValueAsListOfDefs(StringRef FieldName) const
This method looks up the specified field and returns its value as a vector of records,...
Definition Record.cpp:2998
ArrayRef< AssertionInfo > getAssertions() const
Definition Record.h:1808
std::string getNameInitAsString() const
Definition Record.h:1770
void dump() const
Definition Record.cpp:2903
const Record * getValueAsDef(StringRef FieldName) const
This method looks up the specified field and returns its value as a Record, throwing an exception if ...
Definition Record.cpp:3054
const DagInit * getValueAsDag(StringRef FieldName) const
This method looks up the specified field and returns its value as an Dag, throwing an exception if th...
Definition Record.cpp:3093
std::vector< StringRef > getValueAsListOfStrings(StringRef FieldName) const
This method looks up the specified field and returns its value as a vector of strings,...
Definition Record.cpp:3039
const RecordVal * getValue(const Init *Name) const
Definition Record.h:1840
void addValue(const RecordVal &RV)
Definition Record.h:1865
const Record * getValueAsOptionalDef(StringRef FieldName) const
This method looks up the specified field and returns its value as a Record, returning null if the fie...
Definition Record.cpp:3062
ArrayRef< std::pair< const Record *, SMRange > > getDirectSuperClasses() const
Return the direct superclasses of this record.
Definition Record.h:1832
StringRef getName() const
Definition Record.h:1766
Record(const Init *N, ArrayRef< SMLoc > locs, RecordKeeper &records, RecordKind Kind=RK_Def)
Definition Record.h:1741
void setName(const Init *Name)
Definition Record.cpp:2835
const ListInit * getValueAsListInit(StringRef FieldName) const
This method looks up the specified field and returns its value as a ListInit, throwing an exception i...
Definition Record.cpp:2989
void appendDumps(const Record *Rec)
Definition Record.h:1894
bool isSubClassOf(const Record *R) const
Definition Record.h:1900
DefInit * getDefInit() const
get the corresponding DefInit.
Definition Record.cpp:2823
SMLoc getFieldLoc(StringRef FieldName) const
Return the source location for the named field.
Definition Record.cpp:2941
void resolveReferences(const Init *NewName=nullptr)
If there are any field references that refer to fields that have been filled in, we can propagate the...
Definition Record.cpp:2895
std::optional< StringRef > getValueAsOptionalString(StringRef FieldName) const
This method looks up the specified field and returns its value as a string, throwing an exception if ...
Definition Record.cpp:2966
void removeValue(const Init *Name)
Definition Record.h:1870
ArrayRef< const Init * > getTemplateArgs() const
Definition Record.h:1804
void updateClassLoc(SMLoc Loc)
Definition Record.cpp:2801
const BitsInit * getValueAsBitsInit(StringRef FieldName) const
This method looks up the specified field and returns its value as a BitsInit, throwing an exception i...
Definition Record.cpp:2981
void addDirectSuperClass(const Record *R, SMRange Range)
Definition Record.h:1922
void appendAssertions(const Record *Rec)
Definition Record.h:1890
const Init * getNameInit() const
Definition Record.h:1768
int64_t getValueAsInt(StringRef FieldName) const
This method looks up the specified field and returns its value as an int64_t, throwing an exception i...
Definition Record.cpp:3012
void checkRecordAssertions()
Definition Record.cpp:3105
StringRef getValueAsString(StringRef FieldName) const
This method looks up the specified field and returns its value as a string, throwing an exception if ...
Definition Record.cpp:2957
Interface for looking up the initializer for a variable name, used by Init::resolveReferences.
Definition Record.h:2255
const Record * getCurrentRecord() const
Definition Record.h:2263
Represents a location in source code.
Definition SMLoc.h:22
Delegate resolving to a sub-resolver, but shadow some variable names.
Definition Record.h:2325
void addShadow(const Init *Key)
Definition Record.h:2335
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition SmallString.h:26
reference emplace_back(ArgTypes &&... Args)
void reserve(size_type N)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
"foo" - Represent an initialization by a string value.
Definition Record.h:714
static const StringInit * get(RecordKeeper &RK, StringRef, StringFormat Fmt=SF_String)
Definition Record.cpp:638
StringFormat getFormat() const
Definition Record.h:744
StringRef getValue() const
Definition Record.h:743
static StringFormat determineFormat(StringFormat Fmt1, StringFormat Fmt2)
Definition Record.h:739
const Init * convertInitializerTo(const RecTy *Ty) const override
Convert to a value whose type is Ty, or return null if this is not possible.
Definition Record.cpp:649
StringMap - This is an unconventional map that is specialized for handling keys that are "strings",...
Definition StringMap.h:129
std::pair< iterator, bool > try_emplace(StringRef Key, ArgsTy &&...Args)
Emplace a new element for the specified key into the map if the key isn't already in the map.
Definition StringMap.h:370
'string' - Represent an string value
Definition Record.h:172
std::string getAsString() const override
Definition Record.cpp:195
static const StringRecTy * get(RecordKeeper &RK)
Definition Record.cpp:191
bool typeIsConvertibleTo(const RecTy *RHS) const override
Return true if all values of 'this' type can be converted to the specified type.
Definition Record.cpp:199
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
std::string str() const
Get the contents as an std::string.
Definition StringRef.h:222
const Init * Fold(const Record *CurRec) const
Definition Record.cpp:1742
static const TernOpInit * get(TernaryOp opc, const Init *lhs, const Init *mhs, const Init *rhs, const RecTy *Type)
Definition Record.cpp:1596
std::string getAsString() const override
Convert this value to a literal form.
Definition Record.cpp:1978
const Init * resolveReferences(Resolver &R) const override
This function is used by classes that refer to other variables which may not be defined at the time t...
Definition Record.cpp:1948
TernaryOp getOpcode() const
Definition Record.h:1017
(Optionally) delegate resolving to a sub-resolver, and keep track whether there were unresolved refer...
Definition Record.h:2346
const Init * resolve(const Init *VarName) override
Return the initializer for the given variable name (should normally be a StringInit),...
Definition Record.cpp:3258
TrackUnresolvedResolver(Resolver *R=nullptr)
Definition Record.h:2351
See the file comment for details on the usage of the TrailingObjects type.
static constexpr std::enable_if_t< std::is_same_v< Foo< TrailingTys... >, Foo< Tys... > >, size_t > totalSizeToAlloc(typename trailing_objects_internal::ExtractSecondType< TrailingTys, size_t >::type... Counts)
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
This is the common superclass of types that have a specific, explicit type, stored in ValueTy.
Definition Record.h:434
const RecTy * getFieldType(const StringInit *FieldName) const override
This method is used to implement the FieldInit class.
Definition Record.cpp:2224
TypedInit(InitKind K, const RecTy *T, uint8_t Opc=0)
Definition Record.h:438
const Init * convertInitializerBitRange(ArrayRef< unsigned > Bits) const override
This function is used to implement the bit range selection operator.
Definition Record.cpp:2246
RecordKeeper & getRecordKeeper() const
Get the record keeper that initialized this Init.
Definition Record.h:454
const Init * getCastTo(const RecTy *Ty) const override
If this value is convertible to type Ty, return a value whose type is Ty, generating a !...
Definition Record.cpp:2262
const Init * convertInitializerTo(const RecTy *Ty) const override
Convert to a value whose type is Ty, or return null if this is not possible.
Definition Record.cpp:2234
const RecTy * getType() const
Get the type of the Init as a RecTy.
Definition Record.h:451
UnaryOp getOpcode() const
Definition Record.h:890
static const UnOpInit * get(UnaryOp opc, const Init *lhs, const RecTy *Type)
Definition Record.cpp:763
const Init * resolveReferences(Resolver &R) const override
This function is used by classes that refer to other variables which may not be defined at the time t...
Definition Record.cpp:976
std::string getAsString() const override
Convert this value to a literal form.
Definition Record.cpp:985
const Init * Fold(const Record *CurRec, bool IsFinal=false) const
Definition Record.cpp:774
A uniquing set that compares nodes against a typed key rather than a serialized FoldingSetNodeID.
Definition FoldingSet.h:696
T * lookup(const KeyTy &Key, FoldingSetInsertToken &Token)
Look up Key.
Definition FoldingSet.h:719
void insert(T *N, FoldingSetInsertToken Token)
Insert N, which must key identically to the lookup that produced Token.
Definition FoldingSet.h:727
'?' - Represents an uninitialized value.
Definition Record.h:469
const Init * getCastTo(const RecTy *Ty) const override
If this value is convertible to type Ty, return a value whose type is Ty, generating a !...
Definition Record.cpp:377
const Init * convertInitializerTo(const RecTy *Ty) const override
Convert to a value whose type is Ty, or return null if this is not possible.
Definition Record.cpp:379
static UnsetInit * get(RecordKeeper &RK)
Get the singleton unset Init.
Definition Record.cpp:373
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
Opcode{0} - Represent access to one bit of a variable or field.
Definition Record.h:1301
static const VarBitInit * get(const TypedInit *T, unsigned B)
Definition Record.cpp:2309
unsigned getBitNum() const
Definition Record.h:1326
std::string getAsString() const override
Convert this value to a literal form.
Definition Record.cpp:2317
const Init * resolveReferences(Resolver &R) const override
This function is used by classes that refer to other variables which may not be defined at the time t...
Definition Record.cpp:2321
size_t args_size() const
Definition Record.h:1413
ArrayRef< const ArgumentInit * > args() const
Definition Record.h:1416
static const VarDefInit * get(SMLoc Loc, const Record *Class, ArrayRef< const ArgumentInit * > Args)
Definition Record.cpp:2354
const Init * resolveReferences(Resolver &R) const override
This function is used by classes that refer to other variables which may not be defined at the time t...
Definition Record.cpp:2422
const Init * Fold() const
Definition Record.cpp:2443
std::string getAsString() const override
Convert this value to a literal form.
Definition Record.cpp:2456
'Opcode' - Represent a reference to an entire variable object.
Definition Record.h:1264
static const VarInit * get(StringRef VN, const RecTy *T)
Definition Record.cpp:2279
const Init * getBit(unsigned Bit) const override
Get the Init value of the specified bit.
Definition Record.cpp:2297
StringRef getName() const
Definition Record.cpp:2292
const Init * getNameInit() const
Definition Record.h:1282
const Init * resolveReferences(Resolver &R) const override
This method is used by classes that refer to other variables which may not be defined at the time the...
Definition Record.cpp:2303
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
A raw_ostream that writes to an std::string.
Changed
#define INT64_MIN
Definition DataTypes.h:74
#define INT64_MAX
Definition DataTypes.h:71
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
llvm::SmallVector< std::shared_ptr< RecordsSlice >, 4 > Records
This is an optimization pass for GlobalISel generic memory operations.
@ Length
Definition DWP.cpp:577
void stable_sort(R &&Range)
Definition STLExtras.h:2132
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1755
Printable print(const GCNRegPressure &RP, const GCNSubtarget *ST=nullptr, unsigned DynamicVGPRBlockSize=0)
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
Definition STLExtras.h:1685
detail::zippy< detail::zip_first, T, U, Args... > zip_equal(T &&t, U &&u, Args &&...args)
zip iterator that assumes that all iteratees have the same length.
Definition STLExtras.h:856
RelativeUniformCounterPtr Values
Definition InstrProf.h:91
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
Definition STLExtras.h:2570
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
LLVM_ABI void PrintFatalError(const Twine &Msg)
Definition Error.cpp:132
LLVM_ABI void PrintError(const Twine &Msg)
Definition Error.cpp:104
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2224
std::string utostr(uint64_t X, bool isNeg=false)
auto uninitialized_copy(R &&Src, IterTy Dst)
Definition STLExtras.h:2127
unsigned Log2_64(uint64_t Value)
Return the floor log base 2 of the specified value, -1 if the value is zero.
Definition MathExtras.h:332
LLVM_ABI bool CheckAssert(SMLoc Loc, const Init *Condition, const Init *Message)
Definition Error.cpp:163
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1762
LLVM_ABI void PrintWarning(const Twine &Msg)
Definition Error.cpp:90
auto reverse(ContainerTy &&C)
Definition STLExtras.h:408
decltype(auto) get(const PointerIntPair< PointerTy, IntBits, IntType, PtrTraits, Info > &Pair)
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1652
auto make_first_range(ContainerTy &&c)
Given a container of pairs, return a range over the first elements.
Definition STLExtras.h:1415
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
@ Sub
Subtraction of integers.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
Definition InstrProf.h:145
DWARFExpression::Operation Op
raw_ostream & operator<<(raw_ostream &OS, const APFixedPoint &FX)
ArrayRef(const T &OneElt) -> ArrayRef< T >
auto make_second_range(ContainerTy &&c)
Given a container of pairs, return a range over the second elements.
Definition STLExtras.h:1425
LLVM_ABI void dumpMessage(SMLoc Loc, const Init *Message)
Definition Error.cpp:181
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
auto find_if(R &&Range, UnaryPredicate P)
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1788
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1963
const RecTy * resolveTypes(const RecTy *T1, const RecTy *T2)
Find a common type that T1 and T2 convert to.
Definition Record.cpp:326
BumpPtrAllocatorImpl<> BumpPtrAllocator
The standard BumpPtrAllocator which just uses the default template parameters.
Definition Allocator.h:391
@ End
Run the machine verifier once, at the end of the pipeline.
Definition CodeGen.h:267
std::variant< unsigned, const Init * > ArgAuxType
Definition Record.h:506
constexpr detail::IsaCheckPredicate< Types... > IsaPred
Function object wrapper for the llvm::isa type check.
Definition Casting.h:866
std::string itostr(int64_t X)
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:878
#define N
This class represents the internal implementation of the RecordKeeper.
Definition Record.cpp:52
StringMap< const StringInit *, BumpPtrAllocator & > StringInitCodePool
Definition Record.cpp:76
StringRecTy SharedStringRecTy
Definition Record.cpp:64
UniquingSet< ExistsOpInit > TheExistsOpInitPool
Definition Record.cpp:83
UniquingSet< CondOpInit > TheCondOpInitPool
Definition Record.cpp:91
BumpPtrAllocator Allocator
Definition Record.cpp:60
UniquingSet< UnOpInit > TheUnOpInitPool
Definition Record.cpp:78
UniquingSet< ArgumentInit > TheArgumentInitPool
Definition Record.cpp:72
RecordRecTy AnyRecord
Definition Record.cpp:67
DenseMap< std::pair< const Init *, const StringInit * >, FieldInit * > TheFieldInitPool
Definition Record.cpp:90
DenseMap< int64_t, IntInit * > TheIntInitPool
Definition Record.cpp:74
UniquingSet< FoldOpInit > TheFoldOpInitPool
Definition Record.cpp:81
UniquingSet< IsAOpInit > TheIsAOpInitPool
Definition Record.cpp:82
std::vector< BitsRecTy * > SharedBitsRecTys
Definition Record.cpp:61
UniquingSet< ListInit > TheListInitPool
Definition Record.cpp:77
UniquingSet< BitsInit > TheBitsInitPool
Definition Record.cpp:73
RecordKeeperImpl(RecordKeeper &RK)
Definition Record.cpp:53
UniquingSet< DagInit > TheDagInitPool
Definition Record.cpp:92
StringMap< const StringInit *, BumpPtrAllocator & > StringInitStringPool
Definition Record.cpp:75
UniquingSet< TernOpInit > TheTernOpInitPool
Definition Record.cpp:80
UniquingSet< BinOpInit > TheBinOpInitPool
Definition Record.cpp:79
void dumpAllocationStats(raw_ostream &OS) const
Definition Record.cpp:101
DenseMap< std::pair< const RecTy *, const Init * >, VarInit * > TheVarInitPool
Definition Record.cpp:85
UniquingSet< VarDefInit > TheVarDefInitPool
Definition Record.cpp:88
UniquingSet< InstancesOpInit > TheInstancesOpInitPool
Definition Record.cpp:84
UniquingSet< RecordRecTy > RecordTypePool
Definition Record.cpp:93
DenseMap< std::pair< const TypedInit *, unsigned >, VarBitInit * > TheVarBitInitPool
Definition Record.cpp:87
Sorting predicate to sort record pointers by name.
Definition Record.h:2145