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