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