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