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