1 //===- BitcodeReader.cpp - Internal BitcodeReader implementation ----------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 10 #include "llvm/Bitcode/BitcodeReader.h" 11 #include "llvm/ADT/APFloat.h" 12 #include "llvm/ADT/APInt.h" 13 #include "llvm/ADT/ArrayRef.h" 14 #include "llvm/ADT/DenseMap.h" 15 #include "llvm/ADT/None.h" 16 #include "llvm/ADT/STLExtras.h" 17 #include "llvm/ADT/SmallString.h" 18 #include "llvm/ADT/SmallVector.h" 19 #include "llvm/ADT/StringRef.h" 20 #include "llvm/ADT/Triple.h" 21 #include "llvm/ADT/Twine.h" 22 #include "llvm/Bitcode/BitstreamReader.h" 23 #include "llvm/Bitcode/LLVMBitCodes.h" 24 #include "llvm/IR/Argument.h" 25 #include "llvm/IR/Attributes.h" 26 #include "llvm/IR/AutoUpgrade.h" 27 #include "llvm/IR/BasicBlock.h" 28 #include "llvm/IR/CallingConv.h" 29 #include "llvm/IR/CallSite.h" 30 #include "llvm/IR/Comdat.h" 31 #include "llvm/IR/Constant.h" 32 #include "llvm/IR/Constants.h" 33 #include "llvm/IR/DebugInfo.h" 34 #include "llvm/IR/DebugInfoMetadata.h" 35 #include "llvm/IR/DebugLoc.h" 36 #include "llvm/IR/DerivedTypes.h" 37 #include "llvm/IR/DiagnosticInfo.h" 38 #include "llvm/IR/DiagnosticPrinter.h" 39 #include "llvm/IR/Function.h" 40 #include "llvm/IR/GlobalAlias.h" 41 #include "llvm/IR/GlobalIFunc.h" 42 #include "llvm/IR/GlobalIndirectSymbol.h" 43 #include "llvm/IR/GlobalObject.h" 44 #include "llvm/IR/GlobalValue.h" 45 #include "llvm/IR/GlobalVariable.h" 46 #include "llvm/IR/GVMaterializer.h" 47 #include "llvm/IR/InlineAsm.h" 48 #include "llvm/IR/InstrTypes.h" 49 #include "llvm/IR/Instruction.h" 50 #include "llvm/IR/Instructions.h" 51 #include "llvm/IR/Intrinsics.h" 52 #include "llvm/IR/LLVMContext.h" 53 #include "llvm/IR/Module.h" 54 #include "llvm/IR/ModuleSummaryIndex.h" 55 #include "llvm/IR/OperandTraits.h" 56 #include "llvm/IR/Operator.h" 57 #include "llvm/IR/TrackingMDRef.h" 58 #include "llvm/IR/Type.h" 59 #include "llvm/IR/ValueHandle.h" 60 #include "llvm/Support/AtomicOrdering.h" 61 #include "llvm/Support/Casting.h" 62 #include "llvm/Support/CommandLine.h" 63 #include "llvm/Support/Compiler.h" 64 #include "llvm/Support/Debug.h" 65 #include "llvm/Support/Error.h" 66 #include "llvm/Support/ErrorHandling.h" 67 #include "llvm/Support/ManagedStatic.h" 68 #include "llvm/Support/MemoryBuffer.h" 69 #include "llvm/Support/raw_ostream.h" 70 #include <algorithm> 71 #include <cassert> 72 #include <cstddef> 73 #include <cstdint> 74 #include <deque> 75 #include <limits> 76 #include <map> 77 #include <memory> 78 #include <string> 79 #include <system_error> 80 #include <tuple> 81 #include <utility> 82 #include <vector> 83 84 using namespace llvm; 85 86 static cl::opt<bool> PrintSummaryGUIDs( 87 "print-summary-global-ids", cl::init(false), cl::Hidden, 88 cl::desc( 89 "Print the global id for each value when reading the module summary")); 90 91 namespace { 92 93 enum { 94 SWITCH_INST_MAGIC = 0x4B5 // May 2012 => 1205 => Hex 95 }; 96 97 class BitcodeReaderValueList { 98 std::vector<WeakVH> ValuePtrs; 99 100 /// As we resolve forward-referenced constants, we add information about them 101 /// to this vector. This allows us to resolve them in bulk instead of 102 /// resolving each reference at a time. See the code in 103 /// ResolveConstantForwardRefs for more information about this. 104 /// 105 /// The key of this vector is the placeholder constant, the value is the slot 106 /// number that holds the resolved value. 107 typedef std::vector<std::pair<Constant*, unsigned> > ResolveConstantsTy; 108 ResolveConstantsTy ResolveConstants; 109 LLVMContext &Context; 110 111 public: 112 BitcodeReaderValueList(LLVMContext &C) : Context(C) {} 113 ~BitcodeReaderValueList() { 114 assert(ResolveConstants.empty() && "Constants not resolved?"); 115 } 116 117 // vector compatibility methods 118 unsigned size() const { return ValuePtrs.size(); } 119 void resize(unsigned N) { ValuePtrs.resize(N); } 120 void push_back(Value *V) { ValuePtrs.emplace_back(V); } 121 122 void clear() { 123 assert(ResolveConstants.empty() && "Constants not resolved?"); 124 ValuePtrs.clear(); 125 } 126 127 Value *operator[](unsigned i) const { 128 assert(i < ValuePtrs.size()); 129 return ValuePtrs[i]; 130 } 131 132 Value *back() const { return ValuePtrs.back(); } 133 void pop_back() { ValuePtrs.pop_back(); } 134 bool empty() const { return ValuePtrs.empty(); } 135 136 void shrinkTo(unsigned N) { 137 assert(N <= size() && "Invalid shrinkTo request!"); 138 ValuePtrs.resize(N); 139 } 140 141 Constant *getConstantFwdRef(unsigned Idx, Type *Ty); 142 Value *getValueFwdRef(unsigned Idx, Type *Ty); 143 144 void assignValue(Value *V, unsigned Idx); 145 146 /// Once all constants are read, this method bulk resolves any forward 147 /// references. 148 void resolveConstantForwardRefs(); 149 }; 150 151 class BitcodeReaderMetadataList { 152 unsigned NumFwdRefs; 153 bool AnyFwdRefs; 154 unsigned MinFwdRef; 155 unsigned MaxFwdRef; 156 157 /// Array of metadata references. 158 /// 159 /// Don't use std::vector here. Some versions of libc++ copy (instead of 160 /// move) on resize, and TrackingMDRef is very expensive to copy. 161 SmallVector<TrackingMDRef, 1> MetadataPtrs; 162 163 /// Structures for resolving old type refs. 164 struct { 165 SmallDenseMap<MDString *, TempMDTuple, 1> Unknown; 166 SmallDenseMap<MDString *, DICompositeType *, 1> Final; 167 SmallDenseMap<MDString *, DICompositeType *, 1> FwdDecls; 168 SmallVector<std::pair<TrackingMDRef, TempMDTuple>, 1> Arrays; 169 } OldTypeRefs; 170 171 LLVMContext &Context; 172 173 public: 174 BitcodeReaderMetadataList(LLVMContext &C) 175 : NumFwdRefs(0), AnyFwdRefs(false), Context(C) {} 176 177 // vector compatibility methods 178 unsigned size() const { return MetadataPtrs.size(); } 179 void resize(unsigned N) { MetadataPtrs.resize(N); } 180 void push_back(Metadata *MD) { MetadataPtrs.emplace_back(MD); } 181 void clear() { MetadataPtrs.clear(); } 182 Metadata *back() const { return MetadataPtrs.back(); } 183 void pop_back() { MetadataPtrs.pop_back(); } 184 bool empty() const { return MetadataPtrs.empty(); } 185 186 Metadata *operator[](unsigned i) const { 187 assert(i < MetadataPtrs.size()); 188 return MetadataPtrs[i]; 189 } 190 191 Metadata *lookup(unsigned I) const { 192 if (I < MetadataPtrs.size()) 193 return MetadataPtrs[I]; 194 return nullptr; 195 } 196 197 void shrinkTo(unsigned N) { 198 assert(N <= size() && "Invalid shrinkTo request!"); 199 assert(!AnyFwdRefs && "Unexpected forward refs"); 200 MetadataPtrs.resize(N); 201 } 202 203 /// Return the given metadata, creating a replaceable forward reference if 204 /// necessary. 205 Metadata *getMetadataFwdRef(unsigned Idx); 206 207 /// Return the the given metadata only if it is fully resolved. 208 /// 209 /// Gives the same result as \a lookup(), unless \a MDNode::isResolved() 210 /// would give \c false. 211 Metadata *getMetadataIfResolved(unsigned Idx); 212 213 MDNode *getMDNodeFwdRefOrNull(unsigned Idx); 214 void assignValue(Metadata *MD, unsigned Idx); 215 void tryToResolveCycles(); 216 bool hasFwdRefs() const { return AnyFwdRefs; } 217 218 /// Upgrade a type that had an MDString reference. 219 void addTypeRef(MDString &UUID, DICompositeType &CT); 220 221 /// Upgrade a type that had an MDString reference. 222 Metadata *upgradeTypeRef(Metadata *MaybeUUID); 223 224 /// Upgrade a type ref array that may have MDString references. 225 Metadata *upgradeTypeRefArray(Metadata *MaybeTuple); 226 227 private: 228 Metadata *resolveTypeRefArray(Metadata *MaybeTuple); 229 }; 230 231 Error error(const Twine &Message) { 232 return make_error<StringError>( 233 Message, make_error_code(BitcodeError::CorruptedBitcode)); 234 } 235 236 /// Helper to read the header common to all bitcode files. 237 bool hasValidBitcodeHeader(BitstreamCursor &Stream) { 238 // Sniff for the signature. 239 if (!Stream.canSkipToPos(4) || 240 Stream.Read(8) != 'B' || 241 Stream.Read(8) != 'C' || 242 Stream.Read(4) != 0x0 || 243 Stream.Read(4) != 0xC || 244 Stream.Read(4) != 0xE || 245 Stream.Read(4) != 0xD) 246 return false; 247 return true; 248 } 249 250 Expected<BitstreamCursor> initStream(MemoryBufferRef Buffer) { 251 const unsigned char *BufPtr = (const unsigned char *)Buffer.getBufferStart(); 252 const unsigned char *BufEnd = BufPtr + Buffer.getBufferSize(); 253 254 if (Buffer.getBufferSize() & 3) 255 return error("Invalid bitcode signature"); 256 257 // If we have a wrapper header, parse it and ignore the non-bc file contents. 258 // The magic number is 0x0B17C0DE stored in little endian. 259 if (isBitcodeWrapper(BufPtr, BufEnd)) 260 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true)) 261 return error("Invalid bitcode wrapper header"); 262 263 BitstreamCursor Stream(ArrayRef<uint8_t>(BufPtr, BufEnd)); 264 if (!hasValidBitcodeHeader(Stream)) 265 return error("Invalid bitcode signature"); 266 267 return std::move(Stream); 268 } 269 270 /// Convert a string from a record into an std::string, return true on failure. 271 template <typename StrTy> 272 static bool convertToString(ArrayRef<uint64_t> Record, unsigned Idx, 273 StrTy &Result) { 274 if (Idx > Record.size()) 275 return true; 276 277 for (unsigned i = Idx, e = Record.size(); i != e; ++i) 278 Result += (char)Record[i]; 279 return false; 280 } 281 282 /// Read the "IDENTIFICATION_BLOCK_ID" block, do some basic enforcement on the 283 /// "epoch" encoded in the bitcode, and return the producer name if any. 284 Expected<std::string> readIdentificationBlock(BitstreamCursor &Stream) { 285 if (Stream.EnterSubBlock(bitc::IDENTIFICATION_BLOCK_ID)) 286 return error("Invalid record"); 287 288 // Read all the records. 289 SmallVector<uint64_t, 64> Record; 290 291 std::string ProducerIdentification; 292 293 while (true) { 294 BitstreamEntry Entry = Stream.advance(); 295 296 switch (Entry.Kind) { 297 default: 298 case BitstreamEntry::Error: 299 return error("Malformed block"); 300 case BitstreamEntry::EndBlock: 301 return ProducerIdentification; 302 case BitstreamEntry::Record: 303 // The interesting case. 304 break; 305 } 306 307 // Read a record. 308 Record.clear(); 309 unsigned BitCode = Stream.readRecord(Entry.ID, Record); 310 switch (BitCode) { 311 default: // Default behavior: reject 312 return error("Invalid value"); 313 case bitc::IDENTIFICATION_CODE_STRING: // IDENTIFICATION: [strchr x N] 314 convertToString(Record, 0, ProducerIdentification); 315 break; 316 case bitc::IDENTIFICATION_CODE_EPOCH: { // EPOCH: [epoch#] 317 unsigned epoch = (unsigned)Record[0]; 318 if (epoch != bitc::BITCODE_CURRENT_EPOCH) { 319 return error( 320 Twine("Incompatible epoch: Bitcode '") + Twine(epoch) + 321 "' vs current: '" + Twine(bitc::BITCODE_CURRENT_EPOCH) + "'"); 322 } 323 } 324 } 325 } 326 } 327 328 Expected<std::string> readIdentificationCode(BitstreamCursor &Stream) { 329 // We expect a number of well-defined blocks, though we don't necessarily 330 // need to understand them all. 331 while (true) { 332 if (Stream.AtEndOfStream()) 333 return ""; 334 335 BitstreamEntry Entry = Stream.advance(); 336 switch (Entry.Kind) { 337 case BitstreamEntry::EndBlock: 338 case BitstreamEntry::Error: 339 return error("Malformed block"); 340 341 case BitstreamEntry::SubBlock: 342 if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID) 343 return readIdentificationBlock(Stream); 344 345 // Ignore other sub-blocks. 346 if (Stream.SkipBlock()) 347 return error("Malformed block"); 348 continue; 349 case BitstreamEntry::Record: 350 Stream.skipRecord(Entry.ID); 351 continue; 352 } 353 } 354 } 355 356 Expected<bool> hasObjCCategoryInModule(BitstreamCursor &Stream) { 357 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID)) 358 return error("Invalid record"); 359 360 SmallVector<uint64_t, 64> Record; 361 // Read all the records for this module. 362 363 while (true) { 364 BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 365 366 switch (Entry.Kind) { 367 case BitstreamEntry::SubBlock: // Handled for us already. 368 case BitstreamEntry::Error: 369 return error("Malformed block"); 370 case BitstreamEntry::EndBlock: 371 return false; 372 case BitstreamEntry::Record: 373 // The interesting case. 374 break; 375 } 376 377 // Read a record. 378 switch (Stream.readRecord(Entry.ID, Record)) { 379 default: 380 break; // Default behavior, ignore unknown content. 381 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N] 382 std::string S; 383 if (convertToString(Record, 0, S)) 384 return error("Invalid record"); 385 // Check for the i386 and other (x86_64, ARM) conventions 386 if (S.find("__DATA, __objc_catlist") != std::string::npos || 387 S.find("__OBJC,__category") != std::string::npos) 388 return true; 389 break; 390 } 391 } 392 Record.clear(); 393 } 394 llvm_unreachable("Exit infinite loop"); 395 } 396 397 Expected<bool> hasObjCCategory(BitstreamCursor &Stream) { 398 // We expect a number of well-defined blocks, though we don't necessarily 399 // need to understand them all. 400 while (true) { 401 BitstreamEntry Entry = Stream.advance(); 402 403 switch (Entry.Kind) { 404 case BitstreamEntry::Error: 405 return error("Malformed block"); 406 case BitstreamEntry::EndBlock: 407 return false; 408 409 case BitstreamEntry::SubBlock: 410 if (Entry.ID == bitc::MODULE_BLOCK_ID) 411 return hasObjCCategoryInModule(Stream); 412 413 // Ignore other sub-blocks. 414 if (Stream.SkipBlock()) 415 return error("Malformed block"); 416 continue; 417 418 case BitstreamEntry::Record: 419 Stream.skipRecord(Entry.ID); 420 continue; 421 } 422 } 423 } 424 425 Expected<std::string> readModuleTriple(BitstreamCursor &Stream) { 426 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID)) 427 return error("Invalid record"); 428 429 SmallVector<uint64_t, 64> Record; 430 431 std::string Triple; 432 433 // Read all the records for this module. 434 while (true) { 435 BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 436 437 switch (Entry.Kind) { 438 case BitstreamEntry::SubBlock: // Handled for us already. 439 case BitstreamEntry::Error: 440 return error("Malformed block"); 441 case BitstreamEntry::EndBlock: 442 return Triple; 443 case BitstreamEntry::Record: 444 // The interesting case. 445 break; 446 } 447 448 // Read a record. 449 switch (Stream.readRecord(Entry.ID, Record)) { 450 default: break; // Default behavior, ignore unknown content. 451 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N] 452 std::string S; 453 if (convertToString(Record, 0, S)) 454 return error("Invalid record"); 455 Triple = S; 456 break; 457 } 458 } 459 Record.clear(); 460 } 461 llvm_unreachable("Exit infinite loop"); 462 } 463 464 Expected<std::string> readTriple(BitstreamCursor &Stream) { 465 // We expect a number of well-defined blocks, though we don't necessarily 466 // need to understand them all. 467 while (true) { 468 BitstreamEntry Entry = Stream.advance(); 469 470 switch (Entry.Kind) { 471 case BitstreamEntry::Error: 472 return error("Malformed block"); 473 case BitstreamEntry::EndBlock: 474 return ""; 475 476 case BitstreamEntry::SubBlock: 477 if (Entry.ID == bitc::MODULE_BLOCK_ID) 478 return readModuleTriple(Stream); 479 480 // Ignore other sub-blocks. 481 if (Stream.SkipBlock()) 482 return error("Malformed block"); 483 continue; 484 485 case BitstreamEntry::Record: 486 Stream.skipRecord(Entry.ID); 487 continue; 488 } 489 } 490 } 491 492 class BitcodeReaderBase { 493 protected: 494 BitcodeReaderBase(BitstreamCursor Stream) : Stream(std::move(Stream)) { 495 this->Stream.setBlockInfo(&BlockInfo); 496 } 497 498 BitstreamBlockInfo BlockInfo; 499 BitstreamCursor Stream; 500 501 bool readBlockInfo(); 502 503 // Contains an arbitrary and optional string identifying the bitcode producer 504 std::string ProducerIdentification; 505 506 Error error(const Twine &Message); 507 }; 508 509 Error BitcodeReaderBase::error(const Twine &Message) { 510 std::string FullMsg = Message.str(); 511 if (!ProducerIdentification.empty()) 512 FullMsg += " (Producer: '" + ProducerIdentification + "' Reader: 'LLVM " + 513 LLVM_VERSION_STRING "')"; 514 return ::error(FullMsg); 515 } 516 517 class BitcodeReader : public BitcodeReaderBase, public GVMaterializer { 518 LLVMContext &Context; 519 Module *TheModule = nullptr; 520 // Next offset to start scanning for lazy parsing of function bodies. 521 uint64_t NextUnreadBit = 0; 522 // Last function offset found in the VST. 523 uint64_t LastFunctionBlockBit = 0; 524 bool SeenValueSymbolTable = false; 525 uint64_t VSTOffset = 0; 526 527 std::vector<Type*> TypeList; 528 BitcodeReaderValueList ValueList; 529 BitcodeReaderMetadataList MetadataList; 530 std::vector<Comdat *> ComdatList; 531 SmallVector<Instruction *, 64> InstructionList; 532 533 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInits; 534 std::vector<std::pair<GlobalIndirectSymbol*, unsigned> > IndirectSymbolInits; 535 std::vector<std::pair<Function*, unsigned> > FunctionPrefixes; 536 std::vector<std::pair<Function*, unsigned> > FunctionPrologues; 537 std::vector<std::pair<Function*, unsigned> > FunctionPersonalityFns; 538 539 bool HasSeenOldLoopTags = false; 540 541 /// The set of attributes by index. Index zero in the file is for null, and 542 /// is thus not represented here. As such all indices are off by one. 543 std::vector<AttributeSet> MAttributes; 544 545 /// The set of attribute groups. 546 std::map<unsigned, AttributeSet> MAttributeGroups; 547 548 /// While parsing a function body, this is a list of the basic blocks for the 549 /// function. 550 std::vector<BasicBlock*> FunctionBBs; 551 552 // When reading the module header, this list is populated with functions that 553 // have bodies later in the file. 554 std::vector<Function*> FunctionsWithBodies; 555 556 // When intrinsic functions are encountered which require upgrading they are 557 // stored here with their replacement function. 558 typedef DenseMap<Function*, Function*> UpdatedIntrinsicMap; 559 UpdatedIntrinsicMap UpgradedIntrinsics; 560 // Intrinsics which were remangled because of types rename 561 UpdatedIntrinsicMap RemangledIntrinsics; 562 563 // Map the bitcode's custom MDKind ID to the Module's MDKind ID. 564 DenseMap<unsigned, unsigned> MDKindMap; 565 566 // Several operations happen after the module header has been read, but 567 // before function bodies are processed. This keeps track of whether 568 // we've done this yet. 569 bool SeenFirstFunctionBody = false; 570 571 /// When function bodies are initially scanned, this map contains info about 572 /// where to find deferred function body in the stream. 573 DenseMap<Function*, uint64_t> DeferredFunctionInfo; 574 575 /// When Metadata block is initially scanned when parsing the module, we may 576 /// choose to defer parsing of the metadata. This vector contains info about 577 /// which Metadata blocks are deferred. 578 std::vector<uint64_t> DeferredMetadataInfo; 579 580 /// These are basic blocks forward-referenced by block addresses. They are 581 /// inserted lazily into functions when they're loaded. The basic block ID is 582 /// its index into the vector. 583 DenseMap<Function *, std::vector<BasicBlock *>> BasicBlockFwdRefs; 584 std::deque<Function *> BasicBlockFwdRefQueue; 585 586 /// Indicates that we are using a new encoding for instruction operands where 587 /// most operands in the current FUNCTION_BLOCK are encoded relative to the 588 /// instruction number, for a more compact encoding. Some instruction 589 /// operands are not relative to the instruction ID: basic block numbers, and 590 /// types. Once the old style function blocks have been phased out, we would 591 /// not need this flag. 592 bool UseRelativeIDs = false; 593 594 /// True if all functions will be materialized, negating the need to process 595 /// (e.g.) blockaddress forward references. 596 bool WillMaterializeAllForwardRefs = false; 597 598 /// True if any Metadata block has been materialized. 599 bool IsMetadataMaterialized = false; 600 601 bool StripDebugInfo = false; 602 603 /// Functions that need to be matched with subprograms when upgrading old 604 /// metadata. 605 SmallDenseMap<Function *, DISubprogram *, 16> FunctionsWithSPs; 606 607 std::vector<std::string> BundleTags; 608 609 public: 610 BitcodeReader(BitstreamCursor Stream, StringRef ProducerIdentification, 611 LLVMContext &Context); 612 613 Error materializeForwardReferencedFunctions(); 614 615 Error materialize(GlobalValue *GV) override; 616 Error materializeModule() override; 617 std::vector<StructType *> getIdentifiedStructTypes() const override; 618 619 /// \brief Main interface to parsing a bitcode buffer. 620 /// \returns true if an error occurred. 621 Error parseBitcodeInto(Module *M, bool ShouldLazyLoadMetadata = false); 622 623 static uint64_t decodeSignRotatedValue(uint64_t V); 624 625 /// Materialize any deferred Metadata block. 626 Error materializeMetadata() override; 627 628 void setStripDebugInfo() override; 629 630 private: 631 std::vector<StructType *> IdentifiedStructTypes; 632 StructType *createIdentifiedStructType(LLVMContext &Context, StringRef Name); 633 StructType *createIdentifiedStructType(LLVMContext &Context); 634 635 Type *getTypeByID(unsigned ID); 636 637 Value *getFnValueByID(unsigned ID, Type *Ty) { 638 if (Ty && Ty->isMetadataTy()) 639 return MetadataAsValue::get(Ty->getContext(), getFnMetadataByID(ID)); 640 return ValueList.getValueFwdRef(ID, Ty); 641 } 642 643 Metadata *getFnMetadataByID(unsigned ID) { 644 return MetadataList.getMetadataFwdRef(ID); 645 } 646 647 BasicBlock *getBasicBlock(unsigned ID) const { 648 if (ID >= FunctionBBs.size()) return nullptr; // Invalid ID 649 return FunctionBBs[ID]; 650 } 651 652 AttributeSet getAttributes(unsigned i) const { 653 if (i-1 < MAttributes.size()) 654 return MAttributes[i-1]; 655 return AttributeSet(); 656 } 657 658 /// Read a value/type pair out of the specified record from slot 'Slot'. 659 /// Increment Slot past the number of slots used in the record. Return true on 660 /// failure. 661 bool getValueTypePair(SmallVectorImpl<uint64_t> &Record, unsigned &Slot, 662 unsigned InstNum, Value *&ResVal) { 663 if (Slot == Record.size()) return true; 664 unsigned ValNo = (unsigned)Record[Slot++]; 665 // Adjust the ValNo, if it was encoded relative to the InstNum. 666 if (UseRelativeIDs) 667 ValNo = InstNum - ValNo; 668 if (ValNo < InstNum) { 669 // If this is not a forward reference, just return the value we already 670 // have. 671 ResVal = getFnValueByID(ValNo, nullptr); 672 return ResVal == nullptr; 673 } 674 if (Slot == Record.size()) 675 return true; 676 677 unsigned TypeNo = (unsigned)Record[Slot++]; 678 ResVal = getFnValueByID(ValNo, getTypeByID(TypeNo)); 679 return ResVal == nullptr; 680 } 681 682 /// Read a value out of the specified record from slot 'Slot'. Increment Slot 683 /// past the number of slots used by the value in the record. Return true if 684 /// there is an error. 685 bool popValue(SmallVectorImpl<uint64_t> &Record, unsigned &Slot, 686 unsigned InstNum, Type *Ty, Value *&ResVal) { 687 if (getValue(Record, Slot, InstNum, Ty, ResVal)) 688 return true; 689 // All values currently take a single record slot. 690 ++Slot; 691 return false; 692 } 693 694 /// Like popValue, but does not increment the Slot number. 695 bool getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot, 696 unsigned InstNum, Type *Ty, Value *&ResVal) { 697 ResVal = getValue(Record, Slot, InstNum, Ty); 698 return ResVal == nullptr; 699 } 700 701 /// Version of getValue that returns ResVal directly, or 0 if there is an 702 /// error. 703 Value *getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot, 704 unsigned InstNum, Type *Ty) { 705 if (Slot == Record.size()) return nullptr; 706 unsigned ValNo = (unsigned)Record[Slot]; 707 // Adjust the ValNo, if it was encoded relative to the InstNum. 708 if (UseRelativeIDs) 709 ValNo = InstNum - ValNo; 710 return getFnValueByID(ValNo, Ty); 711 } 712 713 /// Like getValue, but decodes signed VBRs. 714 Value *getValueSigned(SmallVectorImpl<uint64_t> &Record, unsigned Slot, 715 unsigned InstNum, Type *Ty) { 716 if (Slot == Record.size()) return nullptr; 717 unsigned ValNo = (unsigned)decodeSignRotatedValue(Record[Slot]); 718 // Adjust the ValNo, if it was encoded relative to the InstNum. 719 if (UseRelativeIDs) 720 ValNo = InstNum - ValNo; 721 return getFnValueByID(ValNo, Ty); 722 } 723 724 /// Converts alignment exponent (i.e. power of two (or zero)) to the 725 /// corresponding alignment to use. If alignment is too large, returns 726 /// a corresponding error code. 727 Error parseAlignmentValue(uint64_t Exponent, unsigned &Alignment); 728 Error parseAttrKind(uint64_t Code, Attribute::AttrKind *Kind); 729 Error parseModule(uint64_t ResumeBit, bool ShouldLazyLoadMetadata = false); 730 Error parseAttributeBlock(); 731 Error parseAttributeGroupBlock(); 732 Error parseTypeTable(); 733 Error parseTypeTableBody(); 734 Error parseOperandBundleTags(); 735 736 Expected<Value *> recordValue(SmallVectorImpl<uint64_t> &Record, 737 unsigned NameIndex, Triple &TT); 738 Error parseValueSymbolTable(uint64_t Offset = 0); 739 Error parseConstants(); 740 Error rememberAndSkipFunctionBodies(); 741 Error rememberAndSkipFunctionBody(); 742 /// Save the positions of the Metadata blocks and skip parsing the blocks. 743 Error rememberAndSkipMetadata(); 744 Error typeCheckLoadStoreInst(Type *ValType, Type *PtrType); 745 Error parseFunctionBody(Function *F); 746 Error globalCleanup(); 747 Error resolveGlobalAndIndirectSymbolInits(); 748 Error parseMetadata(bool ModuleLevel = false); 749 Error parseMetadataStrings(ArrayRef<uint64_t> Record, StringRef Blob, 750 unsigned &NextMetadataNo); 751 Error parseMetadataKinds(); 752 Error parseMetadataKindRecord(SmallVectorImpl<uint64_t> &Record); 753 Error parseGlobalObjectAttachment(GlobalObject &GO, 754 ArrayRef<uint64_t> Record); 755 Error parseMetadataAttachment(Function &F); 756 Error parseUseLists(); 757 Error findFunctionInStream( 758 Function *F, 759 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator); 760 }; 761 762 /// Class to manage reading and parsing function summary index bitcode 763 /// files/sections. 764 class ModuleSummaryIndexBitcodeReader : public BitcodeReaderBase { 765 /// Eventually points to the module index built during parsing. 766 ModuleSummaryIndex *TheIndex = nullptr; 767 768 /// Used to indicate whether caller only wants to check for the presence 769 /// of the global value summary bitcode section. All blocks are skipped, 770 /// but the SeenGlobalValSummary boolean is set. 771 bool CheckGlobalValSummaryPresenceOnly = false; 772 773 /// Indicates whether we have encountered a global value summary section 774 /// yet during parsing, used when checking if file contains global value 775 /// summary section. 776 bool SeenGlobalValSummary = false; 777 778 /// Indicates whether we have already parsed the VST, used for error checking. 779 bool SeenValueSymbolTable = false; 780 781 /// Set to the offset of the VST recorded in the MODULE_CODE_VSTOFFSET record. 782 /// Used to enable on-demand parsing of the VST. 783 uint64_t VSTOffset = 0; 784 785 // Map to save ValueId to GUID association that was recorded in the 786 // ValueSymbolTable. It is used after the VST is parsed to convert 787 // call graph edges read from the function summary from referencing 788 // callees by their ValueId to using the GUID instead, which is how 789 // they are recorded in the summary index being built. 790 // We save a second GUID which is the same as the first one, but ignoring the 791 // linkage, i.e. for value other than local linkage they are identical. 792 DenseMap<unsigned, std::pair<GlobalValue::GUID, GlobalValue::GUID>> 793 ValueIdToCallGraphGUIDMap; 794 795 /// Map populated during module path string table parsing, from the 796 /// module ID to a string reference owned by the index's module 797 /// path string table, used to correlate with combined index 798 /// summary records. 799 DenseMap<uint64_t, StringRef> ModuleIdMap; 800 801 /// Original source file name recorded in a bitcode record. 802 std::string SourceFileName; 803 804 public: 805 ModuleSummaryIndexBitcodeReader( 806 BitstreamCursor Stream, bool CheckGlobalValSummaryPresenceOnly = false); 807 808 /// Check if the parser has encountered a summary section. 809 bool foundGlobalValSummary() { return SeenGlobalValSummary; } 810 811 /// \brief Main interface to parsing a bitcode buffer. 812 /// \returns true if an error occurred. 813 Error parseSummaryIndexInto(ModuleSummaryIndex *I, StringRef ModulePath); 814 815 private: 816 Error parseModule(StringRef ModulePath); 817 Error parseValueSymbolTable( 818 uint64_t Offset, 819 DenseMap<unsigned, GlobalValue::LinkageTypes> &ValueIdToLinkageMap); 820 Error parseEntireSummary(StringRef ModulePath); 821 Error parseModuleStringTable(); 822 std::pair<GlobalValue::GUID, GlobalValue::GUID> 823 824 getGUIDFromValueId(unsigned ValueId); 825 std::pair<GlobalValue::GUID, CalleeInfo::HotnessType> 826 readCallGraphEdge(const SmallVector<uint64_t, 64> &Record, unsigned int &I, 827 bool IsOldProfileFormat, bool HasProfile); 828 }; 829 830 } // end anonymous namespace 831 832 std::error_code llvm::errorToErrorCodeAndEmitErrors(LLVMContext &Ctx, 833 Error Err) { 834 if (Err) { 835 std::error_code EC; 836 handleAllErrors(std::move(Err), [&](ErrorInfoBase &EIB) { 837 EC = EIB.convertToErrorCode(); 838 Ctx.emitError(EIB.message()); 839 }); 840 return EC; 841 } 842 return std::error_code(); 843 } 844 845 BitcodeReader::BitcodeReader(BitstreamCursor Stream, 846 StringRef ProducerIdentification, 847 LLVMContext &Context) 848 : BitcodeReaderBase(std::move(Stream)), Context(Context), 849 ValueList(Context), MetadataList(Context) { 850 this->ProducerIdentification = ProducerIdentification; 851 } 852 853 Error BitcodeReader::materializeForwardReferencedFunctions() { 854 if (WillMaterializeAllForwardRefs) 855 return Error::success(); 856 857 // Prevent recursion. 858 WillMaterializeAllForwardRefs = true; 859 860 while (!BasicBlockFwdRefQueue.empty()) { 861 Function *F = BasicBlockFwdRefQueue.front(); 862 BasicBlockFwdRefQueue.pop_front(); 863 assert(F && "Expected valid function"); 864 if (!BasicBlockFwdRefs.count(F)) 865 // Already materialized. 866 continue; 867 868 // Check for a function that isn't materializable to prevent an infinite 869 // loop. When parsing a blockaddress stored in a global variable, there 870 // isn't a trivial way to check if a function will have a body without a 871 // linear search through FunctionsWithBodies, so just check it here. 872 if (!F->isMaterializable()) 873 return error("Never resolved function from blockaddress"); 874 875 // Try to materialize F. 876 if (Error Err = materialize(F)) 877 return Err; 878 } 879 assert(BasicBlockFwdRefs.empty() && "Function missing from queue"); 880 881 // Reset state. 882 WillMaterializeAllForwardRefs = false; 883 return Error::success(); 884 } 885 886 //===----------------------------------------------------------------------===// 887 // Helper functions to implement forward reference resolution, etc. 888 //===----------------------------------------------------------------------===// 889 890 static bool hasImplicitComdat(size_t Val) { 891 switch (Val) { 892 default: 893 return false; 894 case 1: // Old WeakAnyLinkage 895 case 4: // Old LinkOnceAnyLinkage 896 case 10: // Old WeakODRLinkage 897 case 11: // Old LinkOnceODRLinkage 898 return true; 899 } 900 } 901 902 static GlobalValue::LinkageTypes getDecodedLinkage(unsigned Val) { 903 switch (Val) { 904 default: // Map unknown/new linkages to external 905 case 0: 906 return GlobalValue::ExternalLinkage; 907 case 2: 908 return GlobalValue::AppendingLinkage; 909 case 3: 910 return GlobalValue::InternalLinkage; 911 case 5: 912 return GlobalValue::ExternalLinkage; // Obsolete DLLImportLinkage 913 case 6: 914 return GlobalValue::ExternalLinkage; // Obsolete DLLExportLinkage 915 case 7: 916 return GlobalValue::ExternalWeakLinkage; 917 case 8: 918 return GlobalValue::CommonLinkage; 919 case 9: 920 return GlobalValue::PrivateLinkage; 921 case 12: 922 return GlobalValue::AvailableExternallyLinkage; 923 case 13: 924 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateLinkage 925 case 14: 926 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateWeakLinkage 927 case 15: 928 return GlobalValue::ExternalLinkage; // Obsolete LinkOnceODRAutoHideLinkage 929 case 1: // Old value with implicit comdat. 930 case 16: 931 return GlobalValue::WeakAnyLinkage; 932 case 10: // Old value with implicit comdat. 933 case 17: 934 return GlobalValue::WeakODRLinkage; 935 case 4: // Old value with implicit comdat. 936 case 18: 937 return GlobalValue::LinkOnceAnyLinkage; 938 case 11: // Old value with implicit comdat. 939 case 19: 940 return GlobalValue::LinkOnceODRLinkage; 941 } 942 } 943 944 /// Decode the flags for GlobalValue in the summary. 945 static GlobalValueSummary::GVFlags getDecodedGVSummaryFlags(uint64_t RawFlags, 946 uint64_t Version) { 947 // Summary were not emitted before LLVM 3.9, we don't need to upgrade Linkage 948 // like getDecodedLinkage() above. Any future change to the linkage enum and 949 // to getDecodedLinkage() will need to be taken into account here as above. 950 auto Linkage = GlobalValue::LinkageTypes(RawFlags & 0xF); // 4 bits 951 RawFlags = RawFlags >> 4; 952 bool NoRename = RawFlags & 0x1; 953 bool IsNotViableToInline = RawFlags & 0x2; 954 bool HasInlineAsmMaybeReferencingInternal = RawFlags & 0x4; 955 return GlobalValueSummary::GVFlags(Linkage, NoRename, 956 HasInlineAsmMaybeReferencingInternal, 957 IsNotViableToInline); 958 } 959 960 static GlobalValue::VisibilityTypes getDecodedVisibility(unsigned Val) { 961 switch (Val) { 962 default: // Map unknown visibilities to default. 963 case 0: return GlobalValue::DefaultVisibility; 964 case 1: return GlobalValue::HiddenVisibility; 965 case 2: return GlobalValue::ProtectedVisibility; 966 } 967 } 968 969 static GlobalValue::DLLStorageClassTypes 970 getDecodedDLLStorageClass(unsigned Val) { 971 switch (Val) { 972 default: // Map unknown values to default. 973 case 0: return GlobalValue::DefaultStorageClass; 974 case 1: return GlobalValue::DLLImportStorageClass; 975 case 2: return GlobalValue::DLLExportStorageClass; 976 } 977 } 978 979 static GlobalVariable::ThreadLocalMode getDecodedThreadLocalMode(unsigned Val) { 980 switch (Val) { 981 case 0: return GlobalVariable::NotThreadLocal; 982 default: // Map unknown non-zero value to general dynamic. 983 case 1: return GlobalVariable::GeneralDynamicTLSModel; 984 case 2: return GlobalVariable::LocalDynamicTLSModel; 985 case 3: return GlobalVariable::InitialExecTLSModel; 986 case 4: return GlobalVariable::LocalExecTLSModel; 987 } 988 } 989 990 static GlobalVariable::UnnamedAddr getDecodedUnnamedAddrType(unsigned Val) { 991 switch (Val) { 992 default: // Map unknown to UnnamedAddr::None. 993 case 0: return GlobalVariable::UnnamedAddr::None; 994 case 1: return GlobalVariable::UnnamedAddr::Global; 995 case 2: return GlobalVariable::UnnamedAddr::Local; 996 } 997 } 998 999 static int getDecodedCastOpcode(unsigned Val) { 1000 switch (Val) { 1001 default: return -1; 1002 case bitc::CAST_TRUNC : return Instruction::Trunc; 1003 case bitc::CAST_ZEXT : return Instruction::ZExt; 1004 case bitc::CAST_SEXT : return Instruction::SExt; 1005 case bitc::CAST_FPTOUI : return Instruction::FPToUI; 1006 case bitc::CAST_FPTOSI : return Instruction::FPToSI; 1007 case bitc::CAST_UITOFP : return Instruction::UIToFP; 1008 case bitc::CAST_SITOFP : return Instruction::SIToFP; 1009 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc; 1010 case bitc::CAST_FPEXT : return Instruction::FPExt; 1011 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt; 1012 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr; 1013 case bitc::CAST_BITCAST : return Instruction::BitCast; 1014 case bitc::CAST_ADDRSPACECAST: return Instruction::AddrSpaceCast; 1015 } 1016 } 1017 1018 static int getDecodedBinaryOpcode(unsigned Val, Type *Ty) { 1019 bool IsFP = Ty->isFPOrFPVectorTy(); 1020 // BinOps are only valid for int/fp or vector of int/fp types 1021 if (!IsFP && !Ty->isIntOrIntVectorTy()) 1022 return -1; 1023 1024 switch (Val) { 1025 default: 1026 return -1; 1027 case bitc::BINOP_ADD: 1028 return IsFP ? Instruction::FAdd : Instruction::Add; 1029 case bitc::BINOP_SUB: 1030 return IsFP ? Instruction::FSub : Instruction::Sub; 1031 case bitc::BINOP_MUL: 1032 return IsFP ? Instruction::FMul : Instruction::Mul; 1033 case bitc::BINOP_UDIV: 1034 return IsFP ? -1 : Instruction::UDiv; 1035 case bitc::BINOP_SDIV: 1036 return IsFP ? Instruction::FDiv : Instruction::SDiv; 1037 case bitc::BINOP_UREM: 1038 return IsFP ? -1 : Instruction::URem; 1039 case bitc::BINOP_SREM: 1040 return IsFP ? Instruction::FRem : Instruction::SRem; 1041 case bitc::BINOP_SHL: 1042 return IsFP ? -1 : Instruction::Shl; 1043 case bitc::BINOP_LSHR: 1044 return IsFP ? -1 : Instruction::LShr; 1045 case bitc::BINOP_ASHR: 1046 return IsFP ? -1 : Instruction::AShr; 1047 case bitc::BINOP_AND: 1048 return IsFP ? -1 : Instruction::And; 1049 case bitc::BINOP_OR: 1050 return IsFP ? -1 : Instruction::Or; 1051 case bitc::BINOP_XOR: 1052 return IsFP ? -1 : Instruction::Xor; 1053 } 1054 } 1055 1056 static AtomicRMWInst::BinOp getDecodedRMWOperation(unsigned Val) { 1057 switch (Val) { 1058 default: return AtomicRMWInst::BAD_BINOP; 1059 case bitc::RMW_XCHG: return AtomicRMWInst::Xchg; 1060 case bitc::RMW_ADD: return AtomicRMWInst::Add; 1061 case bitc::RMW_SUB: return AtomicRMWInst::Sub; 1062 case bitc::RMW_AND: return AtomicRMWInst::And; 1063 case bitc::RMW_NAND: return AtomicRMWInst::Nand; 1064 case bitc::RMW_OR: return AtomicRMWInst::Or; 1065 case bitc::RMW_XOR: return AtomicRMWInst::Xor; 1066 case bitc::RMW_MAX: return AtomicRMWInst::Max; 1067 case bitc::RMW_MIN: return AtomicRMWInst::Min; 1068 case bitc::RMW_UMAX: return AtomicRMWInst::UMax; 1069 case bitc::RMW_UMIN: return AtomicRMWInst::UMin; 1070 } 1071 } 1072 1073 static AtomicOrdering getDecodedOrdering(unsigned Val) { 1074 switch (Val) { 1075 case bitc::ORDERING_NOTATOMIC: return AtomicOrdering::NotAtomic; 1076 case bitc::ORDERING_UNORDERED: return AtomicOrdering::Unordered; 1077 case bitc::ORDERING_MONOTONIC: return AtomicOrdering::Monotonic; 1078 case bitc::ORDERING_ACQUIRE: return AtomicOrdering::Acquire; 1079 case bitc::ORDERING_RELEASE: return AtomicOrdering::Release; 1080 case bitc::ORDERING_ACQREL: return AtomicOrdering::AcquireRelease; 1081 default: // Map unknown orderings to sequentially-consistent. 1082 case bitc::ORDERING_SEQCST: return AtomicOrdering::SequentiallyConsistent; 1083 } 1084 } 1085 1086 static SynchronizationScope getDecodedSynchScope(unsigned Val) { 1087 switch (Val) { 1088 case bitc::SYNCHSCOPE_SINGLETHREAD: return SingleThread; 1089 default: // Map unknown scopes to cross-thread. 1090 case bitc::SYNCHSCOPE_CROSSTHREAD: return CrossThread; 1091 } 1092 } 1093 1094 static Comdat::SelectionKind getDecodedComdatSelectionKind(unsigned Val) { 1095 switch (Val) { 1096 default: // Map unknown selection kinds to any. 1097 case bitc::COMDAT_SELECTION_KIND_ANY: 1098 return Comdat::Any; 1099 case bitc::COMDAT_SELECTION_KIND_EXACT_MATCH: 1100 return Comdat::ExactMatch; 1101 case bitc::COMDAT_SELECTION_KIND_LARGEST: 1102 return Comdat::Largest; 1103 case bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES: 1104 return Comdat::NoDuplicates; 1105 case bitc::COMDAT_SELECTION_KIND_SAME_SIZE: 1106 return Comdat::SameSize; 1107 } 1108 } 1109 1110 static FastMathFlags getDecodedFastMathFlags(unsigned Val) { 1111 FastMathFlags FMF; 1112 if (0 != (Val & FastMathFlags::UnsafeAlgebra)) 1113 FMF.setUnsafeAlgebra(); 1114 if (0 != (Val & FastMathFlags::NoNaNs)) 1115 FMF.setNoNaNs(); 1116 if (0 != (Val & FastMathFlags::NoInfs)) 1117 FMF.setNoInfs(); 1118 if (0 != (Val & FastMathFlags::NoSignedZeros)) 1119 FMF.setNoSignedZeros(); 1120 if (0 != (Val & FastMathFlags::AllowReciprocal)) 1121 FMF.setAllowReciprocal(); 1122 return FMF; 1123 } 1124 1125 static void upgradeDLLImportExportLinkage(GlobalValue *GV, unsigned Val) { 1126 switch (Val) { 1127 case 5: GV->setDLLStorageClass(GlobalValue::DLLImportStorageClass); break; 1128 case 6: GV->setDLLStorageClass(GlobalValue::DLLExportStorageClass); break; 1129 } 1130 } 1131 1132 namespace llvm { 1133 namespace { 1134 1135 /// \brief A class for maintaining the slot number definition 1136 /// as a placeholder for the actual definition for forward constants defs. 1137 class ConstantPlaceHolder : public ConstantExpr { 1138 void operator=(const ConstantPlaceHolder &) = delete; 1139 1140 public: 1141 // allocate space for exactly one operand 1142 void *operator new(size_t s) { return User::operator new(s, 1); } 1143 explicit ConstantPlaceHolder(Type *Ty, LLVMContext &Context) 1144 : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) { 1145 Op<0>() = UndefValue::get(Type::getInt32Ty(Context)); 1146 } 1147 1148 /// \brief Methods to support type inquiry through isa, cast, and dyn_cast. 1149 static bool classof(const Value *V) { 1150 return isa<ConstantExpr>(V) && 1151 cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1; 1152 } 1153 1154 /// Provide fast operand accessors 1155 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value); 1156 }; 1157 1158 } // end anonymous namespace 1159 1160 // FIXME: can we inherit this from ConstantExpr? 1161 template <> 1162 struct OperandTraits<ConstantPlaceHolder> : 1163 public FixedNumOperandTraits<ConstantPlaceHolder, 1> { 1164 }; 1165 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ConstantPlaceHolder, Value) 1166 1167 } // end namespace llvm 1168 1169 void BitcodeReaderValueList::assignValue(Value *V, unsigned Idx) { 1170 if (Idx == size()) { 1171 push_back(V); 1172 return; 1173 } 1174 1175 if (Idx >= size()) 1176 resize(Idx+1); 1177 1178 WeakVH &OldV = ValuePtrs[Idx]; 1179 if (!OldV) { 1180 OldV = V; 1181 return; 1182 } 1183 1184 // Handle constants and non-constants (e.g. instrs) differently for 1185 // efficiency. 1186 if (Constant *PHC = dyn_cast<Constant>(&*OldV)) { 1187 ResolveConstants.push_back(std::make_pair(PHC, Idx)); 1188 OldV = V; 1189 } else { 1190 // If there was a forward reference to this value, replace it. 1191 Value *PrevVal = OldV; 1192 OldV->replaceAllUsesWith(V); 1193 delete PrevVal; 1194 } 1195 } 1196 1197 Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx, 1198 Type *Ty) { 1199 if (Idx >= size()) 1200 resize(Idx + 1); 1201 1202 if (Value *V = ValuePtrs[Idx]) { 1203 if (Ty != V->getType()) 1204 report_fatal_error("Type mismatch in constant table!"); 1205 return cast<Constant>(V); 1206 } 1207 1208 // Create and return a placeholder, which will later be RAUW'd. 1209 Constant *C = new ConstantPlaceHolder(Ty, Context); 1210 ValuePtrs[Idx] = C; 1211 return C; 1212 } 1213 1214 Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, Type *Ty) { 1215 // Bail out for a clearly invalid value. This would make us call resize(0) 1216 if (Idx == std::numeric_limits<unsigned>::max()) 1217 return nullptr; 1218 1219 if (Idx >= size()) 1220 resize(Idx + 1); 1221 1222 if (Value *V = ValuePtrs[Idx]) { 1223 // If the types don't match, it's invalid. 1224 if (Ty && Ty != V->getType()) 1225 return nullptr; 1226 return V; 1227 } 1228 1229 // No type specified, must be invalid reference. 1230 if (!Ty) return nullptr; 1231 1232 // Create and return a placeholder, which will later be RAUW'd. 1233 Value *V = new Argument(Ty); 1234 ValuePtrs[Idx] = V; 1235 return V; 1236 } 1237 1238 /// Once all constants are read, this method bulk resolves any forward 1239 /// references. The idea behind this is that we sometimes get constants (such 1240 /// as large arrays) which reference *many* forward ref constants. Replacing 1241 /// each of these causes a lot of thrashing when building/reuniquing the 1242 /// constant. Instead of doing this, we look at all the uses and rewrite all 1243 /// the place holders at once for any constant that uses a placeholder. 1244 void BitcodeReaderValueList::resolveConstantForwardRefs() { 1245 // Sort the values by-pointer so that they are efficient to look up with a 1246 // binary search. 1247 std::sort(ResolveConstants.begin(), ResolveConstants.end()); 1248 1249 SmallVector<Constant*, 64> NewOps; 1250 1251 while (!ResolveConstants.empty()) { 1252 Value *RealVal = operator[](ResolveConstants.back().second); 1253 Constant *Placeholder = ResolveConstants.back().first; 1254 ResolveConstants.pop_back(); 1255 1256 // Loop over all users of the placeholder, updating them to reference the 1257 // new value. If they reference more than one placeholder, update them all 1258 // at once. 1259 while (!Placeholder->use_empty()) { 1260 auto UI = Placeholder->user_begin(); 1261 User *U = *UI; 1262 1263 // If the using object isn't uniqued, just update the operands. This 1264 // handles instructions and initializers for global variables. 1265 if (!isa<Constant>(U) || isa<GlobalValue>(U)) { 1266 UI.getUse().set(RealVal); 1267 continue; 1268 } 1269 1270 // Otherwise, we have a constant that uses the placeholder. Replace that 1271 // constant with a new constant that has *all* placeholder uses updated. 1272 Constant *UserC = cast<Constant>(U); 1273 for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end(); 1274 I != E; ++I) { 1275 Value *NewOp; 1276 if (!isa<ConstantPlaceHolder>(*I)) { 1277 // Not a placeholder reference. 1278 NewOp = *I; 1279 } else if (*I == Placeholder) { 1280 // Common case is that it just references this one placeholder. 1281 NewOp = RealVal; 1282 } else { 1283 // Otherwise, look up the placeholder in ResolveConstants. 1284 ResolveConstantsTy::iterator It = 1285 std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(), 1286 std::pair<Constant*, unsigned>(cast<Constant>(*I), 1287 0)); 1288 assert(It != ResolveConstants.end() && It->first == *I); 1289 NewOp = operator[](It->second); 1290 } 1291 1292 NewOps.push_back(cast<Constant>(NewOp)); 1293 } 1294 1295 // Make the new constant. 1296 Constant *NewC; 1297 if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) { 1298 NewC = ConstantArray::get(UserCA->getType(), NewOps); 1299 } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) { 1300 NewC = ConstantStruct::get(UserCS->getType(), NewOps); 1301 } else if (isa<ConstantVector>(UserC)) { 1302 NewC = ConstantVector::get(NewOps); 1303 } else { 1304 assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr."); 1305 NewC = cast<ConstantExpr>(UserC)->getWithOperands(NewOps); 1306 } 1307 1308 UserC->replaceAllUsesWith(NewC); 1309 UserC->destroyConstant(); 1310 NewOps.clear(); 1311 } 1312 1313 // Update all ValueHandles, they should be the only users at this point. 1314 Placeholder->replaceAllUsesWith(RealVal); 1315 delete Placeholder; 1316 } 1317 } 1318 1319 void BitcodeReaderMetadataList::assignValue(Metadata *MD, unsigned Idx) { 1320 if (Idx == size()) { 1321 push_back(MD); 1322 return; 1323 } 1324 1325 if (Idx >= size()) 1326 resize(Idx+1); 1327 1328 TrackingMDRef &OldMD = MetadataPtrs[Idx]; 1329 if (!OldMD) { 1330 OldMD.reset(MD); 1331 return; 1332 } 1333 1334 // If there was a forward reference to this value, replace it. 1335 TempMDTuple PrevMD(cast<MDTuple>(OldMD.get())); 1336 PrevMD->replaceAllUsesWith(MD); 1337 --NumFwdRefs; 1338 } 1339 1340 Metadata *BitcodeReaderMetadataList::getMetadataFwdRef(unsigned Idx) { 1341 if (Idx >= size()) 1342 resize(Idx + 1); 1343 1344 if (Metadata *MD = MetadataPtrs[Idx]) 1345 return MD; 1346 1347 // Track forward refs to be resolved later. 1348 if (AnyFwdRefs) { 1349 MinFwdRef = std::min(MinFwdRef, Idx); 1350 MaxFwdRef = std::max(MaxFwdRef, Idx); 1351 } else { 1352 AnyFwdRefs = true; 1353 MinFwdRef = MaxFwdRef = Idx; 1354 } 1355 ++NumFwdRefs; 1356 1357 // Create and return a placeholder, which will later be RAUW'd. 1358 Metadata *MD = MDNode::getTemporary(Context, None).release(); 1359 MetadataPtrs[Idx].reset(MD); 1360 return MD; 1361 } 1362 1363 Metadata *BitcodeReaderMetadataList::getMetadataIfResolved(unsigned Idx) { 1364 Metadata *MD = lookup(Idx); 1365 if (auto *N = dyn_cast_or_null<MDNode>(MD)) 1366 if (!N->isResolved()) 1367 return nullptr; 1368 return MD; 1369 } 1370 1371 MDNode *BitcodeReaderMetadataList::getMDNodeFwdRefOrNull(unsigned Idx) { 1372 return dyn_cast_or_null<MDNode>(getMetadataFwdRef(Idx)); 1373 } 1374 1375 void BitcodeReaderMetadataList::tryToResolveCycles() { 1376 if (NumFwdRefs) 1377 // Still forward references... can't resolve cycles. 1378 return; 1379 1380 bool DidReplaceTypeRefs = false; 1381 1382 // Give up on finding a full definition for any forward decls that remain. 1383 for (const auto &Ref : OldTypeRefs.FwdDecls) 1384 OldTypeRefs.Final.insert(Ref); 1385 OldTypeRefs.FwdDecls.clear(); 1386 1387 // Upgrade from old type ref arrays. In strange cases, this could add to 1388 // OldTypeRefs.Unknown. 1389 for (const auto &Array : OldTypeRefs.Arrays) { 1390 DidReplaceTypeRefs = true; 1391 Array.second->replaceAllUsesWith(resolveTypeRefArray(Array.first.get())); 1392 } 1393 OldTypeRefs.Arrays.clear(); 1394 1395 // Replace old string-based type refs with the resolved node, if possible. 1396 // If we haven't seen the node, leave it to the verifier to complain about 1397 // the invalid string reference. 1398 for (const auto &Ref : OldTypeRefs.Unknown) { 1399 DidReplaceTypeRefs = true; 1400 if (DICompositeType *CT = OldTypeRefs.Final.lookup(Ref.first)) 1401 Ref.second->replaceAllUsesWith(CT); 1402 else 1403 Ref.second->replaceAllUsesWith(Ref.first); 1404 } 1405 OldTypeRefs.Unknown.clear(); 1406 1407 // Make sure all the upgraded types are resolved. 1408 if (DidReplaceTypeRefs) { 1409 AnyFwdRefs = true; 1410 MinFwdRef = 0; 1411 MaxFwdRef = MetadataPtrs.size() - 1; 1412 } 1413 1414 if (!AnyFwdRefs) 1415 // Nothing to do. 1416 return; 1417 1418 // Resolve any cycles. 1419 for (unsigned I = MinFwdRef, E = MaxFwdRef + 1; I != E; ++I) { 1420 auto &MD = MetadataPtrs[I]; 1421 auto *N = dyn_cast_or_null<MDNode>(MD); 1422 if (!N) 1423 continue; 1424 1425 assert(!N->isTemporary() && "Unexpected forward reference"); 1426 N->resolveCycles(); 1427 } 1428 1429 // Make sure we return early again until there's another forward ref. 1430 AnyFwdRefs = false; 1431 } 1432 1433 void BitcodeReaderMetadataList::addTypeRef(MDString &UUID, 1434 DICompositeType &CT) { 1435 assert(CT.getRawIdentifier() == &UUID && "Mismatched UUID"); 1436 if (CT.isForwardDecl()) 1437 OldTypeRefs.FwdDecls.insert(std::make_pair(&UUID, &CT)); 1438 else 1439 OldTypeRefs.Final.insert(std::make_pair(&UUID, &CT)); 1440 } 1441 1442 Metadata *BitcodeReaderMetadataList::upgradeTypeRef(Metadata *MaybeUUID) { 1443 auto *UUID = dyn_cast_or_null<MDString>(MaybeUUID); 1444 if (LLVM_LIKELY(!UUID)) 1445 return MaybeUUID; 1446 1447 if (auto *CT = OldTypeRefs.Final.lookup(UUID)) 1448 return CT; 1449 1450 auto &Ref = OldTypeRefs.Unknown[UUID]; 1451 if (!Ref) 1452 Ref = MDNode::getTemporary(Context, None); 1453 return Ref.get(); 1454 } 1455 1456 Metadata *BitcodeReaderMetadataList::upgradeTypeRefArray(Metadata *MaybeTuple) { 1457 auto *Tuple = dyn_cast_or_null<MDTuple>(MaybeTuple); 1458 if (!Tuple || Tuple->isDistinct()) 1459 return MaybeTuple; 1460 1461 // Look through the array immediately if possible. 1462 if (!Tuple->isTemporary()) 1463 return resolveTypeRefArray(Tuple); 1464 1465 // Create and return a placeholder to use for now. Eventually 1466 // resolveTypeRefArrays() will be resolve this forward reference. 1467 OldTypeRefs.Arrays.emplace_back( 1468 std::piecewise_construct, std::forward_as_tuple(Tuple), 1469 std::forward_as_tuple(MDTuple::getTemporary(Context, None))); 1470 return OldTypeRefs.Arrays.back().second.get(); 1471 } 1472 1473 Metadata *BitcodeReaderMetadataList::resolveTypeRefArray(Metadata *MaybeTuple) { 1474 auto *Tuple = dyn_cast_or_null<MDTuple>(MaybeTuple); 1475 if (!Tuple || Tuple->isDistinct()) 1476 return MaybeTuple; 1477 1478 // Look through the DITypeRefArray, upgrading each DITypeRef. 1479 SmallVector<Metadata *, 32> Ops; 1480 Ops.reserve(Tuple->getNumOperands()); 1481 for (Metadata *MD : Tuple->operands()) 1482 Ops.push_back(upgradeTypeRef(MD)); 1483 1484 return MDTuple::get(Context, Ops); 1485 } 1486 1487 Type *BitcodeReader::getTypeByID(unsigned ID) { 1488 // The type table size is always specified correctly. 1489 if (ID >= TypeList.size()) 1490 return nullptr; 1491 1492 if (Type *Ty = TypeList[ID]) 1493 return Ty; 1494 1495 // If we have a forward reference, the only possible case is when it is to a 1496 // named struct. Just create a placeholder for now. 1497 return TypeList[ID] = createIdentifiedStructType(Context); 1498 } 1499 1500 StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context, 1501 StringRef Name) { 1502 auto *Ret = StructType::create(Context, Name); 1503 IdentifiedStructTypes.push_back(Ret); 1504 return Ret; 1505 } 1506 1507 StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context) { 1508 auto *Ret = StructType::create(Context); 1509 IdentifiedStructTypes.push_back(Ret); 1510 return Ret; 1511 } 1512 1513 //===----------------------------------------------------------------------===// 1514 // Functions for parsing blocks from the bitcode file 1515 //===----------------------------------------------------------------------===// 1516 1517 static uint64_t getRawAttributeMask(Attribute::AttrKind Val) { 1518 switch (Val) { 1519 case Attribute::EndAttrKinds: 1520 llvm_unreachable("Synthetic enumerators which should never get here"); 1521 1522 case Attribute::None: return 0; 1523 case Attribute::ZExt: return 1 << 0; 1524 case Attribute::SExt: return 1 << 1; 1525 case Attribute::NoReturn: return 1 << 2; 1526 case Attribute::InReg: return 1 << 3; 1527 case Attribute::StructRet: return 1 << 4; 1528 case Attribute::NoUnwind: return 1 << 5; 1529 case Attribute::NoAlias: return 1 << 6; 1530 case Attribute::ByVal: return 1 << 7; 1531 case Attribute::Nest: return 1 << 8; 1532 case Attribute::ReadNone: return 1 << 9; 1533 case Attribute::ReadOnly: return 1 << 10; 1534 case Attribute::NoInline: return 1 << 11; 1535 case Attribute::AlwaysInline: return 1 << 12; 1536 case Attribute::OptimizeForSize: return 1 << 13; 1537 case Attribute::StackProtect: return 1 << 14; 1538 case Attribute::StackProtectReq: return 1 << 15; 1539 case Attribute::Alignment: return 31 << 16; 1540 case Attribute::NoCapture: return 1 << 21; 1541 case Attribute::NoRedZone: return 1 << 22; 1542 case Attribute::NoImplicitFloat: return 1 << 23; 1543 case Attribute::Naked: return 1 << 24; 1544 case Attribute::InlineHint: return 1 << 25; 1545 case Attribute::StackAlignment: return 7 << 26; 1546 case Attribute::ReturnsTwice: return 1 << 29; 1547 case Attribute::UWTable: return 1 << 30; 1548 case Attribute::NonLazyBind: return 1U << 31; 1549 case Attribute::SanitizeAddress: return 1ULL << 32; 1550 case Attribute::MinSize: return 1ULL << 33; 1551 case Attribute::NoDuplicate: return 1ULL << 34; 1552 case Attribute::StackProtectStrong: return 1ULL << 35; 1553 case Attribute::SanitizeThread: return 1ULL << 36; 1554 case Attribute::SanitizeMemory: return 1ULL << 37; 1555 case Attribute::NoBuiltin: return 1ULL << 38; 1556 case Attribute::Returned: return 1ULL << 39; 1557 case Attribute::Cold: return 1ULL << 40; 1558 case Attribute::Builtin: return 1ULL << 41; 1559 case Attribute::OptimizeNone: return 1ULL << 42; 1560 case Attribute::InAlloca: return 1ULL << 43; 1561 case Attribute::NonNull: return 1ULL << 44; 1562 case Attribute::JumpTable: return 1ULL << 45; 1563 case Attribute::Convergent: return 1ULL << 46; 1564 case Attribute::SafeStack: return 1ULL << 47; 1565 case Attribute::NoRecurse: return 1ULL << 48; 1566 case Attribute::InaccessibleMemOnly: return 1ULL << 49; 1567 case Attribute::InaccessibleMemOrArgMemOnly: return 1ULL << 50; 1568 case Attribute::SwiftSelf: return 1ULL << 51; 1569 case Attribute::SwiftError: return 1ULL << 52; 1570 case Attribute::WriteOnly: return 1ULL << 53; 1571 case Attribute::Dereferenceable: 1572 llvm_unreachable("dereferenceable attribute not supported in raw format"); 1573 break; 1574 case Attribute::DereferenceableOrNull: 1575 llvm_unreachable("dereferenceable_or_null attribute not supported in raw " 1576 "format"); 1577 break; 1578 case Attribute::ArgMemOnly: 1579 llvm_unreachable("argmemonly attribute not supported in raw format"); 1580 break; 1581 case Attribute::AllocSize: 1582 llvm_unreachable("allocsize not supported in raw format"); 1583 break; 1584 } 1585 llvm_unreachable("Unsupported attribute type"); 1586 } 1587 1588 static void addRawAttributeValue(AttrBuilder &B, uint64_t Val) { 1589 if (!Val) return; 1590 1591 for (Attribute::AttrKind I = Attribute::None; I != Attribute::EndAttrKinds; 1592 I = Attribute::AttrKind(I + 1)) { 1593 if (I == Attribute::Dereferenceable || 1594 I == Attribute::DereferenceableOrNull || 1595 I == Attribute::ArgMemOnly || 1596 I == Attribute::AllocSize) 1597 continue; 1598 if (uint64_t A = (Val & getRawAttributeMask(I))) { 1599 if (I == Attribute::Alignment) 1600 B.addAlignmentAttr(1ULL << ((A >> 16) - 1)); 1601 else if (I == Attribute::StackAlignment) 1602 B.addStackAlignmentAttr(1ULL << ((A >> 26)-1)); 1603 else 1604 B.addAttribute(I); 1605 } 1606 } 1607 } 1608 1609 /// \brief This fills an AttrBuilder object with the LLVM attributes that have 1610 /// been decoded from the given integer. This function must stay in sync with 1611 /// 'encodeLLVMAttributesForBitcode'. 1612 static void decodeLLVMAttributesForBitcode(AttrBuilder &B, 1613 uint64_t EncodedAttrs) { 1614 // FIXME: Remove in 4.0. 1615 1616 // The alignment is stored as a 16-bit raw value from bits 31--16. We shift 1617 // the bits above 31 down by 11 bits. 1618 unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16; 1619 assert((!Alignment || isPowerOf2_32(Alignment)) && 1620 "Alignment must be a power of two."); 1621 1622 if (Alignment) 1623 B.addAlignmentAttr(Alignment); 1624 addRawAttributeValue(B, ((EncodedAttrs & (0xfffffULL << 32)) >> 11) | 1625 (EncodedAttrs & 0xffff)); 1626 } 1627 1628 Error BitcodeReader::parseAttributeBlock() { 1629 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID)) 1630 return error("Invalid record"); 1631 1632 if (!MAttributes.empty()) 1633 return error("Invalid multiple blocks"); 1634 1635 SmallVector<uint64_t, 64> Record; 1636 1637 SmallVector<AttributeSet, 8> Attrs; 1638 1639 // Read all the records. 1640 while (true) { 1641 BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 1642 1643 switch (Entry.Kind) { 1644 case BitstreamEntry::SubBlock: // Handled for us already. 1645 case BitstreamEntry::Error: 1646 return error("Malformed block"); 1647 case BitstreamEntry::EndBlock: 1648 return Error::success(); 1649 case BitstreamEntry::Record: 1650 // The interesting case. 1651 break; 1652 } 1653 1654 // Read a record. 1655 Record.clear(); 1656 switch (Stream.readRecord(Entry.ID, Record)) { 1657 default: // Default behavior: ignore. 1658 break; 1659 case bitc::PARAMATTR_CODE_ENTRY_OLD: { // ENTRY: [paramidx0, attr0, ...] 1660 // FIXME: Remove in 4.0. 1661 if (Record.size() & 1) 1662 return error("Invalid record"); 1663 1664 for (unsigned i = 0, e = Record.size(); i != e; i += 2) { 1665 AttrBuilder B; 1666 decodeLLVMAttributesForBitcode(B, Record[i+1]); 1667 Attrs.push_back(AttributeSet::get(Context, Record[i], B)); 1668 } 1669 1670 MAttributes.push_back(AttributeSet::get(Context, Attrs)); 1671 Attrs.clear(); 1672 break; 1673 } 1674 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [attrgrp0, attrgrp1, ...] 1675 for (unsigned i = 0, e = Record.size(); i != e; ++i) 1676 Attrs.push_back(MAttributeGroups[Record[i]]); 1677 1678 MAttributes.push_back(AttributeSet::get(Context, Attrs)); 1679 Attrs.clear(); 1680 break; 1681 } 1682 } 1683 } 1684 } 1685 1686 // Returns Attribute::None on unrecognized codes. 1687 static Attribute::AttrKind getAttrFromCode(uint64_t Code) { 1688 switch (Code) { 1689 default: 1690 return Attribute::None; 1691 case bitc::ATTR_KIND_ALIGNMENT: 1692 return Attribute::Alignment; 1693 case bitc::ATTR_KIND_ALWAYS_INLINE: 1694 return Attribute::AlwaysInline; 1695 case bitc::ATTR_KIND_ARGMEMONLY: 1696 return Attribute::ArgMemOnly; 1697 case bitc::ATTR_KIND_BUILTIN: 1698 return Attribute::Builtin; 1699 case bitc::ATTR_KIND_BY_VAL: 1700 return Attribute::ByVal; 1701 case bitc::ATTR_KIND_IN_ALLOCA: 1702 return Attribute::InAlloca; 1703 case bitc::ATTR_KIND_COLD: 1704 return Attribute::Cold; 1705 case bitc::ATTR_KIND_CONVERGENT: 1706 return Attribute::Convergent; 1707 case bitc::ATTR_KIND_INACCESSIBLEMEM_ONLY: 1708 return Attribute::InaccessibleMemOnly; 1709 case bitc::ATTR_KIND_INACCESSIBLEMEM_OR_ARGMEMONLY: 1710 return Attribute::InaccessibleMemOrArgMemOnly; 1711 case bitc::ATTR_KIND_INLINE_HINT: 1712 return Attribute::InlineHint; 1713 case bitc::ATTR_KIND_IN_REG: 1714 return Attribute::InReg; 1715 case bitc::ATTR_KIND_JUMP_TABLE: 1716 return Attribute::JumpTable; 1717 case bitc::ATTR_KIND_MIN_SIZE: 1718 return Attribute::MinSize; 1719 case bitc::ATTR_KIND_NAKED: 1720 return Attribute::Naked; 1721 case bitc::ATTR_KIND_NEST: 1722 return Attribute::Nest; 1723 case bitc::ATTR_KIND_NO_ALIAS: 1724 return Attribute::NoAlias; 1725 case bitc::ATTR_KIND_NO_BUILTIN: 1726 return Attribute::NoBuiltin; 1727 case bitc::ATTR_KIND_NO_CAPTURE: 1728 return Attribute::NoCapture; 1729 case bitc::ATTR_KIND_NO_DUPLICATE: 1730 return Attribute::NoDuplicate; 1731 case bitc::ATTR_KIND_NO_IMPLICIT_FLOAT: 1732 return Attribute::NoImplicitFloat; 1733 case bitc::ATTR_KIND_NO_INLINE: 1734 return Attribute::NoInline; 1735 case bitc::ATTR_KIND_NO_RECURSE: 1736 return Attribute::NoRecurse; 1737 case bitc::ATTR_KIND_NON_LAZY_BIND: 1738 return Attribute::NonLazyBind; 1739 case bitc::ATTR_KIND_NON_NULL: 1740 return Attribute::NonNull; 1741 case bitc::ATTR_KIND_DEREFERENCEABLE: 1742 return Attribute::Dereferenceable; 1743 case bitc::ATTR_KIND_DEREFERENCEABLE_OR_NULL: 1744 return Attribute::DereferenceableOrNull; 1745 case bitc::ATTR_KIND_ALLOC_SIZE: 1746 return Attribute::AllocSize; 1747 case bitc::ATTR_KIND_NO_RED_ZONE: 1748 return Attribute::NoRedZone; 1749 case bitc::ATTR_KIND_NO_RETURN: 1750 return Attribute::NoReturn; 1751 case bitc::ATTR_KIND_NO_UNWIND: 1752 return Attribute::NoUnwind; 1753 case bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE: 1754 return Attribute::OptimizeForSize; 1755 case bitc::ATTR_KIND_OPTIMIZE_NONE: 1756 return Attribute::OptimizeNone; 1757 case bitc::ATTR_KIND_READ_NONE: 1758 return Attribute::ReadNone; 1759 case bitc::ATTR_KIND_READ_ONLY: 1760 return Attribute::ReadOnly; 1761 case bitc::ATTR_KIND_RETURNED: 1762 return Attribute::Returned; 1763 case bitc::ATTR_KIND_RETURNS_TWICE: 1764 return Attribute::ReturnsTwice; 1765 case bitc::ATTR_KIND_S_EXT: 1766 return Attribute::SExt; 1767 case bitc::ATTR_KIND_STACK_ALIGNMENT: 1768 return Attribute::StackAlignment; 1769 case bitc::ATTR_KIND_STACK_PROTECT: 1770 return Attribute::StackProtect; 1771 case bitc::ATTR_KIND_STACK_PROTECT_REQ: 1772 return Attribute::StackProtectReq; 1773 case bitc::ATTR_KIND_STACK_PROTECT_STRONG: 1774 return Attribute::StackProtectStrong; 1775 case bitc::ATTR_KIND_SAFESTACK: 1776 return Attribute::SafeStack; 1777 case bitc::ATTR_KIND_STRUCT_RET: 1778 return Attribute::StructRet; 1779 case bitc::ATTR_KIND_SANITIZE_ADDRESS: 1780 return Attribute::SanitizeAddress; 1781 case bitc::ATTR_KIND_SANITIZE_THREAD: 1782 return Attribute::SanitizeThread; 1783 case bitc::ATTR_KIND_SANITIZE_MEMORY: 1784 return Attribute::SanitizeMemory; 1785 case bitc::ATTR_KIND_SWIFT_ERROR: 1786 return Attribute::SwiftError; 1787 case bitc::ATTR_KIND_SWIFT_SELF: 1788 return Attribute::SwiftSelf; 1789 case bitc::ATTR_KIND_UW_TABLE: 1790 return Attribute::UWTable; 1791 case bitc::ATTR_KIND_WRITEONLY: 1792 return Attribute::WriteOnly; 1793 case bitc::ATTR_KIND_Z_EXT: 1794 return Attribute::ZExt; 1795 } 1796 } 1797 1798 Error BitcodeReader::parseAlignmentValue(uint64_t Exponent, 1799 unsigned &Alignment) { 1800 // Note: Alignment in bitcode files is incremented by 1, so that zero 1801 // can be used for default alignment. 1802 if (Exponent > Value::MaxAlignmentExponent + 1) 1803 return error("Invalid alignment value"); 1804 Alignment = (1 << static_cast<unsigned>(Exponent)) >> 1; 1805 return Error::success(); 1806 } 1807 1808 Error BitcodeReader::parseAttrKind(uint64_t Code, Attribute::AttrKind *Kind) { 1809 *Kind = getAttrFromCode(Code); 1810 if (*Kind == Attribute::None) 1811 return error("Unknown attribute kind (" + Twine(Code) + ")"); 1812 return Error::success(); 1813 } 1814 1815 Error BitcodeReader::parseAttributeGroupBlock() { 1816 if (Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID)) 1817 return error("Invalid record"); 1818 1819 if (!MAttributeGroups.empty()) 1820 return error("Invalid multiple blocks"); 1821 1822 SmallVector<uint64_t, 64> Record; 1823 1824 // Read all the records. 1825 while (true) { 1826 BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 1827 1828 switch (Entry.Kind) { 1829 case BitstreamEntry::SubBlock: // Handled for us already. 1830 case BitstreamEntry::Error: 1831 return error("Malformed block"); 1832 case BitstreamEntry::EndBlock: 1833 return Error::success(); 1834 case BitstreamEntry::Record: 1835 // The interesting case. 1836 break; 1837 } 1838 1839 // Read a record. 1840 Record.clear(); 1841 switch (Stream.readRecord(Entry.ID, Record)) { 1842 default: // Default behavior: ignore. 1843 break; 1844 case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...] 1845 if (Record.size() < 3) 1846 return error("Invalid record"); 1847 1848 uint64_t GrpID = Record[0]; 1849 uint64_t Idx = Record[1]; // Index of the object this attribute refers to. 1850 1851 AttrBuilder B; 1852 for (unsigned i = 2, e = Record.size(); i != e; ++i) { 1853 if (Record[i] == 0) { // Enum attribute 1854 Attribute::AttrKind Kind; 1855 if (Error Err = parseAttrKind(Record[++i], &Kind)) 1856 return Err; 1857 1858 B.addAttribute(Kind); 1859 } else if (Record[i] == 1) { // Integer attribute 1860 Attribute::AttrKind Kind; 1861 if (Error Err = parseAttrKind(Record[++i], &Kind)) 1862 return Err; 1863 if (Kind == Attribute::Alignment) 1864 B.addAlignmentAttr(Record[++i]); 1865 else if (Kind == Attribute::StackAlignment) 1866 B.addStackAlignmentAttr(Record[++i]); 1867 else if (Kind == Attribute::Dereferenceable) 1868 B.addDereferenceableAttr(Record[++i]); 1869 else if (Kind == Attribute::DereferenceableOrNull) 1870 B.addDereferenceableOrNullAttr(Record[++i]); 1871 else if (Kind == Attribute::AllocSize) 1872 B.addAllocSizeAttrFromRawRepr(Record[++i]); 1873 } else { // String attribute 1874 assert((Record[i] == 3 || Record[i] == 4) && 1875 "Invalid attribute group entry"); 1876 bool HasValue = (Record[i++] == 4); 1877 SmallString<64> KindStr; 1878 SmallString<64> ValStr; 1879 1880 while (Record[i] != 0 && i != e) 1881 KindStr += Record[i++]; 1882 assert(Record[i] == 0 && "Kind string not null terminated"); 1883 1884 if (HasValue) { 1885 // Has a value associated with it. 1886 ++i; // Skip the '0' that terminates the "kind" string. 1887 while (Record[i] != 0 && i != e) 1888 ValStr += Record[i++]; 1889 assert(Record[i] == 0 && "Value string not null terminated"); 1890 } 1891 1892 B.addAttribute(KindStr.str(), ValStr.str()); 1893 } 1894 } 1895 1896 MAttributeGroups[GrpID] = AttributeSet::get(Context, Idx, B); 1897 break; 1898 } 1899 } 1900 } 1901 } 1902 1903 Error BitcodeReader::parseTypeTable() { 1904 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW)) 1905 return error("Invalid record"); 1906 1907 return parseTypeTableBody(); 1908 } 1909 1910 Error BitcodeReader::parseTypeTableBody() { 1911 if (!TypeList.empty()) 1912 return error("Invalid multiple blocks"); 1913 1914 SmallVector<uint64_t, 64> Record; 1915 unsigned NumRecords = 0; 1916 1917 SmallString<64> TypeName; 1918 1919 // Read all the records for this type table. 1920 while (true) { 1921 BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 1922 1923 switch (Entry.Kind) { 1924 case BitstreamEntry::SubBlock: // Handled for us already. 1925 case BitstreamEntry::Error: 1926 return error("Malformed block"); 1927 case BitstreamEntry::EndBlock: 1928 if (NumRecords != TypeList.size()) 1929 return error("Malformed block"); 1930 return Error::success(); 1931 case BitstreamEntry::Record: 1932 // The interesting case. 1933 break; 1934 } 1935 1936 // Read a record. 1937 Record.clear(); 1938 Type *ResultTy = nullptr; 1939 switch (Stream.readRecord(Entry.ID, Record)) { 1940 default: 1941 return error("Invalid value"); 1942 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries] 1943 // TYPE_CODE_NUMENTRY contains a count of the number of types in the 1944 // type list. This allows us to reserve space. 1945 if (Record.size() < 1) 1946 return error("Invalid record"); 1947 TypeList.resize(Record[0]); 1948 continue; 1949 case bitc::TYPE_CODE_VOID: // VOID 1950 ResultTy = Type::getVoidTy(Context); 1951 break; 1952 case bitc::TYPE_CODE_HALF: // HALF 1953 ResultTy = Type::getHalfTy(Context); 1954 break; 1955 case bitc::TYPE_CODE_FLOAT: // FLOAT 1956 ResultTy = Type::getFloatTy(Context); 1957 break; 1958 case bitc::TYPE_CODE_DOUBLE: // DOUBLE 1959 ResultTy = Type::getDoubleTy(Context); 1960 break; 1961 case bitc::TYPE_CODE_X86_FP80: // X86_FP80 1962 ResultTy = Type::getX86_FP80Ty(Context); 1963 break; 1964 case bitc::TYPE_CODE_FP128: // FP128 1965 ResultTy = Type::getFP128Ty(Context); 1966 break; 1967 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128 1968 ResultTy = Type::getPPC_FP128Ty(Context); 1969 break; 1970 case bitc::TYPE_CODE_LABEL: // LABEL 1971 ResultTy = Type::getLabelTy(Context); 1972 break; 1973 case bitc::TYPE_CODE_METADATA: // METADATA 1974 ResultTy = Type::getMetadataTy(Context); 1975 break; 1976 case bitc::TYPE_CODE_X86_MMX: // X86_MMX 1977 ResultTy = Type::getX86_MMXTy(Context); 1978 break; 1979 case bitc::TYPE_CODE_TOKEN: // TOKEN 1980 ResultTy = Type::getTokenTy(Context); 1981 break; 1982 case bitc::TYPE_CODE_INTEGER: { // INTEGER: [width] 1983 if (Record.size() < 1) 1984 return error("Invalid record"); 1985 1986 uint64_t NumBits = Record[0]; 1987 if (NumBits < IntegerType::MIN_INT_BITS || 1988 NumBits > IntegerType::MAX_INT_BITS) 1989 return error("Bitwidth for integer type out of range"); 1990 ResultTy = IntegerType::get(Context, NumBits); 1991 break; 1992 } 1993 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or 1994 // [pointee type, address space] 1995 if (Record.size() < 1) 1996 return error("Invalid record"); 1997 unsigned AddressSpace = 0; 1998 if (Record.size() == 2) 1999 AddressSpace = Record[1]; 2000 ResultTy = getTypeByID(Record[0]); 2001 if (!ResultTy || 2002 !PointerType::isValidElementType(ResultTy)) 2003 return error("Invalid type"); 2004 ResultTy = PointerType::get(ResultTy, AddressSpace); 2005 break; 2006 } 2007 case bitc::TYPE_CODE_FUNCTION_OLD: { 2008 // FIXME: attrid is dead, remove it in LLVM 4.0 2009 // FUNCTION: [vararg, attrid, retty, paramty x N] 2010 if (Record.size() < 3) 2011 return error("Invalid record"); 2012 SmallVector<Type*, 8> ArgTys; 2013 for (unsigned i = 3, e = Record.size(); i != e; ++i) { 2014 if (Type *T = getTypeByID(Record[i])) 2015 ArgTys.push_back(T); 2016 else 2017 break; 2018 } 2019 2020 ResultTy = getTypeByID(Record[2]); 2021 if (!ResultTy || ArgTys.size() < Record.size()-3) 2022 return error("Invalid type"); 2023 2024 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]); 2025 break; 2026 } 2027 case bitc::TYPE_CODE_FUNCTION: { 2028 // FUNCTION: [vararg, retty, paramty x N] 2029 if (Record.size() < 2) 2030 return error("Invalid record"); 2031 SmallVector<Type*, 8> ArgTys; 2032 for (unsigned i = 2, e = Record.size(); i != e; ++i) { 2033 if (Type *T = getTypeByID(Record[i])) { 2034 if (!FunctionType::isValidArgumentType(T)) 2035 return error("Invalid function argument type"); 2036 ArgTys.push_back(T); 2037 } 2038 else 2039 break; 2040 } 2041 2042 ResultTy = getTypeByID(Record[1]); 2043 if (!ResultTy || ArgTys.size() < Record.size()-2) 2044 return error("Invalid type"); 2045 2046 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]); 2047 break; 2048 } 2049 case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N] 2050 if (Record.size() < 1) 2051 return error("Invalid record"); 2052 SmallVector<Type*, 8> EltTys; 2053 for (unsigned i = 1, e = Record.size(); i != e; ++i) { 2054 if (Type *T = getTypeByID(Record[i])) 2055 EltTys.push_back(T); 2056 else 2057 break; 2058 } 2059 if (EltTys.size() != Record.size()-1) 2060 return error("Invalid type"); 2061 ResultTy = StructType::get(Context, EltTys, Record[0]); 2062 break; 2063 } 2064 case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N] 2065 if (convertToString(Record, 0, TypeName)) 2066 return error("Invalid record"); 2067 continue; 2068 2069 case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N] 2070 if (Record.size() < 1) 2071 return error("Invalid record"); 2072 2073 if (NumRecords >= TypeList.size()) 2074 return error("Invalid TYPE table"); 2075 2076 // Check to see if this was forward referenced, if so fill in the temp. 2077 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]); 2078 if (Res) { 2079 Res->setName(TypeName); 2080 TypeList[NumRecords] = nullptr; 2081 } else // Otherwise, create a new struct. 2082 Res = createIdentifiedStructType(Context, TypeName); 2083 TypeName.clear(); 2084 2085 SmallVector<Type*, 8> EltTys; 2086 for (unsigned i = 1, e = Record.size(); i != e; ++i) { 2087 if (Type *T = getTypeByID(Record[i])) 2088 EltTys.push_back(T); 2089 else 2090 break; 2091 } 2092 if (EltTys.size() != Record.size()-1) 2093 return error("Invalid record"); 2094 Res->setBody(EltTys, Record[0]); 2095 ResultTy = Res; 2096 break; 2097 } 2098 case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: [] 2099 if (Record.size() != 1) 2100 return error("Invalid record"); 2101 2102 if (NumRecords >= TypeList.size()) 2103 return error("Invalid TYPE table"); 2104 2105 // Check to see if this was forward referenced, if so fill in the temp. 2106 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]); 2107 if (Res) { 2108 Res->setName(TypeName); 2109 TypeList[NumRecords] = nullptr; 2110 } else // Otherwise, create a new struct with no body. 2111 Res = createIdentifiedStructType(Context, TypeName); 2112 TypeName.clear(); 2113 ResultTy = Res; 2114 break; 2115 } 2116 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty] 2117 if (Record.size() < 2) 2118 return error("Invalid record"); 2119 ResultTy = getTypeByID(Record[1]); 2120 if (!ResultTy || !ArrayType::isValidElementType(ResultTy)) 2121 return error("Invalid type"); 2122 ResultTy = ArrayType::get(ResultTy, Record[0]); 2123 break; 2124 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty] 2125 if (Record.size() < 2) 2126 return error("Invalid record"); 2127 if (Record[0] == 0) 2128 return error("Invalid vector length"); 2129 ResultTy = getTypeByID(Record[1]); 2130 if (!ResultTy || !StructType::isValidElementType(ResultTy)) 2131 return error("Invalid type"); 2132 ResultTy = VectorType::get(ResultTy, Record[0]); 2133 break; 2134 } 2135 2136 if (NumRecords >= TypeList.size()) 2137 return error("Invalid TYPE table"); 2138 if (TypeList[NumRecords]) 2139 return error( 2140 "Invalid TYPE table: Only named structs can be forward referenced"); 2141 assert(ResultTy && "Didn't read a type?"); 2142 TypeList[NumRecords++] = ResultTy; 2143 } 2144 } 2145 2146 Error BitcodeReader::parseOperandBundleTags() { 2147 if (Stream.EnterSubBlock(bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID)) 2148 return error("Invalid record"); 2149 2150 if (!BundleTags.empty()) 2151 return error("Invalid multiple blocks"); 2152 2153 SmallVector<uint64_t, 64> Record; 2154 2155 while (true) { 2156 BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 2157 2158 switch (Entry.Kind) { 2159 case BitstreamEntry::SubBlock: // Handled for us already. 2160 case BitstreamEntry::Error: 2161 return error("Malformed block"); 2162 case BitstreamEntry::EndBlock: 2163 return Error::success(); 2164 case BitstreamEntry::Record: 2165 // The interesting case. 2166 break; 2167 } 2168 2169 // Tags are implicitly mapped to integers by their order. 2170 2171 if (Stream.readRecord(Entry.ID, Record) != bitc::OPERAND_BUNDLE_TAG) 2172 return error("Invalid record"); 2173 2174 // OPERAND_BUNDLE_TAG: [strchr x N] 2175 BundleTags.emplace_back(); 2176 if (convertToString(Record, 0, BundleTags.back())) 2177 return error("Invalid record"); 2178 Record.clear(); 2179 } 2180 } 2181 2182 /// Associate a value with its name from the given index in the provided record. 2183 Expected<Value *> BitcodeReader::recordValue(SmallVectorImpl<uint64_t> &Record, 2184 unsigned NameIndex, Triple &TT) { 2185 SmallString<128> ValueName; 2186 if (convertToString(Record, NameIndex, ValueName)) 2187 return error("Invalid record"); 2188 unsigned ValueID = Record[0]; 2189 if (ValueID >= ValueList.size() || !ValueList[ValueID]) 2190 return error("Invalid record"); 2191 Value *V = ValueList[ValueID]; 2192 2193 StringRef NameStr(ValueName.data(), ValueName.size()); 2194 if (NameStr.find_first_of(0) != StringRef::npos) 2195 return error("Invalid value name"); 2196 V->setName(NameStr); 2197 auto *GO = dyn_cast<GlobalObject>(V); 2198 if (GO) { 2199 if (GO->getComdat() == reinterpret_cast<Comdat *>(1)) { 2200 if (TT.isOSBinFormatMachO()) 2201 GO->setComdat(nullptr); 2202 else 2203 GO->setComdat(TheModule->getOrInsertComdat(V->getName())); 2204 } 2205 } 2206 return V; 2207 } 2208 2209 /// Helper to note and return the current location, and jump to the given 2210 /// offset. 2211 static uint64_t jumpToValueSymbolTable(uint64_t Offset, 2212 BitstreamCursor &Stream) { 2213 // Save the current parsing location so we can jump back at the end 2214 // of the VST read. 2215 uint64_t CurrentBit = Stream.GetCurrentBitNo(); 2216 Stream.JumpToBit(Offset * 32); 2217 #ifndef NDEBUG 2218 // Do some checking if we are in debug mode. 2219 BitstreamEntry Entry = Stream.advance(); 2220 assert(Entry.Kind == BitstreamEntry::SubBlock); 2221 assert(Entry.ID == bitc::VALUE_SYMTAB_BLOCK_ID); 2222 #else 2223 // In NDEBUG mode ignore the output so we don't get an unused variable 2224 // warning. 2225 Stream.advance(); 2226 #endif 2227 return CurrentBit; 2228 } 2229 2230 /// Parse the value symbol table at either the current parsing location or 2231 /// at the given bit offset if provided. 2232 Error BitcodeReader::parseValueSymbolTable(uint64_t Offset) { 2233 uint64_t CurrentBit; 2234 // Pass in the Offset to distinguish between calling for the module-level 2235 // VST (where we want to jump to the VST offset) and the function-level 2236 // VST (where we don't). 2237 if (Offset > 0) 2238 CurrentBit = jumpToValueSymbolTable(Offset, Stream); 2239 2240 // Compute the delta between the bitcode indices in the VST (the word offset 2241 // to the word-aligned ENTER_SUBBLOCK for the function block, and that 2242 // expected by the lazy reader. The reader's EnterSubBlock expects to have 2243 // already read the ENTER_SUBBLOCK code (size getAbbrevIDWidth) and BlockID 2244 // (size BlockIDWidth). Note that we access the stream's AbbrevID width here 2245 // just before entering the VST subblock because: 1) the EnterSubBlock 2246 // changes the AbbrevID width; 2) the VST block is nested within the same 2247 // outer MODULE_BLOCK as the FUNCTION_BLOCKs and therefore have the same 2248 // AbbrevID width before calling EnterSubBlock; and 3) when we want to 2249 // jump to the FUNCTION_BLOCK using this offset later, we don't want 2250 // to rely on the stream's AbbrevID width being that of the MODULE_BLOCK. 2251 unsigned FuncBitcodeOffsetDelta = 2252 Stream.getAbbrevIDWidth() + bitc::BlockIDWidth; 2253 2254 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID)) 2255 return error("Invalid record"); 2256 2257 SmallVector<uint64_t, 64> Record; 2258 2259 Triple TT(TheModule->getTargetTriple()); 2260 2261 // Read all the records for this value table. 2262 SmallString<128> ValueName; 2263 2264 while (true) { 2265 BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 2266 2267 switch (Entry.Kind) { 2268 case BitstreamEntry::SubBlock: // Handled for us already. 2269 case BitstreamEntry::Error: 2270 return error("Malformed block"); 2271 case BitstreamEntry::EndBlock: 2272 if (Offset > 0) 2273 Stream.JumpToBit(CurrentBit); 2274 return Error::success(); 2275 case BitstreamEntry::Record: 2276 // The interesting case. 2277 break; 2278 } 2279 2280 // Read a record. 2281 Record.clear(); 2282 switch (Stream.readRecord(Entry.ID, Record)) { 2283 default: // Default behavior: unknown type. 2284 break; 2285 case bitc::VST_CODE_ENTRY: { // VST_CODE_ENTRY: [valueid, namechar x N] 2286 Expected<Value *> ValOrErr = recordValue(Record, 1, TT); 2287 if (Error Err = ValOrErr.takeError()) 2288 return Err; 2289 ValOrErr.get(); 2290 break; 2291 } 2292 case bitc::VST_CODE_FNENTRY: { 2293 // VST_CODE_FNENTRY: [valueid, offset, namechar x N] 2294 Expected<Value *> ValOrErr = recordValue(Record, 2, TT); 2295 if (Error Err = ValOrErr.takeError()) 2296 return Err; 2297 Value *V = ValOrErr.get(); 2298 2299 auto *GO = dyn_cast<GlobalObject>(V); 2300 if (!GO) { 2301 // If this is an alias, need to get the actual Function object 2302 // it aliases, in order to set up the DeferredFunctionInfo entry below. 2303 auto *GA = dyn_cast<GlobalAlias>(V); 2304 if (GA) 2305 GO = GA->getBaseObject(); 2306 assert(GO); 2307 } 2308 2309 uint64_t FuncWordOffset = Record[1]; 2310 Function *F = dyn_cast<Function>(GO); 2311 assert(F); 2312 uint64_t FuncBitOffset = FuncWordOffset * 32; 2313 DeferredFunctionInfo[F] = FuncBitOffset + FuncBitcodeOffsetDelta; 2314 // Set the LastFunctionBlockBit to point to the last function block. 2315 // Later when parsing is resumed after function materialization, 2316 // we can simply skip that last function block. 2317 if (FuncBitOffset > LastFunctionBlockBit) 2318 LastFunctionBlockBit = FuncBitOffset; 2319 break; 2320 } 2321 case bitc::VST_CODE_BBENTRY: { 2322 if (convertToString(Record, 1, ValueName)) 2323 return error("Invalid record"); 2324 BasicBlock *BB = getBasicBlock(Record[0]); 2325 if (!BB) 2326 return error("Invalid record"); 2327 2328 BB->setName(StringRef(ValueName.data(), ValueName.size())); 2329 ValueName.clear(); 2330 break; 2331 } 2332 } 2333 } 2334 } 2335 2336 /// Parse a single METADATA_KIND record, inserting result in MDKindMap. 2337 Error BitcodeReader::parseMetadataKindRecord( 2338 SmallVectorImpl<uint64_t> &Record) { 2339 if (Record.size() < 2) 2340 return error("Invalid record"); 2341 2342 unsigned Kind = Record[0]; 2343 SmallString<8> Name(Record.begin() + 1, Record.end()); 2344 2345 unsigned NewKind = TheModule->getMDKindID(Name.str()); 2346 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second) 2347 return error("Conflicting METADATA_KIND records"); 2348 return Error::success(); 2349 } 2350 2351 static int64_t unrotateSign(uint64_t U) { return U & 1 ? ~(U >> 1) : U >> 1; } 2352 2353 Error BitcodeReader::parseMetadataStrings(ArrayRef<uint64_t> Record, 2354 StringRef Blob, 2355 unsigned &NextMetadataNo) { 2356 // All the MDStrings in the block are emitted together in a single 2357 // record. The strings are concatenated and stored in a blob along with 2358 // their sizes. 2359 if (Record.size() != 2) 2360 return error("Invalid record: metadata strings layout"); 2361 2362 unsigned NumStrings = Record[0]; 2363 unsigned StringsOffset = Record[1]; 2364 if (!NumStrings) 2365 return error("Invalid record: metadata strings with no strings"); 2366 if (StringsOffset > Blob.size()) 2367 return error("Invalid record: metadata strings corrupt offset"); 2368 2369 StringRef Lengths = Blob.slice(0, StringsOffset); 2370 SimpleBitstreamCursor R(Lengths); 2371 2372 StringRef Strings = Blob.drop_front(StringsOffset); 2373 do { 2374 if (R.AtEndOfStream()) 2375 return error("Invalid record: metadata strings bad length"); 2376 2377 unsigned Size = R.ReadVBR(6); 2378 if (Strings.size() < Size) 2379 return error("Invalid record: metadata strings truncated chars"); 2380 2381 MetadataList.assignValue(MDString::get(Context, Strings.slice(0, Size)), 2382 NextMetadataNo++); 2383 Strings = Strings.drop_front(Size); 2384 } while (--NumStrings); 2385 2386 return Error::success(); 2387 } 2388 2389 namespace { 2390 2391 class PlaceholderQueue { 2392 // Placeholders would thrash around when moved, so store in a std::deque 2393 // instead of some sort of vector. 2394 std::deque<DistinctMDOperandPlaceholder> PHs; 2395 2396 public: 2397 DistinctMDOperandPlaceholder &getPlaceholderOp(unsigned ID); 2398 void flush(BitcodeReaderMetadataList &MetadataList); 2399 }; 2400 2401 } // end anonymous namespace 2402 2403 DistinctMDOperandPlaceholder &PlaceholderQueue::getPlaceholderOp(unsigned ID) { 2404 PHs.emplace_back(ID); 2405 return PHs.back(); 2406 } 2407 2408 void PlaceholderQueue::flush(BitcodeReaderMetadataList &MetadataList) { 2409 while (!PHs.empty()) { 2410 PHs.front().replaceUseWith( 2411 MetadataList.getMetadataFwdRef(PHs.front().getID())); 2412 PHs.pop_front(); 2413 } 2414 } 2415 2416 /// Parse a METADATA_BLOCK. If ModuleLevel is true then we are parsing 2417 /// module level metadata. 2418 Error BitcodeReader::parseMetadata(bool ModuleLevel) { 2419 assert((ModuleLevel || DeferredMetadataInfo.empty()) && 2420 "Must read all module-level metadata before function-level"); 2421 2422 IsMetadataMaterialized = true; 2423 unsigned NextMetadataNo = MetadataList.size(); 2424 2425 if (!ModuleLevel && MetadataList.hasFwdRefs()) 2426 return error("Invalid metadata: fwd refs into function blocks"); 2427 2428 if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID)) 2429 return error("Invalid record"); 2430 2431 std::vector<std::pair<DICompileUnit *, Metadata *>> CUSubprograms; 2432 SmallVector<uint64_t, 64> Record; 2433 2434 PlaceholderQueue Placeholders; 2435 bool IsDistinct; 2436 auto getMD = [&](unsigned ID) -> Metadata * { 2437 if (!IsDistinct) 2438 return MetadataList.getMetadataFwdRef(ID); 2439 if (auto *MD = MetadataList.getMetadataIfResolved(ID)) 2440 return MD; 2441 return &Placeholders.getPlaceholderOp(ID); 2442 }; 2443 auto getMDOrNull = [&](unsigned ID) -> Metadata * { 2444 if (ID) 2445 return getMD(ID - 1); 2446 return nullptr; 2447 }; 2448 auto getMDOrNullWithoutPlaceholders = [&](unsigned ID) -> Metadata * { 2449 if (ID) 2450 return MetadataList.getMetadataFwdRef(ID - 1); 2451 return nullptr; 2452 }; 2453 auto getMDString = [&](unsigned ID) -> MDString *{ 2454 // This requires that the ID is not really a forward reference. In 2455 // particular, the MDString must already have been resolved. 2456 return cast_or_null<MDString>(getMDOrNull(ID)); 2457 }; 2458 2459 // Support for old type refs. 2460 auto getDITypeRefOrNull = [&](unsigned ID) { 2461 return MetadataList.upgradeTypeRef(getMDOrNull(ID)); 2462 }; 2463 2464 #define GET_OR_DISTINCT(CLASS, ARGS) \ 2465 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS) 2466 2467 // Read all the records. 2468 while (true) { 2469 BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 2470 2471 switch (Entry.Kind) { 2472 case BitstreamEntry::SubBlock: // Handled for us already. 2473 case BitstreamEntry::Error: 2474 return error("Malformed block"); 2475 case BitstreamEntry::EndBlock: 2476 // Upgrade old-style CU <-> SP pointers to point from SP to CU. 2477 for (auto CU_SP : CUSubprograms) 2478 if (auto *SPs = dyn_cast_or_null<MDTuple>(CU_SP.second)) 2479 for (auto &Op : SPs->operands()) 2480 if (auto *SP = dyn_cast_or_null<MDNode>(Op)) 2481 SP->replaceOperandWith(7, CU_SP.first); 2482 2483 MetadataList.tryToResolveCycles(); 2484 Placeholders.flush(MetadataList); 2485 return Error::success(); 2486 case BitstreamEntry::Record: 2487 // The interesting case. 2488 break; 2489 } 2490 2491 // Read a record. 2492 Record.clear(); 2493 StringRef Blob; 2494 unsigned Code = Stream.readRecord(Entry.ID, Record, &Blob); 2495 IsDistinct = false; 2496 switch (Code) { 2497 default: // Default behavior: ignore. 2498 break; 2499 case bitc::METADATA_NAME: { 2500 // Read name of the named metadata. 2501 SmallString<8> Name(Record.begin(), Record.end()); 2502 Record.clear(); 2503 Code = Stream.ReadCode(); 2504 2505 unsigned NextBitCode = Stream.readRecord(Code, Record); 2506 if (NextBitCode != bitc::METADATA_NAMED_NODE) 2507 return error("METADATA_NAME not followed by METADATA_NAMED_NODE"); 2508 2509 // Read named metadata elements. 2510 unsigned Size = Record.size(); 2511 NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name); 2512 for (unsigned i = 0; i != Size; ++i) { 2513 MDNode *MD = MetadataList.getMDNodeFwdRefOrNull(Record[i]); 2514 if (!MD) 2515 return error("Invalid record"); 2516 NMD->addOperand(MD); 2517 } 2518 break; 2519 } 2520 case bitc::METADATA_OLD_FN_NODE: { 2521 // FIXME: Remove in 4.0. 2522 // This is a LocalAsMetadata record, the only type of function-local 2523 // metadata. 2524 if (Record.size() % 2 == 1) 2525 return error("Invalid record"); 2526 2527 // If this isn't a LocalAsMetadata record, we're dropping it. This used 2528 // to be legal, but there's no upgrade path. 2529 auto dropRecord = [&] { 2530 MetadataList.assignValue(MDNode::get(Context, None), NextMetadataNo++); 2531 }; 2532 if (Record.size() != 2) { 2533 dropRecord(); 2534 break; 2535 } 2536 2537 Type *Ty = getTypeByID(Record[0]); 2538 if (Ty->isMetadataTy() || Ty->isVoidTy()) { 2539 dropRecord(); 2540 break; 2541 } 2542 2543 MetadataList.assignValue( 2544 LocalAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)), 2545 NextMetadataNo++); 2546 break; 2547 } 2548 case bitc::METADATA_OLD_NODE: { 2549 // FIXME: Remove in 4.0. 2550 if (Record.size() % 2 == 1) 2551 return error("Invalid record"); 2552 2553 unsigned Size = Record.size(); 2554 SmallVector<Metadata *, 8> Elts; 2555 for (unsigned i = 0; i != Size; i += 2) { 2556 Type *Ty = getTypeByID(Record[i]); 2557 if (!Ty) 2558 return error("Invalid record"); 2559 if (Ty->isMetadataTy()) 2560 Elts.push_back(getMD(Record[i + 1])); 2561 else if (!Ty->isVoidTy()) { 2562 auto *MD = 2563 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[i + 1], Ty)); 2564 assert(isa<ConstantAsMetadata>(MD) && 2565 "Expected non-function-local metadata"); 2566 Elts.push_back(MD); 2567 } else 2568 Elts.push_back(nullptr); 2569 } 2570 MetadataList.assignValue(MDNode::get(Context, Elts), NextMetadataNo++); 2571 break; 2572 } 2573 case bitc::METADATA_VALUE: { 2574 if (Record.size() != 2) 2575 return error("Invalid record"); 2576 2577 Type *Ty = getTypeByID(Record[0]); 2578 if (Ty->isMetadataTy() || Ty->isVoidTy()) 2579 return error("Invalid record"); 2580 2581 MetadataList.assignValue( 2582 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)), 2583 NextMetadataNo++); 2584 break; 2585 } 2586 case bitc::METADATA_DISTINCT_NODE: 2587 IsDistinct = true; 2588 LLVM_FALLTHROUGH; 2589 case bitc::METADATA_NODE: { 2590 SmallVector<Metadata *, 8> Elts; 2591 Elts.reserve(Record.size()); 2592 for (unsigned ID : Record) 2593 Elts.push_back(getMDOrNull(ID)); 2594 MetadataList.assignValue(IsDistinct ? MDNode::getDistinct(Context, Elts) 2595 : MDNode::get(Context, Elts), 2596 NextMetadataNo++); 2597 break; 2598 } 2599 case bitc::METADATA_LOCATION: { 2600 if (Record.size() != 5) 2601 return error("Invalid record"); 2602 2603 IsDistinct = Record[0]; 2604 unsigned Line = Record[1]; 2605 unsigned Column = Record[2]; 2606 Metadata *Scope = getMD(Record[3]); 2607 Metadata *InlinedAt = getMDOrNull(Record[4]); 2608 MetadataList.assignValue( 2609 GET_OR_DISTINCT(DILocation, 2610 (Context, Line, Column, Scope, InlinedAt)), 2611 NextMetadataNo++); 2612 break; 2613 } 2614 case bitc::METADATA_GENERIC_DEBUG: { 2615 if (Record.size() < 4) 2616 return error("Invalid record"); 2617 2618 IsDistinct = Record[0]; 2619 unsigned Tag = Record[1]; 2620 unsigned Version = Record[2]; 2621 2622 if (Tag >= 1u << 16 || Version != 0) 2623 return error("Invalid record"); 2624 2625 auto *Header = getMDString(Record[3]); 2626 SmallVector<Metadata *, 8> DwarfOps; 2627 for (unsigned I = 4, E = Record.size(); I != E; ++I) 2628 DwarfOps.push_back(getMDOrNull(Record[I])); 2629 MetadataList.assignValue( 2630 GET_OR_DISTINCT(GenericDINode, (Context, Tag, Header, DwarfOps)), 2631 NextMetadataNo++); 2632 break; 2633 } 2634 case bitc::METADATA_SUBRANGE: { 2635 if (Record.size() != 3) 2636 return error("Invalid record"); 2637 2638 IsDistinct = Record[0]; 2639 MetadataList.assignValue( 2640 GET_OR_DISTINCT(DISubrange, 2641 (Context, Record[1], unrotateSign(Record[2]))), 2642 NextMetadataNo++); 2643 break; 2644 } 2645 case bitc::METADATA_ENUMERATOR: { 2646 if (Record.size() != 3) 2647 return error("Invalid record"); 2648 2649 IsDistinct = Record[0]; 2650 MetadataList.assignValue( 2651 GET_OR_DISTINCT(DIEnumerator, (Context, unrotateSign(Record[1]), 2652 getMDString(Record[2]))), 2653 NextMetadataNo++); 2654 break; 2655 } 2656 case bitc::METADATA_BASIC_TYPE: { 2657 if (Record.size() != 6) 2658 return error("Invalid record"); 2659 2660 IsDistinct = Record[0]; 2661 MetadataList.assignValue( 2662 GET_OR_DISTINCT(DIBasicType, 2663 (Context, Record[1], getMDString(Record[2]), 2664 Record[3], Record[4], Record[5])), 2665 NextMetadataNo++); 2666 break; 2667 } 2668 case bitc::METADATA_DERIVED_TYPE: { 2669 if (Record.size() != 12) 2670 return error("Invalid record"); 2671 2672 IsDistinct = Record[0]; 2673 DINode::DIFlags Flags = static_cast<DINode::DIFlags>(Record[10]); 2674 MetadataList.assignValue( 2675 GET_OR_DISTINCT(DIDerivedType, 2676 (Context, Record[1], getMDString(Record[2]), 2677 getMDOrNull(Record[3]), Record[4], 2678 getDITypeRefOrNull(Record[5]), 2679 getDITypeRefOrNull(Record[6]), Record[7], Record[8], 2680 Record[9], Flags, getDITypeRefOrNull(Record[11]))), 2681 NextMetadataNo++); 2682 break; 2683 } 2684 case bitc::METADATA_COMPOSITE_TYPE: { 2685 if (Record.size() != 16) 2686 return error("Invalid record"); 2687 2688 // If we have a UUID and this is not a forward declaration, lookup the 2689 // mapping. 2690 IsDistinct = Record[0] & 0x1; 2691 bool IsNotUsedInTypeRef = Record[0] >= 2; 2692 unsigned Tag = Record[1]; 2693 MDString *Name = getMDString(Record[2]); 2694 Metadata *File = getMDOrNull(Record[3]); 2695 unsigned Line = Record[4]; 2696 Metadata *Scope = getDITypeRefOrNull(Record[5]); 2697 Metadata *BaseType = getDITypeRefOrNull(Record[6]); 2698 uint64_t SizeInBits = Record[7]; 2699 if (Record[8] > (uint64_t)std::numeric_limits<uint32_t>::max()) 2700 return error("Alignment value is too large"); 2701 uint32_t AlignInBits = Record[8]; 2702 uint64_t OffsetInBits = Record[9]; 2703 DINode::DIFlags Flags = static_cast<DINode::DIFlags>(Record[10]); 2704 Metadata *Elements = getMDOrNull(Record[11]); 2705 unsigned RuntimeLang = Record[12]; 2706 Metadata *VTableHolder = getDITypeRefOrNull(Record[13]); 2707 Metadata *TemplateParams = getMDOrNull(Record[14]); 2708 auto *Identifier = getMDString(Record[15]); 2709 DICompositeType *CT = nullptr; 2710 if (Identifier) 2711 CT = DICompositeType::buildODRType( 2712 Context, *Identifier, Tag, Name, File, Line, Scope, BaseType, 2713 SizeInBits, AlignInBits, OffsetInBits, Flags, Elements, RuntimeLang, 2714 VTableHolder, TemplateParams); 2715 2716 // Create a node if we didn't get a lazy ODR type. 2717 if (!CT) 2718 CT = GET_OR_DISTINCT(DICompositeType, 2719 (Context, Tag, Name, File, Line, Scope, BaseType, 2720 SizeInBits, AlignInBits, OffsetInBits, Flags, 2721 Elements, RuntimeLang, VTableHolder, 2722 TemplateParams, Identifier)); 2723 if (!IsNotUsedInTypeRef && Identifier) 2724 MetadataList.addTypeRef(*Identifier, *cast<DICompositeType>(CT)); 2725 2726 MetadataList.assignValue(CT, NextMetadataNo++); 2727 break; 2728 } 2729 case bitc::METADATA_SUBROUTINE_TYPE: { 2730 if (Record.size() < 3 || Record.size() > 4) 2731 return error("Invalid record"); 2732 bool IsOldTypeRefArray = Record[0] < 2; 2733 unsigned CC = (Record.size() > 3) ? Record[3] : 0; 2734 2735 IsDistinct = Record[0] & 0x1; 2736 DINode::DIFlags Flags = static_cast<DINode::DIFlags>(Record[1]); 2737 Metadata *Types = getMDOrNull(Record[2]); 2738 if (LLVM_UNLIKELY(IsOldTypeRefArray)) 2739 Types = MetadataList.upgradeTypeRefArray(Types); 2740 2741 MetadataList.assignValue( 2742 GET_OR_DISTINCT(DISubroutineType, (Context, Flags, CC, Types)), 2743 NextMetadataNo++); 2744 break; 2745 } 2746 2747 case bitc::METADATA_MODULE: { 2748 if (Record.size() != 6) 2749 return error("Invalid record"); 2750 2751 IsDistinct = Record[0]; 2752 MetadataList.assignValue( 2753 GET_OR_DISTINCT(DIModule, 2754 (Context, getMDOrNull(Record[1]), 2755 getMDString(Record[2]), getMDString(Record[3]), 2756 getMDString(Record[4]), getMDString(Record[5]))), 2757 NextMetadataNo++); 2758 break; 2759 } 2760 2761 case bitc::METADATA_FILE: { 2762 if (Record.size() != 3) 2763 return error("Invalid record"); 2764 2765 IsDistinct = Record[0]; 2766 MetadataList.assignValue( 2767 GET_OR_DISTINCT(DIFile, (Context, getMDString(Record[1]), 2768 getMDString(Record[2]))), 2769 NextMetadataNo++); 2770 break; 2771 } 2772 case bitc::METADATA_COMPILE_UNIT: { 2773 if (Record.size() < 14 || Record.size() > 17) 2774 return error("Invalid record"); 2775 2776 // Ignore Record[0], which indicates whether this compile unit is 2777 // distinct. It's always distinct. 2778 IsDistinct = true; 2779 auto *CU = DICompileUnit::getDistinct( 2780 Context, Record[1], getMDOrNull(Record[2]), getMDString(Record[3]), 2781 Record[4], getMDString(Record[5]), Record[6], getMDString(Record[7]), 2782 Record[8], getMDOrNull(Record[9]), getMDOrNull(Record[10]), 2783 getMDOrNull(Record[12]), getMDOrNull(Record[13]), 2784 Record.size() <= 15 ? nullptr : getMDOrNull(Record[15]), 2785 Record.size() <= 14 ? 0 : Record[14], 2786 Record.size() <= 16 ? true : Record[16]); 2787 2788 MetadataList.assignValue(CU, NextMetadataNo++); 2789 2790 // Move the Upgrade the list of subprograms. 2791 if (Metadata *SPs = getMDOrNullWithoutPlaceholders(Record[11])) 2792 CUSubprograms.push_back({CU, SPs}); 2793 break; 2794 } 2795 case bitc::METADATA_SUBPROGRAM: { 2796 if (Record.size() < 18 || Record.size() > 20) 2797 return error("Invalid record"); 2798 2799 IsDistinct = 2800 (Record[0] & 1) || Record[8]; // All definitions should be distinct. 2801 // Version 1 has a Function as Record[15]. 2802 // Version 2 has removed Record[15]. 2803 // Version 3 has the Unit as Record[15]. 2804 // Version 4 added thisAdjustment. 2805 bool HasUnit = Record[0] >= 2; 2806 if (HasUnit && Record.size() < 19) 2807 return error("Invalid record"); 2808 Metadata *CUorFn = getMDOrNull(Record[15]); 2809 unsigned Offset = Record.size() >= 19 ? 1 : 0; 2810 bool HasFn = Offset && !HasUnit; 2811 bool HasThisAdj = Record.size() >= 20; 2812 DISubprogram *SP = GET_OR_DISTINCT( 2813 DISubprogram, (Context, 2814 getDITypeRefOrNull(Record[1]), // scope 2815 getMDString(Record[2]), // name 2816 getMDString(Record[3]), // linkageName 2817 getMDOrNull(Record[4]), // file 2818 Record[5], // line 2819 getMDOrNull(Record[6]), // type 2820 Record[7], // isLocal 2821 Record[8], // isDefinition 2822 Record[9], // scopeLine 2823 getDITypeRefOrNull(Record[10]), // containingType 2824 Record[11], // virtuality 2825 Record[12], // virtualIndex 2826 HasThisAdj ? Record[19] : 0, // thisAdjustment 2827 static_cast<DINode::DIFlags>(Record[13] // flags 2828 ), 2829 Record[14], // isOptimized 2830 HasUnit ? CUorFn : nullptr, // unit 2831 getMDOrNull(Record[15 + Offset]), // templateParams 2832 getMDOrNull(Record[16 + Offset]), // declaration 2833 getMDOrNull(Record[17 + Offset]) // variables 2834 )); 2835 MetadataList.assignValue(SP, NextMetadataNo++); 2836 2837 // Upgrade sp->function mapping to function->sp mapping. 2838 if (HasFn) { 2839 if (auto *CMD = dyn_cast_or_null<ConstantAsMetadata>(CUorFn)) 2840 if (auto *F = dyn_cast<Function>(CMD->getValue())) { 2841 if (F->isMaterializable()) 2842 // Defer until materialized; unmaterialized functions may not have 2843 // metadata. 2844 FunctionsWithSPs[F] = SP; 2845 else if (!F->empty()) 2846 F->setSubprogram(SP); 2847 } 2848 } 2849 break; 2850 } 2851 case bitc::METADATA_LEXICAL_BLOCK: { 2852 if (Record.size() != 5) 2853 return error("Invalid record"); 2854 2855 IsDistinct = Record[0]; 2856 MetadataList.assignValue( 2857 GET_OR_DISTINCT(DILexicalBlock, 2858 (Context, getMDOrNull(Record[1]), 2859 getMDOrNull(Record[2]), Record[3], Record[4])), 2860 NextMetadataNo++); 2861 break; 2862 } 2863 case bitc::METADATA_LEXICAL_BLOCK_FILE: { 2864 if (Record.size() != 4) 2865 return error("Invalid record"); 2866 2867 IsDistinct = Record[0]; 2868 MetadataList.assignValue( 2869 GET_OR_DISTINCT(DILexicalBlockFile, 2870 (Context, getMDOrNull(Record[1]), 2871 getMDOrNull(Record[2]), Record[3])), 2872 NextMetadataNo++); 2873 break; 2874 } 2875 case bitc::METADATA_NAMESPACE: { 2876 if (Record.size() != 5) 2877 return error("Invalid record"); 2878 2879 IsDistinct = Record[0] & 1; 2880 bool ExportSymbols = Record[0] & 2; 2881 MetadataList.assignValue( 2882 GET_OR_DISTINCT(DINamespace, 2883 (Context, getMDOrNull(Record[1]), 2884 getMDOrNull(Record[2]), getMDString(Record[3]), 2885 Record[4], ExportSymbols)), 2886 NextMetadataNo++); 2887 break; 2888 } 2889 case bitc::METADATA_MACRO: { 2890 if (Record.size() != 5) 2891 return error("Invalid record"); 2892 2893 IsDistinct = Record[0]; 2894 MetadataList.assignValue( 2895 GET_OR_DISTINCT(DIMacro, 2896 (Context, Record[1], Record[2], 2897 getMDString(Record[3]), getMDString(Record[4]))), 2898 NextMetadataNo++); 2899 break; 2900 } 2901 case bitc::METADATA_MACRO_FILE: { 2902 if (Record.size() != 5) 2903 return error("Invalid record"); 2904 2905 IsDistinct = Record[0]; 2906 MetadataList.assignValue( 2907 GET_OR_DISTINCT(DIMacroFile, 2908 (Context, Record[1], Record[2], 2909 getMDOrNull(Record[3]), getMDOrNull(Record[4]))), 2910 NextMetadataNo++); 2911 break; 2912 } 2913 case bitc::METADATA_TEMPLATE_TYPE: { 2914 if (Record.size() != 3) 2915 return error("Invalid record"); 2916 2917 IsDistinct = Record[0]; 2918 MetadataList.assignValue(GET_OR_DISTINCT(DITemplateTypeParameter, 2919 (Context, getMDString(Record[1]), 2920 getDITypeRefOrNull(Record[2]))), 2921 NextMetadataNo++); 2922 break; 2923 } 2924 case bitc::METADATA_TEMPLATE_VALUE: { 2925 if (Record.size() != 5) 2926 return error("Invalid record"); 2927 2928 IsDistinct = Record[0]; 2929 MetadataList.assignValue( 2930 GET_OR_DISTINCT(DITemplateValueParameter, 2931 (Context, Record[1], getMDString(Record[2]), 2932 getDITypeRefOrNull(Record[3]), 2933 getMDOrNull(Record[4]))), 2934 NextMetadataNo++); 2935 break; 2936 } 2937 case bitc::METADATA_GLOBAL_VAR: { 2938 if (Record.size() < 11 || Record.size() > 12) 2939 return error("Invalid record"); 2940 2941 IsDistinct = Record[0]; 2942 2943 // Upgrade old metadata, which stored a global variable reference or a 2944 // ConstantInt here. 2945 Metadata *Expr = getMDOrNull(Record[9]); 2946 uint32_t AlignInBits = 0; 2947 if (Record.size() > 11) { 2948 if (Record[11] > (uint64_t)std::numeric_limits<uint32_t>::max()) 2949 return error("Alignment value is too large"); 2950 AlignInBits = Record[11]; 2951 } 2952 GlobalVariable *Attach = nullptr; 2953 if (auto *CMD = dyn_cast_or_null<ConstantAsMetadata>(Expr)) { 2954 if (auto *GV = dyn_cast<GlobalVariable>(CMD->getValue())) { 2955 Attach = GV; 2956 Expr = nullptr; 2957 } else if (auto *CI = dyn_cast<ConstantInt>(CMD->getValue())) { 2958 Expr = DIExpression::get(Context, 2959 {dwarf::DW_OP_constu, CI->getZExtValue(), 2960 dwarf::DW_OP_stack_value}); 2961 } else { 2962 Expr = nullptr; 2963 } 2964 } 2965 2966 DIGlobalVariable *DGV = GET_OR_DISTINCT( 2967 DIGlobalVariable, 2968 (Context, getMDOrNull(Record[1]), getMDString(Record[2]), 2969 getMDString(Record[3]), getMDOrNull(Record[4]), Record[5], 2970 getDITypeRefOrNull(Record[6]), Record[7], Record[8], Expr, 2971 getMDOrNull(Record[10]), AlignInBits)); 2972 MetadataList.assignValue(DGV, NextMetadataNo++); 2973 2974 if (Attach) 2975 Attach->addDebugInfo(DGV); 2976 2977 break; 2978 } 2979 case bitc::METADATA_LOCAL_VAR: { 2980 // 10th field is for the obseleted 'inlinedAt:' field. 2981 if (Record.size() < 8 || Record.size() > 10) 2982 return error("Invalid record"); 2983 2984 IsDistinct = Record[0] & 1; 2985 bool HasAlignment = Record[0] & 2; 2986 // 2nd field used to be an artificial tag, either DW_TAG_auto_variable or 2987 // DW_TAG_arg_variable, if we have alignment flag encoded it means, that 2988 // this is newer version of record which doesn't have artifical tag. 2989 bool HasTag = !HasAlignment && Record.size() > 8; 2990 DINode::DIFlags Flags = static_cast<DINode::DIFlags>(Record[7 + HasTag]); 2991 uint32_t AlignInBits = 0; 2992 if (HasAlignment) { 2993 if (Record[8 + HasTag] > 2994 (uint64_t)std::numeric_limits<uint32_t>::max()) 2995 return error("Alignment value is too large"); 2996 AlignInBits = Record[8 + HasTag]; 2997 } 2998 MetadataList.assignValue( 2999 GET_OR_DISTINCT(DILocalVariable, 3000 (Context, getMDOrNull(Record[1 + HasTag]), 3001 getMDString(Record[2 + HasTag]), 3002 getMDOrNull(Record[3 + HasTag]), Record[4 + HasTag], 3003 getDITypeRefOrNull(Record[5 + HasTag]), 3004 Record[6 + HasTag], Flags, AlignInBits)), 3005 NextMetadataNo++); 3006 break; 3007 } 3008 case bitc::METADATA_EXPRESSION: { 3009 if (Record.size() < 1) 3010 return error("Invalid record"); 3011 3012 IsDistinct = Record[0]; 3013 MetadataList.assignValue( 3014 GET_OR_DISTINCT(DIExpression, 3015 (Context, makeArrayRef(Record).slice(1))), 3016 NextMetadataNo++); 3017 break; 3018 } 3019 case bitc::METADATA_OBJC_PROPERTY: { 3020 if (Record.size() != 8) 3021 return error("Invalid record"); 3022 3023 IsDistinct = Record[0]; 3024 MetadataList.assignValue( 3025 GET_OR_DISTINCT(DIObjCProperty, 3026 (Context, getMDString(Record[1]), 3027 getMDOrNull(Record[2]), Record[3], 3028 getMDString(Record[4]), getMDString(Record[5]), 3029 Record[6], getDITypeRefOrNull(Record[7]))), 3030 NextMetadataNo++); 3031 break; 3032 } 3033 case bitc::METADATA_IMPORTED_ENTITY: { 3034 if (Record.size() != 6) 3035 return error("Invalid record"); 3036 3037 IsDistinct = Record[0]; 3038 MetadataList.assignValue( 3039 GET_OR_DISTINCT(DIImportedEntity, 3040 (Context, Record[1], getMDOrNull(Record[2]), 3041 getDITypeRefOrNull(Record[3]), Record[4], 3042 getMDString(Record[5]))), 3043 NextMetadataNo++); 3044 break; 3045 } 3046 case bitc::METADATA_STRING_OLD: { 3047 std::string String(Record.begin(), Record.end()); 3048 3049 // Test for upgrading !llvm.loop. 3050 HasSeenOldLoopTags |= mayBeOldLoopAttachmentTag(String); 3051 3052 Metadata *MD = MDString::get(Context, String); 3053 MetadataList.assignValue(MD, NextMetadataNo++); 3054 break; 3055 } 3056 case bitc::METADATA_STRINGS: 3057 if (Error Err = parseMetadataStrings(Record, Blob, NextMetadataNo)) 3058 return Err; 3059 break; 3060 case bitc::METADATA_GLOBAL_DECL_ATTACHMENT: { 3061 if (Record.size() % 2 == 0) 3062 return error("Invalid record"); 3063 unsigned ValueID = Record[0]; 3064 if (ValueID >= ValueList.size()) 3065 return error("Invalid record"); 3066 if (auto *GO = dyn_cast<GlobalObject>(ValueList[ValueID])) 3067 if (Error Err = parseGlobalObjectAttachment( 3068 *GO, ArrayRef<uint64_t>(Record).slice(1))) 3069 return Err; 3070 break; 3071 } 3072 case bitc::METADATA_KIND: { 3073 // Support older bitcode files that had METADATA_KIND records in a 3074 // block with METADATA_BLOCK_ID. 3075 if (Error Err = parseMetadataKindRecord(Record)) 3076 return Err; 3077 break; 3078 } 3079 } 3080 } 3081 3082 #undef GET_OR_DISTINCT 3083 } 3084 3085 /// Parse the metadata kinds out of the METADATA_KIND_BLOCK. 3086 Error BitcodeReader::parseMetadataKinds() { 3087 if (Stream.EnterSubBlock(bitc::METADATA_KIND_BLOCK_ID)) 3088 return error("Invalid record"); 3089 3090 SmallVector<uint64_t, 64> Record; 3091 3092 // Read all the records. 3093 while (true) { 3094 BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 3095 3096 switch (Entry.Kind) { 3097 case BitstreamEntry::SubBlock: // Handled for us already. 3098 case BitstreamEntry::Error: 3099 return error("Malformed block"); 3100 case BitstreamEntry::EndBlock: 3101 return Error::success(); 3102 case BitstreamEntry::Record: 3103 // The interesting case. 3104 break; 3105 } 3106 3107 // Read a record. 3108 Record.clear(); 3109 unsigned Code = Stream.readRecord(Entry.ID, Record); 3110 switch (Code) { 3111 default: // Default behavior: ignore. 3112 break; 3113 case bitc::METADATA_KIND: { 3114 if (Error Err = parseMetadataKindRecord(Record)) 3115 return Err; 3116 break; 3117 } 3118 } 3119 } 3120 } 3121 3122 /// Decode a signed value stored with the sign bit in the LSB for dense VBR 3123 /// encoding. 3124 uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) { 3125 if ((V & 1) == 0) 3126 return V >> 1; 3127 if (V != 1) 3128 return -(V >> 1); 3129 // There is no such thing as -0 with integers. "-0" really means MININT. 3130 return 1ULL << 63; 3131 } 3132 3133 /// Resolve all of the initializers for global values and aliases that we can. 3134 Error BitcodeReader::resolveGlobalAndIndirectSymbolInits() { 3135 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist; 3136 std::vector<std::pair<GlobalIndirectSymbol*, unsigned> > 3137 IndirectSymbolInitWorklist; 3138 std::vector<std::pair<Function*, unsigned> > FunctionPrefixWorklist; 3139 std::vector<std::pair<Function*, unsigned> > FunctionPrologueWorklist; 3140 std::vector<std::pair<Function*, unsigned> > FunctionPersonalityFnWorklist; 3141 3142 GlobalInitWorklist.swap(GlobalInits); 3143 IndirectSymbolInitWorklist.swap(IndirectSymbolInits); 3144 FunctionPrefixWorklist.swap(FunctionPrefixes); 3145 FunctionPrologueWorklist.swap(FunctionPrologues); 3146 FunctionPersonalityFnWorklist.swap(FunctionPersonalityFns); 3147 3148 while (!GlobalInitWorklist.empty()) { 3149 unsigned ValID = GlobalInitWorklist.back().second; 3150 if (ValID >= ValueList.size()) { 3151 // Not ready to resolve this yet, it requires something later in the file. 3152 GlobalInits.push_back(GlobalInitWorklist.back()); 3153 } else { 3154 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID])) 3155 GlobalInitWorklist.back().first->setInitializer(C); 3156 else 3157 return error("Expected a constant"); 3158 } 3159 GlobalInitWorklist.pop_back(); 3160 } 3161 3162 while (!IndirectSymbolInitWorklist.empty()) { 3163 unsigned ValID = IndirectSymbolInitWorklist.back().second; 3164 if (ValID >= ValueList.size()) { 3165 IndirectSymbolInits.push_back(IndirectSymbolInitWorklist.back()); 3166 } else { 3167 Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]); 3168 if (!C) 3169 return error("Expected a constant"); 3170 GlobalIndirectSymbol *GIS = IndirectSymbolInitWorklist.back().first; 3171 if (isa<GlobalAlias>(GIS) && C->getType() != GIS->getType()) 3172 return error("Alias and aliasee types don't match"); 3173 GIS->setIndirectSymbol(C); 3174 } 3175 IndirectSymbolInitWorklist.pop_back(); 3176 } 3177 3178 while (!FunctionPrefixWorklist.empty()) { 3179 unsigned ValID = FunctionPrefixWorklist.back().second; 3180 if (ValID >= ValueList.size()) { 3181 FunctionPrefixes.push_back(FunctionPrefixWorklist.back()); 3182 } else { 3183 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID])) 3184 FunctionPrefixWorklist.back().first->setPrefixData(C); 3185 else 3186 return error("Expected a constant"); 3187 } 3188 FunctionPrefixWorklist.pop_back(); 3189 } 3190 3191 while (!FunctionPrologueWorklist.empty()) { 3192 unsigned ValID = FunctionPrologueWorklist.back().second; 3193 if (ValID >= ValueList.size()) { 3194 FunctionPrologues.push_back(FunctionPrologueWorklist.back()); 3195 } else { 3196 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID])) 3197 FunctionPrologueWorklist.back().first->setPrologueData(C); 3198 else 3199 return error("Expected a constant"); 3200 } 3201 FunctionPrologueWorklist.pop_back(); 3202 } 3203 3204 while (!FunctionPersonalityFnWorklist.empty()) { 3205 unsigned ValID = FunctionPersonalityFnWorklist.back().second; 3206 if (ValID >= ValueList.size()) { 3207 FunctionPersonalityFns.push_back(FunctionPersonalityFnWorklist.back()); 3208 } else { 3209 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID])) 3210 FunctionPersonalityFnWorklist.back().first->setPersonalityFn(C); 3211 else 3212 return error("Expected a constant"); 3213 } 3214 FunctionPersonalityFnWorklist.pop_back(); 3215 } 3216 3217 return Error::success(); 3218 } 3219 3220 static APInt readWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) { 3221 SmallVector<uint64_t, 8> Words(Vals.size()); 3222 transform(Vals, Words.begin(), 3223 BitcodeReader::decodeSignRotatedValue); 3224 3225 return APInt(TypeBits, Words); 3226 } 3227 3228 Error BitcodeReader::parseConstants() { 3229 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID)) 3230 return error("Invalid record"); 3231 3232 SmallVector<uint64_t, 64> Record; 3233 3234 // Read all the records for this value table. 3235 Type *CurTy = Type::getInt32Ty(Context); 3236 unsigned NextCstNo = ValueList.size(); 3237 3238 while (true) { 3239 BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 3240 3241 switch (Entry.Kind) { 3242 case BitstreamEntry::SubBlock: // Handled for us already. 3243 case BitstreamEntry::Error: 3244 return error("Malformed block"); 3245 case BitstreamEntry::EndBlock: 3246 if (NextCstNo != ValueList.size()) 3247 return error("Invalid constant reference"); 3248 3249 // Once all the constants have been read, go through and resolve forward 3250 // references. 3251 ValueList.resolveConstantForwardRefs(); 3252 return Error::success(); 3253 case BitstreamEntry::Record: 3254 // The interesting case. 3255 break; 3256 } 3257 3258 // Read a record. 3259 Record.clear(); 3260 Type *VoidType = Type::getVoidTy(Context); 3261 Value *V = nullptr; 3262 unsigned BitCode = Stream.readRecord(Entry.ID, Record); 3263 switch (BitCode) { 3264 default: // Default behavior: unknown constant 3265 case bitc::CST_CODE_UNDEF: // UNDEF 3266 V = UndefValue::get(CurTy); 3267 break; 3268 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid] 3269 if (Record.empty()) 3270 return error("Invalid record"); 3271 if (Record[0] >= TypeList.size() || !TypeList[Record[0]]) 3272 return error("Invalid record"); 3273 if (TypeList[Record[0]] == VoidType) 3274 return error("Invalid constant type"); 3275 CurTy = TypeList[Record[0]]; 3276 continue; // Skip the ValueList manipulation. 3277 case bitc::CST_CODE_NULL: // NULL 3278 V = Constant::getNullValue(CurTy); 3279 break; 3280 case bitc::CST_CODE_INTEGER: // INTEGER: [intval] 3281 if (!CurTy->isIntegerTy() || Record.empty()) 3282 return error("Invalid record"); 3283 V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0])); 3284 break; 3285 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval] 3286 if (!CurTy->isIntegerTy() || Record.empty()) 3287 return error("Invalid record"); 3288 3289 APInt VInt = 3290 readWideAPInt(Record, cast<IntegerType>(CurTy)->getBitWidth()); 3291 V = ConstantInt::get(Context, VInt); 3292 3293 break; 3294 } 3295 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval] 3296 if (Record.empty()) 3297 return error("Invalid record"); 3298 if (CurTy->isHalfTy()) 3299 V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf, 3300 APInt(16, (uint16_t)Record[0]))); 3301 else if (CurTy->isFloatTy()) 3302 V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle, 3303 APInt(32, (uint32_t)Record[0]))); 3304 else if (CurTy->isDoubleTy()) 3305 V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble, 3306 APInt(64, Record[0]))); 3307 else if (CurTy->isX86_FP80Ty()) { 3308 // Bits are not stored the same way as a normal i80 APInt, compensate. 3309 uint64_t Rearrange[2]; 3310 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16); 3311 Rearrange[1] = Record[0] >> 48; 3312 V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended, 3313 APInt(80, Rearrange))); 3314 } else if (CurTy->isFP128Ty()) 3315 V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad, 3316 APInt(128, Record))); 3317 else if (CurTy->isPPC_FP128Ty()) 3318 V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble, 3319 APInt(128, Record))); 3320 else 3321 V = UndefValue::get(CurTy); 3322 break; 3323 } 3324 3325 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number] 3326 if (Record.empty()) 3327 return error("Invalid record"); 3328 3329 unsigned Size = Record.size(); 3330 SmallVector<Constant*, 16> Elts; 3331 3332 if (StructType *STy = dyn_cast<StructType>(CurTy)) { 3333 for (unsigned i = 0; i != Size; ++i) 3334 Elts.push_back(ValueList.getConstantFwdRef(Record[i], 3335 STy->getElementType(i))); 3336 V = ConstantStruct::get(STy, Elts); 3337 } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) { 3338 Type *EltTy = ATy->getElementType(); 3339 for (unsigned i = 0; i != Size; ++i) 3340 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy)); 3341 V = ConstantArray::get(ATy, Elts); 3342 } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) { 3343 Type *EltTy = VTy->getElementType(); 3344 for (unsigned i = 0; i != Size; ++i) 3345 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy)); 3346 V = ConstantVector::get(Elts); 3347 } else { 3348 V = UndefValue::get(CurTy); 3349 } 3350 break; 3351 } 3352 case bitc::CST_CODE_STRING: // STRING: [values] 3353 case bitc::CST_CODE_CSTRING: { // CSTRING: [values] 3354 if (Record.empty()) 3355 return error("Invalid record"); 3356 3357 SmallString<16> Elts(Record.begin(), Record.end()); 3358 V = ConstantDataArray::getString(Context, Elts, 3359 BitCode == bitc::CST_CODE_CSTRING); 3360 break; 3361 } 3362 case bitc::CST_CODE_DATA: {// DATA: [n x value] 3363 if (Record.empty()) 3364 return error("Invalid record"); 3365 3366 Type *EltTy = cast<SequentialType>(CurTy)->getElementType(); 3367 if (EltTy->isIntegerTy(8)) { 3368 SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end()); 3369 if (isa<VectorType>(CurTy)) 3370 V = ConstantDataVector::get(Context, Elts); 3371 else 3372 V = ConstantDataArray::get(Context, Elts); 3373 } else if (EltTy->isIntegerTy(16)) { 3374 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end()); 3375 if (isa<VectorType>(CurTy)) 3376 V = ConstantDataVector::get(Context, Elts); 3377 else 3378 V = ConstantDataArray::get(Context, Elts); 3379 } else if (EltTy->isIntegerTy(32)) { 3380 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end()); 3381 if (isa<VectorType>(CurTy)) 3382 V = ConstantDataVector::get(Context, Elts); 3383 else 3384 V = ConstantDataArray::get(Context, Elts); 3385 } else if (EltTy->isIntegerTy(64)) { 3386 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end()); 3387 if (isa<VectorType>(CurTy)) 3388 V = ConstantDataVector::get(Context, Elts); 3389 else 3390 V = ConstantDataArray::get(Context, Elts); 3391 } else if (EltTy->isHalfTy()) { 3392 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end()); 3393 if (isa<VectorType>(CurTy)) 3394 V = ConstantDataVector::getFP(Context, Elts); 3395 else 3396 V = ConstantDataArray::getFP(Context, Elts); 3397 } else if (EltTy->isFloatTy()) { 3398 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end()); 3399 if (isa<VectorType>(CurTy)) 3400 V = ConstantDataVector::getFP(Context, Elts); 3401 else 3402 V = ConstantDataArray::getFP(Context, Elts); 3403 } else if (EltTy->isDoubleTy()) { 3404 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end()); 3405 if (isa<VectorType>(CurTy)) 3406 V = ConstantDataVector::getFP(Context, Elts); 3407 else 3408 V = ConstantDataArray::getFP(Context, Elts); 3409 } else { 3410 return error("Invalid type for value"); 3411 } 3412 break; 3413 } 3414 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval] 3415 if (Record.size() < 3) 3416 return error("Invalid record"); 3417 int Opc = getDecodedBinaryOpcode(Record[0], CurTy); 3418 if (Opc < 0) { 3419 V = UndefValue::get(CurTy); // Unknown binop. 3420 } else { 3421 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy); 3422 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy); 3423 unsigned Flags = 0; 3424 if (Record.size() >= 4) { 3425 if (Opc == Instruction::Add || 3426 Opc == Instruction::Sub || 3427 Opc == Instruction::Mul || 3428 Opc == Instruction::Shl) { 3429 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP)) 3430 Flags |= OverflowingBinaryOperator::NoSignedWrap; 3431 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP)) 3432 Flags |= OverflowingBinaryOperator::NoUnsignedWrap; 3433 } else if (Opc == Instruction::SDiv || 3434 Opc == Instruction::UDiv || 3435 Opc == Instruction::LShr || 3436 Opc == Instruction::AShr) { 3437 if (Record[3] & (1 << bitc::PEO_EXACT)) 3438 Flags |= SDivOperator::IsExact; 3439 } 3440 } 3441 V = ConstantExpr::get(Opc, LHS, RHS, Flags); 3442 } 3443 break; 3444 } 3445 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval] 3446 if (Record.size() < 3) 3447 return error("Invalid record"); 3448 int Opc = getDecodedCastOpcode(Record[0]); 3449 if (Opc < 0) { 3450 V = UndefValue::get(CurTy); // Unknown cast. 3451 } else { 3452 Type *OpTy = getTypeByID(Record[1]); 3453 if (!OpTy) 3454 return error("Invalid record"); 3455 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy); 3456 V = UpgradeBitCastExpr(Opc, Op, CurTy); 3457 if (!V) V = ConstantExpr::getCast(Opc, Op, CurTy); 3458 } 3459 break; 3460 } 3461 case bitc::CST_CODE_CE_INBOUNDS_GEP: // [ty, n x operands] 3462 case bitc::CST_CODE_CE_GEP: // [ty, n x operands] 3463 case bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX: { // [ty, flags, n x 3464 // operands] 3465 unsigned OpNum = 0; 3466 Type *PointeeType = nullptr; 3467 if (BitCode == bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX || 3468 Record.size() % 2) 3469 PointeeType = getTypeByID(Record[OpNum++]); 3470 3471 bool InBounds = false; 3472 Optional<unsigned> InRangeIndex; 3473 if (BitCode == bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX) { 3474 uint64_t Op = Record[OpNum++]; 3475 InBounds = Op & 1; 3476 InRangeIndex = Op >> 1; 3477 } else if (BitCode == bitc::CST_CODE_CE_INBOUNDS_GEP) 3478 InBounds = true; 3479 3480 SmallVector<Constant*, 16> Elts; 3481 while (OpNum != Record.size()) { 3482 Type *ElTy = getTypeByID(Record[OpNum++]); 3483 if (!ElTy) 3484 return error("Invalid record"); 3485 Elts.push_back(ValueList.getConstantFwdRef(Record[OpNum++], ElTy)); 3486 } 3487 3488 if (PointeeType && 3489 PointeeType != 3490 cast<PointerType>(Elts[0]->getType()->getScalarType()) 3491 ->getElementType()) 3492 return error("Explicit gep operator type does not match pointee type " 3493 "of pointer operand"); 3494 3495 if (Elts.size() < 1) 3496 return error("Invalid gep with no operands"); 3497 3498 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end()); 3499 V = ConstantExpr::getGetElementPtr(PointeeType, Elts[0], Indices, 3500 InBounds, InRangeIndex); 3501 break; 3502 } 3503 case bitc::CST_CODE_CE_SELECT: { // CE_SELECT: [opval#, opval#, opval#] 3504 if (Record.size() < 3) 3505 return error("Invalid record"); 3506 3507 Type *SelectorTy = Type::getInt1Ty(Context); 3508 3509 // The selector might be an i1 or an <n x i1> 3510 // Get the type from the ValueList before getting a forward ref. 3511 if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) 3512 if (Value *V = ValueList[Record[0]]) 3513 if (SelectorTy != V->getType()) 3514 SelectorTy = VectorType::get(SelectorTy, VTy->getNumElements()); 3515 3516 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0], 3517 SelectorTy), 3518 ValueList.getConstantFwdRef(Record[1],CurTy), 3519 ValueList.getConstantFwdRef(Record[2],CurTy)); 3520 break; 3521 } 3522 case bitc::CST_CODE_CE_EXTRACTELT 3523 : { // CE_EXTRACTELT: [opty, opval, opty, opval] 3524 if (Record.size() < 3) 3525 return error("Invalid record"); 3526 VectorType *OpTy = 3527 dyn_cast_or_null<VectorType>(getTypeByID(Record[0])); 3528 if (!OpTy) 3529 return error("Invalid record"); 3530 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy); 3531 Constant *Op1 = nullptr; 3532 if (Record.size() == 4) { 3533 Type *IdxTy = getTypeByID(Record[2]); 3534 if (!IdxTy) 3535 return error("Invalid record"); 3536 Op1 = ValueList.getConstantFwdRef(Record[3], IdxTy); 3537 } else // TODO: Remove with llvm 4.0 3538 Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context)); 3539 if (!Op1) 3540 return error("Invalid record"); 3541 V = ConstantExpr::getExtractElement(Op0, Op1); 3542 break; 3543 } 3544 case bitc::CST_CODE_CE_INSERTELT 3545 : { // CE_INSERTELT: [opval, opval, opty, opval] 3546 VectorType *OpTy = dyn_cast<VectorType>(CurTy); 3547 if (Record.size() < 3 || !OpTy) 3548 return error("Invalid record"); 3549 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy); 3550 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], 3551 OpTy->getElementType()); 3552 Constant *Op2 = nullptr; 3553 if (Record.size() == 4) { 3554 Type *IdxTy = getTypeByID(Record[2]); 3555 if (!IdxTy) 3556 return error("Invalid record"); 3557 Op2 = ValueList.getConstantFwdRef(Record[3], IdxTy); 3558 } else // TODO: Remove with llvm 4.0 3559 Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context)); 3560 if (!Op2) 3561 return error("Invalid record"); 3562 V = ConstantExpr::getInsertElement(Op0, Op1, Op2); 3563 break; 3564 } 3565 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval] 3566 VectorType *OpTy = dyn_cast<VectorType>(CurTy); 3567 if (Record.size() < 3 || !OpTy) 3568 return error("Invalid record"); 3569 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy); 3570 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy); 3571 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context), 3572 OpTy->getNumElements()); 3573 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy); 3574 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2); 3575 break; 3576 } 3577 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval] 3578 VectorType *RTy = dyn_cast<VectorType>(CurTy); 3579 VectorType *OpTy = 3580 dyn_cast_or_null<VectorType>(getTypeByID(Record[0])); 3581 if (Record.size() < 4 || !RTy || !OpTy) 3582 return error("Invalid record"); 3583 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy); 3584 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy); 3585 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context), 3586 RTy->getNumElements()); 3587 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy); 3588 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2); 3589 break; 3590 } 3591 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred] 3592 if (Record.size() < 4) 3593 return error("Invalid record"); 3594 Type *OpTy = getTypeByID(Record[0]); 3595 if (!OpTy) 3596 return error("Invalid record"); 3597 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy); 3598 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy); 3599 3600 if (OpTy->isFPOrFPVectorTy()) 3601 V = ConstantExpr::getFCmp(Record[3], Op0, Op1); 3602 else 3603 V = ConstantExpr::getICmp(Record[3], Op0, Op1); 3604 break; 3605 } 3606 // This maintains backward compatibility, pre-asm dialect keywords. 3607 // FIXME: Remove with the 4.0 release. 3608 case bitc::CST_CODE_INLINEASM_OLD: { 3609 if (Record.size() < 2) 3610 return error("Invalid record"); 3611 std::string AsmStr, ConstrStr; 3612 bool HasSideEffects = Record[0] & 1; 3613 bool IsAlignStack = Record[0] >> 1; 3614 unsigned AsmStrSize = Record[1]; 3615 if (2+AsmStrSize >= Record.size()) 3616 return error("Invalid record"); 3617 unsigned ConstStrSize = Record[2+AsmStrSize]; 3618 if (3+AsmStrSize+ConstStrSize > Record.size()) 3619 return error("Invalid record"); 3620 3621 for (unsigned i = 0; i != AsmStrSize; ++i) 3622 AsmStr += (char)Record[2+i]; 3623 for (unsigned i = 0; i != ConstStrSize; ++i) 3624 ConstrStr += (char)Record[3+AsmStrSize+i]; 3625 PointerType *PTy = cast<PointerType>(CurTy); 3626 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()), 3627 AsmStr, ConstrStr, HasSideEffects, IsAlignStack); 3628 break; 3629 } 3630 // This version adds support for the asm dialect keywords (e.g., 3631 // inteldialect). 3632 case bitc::CST_CODE_INLINEASM: { 3633 if (Record.size() < 2) 3634 return error("Invalid record"); 3635 std::string AsmStr, ConstrStr; 3636 bool HasSideEffects = Record[0] & 1; 3637 bool IsAlignStack = (Record[0] >> 1) & 1; 3638 unsigned AsmDialect = Record[0] >> 2; 3639 unsigned AsmStrSize = Record[1]; 3640 if (2+AsmStrSize >= Record.size()) 3641 return error("Invalid record"); 3642 unsigned ConstStrSize = Record[2+AsmStrSize]; 3643 if (3+AsmStrSize+ConstStrSize > Record.size()) 3644 return error("Invalid record"); 3645 3646 for (unsigned i = 0; i != AsmStrSize; ++i) 3647 AsmStr += (char)Record[2+i]; 3648 for (unsigned i = 0; i != ConstStrSize; ++i) 3649 ConstrStr += (char)Record[3+AsmStrSize+i]; 3650 PointerType *PTy = cast<PointerType>(CurTy); 3651 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()), 3652 AsmStr, ConstrStr, HasSideEffects, IsAlignStack, 3653 InlineAsm::AsmDialect(AsmDialect)); 3654 break; 3655 } 3656 case bitc::CST_CODE_BLOCKADDRESS:{ 3657 if (Record.size() < 3) 3658 return error("Invalid record"); 3659 Type *FnTy = getTypeByID(Record[0]); 3660 if (!FnTy) 3661 return error("Invalid record"); 3662 Function *Fn = 3663 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy)); 3664 if (!Fn) 3665 return error("Invalid record"); 3666 3667 // If the function is already parsed we can insert the block address right 3668 // away. 3669 BasicBlock *BB; 3670 unsigned BBID = Record[2]; 3671 if (!BBID) 3672 // Invalid reference to entry block. 3673 return error("Invalid ID"); 3674 if (!Fn->empty()) { 3675 Function::iterator BBI = Fn->begin(), BBE = Fn->end(); 3676 for (size_t I = 0, E = BBID; I != E; ++I) { 3677 if (BBI == BBE) 3678 return error("Invalid ID"); 3679 ++BBI; 3680 } 3681 BB = &*BBI; 3682 } else { 3683 // Otherwise insert a placeholder and remember it so it can be inserted 3684 // when the function is parsed. 3685 auto &FwdBBs = BasicBlockFwdRefs[Fn]; 3686 if (FwdBBs.empty()) 3687 BasicBlockFwdRefQueue.push_back(Fn); 3688 if (FwdBBs.size() < BBID + 1) 3689 FwdBBs.resize(BBID + 1); 3690 if (!FwdBBs[BBID]) 3691 FwdBBs[BBID] = BasicBlock::Create(Context); 3692 BB = FwdBBs[BBID]; 3693 } 3694 V = BlockAddress::get(Fn, BB); 3695 break; 3696 } 3697 } 3698 3699 ValueList.assignValue(V, NextCstNo); 3700 ++NextCstNo; 3701 } 3702 } 3703 3704 Error BitcodeReader::parseUseLists() { 3705 if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID)) 3706 return error("Invalid record"); 3707 3708 // Read all the records. 3709 SmallVector<uint64_t, 64> Record; 3710 3711 while (true) { 3712 BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 3713 3714 switch (Entry.Kind) { 3715 case BitstreamEntry::SubBlock: // Handled for us already. 3716 case BitstreamEntry::Error: 3717 return error("Malformed block"); 3718 case BitstreamEntry::EndBlock: 3719 return Error::success(); 3720 case BitstreamEntry::Record: 3721 // The interesting case. 3722 break; 3723 } 3724 3725 // Read a use list record. 3726 Record.clear(); 3727 bool IsBB = false; 3728 switch (Stream.readRecord(Entry.ID, Record)) { 3729 default: // Default behavior: unknown type. 3730 break; 3731 case bitc::USELIST_CODE_BB: 3732 IsBB = true; 3733 LLVM_FALLTHROUGH; 3734 case bitc::USELIST_CODE_DEFAULT: { 3735 unsigned RecordLength = Record.size(); 3736 if (RecordLength < 3) 3737 // Records should have at least an ID and two indexes. 3738 return error("Invalid record"); 3739 unsigned ID = Record.back(); 3740 Record.pop_back(); 3741 3742 Value *V; 3743 if (IsBB) { 3744 assert(ID < FunctionBBs.size() && "Basic block not found"); 3745 V = FunctionBBs[ID]; 3746 } else 3747 V = ValueList[ID]; 3748 unsigned NumUses = 0; 3749 SmallDenseMap<const Use *, unsigned, 16> Order; 3750 for (const Use &U : V->materialized_uses()) { 3751 if (++NumUses > Record.size()) 3752 break; 3753 Order[&U] = Record[NumUses - 1]; 3754 } 3755 if (Order.size() != Record.size() || NumUses > Record.size()) 3756 // Mismatches can happen if the functions are being materialized lazily 3757 // (out-of-order), or a value has been upgraded. 3758 break; 3759 3760 V->sortUseList([&](const Use &L, const Use &R) { 3761 return Order.lookup(&L) < Order.lookup(&R); 3762 }); 3763 break; 3764 } 3765 } 3766 } 3767 } 3768 3769 /// When we see the block for metadata, remember where it is and then skip it. 3770 /// This lets us lazily deserialize the metadata. 3771 Error BitcodeReader::rememberAndSkipMetadata() { 3772 // Save the current stream state. 3773 uint64_t CurBit = Stream.GetCurrentBitNo(); 3774 DeferredMetadataInfo.push_back(CurBit); 3775 3776 // Skip over the block for now. 3777 if (Stream.SkipBlock()) 3778 return error("Invalid record"); 3779 return Error::success(); 3780 } 3781 3782 Error BitcodeReader::materializeMetadata() { 3783 for (uint64_t BitPos : DeferredMetadataInfo) { 3784 // Move the bit stream to the saved position. 3785 Stream.JumpToBit(BitPos); 3786 if (Error Err = parseMetadata(true)) 3787 return Err; 3788 } 3789 DeferredMetadataInfo.clear(); 3790 return Error::success(); 3791 } 3792 3793 void BitcodeReader::setStripDebugInfo() { StripDebugInfo = true; } 3794 3795 /// When we see the block for a function body, remember where it is and then 3796 /// skip it. This lets us lazily deserialize the functions. 3797 Error BitcodeReader::rememberAndSkipFunctionBody() { 3798 // Get the function we are talking about. 3799 if (FunctionsWithBodies.empty()) 3800 return error("Insufficient function protos"); 3801 3802 Function *Fn = FunctionsWithBodies.back(); 3803 FunctionsWithBodies.pop_back(); 3804 3805 // Save the current stream state. 3806 uint64_t CurBit = Stream.GetCurrentBitNo(); 3807 assert( 3808 (DeferredFunctionInfo[Fn] == 0 || DeferredFunctionInfo[Fn] == CurBit) && 3809 "Mismatch between VST and scanned function offsets"); 3810 DeferredFunctionInfo[Fn] = CurBit; 3811 3812 // Skip over the function block for now. 3813 if (Stream.SkipBlock()) 3814 return error("Invalid record"); 3815 return Error::success(); 3816 } 3817 3818 Error BitcodeReader::globalCleanup() { 3819 // Patch the initializers for globals and aliases up. 3820 if (Error Err = resolveGlobalAndIndirectSymbolInits()) 3821 return Err; 3822 if (!GlobalInits.empty() || !IndirectSymbolInits.empty()) 3823 return error("Malformed global initializer set"); 3824 3825 // Look for intrinsic functions which need to be upgraded at some point 3826 for (Function &F : *TheModule) { 3827 Function *NewFn; 3828 if (UpgradeIntrinsicFunction(&F, NewFn)) 3829 UpgradedIntrinsics[&F] = NewFn; 3830 else if (auto Remangled = Intrinsic::remangleIntrinsicFunction(&F)) 3831 // Some types could be renamed during loading if several modules are 3832 // loaded in the same LLVMContext (LTO scenario). In this case we should 3833 // remangle intrinsics names as well. 3834 RemangledIntrinsics[&F] = Remangled.getValue(); 3835 } 3836 3837 // Look for global variables which need to be renamed. 3838 for (GlobalVariable &GV : TheModule->globals()) 3839 UpgradeGlobalVariable(&GV); 3840 3841 // Force deallocation of memory for these vectors to favor the client that 3842 // want lazy deserialization. 3843 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits); 3844 std::vector<std::pair<GlobalIndirectSymbol*, unsigned> >().swap( 3845 IndirectSymbolInits); 3846 return Error::success(); 3847 } 3848 3849 /// Support for lazy parsing of function bodies. This is required if we 3850 /// either have an old bitcode file without a VST forward declaration record, 3851 /// or if we have an anonymous function being materialized, since anonymous 3852 /// functions do not have a name and are therefore not in the VST. 3853 Error BitcodeReader::rememberAndSkipFunctionBodies() { 3854 Stream.JumpToBit(NextUnreadBit); 3855 3856 if (Stream.AtEndOfStream()) 3857 return error("Could not find function in stream"); 3858 3859 if (!SeenFirstFunctionBody) 3860 return error("Trying to materialize functions before seeing function blocks"); 3861 3862 // An old bitcode file with the symbol table at the end would have 3863 // finished the parse greedily. 3864 assert(SeenValueSymbolTable); 3865 3866 SmallVector<uint64_t, 64> Record; 3867 3868 while (true) { 3869 BitstreamEntry Entry = Stream.advance(); 3870 switch (Entry.Kind) { 3871 default: 3872 return error("Expect SubBlock"); 3873 case BitstreamEntry::SubBlock: 3874 switch (Entry.ID) { 3875 default: 3876 return error("Expect function block"); 3877 case bitc::FUNCTION_BLOCK_ID: 3878 if (Error Err = rememberAndSkipFunctionBody()) 3879 return Err; 3880 NextUnreadBit = Stream.GetCurrentBitNo(); 3881 return Error::success(); 3882 } 3883 } 3884 } 3885 } 3886 3887 bool BitcodeReaderBase::readBlockInfo() { 3888 Optional<BitstreamBlockInfo> NewBlockInfo = Stream.ReadBlockInfoBlock(); 3889 if (!NewBlockInfo) 3890 return true; 3891 BlockInfo = std::move(*NewBlockInfo); 3892 return false; 3893 } 3894 3895 Error BitcodeReader::parseModule(uint64_t ResumeBit, 3896 bool ShouldLazyLoadMetadata) { 3897 if (ResumeBit) 3898 Stream.JumpToBit(ResumeBit); 3899 else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID)) 3900 return error("Invalid record"); 3901 3902 SmallVector<uint64_t, 64> Record; 3903 std::vector<std::string> SectionTable; 3904 std::vector<std::string> GCTable; 3905 3906 // Read all the records for this module. 3907 while (true) { 3908 BitstreamEntry Entry = Stream.advance(); 3909 3910 switch (Entry.Kind) { 3911 case BitstreamEntry::Error: 3912 return error("Malformed block"); 3913 case BitstreamEntry::EndBlock: 3914 return globalCleanup(); 3915 3916 case BitstreamEntry::SubBlock: 3917 switch (Entry.ID) { 3918 default: // Skip unknown content. 3919 if (Stream.SkipBlock()) 3920 return error("Invalid record"); 3921 break; 3922 case bitc::BLOCKINFO_BLOCK_ID: 3923 if (readBlockInfo()) 3924 return error("Malformed block"); 3925 break; 3926 case bitc::PARAMATTR_BLOCK_ID: 3927 if (Error Err = parseAttributeBlock()) 3928 return Err; 3929 break; 3930 case bitc::PARAMATTR_GROUP_BLOCK_ID: 3931 if (Error Err = parseAttributeGroupBlock()) 3932 return Err; 3933 break; 3934 case bitc::TYPE_BLOCK_ID_NEW: 3935 if (Error Err = parseTypeTable()) 3936 return Err; 3937 break; 3938 case bitc::VALUE_SYMTAB_BLOCK_ID: 3939 if (!SeenValueSymbolTable) { 3940 // Either this is an old form VST without function index and an 3941 // associated VST forward declaration record (which would have caused 3942 // the VST to be jumped to and parsed before it was encountered 3943 // normally in the stream), or there were no function blocks to 3944 // trigger an earlier parsing of the VST. 3945 assert(VSTOffset == 0 || FunctionsWithBodies.empty()); 3946 if (Error Err = parseValueSymbolTable()) 3947 return Err; 3948 SeenValueSymbolTable = true; 3949 } else { 3950 // We must have had a VST forward declaration record, which caused 3951 // the parser to jump to and parse the VST earlier. 3952 assert(VSTOffset > 0); 3953 if (Stream.SkipBlock()) 3954 return error("Invalid record"); 3955 } 3956 break; 3957 case bitc::CONSTANTS_BLOCK_ID: 3958 if (Error Err = parseConstants()) 3959 return Err; 3960 if (Error Err = resolveGlobalAndIndirectSymbolInits()) 3961 return Err; 3962 break; 3963 case bitc::METADATA_BLOCK_ID: 3964 if (ShouldLazyLoadMetadata && !IsMetadataMaterialized) { 3965 if (Error Err = rememberAndSkipMetadata()) 3966 return Err; 3967 break; 3968 } 3969 assert(DeferredMetadataInfo.empty() && "Unexpected deferred metadata"); 3970 if (Error Err = parseMetadata(true)) 3971 return Err; 3972 break; 3973 case bitc::METADATA_KIND_BLOCK_ID: 3974 if (Error Err = parseMetadataKinds()) 3975 return Err; 3976 break; 3977 case bitc::FUNCTION_BLOCK_ID: 3978 // If this is the first function body we've seen, reverse the 3979 // FunctionsWithBodies list. 3980 if (!SeenFirstFunctionBody) { 3981 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end()); 3982 if (Error Err = globalCleanup()) 3983 return Err; 3984 SeenFirstFunctionBody = true; 3985 } 3986 3987 if (VSTOffset > 0) { 3988 // If we have a VST forward declaration record, make sure we 3989 // parse the VST now if we haven't already. It is needed to 3990 // set up the DeferredFunctionInfo vector for lazy reading. 3991 if (!SeenValueSymbolTable) { 3992 if (Error Err = BitcodeReader::parseValueSymbolTable(VSTOffset)) 3993 return Err; 3994 SeenValueSymbolTable = true; 3995 // Fall through so that we record the NextUnreadBit below. 3996 // This is necessary in case we have an anonymous function that 3997 // is later materialized. Since it will not have a VST entry we 3998 // need to fall back to the lazy parse to find its offset. 3999 } else { 4000 // If we have a VST forward declaration record, but have already 4001 // parsed the VST (just above, when the first function body was 4002 // encountered here), then we are resuming the parse after 4003 // materializing functions. The ResumeBit points to the 4004 // start of the last function block recorded in the 4005 // DeferredFunctionInfo map. Skip it. 4006 if (Stream.SkipBlock()) 4007 return error("Invalid record"); 4008 continue; 4009 } 4010 } 4011 4012 // Support older bitcode files that did not have the function 4013 // index in the VST, nor a VST forward declaration record, as 4014 // well as anonymous functions that do not have VST entries. 4015 // Build the DeferredFunctionInfo vector on the fly. 4016 if (Error Err = rememberAndSkipFunctionBody()) 4017 return Err; 4018 4019 // Suspend parsing when we reach the function bodies. Subsequent 4020 // materialization calls will resume it when necessary. If the bitcode 4021 // file is old, the symbol table will be at the end instead and will not 4022 // have been seen yet. In this case, just finish the parse now. 4023 if (SeenValueSymbolTable) { 4024 NextUnreadBit = Stream.GetCurrentBitNo(); 4025 // After the VST has been parsed, we need to make sure intrinsic name 4026 // are auto-upgraded. 4027 return globalCleanup(); 4028 } 4029 break; 4030 case bitc::USELIST_BLOCK_ID: 4031 if (Error Err = parseUseLists()) 4032 return Err; 4033 break; 4034 case bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID: 4035 if (Error Err = parseOperandBundleTags()) 4036 return Err; 4037 break; 4038 } 4039 continue; 4040 4041 case BitstreamEntry::Record: 4042 // The interesting case. 4043 break; 4044 } 4045 4046 // Read a record. 4047 auto BitCode = Stream.readRecord(Entry.ID, Record); 4048 switch (BitCode) { 4049 default: break; // Default behavior, ignore unknown content. 4050 case bitc::MODULE_CODE_VERSION: { // VERSION: [version#] 4051 if (Record.size() < 1) 4052 return error("Invalid record"); 4053 // Only version #0 and #1 are supported so far. 4054 unsigned module_version = Record[0]; 4055 switch (module_version) { 4056 default: 4057 return error("Invalid value"); 4058 case 0: 4059 UseRelativeIDs = false; 4060 break; 4061 case 1: 4062 UseRelativeIDs = true; 4063 break; 4064 } 4065 break; 4066 } 4067 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N] 4068 std::string S; 4069 if (convertToString(Record, 0, S)) 4070 return error("Invalid record"); 4071 TheModule->setTargetTriple(S); 4072 break; 4073 } 4074 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N] 4075 std::string S; 4076 if (convertToString(Record, 0, S)) 4077 return error("Invalid record"); 4078 TheModule->setDataLayout(S); 4079 break; 4080 } 4081 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N] 4082 std::string S; 4083 if (convertToString(Record, 0, S)) 4084 return error("Invalid record"); 4085 TheModule->setModuleInlineAsm(S); 4086 break; 4087 } 4088 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N] 4089 // FIXME: Remove in 4.0. 4090 std::string S; 4091 if (convertToString(Record, 0, S)) 4092 return error("Invalid record"); 4093 // Ignore value. 4094 break; 4095 } 4096 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N] 4097 std::string S; 4098 if (convertToString(Record, 0, S)) 4099 return error("Invalid record"); 4100 SectionTable.push_back(S); 4101 break; 4102 } 4103 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N] 4104 std::string S; 4105 if (convertToString(Record, 0, S)) 4106 return error("Invalid record"); 4107 GCTable.push_back(S); 4108 break; 4109 } 4110 case bitc::MODULE_CODE_COMDAT: { // COMDAT: [selection_kind, name] 4111 if (Record.size() < 2) 4112 return error("Invalid record"); 4113 Comdat::SelectionKind SK = getDecodedComdatSelectionKind(Record[0]); 4114 unsigned ComdatNameSize = Record[1]; 4115 std::string ComdatName; 4116 ComdatName.reserve(ComdatNameSize); 4117 for (unsigned i = 0; i != ComdatNameSize; ++i) 4118 ComdatName += (char)Record[2 + i]; 4119 Comdat *C = TheModule->getOrInsertComdat(ComdatName); 4120 C->setSelectionKind(SK); 4121 ComdatList.push_back(C); 4122 break; 4123 } 4124 // GLOBALVAR: [pointer type, isconst, initid, 4125 // linkage, alignment, section, visibility, threadlocal, 4126 // unnamed_addr, externally_initialized, dllstorageclass, 4127 // comdat] 4128 case bitc::MODULE_CODE_GLOBALVAR: { 4129 if (Record.size() < 6) 4130 return error("Invalid record"); 4131 Type *Ty = getTypeByID(Record[0]); 4132 if (!Ty) 4133 return error("Invalid record"); 4134 bool isConstant = Record[1] & 1; 4135 bool explicitType = Record[1] & 2; 4136 unsigned AddressSpace; 4137 if (explicitType) { 4138 AddressSpace = Record[1] >> 2; 4139 } else { 4140 if (!Ty->isPointerTy()) 4141 return error("Invalid type for value"); 4142 AddressSpace = cast<PointerType>(Ty)->getAddressSpace(); 4143 Ty = cast<PointerType>(Ty)->getElementType(); 4144 } 4145 4146 uint64_t RawLinkage = Record[3]; 4147 GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage); 4148 unsigned Alignment; 4149 if (Error Err = parseAlignmentValue(Record[4], Alignment)) 4150 return Err; 4151 std::string Section; 4152 if (Record[5]) { 4153 if (Record[5]-1 >= SectionTable.size()) 4154 return error("Invalid ID"); 4155 Section = SectionTable[Record[5]-1]; 4156 } 4157 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility; 4158 // Local linkage must have default visibility. 4159 if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage)) 4160 // FIXME: Change to an error if non-default in 4.0. 4161 Visibility = getDecodedVisibility(Record[6]); 4162 4163 GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal; 4164 if (Record.size() > 7) 4165 TLM = getDecodedThreadLocalMode(Record[7]); 4166 4167 GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None; 4168 if (Record.size() > 8) 4169 UnnamedAddr = getDecodedUnnamedAddrType(Record[8]); 4170 4171 bool ExternallyInitialized = false; 4172 if (Record.size() > 9) 4173 ExternallyInitialized = Record[9]; 4174 4175 GlobalVariable *NewGV = 4176 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, "", nullptr, 4177 TLM, AddressSpace, ExternallyInitialized); 4178 NewGV->setAlignment(Alignment); 4179 if (!Section.empty()) 4180 NewGV->setSection(Section); 4181 NewGV->setVisibility(Visibility); 4182 NewGV->setUnnamedAddr(UnnamedAddr); 4183 4184 if (Record.size() > 10) 4185 NewGV->setDLLStorageClass(getDecodedDLLStorageClass(Record[10])); 4186 else 4187 upgradeDLLImportExportLinkage(NewGV, RawLinkage); 4188 4189 ValueList.push_back(NewGV); 4190 4191 // Remember which value to use for the global initializer. 4192 if (unsigned InitID = Record[2]) 4193 GlobalInits.push_back(std::make_pair(NewGV, InitID-1)); 4194 4195 if (Record.size() > 11) { 4196 if (unsigned ComdatID = Record[11]) { 4197 if (ComdatID > ComdatList.size()) 4198 return error("Invalid global variable comdat ID"); 4199 NewGV->setComdat(ComdatList[ComdatID - 1]); 4200 } 4201 } else if (hasImplicitComdat(RawLinkage)) { 4202 NewGV->setComdat(reinterpret_cast<Comdat *>(1)); 4203 } 4204 4205 break; 4206 } 4207 // FUNCTION: [type, callingconv, isproto, linkage, paramattr, 4208 // alignment, section, visibility, gc, unnamed_addr, 4209 // prologuedata, dllstorageclass, comdat, prefixdata] 4210 case bitc::MODULE_CODE_FUNCTION: { 4211 if (Record.size() < 8) 4212 return error("Invalid record"); 4213 Type *Ty = getTypeByID(Record[0]); 4214 if (!Ty) 4215 return error("Invalid record"); 4216 if (auto *PTy = dyn_cast<PointerType>(Ty)) 4217 Ty = PTy->getElementType(); 4218 auto *FTy = dyn_cast<FunctionType>(Ty); 4219 if (!FTy) 4220 return error("Invalid type for value"); 4221 auto CC = static_cast<CallingConv::ID>(Record[1]); 4222 if (CC & ~CallingConv::MaxID) 4223 return error("Invalid calling convention ID"); 4224 4225 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage, 4226 "", TheModule); 4227 4228 Func->setCallingConv(CC); 4229 bool isProto = Record[2]; 4230 uint64_t RawLinkage = Record[3]; 4231 Func->setLinkage(getDecodedLinkage(RawLinkage)); 4232 Func->setAttributes(getAttributes(Record[4])); 4233 4234 unsigned Alignment; 4235 if (Error Err = parseAlignmentValue(Record[5], Alignment)) 4236 return Err; 4237 Func->setAlignment(Alignment); 4238 if (Record[6]) { 4239 if (Record[6]-1 >= SectionTable.size()) 4240 return error("Invalid ID"); 4241 Func->setSection(SectionTable[Record[6]-1]); 4242 } 4243 // Local linkage must have default visibility. 4244 if (!Func->hasLocalLinkage()) 4245 // FIXME: Change to an error if non-default in 4.0. 4246 Func->setVisibility(getDecodedVisibility(Record[7])); 4247 if (Record.size() > 8 && Record[8]) { 4248 if (Record[8]-1 >= GCTable.size()) 4249 return error("Invalid ID"); 4250 Func->setGC(GCTable[Record[8] - 1]); 4251 } 4252 GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None; 4253 if (Record.size() > 9) 4254 UnnamedAddr = getDecodedUnnamedAddrType(Record[9]); 4255 Func->setUnnamedAddr(UnnamedAddr); 4256 if (Record.size() > 10 && Record[10] != 0) 4257 FunctionPrologues.push_back(std::make_pair(Func, Record[10]-1)); 4258 4259 if (Record.size() > 11) 4260 Func->setDLLStorageClass(getDecodedDLLStorageClass(Record[11])); 4261 else 4262 upgradeDLLImportExportLinkage(Func, RawLinkage); 4263 4264 if (Record.size() > 12) { 4265 if (unsigned ComdatID = Record[12]) { 4266 if (ComdatID > ComdatList.size()) 4267 return error("Invalid function comdat ID"); 4268 Func->setComdat(ComdatList[ComdatID - 1]); 4269 } 4270 } else if (hasImplicitComdat(RawLinkage)) { 4271 Func->setComdat(reinterpret_cast<Comdat *>(1)); 4272 } 4273 4274 if (Record.size() > 13 && Record[13] != 0) 4275 FunctionPrefixes.push_back(std::make_pair(Func, Record[13]-1)); 4276 4277 if (Record.size() > 14 && Record[14] != 0) 4278 FunctionPersonalityFns.push_back(std::make_pair(Func, Record[14] - 1)); 4279 4280 ValueList.push_back(Func); 4281 4282 // If this is a function with a body, remember the prototype we are 4283 // creating now, so that we can match up the body with them later. 4284 if (!isProto) { 4285 Func->setIsMaterializable(true); 4286 FunctionsWithBodies.push_back(Func); 4287 DeferredFunctionInfo[Func] = 0; 4288 } 4289 break; 4290 } 4291 // ALIAS: [alias type, addrspace, aliasee val#, linkage] 4292 // ALIAS: [alias type, addrspace, aliasee val#, linkage, visibility, dllstorageclass] 4293 // IFUNC: [alias type, addrspace, aliasee val#, linkage, visibility, dllstorageclass] 4294 case bitc::MODULE_CODE_IFUNC: 4295 case bitc::MODULE_CODE_ALIAS: 4296 case bitc::MODULE_CODE_ALIAS_OLD: { 4297 bool NewRecord = BitCode != bitc::MODULE_CODE_ALIAS_OLD; 4298 if (Record.size() < (3 + (unsigned)NewRecord)) 4299 return error("Invalid record"); 4300 unsigned OpNum = 0; 4301 Type *Ty = getTypeByID(Record[OpNum++]); 4302 if (!Ty) 4303 return error("Invalid record"); 4304 4305 unsigned AddrSpace; 4306 if (!NewRecord) { 4307 auto *PTy = dyn_cast<PointerType>(Ty); 4308 if (!PTy) 4309 return error("Invalid type for value"); 4310 Ty = PTy->getElementType(); 4311 AddrSpace = PTy->getAddressSpace(); 4312 } else { 4313 AddrSpace = Record[OpNum++]; 4314 } 4315 4316 auto Val = Record[OpNum++]; 4317 auto Linkage = Record[OpNum++]; 4318 GlobalIndirectSymbol *NewGA; 4319 if (BitCode == bitc::MODULE_CODE_ALIAS || 4320 BitCode == bitc::MODULE_CODE_ALIAS_OLD) 4321 NewGA = GlobalAlias::create(Ty, AddrSpace, getDecodedLinkage(Linkage), 4322 "", TheModule); 4323 else 4324 NewGA = GlobalIFunc::create(Ty, AddrSpace, getDecodedLinkage(Linkage), 4325 "", nullptr, TheModule); 4326 // Old bitcode files didn't have visibility field. 4327 // Local linkage must have default visibility. 4328 if (OpNum != Record.size()) { 4329 auto VisInd = OpNum++; 4330 if (!NewGA->hasLocalLinkage()) 4331 // FIXME: Change to an error if non-default in 4.0. 4332 NewGA->setVisibility(getDecodedVisibility(Record[VisInd])); 4333 } 4334 if (OpNum != Record.size()) 4335 NewGA->setDLLStorageClass(getDecodedDLLStorageClass(Record[OpNum++])); 4336 else 4337 upgradeDLLImportExportLinkage(NewGA, Linkage); 4338 if (OpNum != Record.size()) 4339 NewGA->setThreadLocalMode(getDecodedThreadLocalMode(Record[OpNum++])); 4340 if (OpNum != Record.size()) 4341 NewGA->setUnnamedAddr(getDecodedUnnamedAddrType(Record[OpNum++])); 4342 ValueList.push_back(NewGA); 4343 IndirectSymbolInits.push_back(std::make_pair(NewGA, Val)); 4344 break; 4345 } 4346 /// MODULE_CODE_PURGEVALS: [numvals] 4347 case bitc::MODULE_CODE_PURGEVALS: 4348 // Trim down the value list to the specified size. 4349 if (Record.size() < 1 || Record[0] > ValueList.size()) 4350 return error("Invalid record"); 4351 ValueList.shrinkTo(Record[0]); 4352 break; 4353 /// MODULE_CODE_VSTOFFSET: [offset] 4354 case bitc::MODULE_CODE_VSTOFFSET: 4355 if (Record.size() < 1) 4356 return error("Invalid record"); 4357 VSTOffset = Record[0]; 4358 break; 4359 /// MODULE_CODE_SOURCE_FILENAME: [namechar x N] 4360 case bitc::MODULE_CODE_SOURCE_FILENAME: 4361 SmallString<128> ValueName; 4362 if (convertToString(Record, 0, ValueName)) 4363 return error("Invalid record"); 4364 TheModule->setSourceFileName(ValueName); 4365 break; 4366 } 4367 Record.clear(); 4368 } 4369 } 4370 4371 Error BitcodeReader::parseBitcodeInto(Module *M, bool ShouldLazyLoadMetadata) { 4372 TheModule = M; 4373 return parseModule(0, ShouldLazyLoadMetadata); 4374 } 4375 4376 Error BitcodeReader::parseGlobalObjectAttachment(GlobalObject &GO, 4377 ArrayRef<uint64_t> Record) { 4378 assert(Record.size() % 2 == 0); 4379 for (unsigned I = 0, E = Record.size(); I != E; I += 2) { 4380 auto K = MDKindMap.find(Record[I]); 4381 if (K == MDKindMap.end()) 4382 return error("Invalid ID"); 4383 MDNode *MD = MetadataList.getMDNodeFwdRefOrNull(Record[I + 1]); 4384 if (!MD) 4385 return error("Invalid metadata attachment"); 4386 GO.addMetadata(K->second, *MD); 4387 } 4388 return Error::success(); 4389 } 4390 4391 /// Parse metadata attachments. 4392 Error BitcodeReader::parseMetadataAttachment(Function &F) { 4393 if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID)) 4394 return error("Invalid record"); 4395 4396 SmallVector<uint64_t, 64> Record; 4397 4398 while (true) { 4399 BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 4400 4401 switch (Entry.Kind) { 4402 case BitstreamEntry::SubBlock: // Handled for us already. 4403 case BitstreamEntry::Error: 4404 return error("Malformed block"); 4405 case BitstreamEntry::EndBlock: 4406 return Error::success(); 4407 case BitstreamEntry::Record: 4408 // The interesting case. 4409 break; 4410 } 4411 4412 // Read a metadata attachment record. 4413 Record.clear(); 4414 switch (Stream.readRecord(Entry.ID, Record)) { 4415 default: // Default behavior: ignore. 4416 break; 4417 case bitc::METADATA_ATTACHMENT: { 4418 unsigned RecordLength = Record.size(); 4419 if (Record.empty()) 4420 return error("Invalid record"); 4421 if (RecordLength % 2 == 0) { 4422 // A function attachment. 4423 if (Error Err = parseGlobalObjectAttachment(F, Record)) 4424 return Err; 4425 continue; 4426 } 4427 4428 // An instruction attachment. 4429 Instruction *Inst = InstructionList[Record[0]]; 4430 for (unsigned i = 1; i != RecordLength; i = i+2) { 4431 unsigned Kind = Record[i]; 4432 DenseMap<unsigned, unsigned>::iterator I = 4433 MDKindMap.find(Kind); 4434 if (I == MDKindMap.end()) 4435 return error("Invalid ID"); 4436 Metadata *Node = MetadataList.getMetadataFwdRef(Record[i + 1]); 4437 if (isa<LocalAsMetadata>(Node)) 4438 // Drop the attachment. This used to be legal, but there's no 4439 // upgrade path. 4440 break; 4441 MDNode *MD = dyn_cast_or_null<MDNode>(Node); 4442 if (!MD) 4443 return error("Invalid metadata attachment"); 4444 4445 if (HasSeenOldLoopTags && I->second == LLVMContext::MD_loop) 4446 MD = upgradeInstructionLoopAttachment(*MD); 4447 4448 if (I->second == LLVMContext::MD_tbaa) { 4449 assert(!MD->isTemporary() && "should load MDs before attachments"); 4450 MD = UpgradeTBAANode(*MD); 4451 } 4452 Inst->setMetadata(I->second, MD); 4453 } 4454 break; 4455 } 4456 } 4457 } 4458 } 4459 4460 Error BitcodeReader::typeCheckLoadStoreInst(Type *ValType, Type *PtrType) { 4461 if (!isa<PointerType>(PtrType)) 4462 return error("Load/Store operand is not a pointer type"); 4463 Type *ElemType = cast<PointerType>(PtrType)->getElementType(); 4464 4465 if (ValType && ValType != ElemType) 4466 return error("Explicit load/store type does not match pointee " 4467 "type of pointer operand"); 4468 if (!PointerType::isLoadableOrStorableType(ElemType)) 4469 return error("Cannot load/store from pointer"); 4470 return Error::success(); 4471 } 4472 4473 /// Lazily parse the specified function body block. 4474 Error BitcodeReader::parseFunctionBody(Function *F) { 4475 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID)) 4476 return error("Invalid record"); 4477 4478 // Unexpected unresolved metadata when parsing function. 4479 if (MetadataList.hasFwdRefs()) 4480 return error("Invalid function metadata: incoming forward references"); 4481 4482 InstructionList.clear(); 4483 unsigned ModuleValueListSize = ValueList.size(); 4484 unsigned ModuleMetadataListSize = MetadataList.size(); 4485 4486 // Add all the function arguments to the value table. 4487 for (Argument &I : F->args()) 4488 ValueList.push_back(&I); 4489 4490 unsigned NextValueNo = ValueList.size(); 4491 BasicBlock *CurBB = nullptr; 4492 unsigned CurBBNo = 0; 4493 4494 DebugLoc LastLoc; 4495 auto getLastInstruction = [&]() -> Instruction * { 4496 if (CurBB && !CurBB->empty()) 4497 return &CurBB->back(); 4498 else if (CurBBNo && FunctionBBs[CurBBNo - 1] && 4499 !FunctionBBs[CurBBNo - 1]->empty()) 4500 return &FunctionBBs[CurBBNo - 1]->back(); 4501 return nullptr; 4502 }; 4503 4504 std::vector<OperandBundleDef> OperandBundles; 4505 4506 // Read all the records. 4507 SmallVector<uint64_t, 64> Record; 4508 4509 while (true) { 4510 BitstreamEntry Entry = Stream.advance(); 4511 4512 switch (Entry.Kind) { 4513 case BitstreamEntry::Error: 4514 return error("Malformed block"); 4515 case BitstreamEntry::EndBlock: 4516 goto OutOfRecordLoop; 4517 4518 case BitstreamEntry::SubBlock: 4519 switch (Entry.ID) { 4520 default: // Skip unknown content. 4521 if (Stream.SkipBlock()) 4522 return error("Invalid record"); 4523 break; 4524 case bitc::CONSTANTS_BLOCK_ID: 4525 if (Error Err = parseConstants()) 4526 return Err; 4527 NextValueNo = ValueList.size(); 4528 break; 4529 case bitc::VALUE_SYMTAB_BLOCK_ID: 4530 if (Error Err = parseValueSymbolTable()) 4531 return Err; 4532 break; 4533 case bitc::METADATA_ATTACHMENT_ID: 4534 if (Error Err = parseMetadataAttachment(*F)) 4535 return Err; 4536 break; 4537 case bitc::METADATA_BLOCK_ID: 4538 if (Error Err = parseMetadata()) 4539 return Err; 4540 break; 4541 case bitc::USELIST_BLOCK_ID: 4542 if (Error Err = parseUseLists()) 4543 return Err; 4544 break; 4545 } 4546 continue; 4547 4548 case BitstreamEntry::Record: 4549 // The interesting case. 4550 break; 4551 } 4552 4553 // Read a record. 4554 Record.clear(); 4555 Instruction *I = nullptr; 4556 unsigned BitCode = Stream.readRecord(Entry.ID, Record); 4557 switch (BitCode) { 4558 default: // Default behavior: reject 4559 return error("Invalid value"); 4560 case bitc::FUNC_CODE_DECLAREBLOCKS: { // DECLAREBLOCKS: [nblocks] 4561 if (Record.size() < 1 || Record[0] == 0) 4562 return error("Invalid record"); 4563 // Create all the basic blocks for the function. 4564 FunctionBBs.resize(Record[0]); 4565 4566 // See if anything took the address of blocks in this function. 4567 auto BBFRI = BasicBlockFwdRefs.find(F); 4568 if (BBFRI == BasicBlockFwdRefs.end()) { 4569 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i) 4570 FunctionBBs[i] = BasicBlock::Create(Context, "", F); 4571 } else { 4572 auto &BBRefs = BBFRI->second; 4573 // Check for invalid basic block references. 4574 if (BBRefs.size() > FunctionBBs.size()) 4575 return error("Invalid ID"); 4576 assert(!BBRefs.empty() && "Unexpected empty array"); 4577 assert(!BBRefs.front() && "Invalid reference to entry block"); 4578 for (unsigned I = 0, E = FunctionBBs.size(), RE = BBRefs.size(); I != E; 4579 ++I) 4580 if (I < RE && BBRefs[I]) { 4581 BBRefs[I]->insertInto(F); 4582 FunctionBBs[I] = BBRefs[I]; 4583 } else { 4584 FunctionBBs[I] = BasicBlock::Create(Context, "", F); 4585 } 4586 4587 // Erase from the table. 4588 BasicBlockFwdRefs.erase(BBFRI); 4589 } 4590 4591 CurBB = FunctionBBs[0]; 4592 continue; 4593 } 4594 4595 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN 4596 // This record indicates that the last instruction is at the same 4597 // location as the previous instruction with a location. 4598 I = getLastInstruction(); 4599 4600 if (!I) 4601 return error("Invalid record"); 4602 I->setDebugLoc(LastLoc); 4603 I = nullptr; 4604 continue; 4605 4606 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia] 4607 I = getLastInstruction(); 4608 if (!I || Record.size() < 4) 4609 return error("Invalid record"); 4610 4611 unsigned Line = Record[0], Col = Record[1]; 4612 unsigned ScopeID = Record[2], IAID = Record[3]; 4613 4614 MDNode *Scope = nullptr, *IA = nullptr; 4615 if (ScopeID) { 4616 Scope = MetadataList.getMDNodeFwdRefOrNull(ScopeID - 1); 4617 if (!Scope) 4618 return error("Invalid record"); 4619 } 4620 if (IAID) { 4621 IA = MetadataList.getMDNodeFwdRefOrNull(IAID - 1); 4622 if (!IA) 4623 return error("Invalid record"); 4624 } 4625 LastLoc = DebugLoc::get(Line, Col, Scope, IA); 4626 I->setDebugLoc(LastLoc); 4627 I = nullptr; 4628 continue; 4629 } 4630 4631 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode] 4632 unsigned OpNum = 0; 4633 Value *LHS, *RHS; 4634 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) || 4635 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) || 4636 OpNum+1 > Record.size()) 4637 return error("Invalid record"); 4638 4639 int Opc = getDecodedBinaryOpcode(Record[OpNum++], LHS->getType()); 4640 if (Opc == -1) 4641 return error("Invalid record"); 4642 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS); 4643 InstructionList.push_back(I); 4644 if (OpNum < Record.size()) { 4645 if (Opc == Instruction::Add || 4646 Opc == Instruction::Sub || 4647 Opc == Instruction::Mul || 4648 Opc == Instruction::Shl) { 4649 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP)) 4650 cast<BinaryOperator>(I)->setHasNoSignedWrap(true); 4651 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP)) 4652 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true); 4653 } else if (Opc == Instruction::SDiv || 4654 Opc == Instruction::UDiv || 4655 Opc == Instruction::LShr || 4656 Opc == Instruction::AShr) { 4657 if (Record[OpNum] & (1 << bitc::PEO_EXACT)) 4658 cast<BinaryOperator>(I)->setIsExact(true); 4659 } else if (isa<FPMathOperator>(I)) { 4660 FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]); 4661 if (FMF.any()) 4662 I->setFastMathFlags(FMF); 4663 } 4664 4665 } 4666 break; 4667 } 4668 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc] 4669 unsigned OpNum = 0; 4670 Value *Op; 4671 if (getValueTypePair(Record, OpNum, NextValueNo, Op) || 4672 OpNum+2 != Record.size()) 4673 return error("Invalid record"); 4674 4675 Type *ResTy = getTypeByID(Record[OpNum]); 4676 int Opc = getDecodedCastOpcode(Record[OpNum + 1]); 4677 if (Opc == -1 || !ResTy) 4678 return error("Invalid record"); 4679 Instruction *Temp = nullptr; 4680 if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) { 4681 if (Temp) { 4682 InstructionList.push_back(Temp); 4683 CurBB->getInstList().push_back(Temp); 4684 } 4685 } else { 4686 auto CastOp = (Instruction::CastOps)Opc; 4687 if (!CastInst::castIsValid(CastOp, Op, ResTy)) 4688 return error("Invalid cast"); 4689 I = CastInst::Create(CastOp, Op, ResTy); 4690 } 4691 InstructionList.push_back(I); 4692 break; 4693 } 4694 case bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD: 4695 case bitc::FUNC_CODE_INST_GEP_OLD: 4696 case bitc::FUNC_CODE_INST_GEP: { // GEP: type, [n x operands] 4697 unsigned OpNum = 0; 4698 4699 Type *Ty; 4700 bool InBounds; 4701 4702 if (BitCode == bitc::FUNC_CODE_INST_GEP) { 4703 InBounds = Record[OpNum++]; 4704 Ty = getTypeByID(Record[OpNum++]); 4705 } else { 4706 InBounds = BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD; 4707 Ty = nullptr; 4708 } 4709 4710 Value *BasePtr; 4711 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr)) 4712 return error("Invalid record"); 4713 4714 if (!Ty) 4715 Ty = cast<PointerType>(BasePtr->getType()->getScalarType()) 4716 ->getElementType(); 4717 else if (Ty != 4718 cast<PointerType>(BasePtr->getType()->getScalarType()) 4719 ->getElementType()) 4720 return error( 4721 "Explicit gep type does not match pointee type of pointer operand"); 4722 4723 SmallVector<Value*, 16> GEPIdx; 4724 while (OpNum != Record.size()) { 4725 Value *Op; 4726 if (getValueTypePair(Record, OpNum, NextValueNo, Op)) 4727 return error("Invalid record"); 4728 GEPIdx.push_back(Op); 4729 } 4730 4731 I = GetElementPtrInst::Create(Ty, BasePtr, GEPIdx); 4732 4733 InstructionList.push_back(I); 4734 if (InBounds) 4735 cast<GetElementPtrInst>(I)->setIsInBounds(true); 4736 break; 4737 } 4738 4739 case bitc::FUNC_CODE_INST_EXTRACTVAL: { 4740 // EXTRACTVAL: [opty, opval, n x indices] 4741 unsigned OpNum = 0; 4742 Value *Agg; 4743 if (getValueTypePair(Record, OpNum, NextValueNo, Agg)) 4744 return error("Invalid record"); 4745 4746 unsigned RecSize = Record.size(); 4747 if (OpNum == RecSize) 4748 return error("EXTRACTVAL: Invalid instruction with 0 indices"); 4749 4750 SmallVector<unsigned, 4> EXTRACTVALIdx; 4751 Type *CurTy = Agg->getType(); 4752 for (; OpNum != RecSize; ++OpNum) { 4753 bool IsArray = CurTy->isArrayTy(); 4754 bool IsStruct = CurTy->isStructTy(); 4755 uint64_t Index = Record[OpNum]; 4756 4757 if (!IsStruct && !IsArray) 4758 return error("EXTRACTVAL: Invalid type"); 4759 if ((unsigned)Index != Index) 4760 return error("Invalid value"); 4761 if (IsStruct && Index >= CurTy->subtypes().size()) 4762 return error("EXTRACTVAL: Invalid struct index"); 4763 if (IsArray && Index >= CurTy->getArrayNumElements()) 4764 return error("EXTRACTVAL: Invalid array index"); 4765 EXTRACTVALIdx.push_back((unsigned)Index); 4766 4767 if (IsStruct) 4768 CurTy = CurTy->subtypes()[Index]; 4769 else 4770 CurTy = CurTy->subtypes()[0]; 4771 } 4772 4773 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx); 4774 InstructionList.push_back(I); 4775 break; 4776 } 4777 4778 case bitc::FUNC_CODE_INST_INSERTVAL: { 4779 // INSERTVAL: [opty, opval, opty, opval, n x indices] 4780 unsigned OpNum = 0; 4781 Value *Agg; 4782 if (getValueTypePair(Record, OpNum, NextValueNo, Agg)) 4783 return error("Invalid record"); 4784 Value *Val; 4785 if (getValueTypePair(Record, OpNum, NextValueNo, Val)) 4786 return error("Invalid record"); 4787 4788 unsigned RecSize = Record.size(); 4789 if (OpNum == RecSize) 4790 return error("INSERTVAL: Invalid instruction with 0 indices"); 4791 4792 SmallVector<unsigned, 4> INSERTVALIdx; 4793 Type *CurTy = Agg->getType(); 4794 for (; OpNum != RecSize; ++OpNum) { 4795 bool IsArray = CurTy->isArrayTy(); 4796 bool IsStruct = CurTy->isStructTy(); 4797 uint64_t Index = Record[OpNum]; 4798 4799 if (!IsStruct && !IsArray) 4800 return error("INSERTVAL: Invalid type"); 4801 if ((unsigned)Index != Index) 4802 return error("Invalid value"); 4803 if (IsStruct && Index >= CurTy->subtypes().size()) 4804 return error("INSERTVAL: Invalid struct index"); 4805 if (IsArray && Index >= CurTy->getArrayNumElements()) 4806 return error("INSERTVAL: Invalid array index"); 4807 4808 INSERTVALIdx.push_back((unsigned)Index); 4809 if (IsStruct) 4810 CurTy = CurTy->subtypes()[Index]; 4811 else 4812 CurTy = CurTy->subtypes()[0]; 4813 } 4814 4815 if (CurTy != Val->getType()) 4816 return error("Inserted value type doesn't match aggregate type"); 4817 4818 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx); 4819 InstructionList.push_back(I); 4820 break; 4821 } 4822 4823 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval] 4824 // obsolete form of select 4825 // handles select i1 ... in old bitcode 4826 unsigned OpNum = 0; 4827 Value *TrueVal, *FalseVal, *Cond; 4828 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) || 4829 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) || 4830 popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond)) 4831 return error("Invalid record"); 4832 4833 I = SelectInst::Create(Cond, TrueVal, FalseVal); 4834 InstructionList.push_back(I); 4835 break; 4836 } 4837 4838 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred] 4839 // new form of select 4840 // handles select i1 or select [N x i1] 4841 unsigned OpNum = 0; 4842 Value *TrueVal, *FalseVal, *Cond; 4843 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) || 4844 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) || 4845 getValueTypePair(Record, OpNum, NextValueNo, Cond)) 4846 return error("Invalid record"); 4847 4848 // select condition can be either i1 or [N x i1] 4849 if (VectorType* vector_type = 4850 dyn_cast<VectorType>(Cond->getType())) { 4851 // expect <n x i1> 4852 if (vector_type->getElementType() != Type::getInt1Ty(Context)) 4853 return error("Invalid type for value"); 4854 } else { 4855 // expect i1 4856 if (Cond->getType() != Type::getInt1Ty(Context)) 4857 return error("Invalid type for value"); 4858 } 4859 4860 I = SelectInst::Create(Cond, TrueVal, FalseVal); 4861 InstructionList.push_back(I); 4862 break; 4863 } 4864 4865 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval] 4866 unsigned OpNum = 0; 4867 Value *Vec, *Idx; 4868 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) || 4869 getValueTypePair(Record, OpNum, NextValueNo, Idx)) 4870 return error("Invalid record"); 4871 if (!Vec->getType()->isVectorTy()) 4872 return error("Invalid type for value"); 4873 I = ExtractElementInst::Create(Vec, Idx); 4874 InstructionList.push_back(I); 4875 break; 4876 } 4877 4878 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval] 4879 unsigned OpNum = 0; 4880 Value *Vec, *Elt, *Idx; 4881 if (getValueTypePair(Record, OpNum, NextValueNo, Vec)) 4882 return error("Invalid record"); 4883 if (!Vec->getType()->isVectorTy()) 4884 return error("Invalid type for value"); 4885 if (popValue(Record, OpNum, NextValueNo, 4886 cast<VectorType>(Vec->getType())->getElementType(), Elt) || 4887 getValueTypePair(Record, OpNum, NextValueNo, Idx)) 4888 return error("Invalid record"); 4889 I = InsertElementInst::Create(Vec, Elt, Idx); 4890 InstructionList.push_back(I); 4891 break; 4892 } 4893 4894 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval] 4895 unsigned OpNum = 0; 4896 Value *Vec1, *Vec2, *Mask; 4897 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) || 4898 popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2)) 4899 return error("Invalid record"); 4900 4901 if (getValueTypePair(Record, OpNum, NextValueNo, Mask)) 4902 return error("Invalid record"); 4903 if (!Vec1->getType()->isVectorTy() || !Vec2->getType()->isVectorTy()) 4904 return error("Invalid type for value"); 4905 I = new ShuffleVectorInst(Vec1, Vec2, Mask); 4906 InstructionList.push_back(I); 4907 break; 4908 } 4909 4910 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred] 4911 // Old form of ICmp/FCmp returning bool 4912 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were 4913 // both legal on vectors but had different behaviour. 4914 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred] 4915 // FCmp/ICmp returning bool or vector of bool 4916 4917 unsigned OpNum = 0; 4918 Value *LHS, *RHS; 4919 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) || 4920 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS)) 4921 return error("Invalid record"); 4922 4923 unsigned PredVal = Record[OpNum]; 4924 bool IsFP = LHS->getType()->isFPOrFPVectorTy(); 4925 FastMathFlags FMF; 4926 if (IsFP && Record.size() > OpNum+1) 4927 FMF = getDecodedFastMathFlags(Record[++OpNum]); 4928 4929 if (OpNum+1 != Record.size()) 4930 return error("Invalid record"); 4931 4932 if (LHS->getType()->isFPOrFPVectorTy()) 4933 I = new FCmpInst((FCmpInst::Predicate)PredVal, LHS, RHS); 4934 else 4935 I = new ICmpInst((ICmpInst::Predicate)PredVal, LHS, RHS); 4936 4937 if (FMF.any()) 4938 I->setFastMathFlags(FMF); 4939 InstructionList.push_back(I); 4940 break; 4941 } 4942 4943 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>] 4944 { 4945 unsigned Size = Record.size(); 4946 if (Size == 0) { 4947 I = ReturnInst::Create(Context); 4948 InstructionList.push_back(I); 4949 break; 4950 } 4951 4952 unsigned OpNum = 0; 4953 Value *Op = nullptr; 4954 if (getValueTypePair(Record, OpNum, NextValueNo, Op)) 4955 return error("Invalid record"); 4956 if (OpNum != Record.size()) 4957 return error("Invalid record"); 4958 4959 I = ReturnInst::Create(Context, Op); 4960 InstructionList.push_back(I); 4961 break; 4962 } 4963 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#] 4964 if (Record.size() != 1 && Record.size() != 3) 4965 return error("Invalid record"); 4966 BasicBlock *TrueDest = getBasicBlock(Record[0]); 4967 if (!TrueDest) 4968 return error("Invalid record"); 4969 4970 if (Record.size() == 1) { 4971 I = BranchInst::Create(TrueDest); 4972 InstructionList.push_back(I); 4973 } 4974 else { 4975 BasicBlock *FalseDest = getBasicBlock(Record[1]); 4976 Value *Cond = getValue(Record, 2, NextValueNo, 4977 Type::getInt1Ty(Context)); 4978 if (!FalseDest || !Cond) 4979 return error("Invalid record"); 4980 I = BranchInst::Create(TrueDest, FalseDest, Cond); 4981 InstructionList.push_back(I); 4982 } 4983 break; 4984 } 4985 case bitc::FUNC_CODE_INST_CLEANUPRET: { // CLEANUPRET: [val] or [val,bb#] 4986 if (Record.size() != 1 && Record.size() != 2) 4987 return error("Invalid record"); 4988 unsigned Idx = 0; 4989 Value *CleanupPad = 4990 getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context)); 4991 if (!CleanupPad) 4992 return error("Invalid record"); 4993 BasicBlock *UnwindDest = nullptr; 4994 if (Record.size() == 2) { 4995 UnwindDest = getBasicBlock(Record[Idx++]); 4996 if (!UnwindDest) 4997 return error("Invalid record"); 4998 } 4999 5000 I = CleanupReturnInst::Create(CleanupPad, UnwindDest); 5001 InstructionList.push_back(I); 5002 break; 5003 } 5004 case bitc::FUNC_CODE_INST_CATCHRET: { // CATCHRET: [val,bb#] 5005 if (Record.size() != 2) 5006 return error("Invalid record"); 5007 unsigned Idx = 0; 5008 Value *CatchPad = 5009 getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context)); 5010 if (!CatchPad) 5011 return error("Invalid record"); 5012 BasicBlock *BB = getBasicBlock(Record[Idx++]); 5013 if (!BB) 5014 return error("Invalid record"); 5015 5016 I = CatchReturnInst::Create(CatchPad, BB); 5017 InstructionList.push_back(I); 5018 break; 5019 } 5020 case bitc::FUNC_CODE_INST_CATCHSWITCH: { // CATCHSWITCH: [tok,num,(bb)*,bb?] 5021 // We must have, at minimum, the outer scope and the number of arguments. 5022 if (Record.size() < 2) 5023 return error("Invalid record"); 5024 5025 unsigned Idx = 0; 5026 5027 Value *ParentPad = 5028 getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context)); 5029 5030 unsigned NumHandlers = Record[Idx++]; 5031 5032 SmallVector<BasicBlock *, 2> Handlers; 5033 for (unsigned Op = 0; Op != NumHandlers; ++Op) { 5034 BasicBlock *BB = getBasicBlock(Record[Idx++]); 5035 if (!BB) 5036 return error("Invalid record"); 5037 Handlers.push_back(BB); 5038 } 5039 5040 BasicBlock *UnwindDest = nullptr; 5041 if (Idx + 1 == Record.size()) { 5042 UnwindDest = getBasicBlock(Record[Idx++]); 5043 if (!UnwindDest) 5044 return error("Invalid record"); 5045 } 5046 5047 if (Record.size() != Idx) 5048 return error("Invalid record"); 5049 5050 auto *CatchSwitch = 5051 CatchSwitchInst::Create(ParentPad, UnwindDest, NumHandlers); 5052 for (BasicBlock *Handler : Handlers) 5053 CatchSwitch->addHandler(Handler); 5054 I = CatchSwitch; 5055 InstructionList.push_back(I); 5056 break; 5057 } 5058 case bitc::FUNC_CODE_INST_CATCHPAD: 5059 case bitc::FUNC_CODE_INST_CLEANUPPAD: { // [tok,num,(ty,val)*] 5060 // We must have, at minimum, the outer scope and the number of arguments. 5061 if (Record.size() < 2) 5062 return error("Invalid record"); 5063 5064 unsigned Idx = 0; 5065 5066 Value *ParentPad = 5067 getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context)); 5068 5069 unsigned NumArgOperands = Record[Idx++]; 5070 5071 SmallVector<Value *, 2> Args; 5072 for (unsigned Op = 0; Op != NumArgOperands; ++Op) { 5073 Value *Val; 5074 if (getValueTypePair(Record, Idx, NextValueNo, Val)) 5075 return error("Invalid record"); 5076 Args.push_back(Val); 5077 } 5078 5079 if (Record.size() != Idx) 5080 return error("Invalid record"); 5081 5082 if (BitCode == bitc::FUNC_CODE_INST_CLEANUPPAD) 5083 I = CleanupPadInst::Create(ParentPad, Args); 5084 else 5085 I = CatchPadInst::Create(ParentPad, Args); 5086 InstructionList.push_back(I); 5087 break; 5088 } 5089 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...] 5090 // Check magic 5091 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) { 5092 // "New" SwitchInst format with case ranges. The changes to write this 5093 // format were reverted but we still recognize bitcode that uses it. 5094 // Hopefully someday we will have support for case ranges and can use 5095 // this format again. 5096 5097 Type *OpTy = getTypeByID(Record[1]); 5098 unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth(); 5099 5100 Value *Cond = getValue(Record, 2, NextValueNo, OpTy); 5101 BasicBlock *Default = getBasicBlock(Record[3]); 5102 if (!OpTy || !Cond || !Default) 5103 return error("Invalid record"); 5104 5105 unsigned NumCases = Record[4]; 5106 5107 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases); 5108 InstructionList.push_back(SI); 5109 5110 unsigned CurIdx = 5; 5111 for (unsigned i = 0; i != NumCases; ++i) { 5112 SmallVector<ConstantInt*, 1> CaseVals; 5113 unsigned NumItems = Record[CurIdx++]; 5114 for (unsigned ci = 0; ci != NumItems; ++ci) { 5115 bool isSingleNumber = Record[CurIdx++]; 5116 5117 APInt Low; 5118 unsigned ActiveWords = 1; 5119 if (ValueBitWidth > 64) 5120 ActiveWords = Record[CurIdx++]; 5121 Low = readWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords), 5122 ValueBitWidth); 5123 CurIdx += ActiveWords; 5124 5125 if (!isSingleNumber) { 5126 ActiveWords = 1; 5127 if (ValueBitWidth > 64) 5128 ActiveWords = Record[CurIdx++]; 5129 APInt High = readWideAPInt( 5130 makeArrayRef(&Record[CurIdx], ActiveWords), ValueBitWidth); 5131 CurIdx += ActiveWords; 5132 5133 // FIXME: It is not clear whether values in the range should be 5134 // compared as signed or unsigned values. The partially 5135 // implemented changes that used this format in the past used 5136 // unsigned comparisons. 5137 for ( ; Low.ule(High); ++Low) 5138 CaseVals.push_back(ConstantInt::get(Context, Low)); 5139 } else 5140 CaseVals.push_back(ConstantInt::get(Context, Low)); 5141 } 5142 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]); 5143 for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(), 5144 cve = CaseVals.end(); cvi != cve; ++cvi) 5145 SI->addCase(*cvi, DestBB); 5146 } 5147 I = SI; 5148 break; 5149 } 5150 5151 // Old SwitchInst format without case ranges. 5152 5153 if (Record.size() < 3 || (Record.size() & 1) == 0) 5154 return error("Invalid record"); 5155 Type *OpTy = getTypeByID(Record[0]); 5156 Value *Cond = getValue(Record, 1, NextValueNo, OpTy); 5157 BasicBlock *Default = getBasicBlock(Record[2]); 5158 if (!OpTy || !Cond || !Default) 5159 return error("Invalid record"); 5160 unsigned NumCases = (Record.size()-3)/2; 5161 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases); 5162 InstructionList.push_back(SI); 5163 for (unsigned i = 0, e = NumCases; i != e; ++i) { 5164 ConstantInt *CaseVal = 5165 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy)); 5166 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]); 5167 if (!CaseVal || !DestBB) { 5168 delete SI; 5169 return error("Invalid record"); 5170 } 5171 SI->addCase(CaseVal, DestBB); 5172 } 5173 I = SI; 5174 break; 5175 } 5176 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...] 5177 if (Record.size() < 2) 5178 return error("Invalid record"); 5179 Type *OpTy = getTypeByID(Record[0]); 5180 Value *Address = getValue(Record, 1, NextValueNo, OpTy); 5181 if (!OpTy || !Address) 5182 return error("Invalid record"); 5183 unsigned NumDests = Record.size()-2; 5184 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests); 5185 InstructionList.push_back(IBI); 5186 for (unsigned i = 0, e = NumDests; i != e; ++i) { 5187 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) { 5188 IBI->addDestination(DestBB); 5189 } else { 5190 delete IBI; 5191 return error("Invalid record"); 5192 } 5193 } 5194 I = IBI; 5195 break; 5196 } 5197 5198 case bitc::FUNC_CODE_INST_INVOKE: { 5199 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...] 5200 if (Record.size() < 4) 5201 return error("Invalid record"); 5202 unsigned OpNum = 0; 5203 AttributeSet PAL = getAttributes(Record[OpNum++]); 5204 unsigned CCInfo = Record[OpNum++]; 5205 BasicBlock *NormalBB = getBasicBlock(Record[OpNum++]); 5206 BasicBlock *UnwindBB = getBasicBlock(Record[OpNum++]); 5207 5208 FunctionType *FTy = nullptr; 5209 if (CCInfo >> 13 & 1 && 5210 !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++])))) 5211 return error("Explicit invoke type is not a function type"); 5212 5213 Value *Callee; 5214 if (getValueTypePair(Record, OpNum, NextValueNo, Callee)) 5215 return error("Invalid record"); 5216 5217 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType()); 5218 if (!CalleeTy) 5219 return error("Callee is not a pointer"); 5220 if (!FTy) { 5221 FTy = dyn_cast<FunctionType>(CalleeTy->getElementType()); 5222 if (!FTy) 5223 return error("Callee is not of pointer to function type"); 5224 } else if (CalleeTy->getElementType() != FTy) 5225 return error("Explicit invoke type does not match pointee type of " 5226 "callee operand"); 5227 if (Record.size() < FTy->getNumParams() + OpNum) 5228 return error("Insufficient operands to call"); 5229 5230 SmallVector<Value*, 16> Ops; 5231 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) { 5232 Ops.push_back(getValue(Record, OpNum, NextValueNo, 5233 FTy->getParamType(i))); 5234 if (!Ops.back()) 5235 return error("Invalid record"); 5236 } 5237 5238 if (!FTy->isVarArg()) { 5239 if (Record.size() != OpNum) 5240 return error("Invalid record"); 5241 } else { 5242 // Read type/value pairs for varargs params. 5243 while (OpNum != Record.size()) { 5244 Value *Op; 5245 if (getValueTypePair(Record, OpNum, NextValueNo, Op)) 5246 return error("Invalid record"); 5247 Ops.push_back(Op); 5248 } 5249 } 5250 5251 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops, OperandBundles); 5252 OperandBundles.clear(); 5253 InstructionList.push_back(I); 5254 cast<InvokeInst>(I)->setCallingConv( 5255 static_cast<CallingConv::ID>(CallingConv::MaxID & CCInfo)); 5256 cast<InvokeInst>(I)->setAttributes(PAL); 5257 break; 5258 } 5259 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval] 5260 unsigned Idx = 0; 5261 Value *Val = nullptr; 5262 if (getValueTypePair(Record, Idx, NextValueNo, Val)) 5263 return error("Invalid record"); 5264 I = ResumeInst::Create(Val); 5265 InstructionList.push_back(I); 5266 break; 5267 } 5268 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE 5269 I = new UnreachableInst(Context); 5270 InstructionList.push_back(I); 5271 break; 5272 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...] 5273 if (Record.size() < 1 || ((Record.size()-1)&1)) 5274 return error("Invalid record"); 5275 Type *Ty = getTypeByID(Record[0]); 5276 if (!Ty) 5277 return error("Invalid record"); 5278 5279 PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2); 5280 InstructionList.push_back(PN); 5281 5282 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) { 5283 Value *V; 5284 // With the new function encoding, it is possible that operands have 5285 // negative IDs (for forward references). Use a signed VBR 5286 // representation to keep the encoding small. 5287 if (UseRelativeIDs) 5288 V = getValueSigned(Record, 1+i, NextValueNo, Ty); 5289 else 5290 V = getValue(Record, 1+i, NextValueNo, Ty); 5291 BasicBlock *BB = getBasicBlock(Record[2+i]); 5292 if (!V || !BB) 5293 return error("Invalid record"); 5294 PN->addIncoming(V, BB); 5295 } 5296 I = PN; 5297 break; 5298 } 5299 5300 case bitc::FUNC_CODE_INST_LANDINGPAD: 5301 case bitc::FUNC_CODE_INST_LANDINGPAD_OLD: { 5302 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?] 5303 unsigned Idx = 0; 5304 if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD) { 5305 if (Record.size() < 3) 5306 return error("Invalid record"); 5307 } else { 5308 assert(BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD); 5309 if (Record.size() < 4) 5310 return error("Invalid record"); 5311 } 5312 Type *Ty = getTypeByID(Record[Idx++]); 5313 if (!Ty) 5314 return error("Invalid record"); 5315 if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD) { 5316 Value *PersFn = nullptr; 5317 if (getValueTypePair(Record, Idx, NextValueNo, PersFn)) 5318 return error("Invalid record"); 5319 5320 if (!F->hasPersonalityFn()) 5321 F->setPersonalityFn(cast<Constant>(PersFn)); 5322 else if (F->getPersonalityFn() != cast<Constant>(PersFn)) 5323 return error("Personality function mismatch"); 5324 } 5325 5326 bool IsCleanup = !!Record[Idx++]; 5327 unsigned NumClauses = Record[Idx++]; 5328 LandingPadInst *LP = LandingPadInst::Create(Ty, NumClauses); 5329 LP->setCleanup(IsCleanup); 5330 for (unsigned J = 0; J != NumClauses; ++J) { 5331 LandingPadInst::ClauseType CT = 5332 LandingPadInst::ClauseType(Record[Idx++]); (void)CT; 5333 Value *Val; 5334 5335 if (getValueTypePair(Record, Idx, NextValueNo, Val)) { 5336 delete LP; 5337 return error("Invalid record"); 5338 } 5339 5340 assert((CT != LandingPadInst::Catch || 5341 !isa<ArrayType>(Val->getType())) && 5342 "Catch clause has a invalid type!"); 5343 assert((CT != LandingPadInst::Filter || 5344 isa<ArrayType>(Val->getType())) && 5345 "Filter clause has invalid type!"); 5346 LP->addClause(cast<Constant>(Val)); 5347 } 5348 5349 I = LP; 5350 InstructionList.push_back(I); 5351 break; 5352 } 5353 5354 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align] 5355 if (Record.size() != 4) 5356 return error("Invalid record"); 5357 uint64_t AlignRecord = Record[3]; 5358 const uint64_t InAllocaMask = uint64_t(1) << 5; 5359 const uint64_t ExplicitTypeMask = uint64_t(1) << 6; 5360 const uint64_t SwiftErrorMask = uint64_t(1) << 7; 5361 const uint64_t FlagMask = InAllocaMask | ExplicitTypeMask | 5362 SwiftErrorMask; 5363 bool InAlloca = AlignRecord & InAllocaMask; 5364 bool SwiftError = AlignRecord & SwiftErrorMask; 5365 Type *Ty = getTypeByID(Record[0]); 5366 if ((AlignRecord & ExplicitTypeMask) == 0) { 5367 auto *PTy = dyn_cast_or_null<PointerType>(Ty); 5368 if (!PTy) 5369 return error("Old-style alloca with a non-pointer type"); 5370 Ty = PTy->getElementType(); 5371 } 5372 Type *OpTy = getTypeByID(Record[1]); 5373 Value *Size = getFnValueByID(Record[2], OpTy); 5374 unsigned Align; 5375 if (Error Err = parseAlignmentValue(AlignRecord & ~FlagMask, Align)) { 5376 return Err; 5377 } 5378 if (!Ty || !Size) 5379 return error("Invalid record"); 5380 AllocaInst *AI = new AllocaInst(Ty, Size, Align); 5381 AI->setUsedWithInAlloca(InAlloca); 5382 AI->setSwiftError(SwiftError); 5383 I = AI; 5384 InstructionList.push_back(I); 5385 break; 5386 } 5387 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol] 5388 unsigned OpNum = 0; 5389 Value *Op; 5390 if (getValueTypePair(Record, OpNum, NextValueNo, Op) || 5391 (OpNum + 2 != Record.size() && OpNum + 3 != Record.size())) 5392 return error("Invalid record"); 5393 5394 Type *Ty = nullptr; 5395 if (OpNum + 3 == Record.size()) 5396 Ty = getTypeByID(Record[OpNum++]); 5397 if (Error Err = typeCheckLoadStoreInst(Ty, Op->getType())) 5398 return Err; 5399 if (!Ty) 5400 Ty = cast<PointerType>(Op->getType())->getElementType(); 5401 5402 unsigned Align; 5403 if (Error Err = parseAlignmentValue(Record[OpNum], Align)) 5404 return Err; 5405 I = new LoadInst(Ty, Op, "", Record[OpNum + 1], Align); 5406 5407 InstructionList.push_back(I); 5408 break; 5409 } 5410 case bitc::FUNC_CODE_INST_LOADATOMIC: { 5411 // LOADATOMIC: [opty, op, align, vol, ordering, synchscope] 5412 unsigned OpNum = 0; 5413 Value *Op; 5414 if (getValueTypePair(Record, OpNum, NextValueNo, Op) || 5415 (OpNum + 4 != Record.size() && OpNum + 5 != Record.size())) 5416 return error("Invalid record"); 5417 5418 Type *Ty = nullptr; 5419 if (OpNum + 5 == Record.size()) 5420 Ty = getTypeByID(Record[OpNum++]); 5421 if (Error Err = typeCheckLoadStoreInst(Ty, Op->getType())) 5422 return Err; 5423 if (!Ty) 5424 Ty = cast<PointerType>(Op->getType())->getElementType(); 5425 5426 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]); 5427 if (Ordering == AtomicOrdering::NotAtomic || 5428 Ordering == AtomicOrdering::Release || 5429 Ordering == AtomicOrdering::AcquireRelease) 5430 return error("Invalid record"); 5431 if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0) 5432 return error("Invalid record"); 5433 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]); 5434 5435 unsigned Align; 5436 if (Error Err = parseAlignmentValue(Record[OpNum], Align)) 5437 return Err; 5438 I = new LoadInst(Op, "", Record[OpNum+1], Align, Ordering, SynchScope); 5439 5440 InstructionList.push_back(I); 5441 break; 5442 } 5443 case bitc::FUNC_CODE_INST_STORE: 5444 case bitc::FUNC_CODE_INST_STORE_OLD: { // STORE2:[ptrty, ptr, val, align, vol] 5445 unsigned OpNum = 0; 5446 Value *Val, *Ptr; 5447 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) || 5448 (BitCode == bitc::FUNC_CODE_INST_STORE 5449 ? getValueTypePair(Record, OpNum, NextValueNo, Val) 5450 : popValue(Record, OpNum, NextValueNo, 5451 cast<PointerType>(Ptr->getType())->getElementType(), 5452 Val)) || 5453 OpNum + 2 != Record.size()) 5454 return error("Invalid record"); 5455 5456 if (Error Err = typeCheckLoadStoreInst(Val->getType(), Ptr->getType())) 5457 return Err; 5458 unsigned Align; 5459 if (Error Err = parseAlignmentValue(Record[OpNum], Align)) 5460 return Err; 5461 I = new StoreInst(Val, Ptr, Record[OpNum+1], Align); 5462 InstructionList.push_back(I); 5463 break; 5464 } 5465 case bitc::FUNC_CODE_INST_STOREATOMIC: 5466 case bitc::FUNC_CODE_INST_STOREATOMIC_OLD: { 5467 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope] 5468 unsigned OpNum = 0; 5469 Value *Val, *Ptr; 5470 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) || 5471 !isa<PointerType>(Ptr->getType()) || 5472 (BitCode == bitc::FUNC_CODE_INST_STOREATOMIC 5473 ? getValueTypePair(Record, OpNum, NextValueNo, Val) 5474 : popValue(Record, OpNum, NextValueNo, 5475 cast<PointerType>(Ptr->getType())->getElementType(), 5476 Val)) || 5477 OpNum + 4 != Record.size()) 5478 return error("Invalid record"); 5479 5480 if (Error Err = typeCheckLoadStoreInst(Val->getType(), Ptr->getType())) 5481 return Err; 5482 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]); 5483 if (Ordering == AtomicOrdering::NotAtomic || 5484 Ordering == AtomicOrdering::Acquire || 5485 Ordering == AtomicOrdering::AcquireRelease) 5486 return error("Invalid record"); 5487 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]); 5488 if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0) 5489 return error("Invalid record"); 5490 5491 unsigned Align; 5492 if (Error Err = parseAlignmentValue(Record[OpNum], Align)) 5493 return Err; 5494 I = new StoreInst(Val, Ptr, Record[OpNum+1], Align, Ordering, SynchScope); 5495 InstructionList.push_back(I); 5496 break; 5497 } 5498 case bitc::FUNC_CODE_INST_CMPXCHG_OLD: 5499 case bitc::FUNC_CODE_INST_CMPXCHG: { 5500 // CMPXCHG:[ptrty, ptr, cmp, new, vol, successordering, synchscope, 5501 // failureordering?, isweak?] 5502 unsigned OpNum = 0; 5503 Value *Ptr, *Cmp, *New; 5504 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) || 5505 (BitCode == bitc::FUNC_CODE_INST_CMPXCHG 5506 ? getValueTypePair(Record, OpNum, NextValueNo, Cmp) 5507 : popValue(Record, OpNum, NextValueNo, 5508 cast<PointerType>(Ptr->getType())->getElementType(), 5509 Cmp)) || 5510 popValue(Record, OpNum, NextValueNo, Cmp->getType(), New) || 5511 Record.size() < OpNum + 3 || Record.size() > OpNum + 5) 5512 return error("Invalid record"); 5513 AtomicOrdering SuccessOrdering = getDecodedOrdering(Record[OpNum + 1]); 5514 if (SuccessOrdering == AtomicOrdering::NotAtomic || 5515 SuccessOrdering == AtomicOrdering::Unordered) 5516 return error("Invalid record"); 5517 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 2]); 5518 5519 if (Error Err = typeCheckLoadStoreInst(Cmp->getType(), Ptr->getType())) 5520 return Err; 5521 AtomicOrdering FailureOrdering; 5522 if (Record.size() < 7) 5523 FailureOrdering = 5524 AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering); 5525 else 5526 FailureOrdering = getDecodedOrdering(Record[OpNum + 3]); 5527 5528 I = new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering, FailureOrdering, 5529 SynchScope); 5530 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]); 5531 5532 if (Record.size() < 8) { 5533 // Before weak cmpxchgs existed, the instruction simply returned the 5534 // value loaded from memory, so bitcode files from that era will be 5535 // expecting the first component of a modern cmpxchg. 5536 CurBB->getInstList().push_back(I); 5537 I = ExtractValueInst::Create(I, 0); 5538 } else { 5539 cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum+4]); 5540 } 5541 5542 InstructionList.push_back(I); 5543 break; 5544 } 5545 case bitc::FUNC_CODE_INST_ATOMICRMW: { 5546 // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope] 5547 unsigned OpNum = 0; 5548 Value *Ptr, *Val; 5549 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) || 5550 !isa<PointerType>(Ptr->getType()) || 5551 popValue(Record, OpNum, NextValueNo, 5552 cast<PointerType>(Ptr->getType())->getElementType(), Val) || 5553 OpNum+4 != Record.size()) 5554 return error("Invalid record"); 5555 AtomicRMWInst::BinOp Operation = getDecodedRMWOperation(Record[OpNum]); 5556 if (Operation < AtomicRMWInst::FIRST_BINOP || 5557 Operation > AtomicRMWInst::LAST_BINOP) 5558 return error("Invalid record"); 5559 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]); 5560 if (Ordering == AtomicOrdering::NotAtomic || 5561 Ordering == AtomicOrdering::Unordered) 5562 return error("Invalid record"); 5563 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]); 5564 I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope); 5565 cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]); 5566 InstructionList.push_back(I); 5567 break; 5568 } 5569 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope] 5570 if (2 != Record.size()) 5571 return error("Invalid record"); 5572 AtomicOrdering Ordering = getDecodedOrdering(Record[0]); 5573 if (Ordering == AtomicOrdering::NotAtomic || 5574 Ordering == AtomicOrdering::Unordered || 5575 Ordering == AtomicOrdering::Monotonic) 5576 return error("Invalid record"); 5577 SynchronizationScope SynchScope = getDecodedSynchScope(Record[1]); 5578 I = new FenceInst(Context, Ordering, SynchScope); 5579 InstructionList.push_back(I); 5580 break; 5581 } 5582 case bitc::FUNC_CODE_INST_CALL: { 5583 // CALL: [paramattrs, cc, fmf, fnty, fnid, arg0, arg1...] 5584 if (Record.size() < 3) 5585 return error("Invalid record"); 5586 5587 unsigned OpNum = 0; 5588 AttributeSet PAL = getAttributes(Record[OpNum++]); 5589 unsigned CCInfo = Record[OpNum++]; 5590 5591 FastMathFlags FMF; 5592 if ((CCInfo >> bitc::CALL_FMF) & 1) { 5593 FMF = getDecodedFastMathFlags(Record[OpNum++]); 5594 if (!FMF.any()) 5595 return error("Fast math flags indicator set for call with no FMF"); 5596 } 5597 5598 FunctionType *FTy = nullptr; 5599 if (CCInfo >> bitc::CALL_EXPLICIT_TYPE & 1 && 5600 !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++])))) 5601 return error("Explicit call type is not a function type"); 5602 5603 Value *Callee; 5604 if (getValueTypePair(Record, OpNum, NextValueNo, Callee)) 5605 return error("Invalid record"); 5606 5607 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType()); 5608 if (!OpTy) 5609 return error("Callee is not a pointer type"); 5610 if (!FTy) { 5611 FTy = dyn_cast<FunctionType>(OpTy->getElementType()); 5612 if (!FTy) 5613 return error("Callee is not of pointer to function type"); 5614 } else if (OpTy->getElementType() != FTy) 5615 return error("Explicit call type does not match pointee type of " 5616 "callee operand"); 5617 if (Record.size() < FTy->getNumParams() + OpNum) 5618 return error("Insufficient operands to call"); 5619 5620 SmallVector<Value*, 16> Args; 5621 // Read the fixed params. 5622 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) { 5623 if (FTy->getParamType(i)->isLabelTy()) 5624 Args.push_back(getBasicBlock(Record[OpNum])); 5625 else 5626 Args.push_back(getValue(Record, OpNum, NextValueNo, 5627 FTy->getParamType(i))); 5628 if (!Args.back()) 5629 return error("Invalid record"); 5630 } 5631 5632 // Read type/value pairs for varargs params. 5633 if (!FTy->isVarArg()) { 5634 if (OpNum != Record.size()) 5635 return error("Invalid record"); 5636 } else { 5637 while (OpNum != Record.size()) { 5638 Value *Op; 5639 if (getValueTypePair(Record, OpNum, NextValueNo, Op)) 5640 return error("Invalid record"); 5641 Args.push_back(Op); 5642 } 5643 } 5644 5645 I = CallInst::Create(FTy, Callee, Args, OperandBundles); 5646 OperandBundles.clear(); 5647 InstructionList.push_back(I); 5648 cast<CallInst>(I)->setCallingConv( 5649 static_cast<CallingConv::ID>((0x7ff & CCInfo) >> bitc::CALL_CCONV)); 5650 CallInst::TailCallKind TCK = CallInst::TCK_None; 5651 if (CCInfo & 1 << bitc::CALL_TAIL) 5652 TCK = CallInst::TCK_Tail; 5653 if (CCInfo & (1 << bitc::CALL_MUSTTAIL)) 5654 TCK = CallInst::TCK_MustTail; 5655 if (CCInfo & (1 << bitc::CALL_NOTAIL)) 5656 TCK = CallInst::TCK_NoTail; 5657 cast<CallInst>(I)->setTailCallKind(TCK); 5658 cast<CallInst>(I)->setAttributes(PAL); 5659 if (FMF.any()) { 5660 if (!isa<FPMathOperator>(I)) 5661 return error("Fast-math-flags specified for call without " 5662 "floating-point scalar or vector return type"); 5663 I->setFastMathFlags(FMF); 5664 } 5665 break; 5666 } 5667 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty] 5668 if (Record.size() < 3) 5669 return error("Invalid record"); 5670 Type *OpTy = getTypeByID(Record[0]); 5671 Value *Op = getValue(Record, 1, NextValueNo, OpTy); 5672 Type *ResTy = getTypeByID(Record[2]); 5673 if (!OpTy || !Op || !ResTy) 5674 return error("Invalid record"); 5675 I = new VAArgInst(Op, ResTy); 5676 InstructionList.push_back(I); 5677 break; 5678 } 5679 5680 case bitc::FUNC_CODE_OPERAND_BUNDLE: { 5681 // A call or an invoke can be optionally prefixed with some variable 5682 // number of operand bundle blocks. These blocks are read into 5683 // OperandBundles and consumed at the next call or invoke instruction. 5684 5685 if (Record.size() < 1 || Record[0] >= BundleTags.size()) 5686 return error("Invalid record"); 5687 5688 std::vector<Value *> Inputs; 5689 5690 unsigned OpNum = 1; 5691 while (OpNum != Record.size()) { 5692 Value *Op; 5693 if (getValueTypePair(Record, OpNum, NextValueNo, Op)) 5694 return error("Invalid record"); 5695 Inputs.push_back(Op); 5696 } 5697 5698 OperandBundles.emplace_back(BundleTags[Record[0]], std::move(Inputs)); 5699 continue; 5700 } 5701 } 5702 5703 // Add instruction to end of current BB. If there is no current BB, reject 5704 // this file. 5705 if (!CurBB) { 5706 delete I; 5707 return error("Invalid instruction with no BB"); 5708 } 5709 if (!OperandBundles.empty()) { 5710 delete I; 5711 return error("Operand bundles found with no consumer"); 5712 } 5713 CurBB->getInstList().push_back(I); 5714 5715 // If this was a terminator instruction, move to the next block. 5716 if (isa<TerminatorInst>(I)) { 5717 ++CurBBNo; 5718 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr; 5719 } 5720 5721 // Non-void values get registered in the value table for future use. 5722 if (I && !I->getType()->isVoidTy()) 5723 ValueList.assignValue(I, NextValueNo++); 5724 } 5725 5726 OutOfRecordLoop: 5727 5728 if (!OperandBundles.empty()) 5729 return error("Operand bundles found with no consumer"); 5730 5731 // Check the function list for unresolved values. 5732 if (Argument *A = dyn_cast<Argument>(ValueList.back())) { 5733 if (!A->getParent()) { 5734 // We found at least one unresolved value. Nuke them all to avoid leaks. 5735 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){ 5736 if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) { 5737 A->replaceAllUsesWith(UndefValue::get(A->getType())); 5738 delete A; 5739 } 5740 } 5741 return error("Never resolved value found in function"); 5742 } 5743 } 5744 5745 // Unexpected unresolved metadata about to be dropped. 5746 if (MetadataList.hasFwdRefs()) 5747 return error("Invalid function metadata: outgoing forward refs"); 5748 5749 // Trim the value list down to the size it was before we parsed this function. 5750 ValueList.shrinkTo(ModuleValueListSize); 5751 MetadataList.shrinkTo(ModuleMetadataListSize); 5752 std::vector<BasicBlock*>().swap(FunctionBBs); 5753 return Error::success(); 5754 } 5755 5756 /// Find the function body in the bitcode stream 5757 Error BitcodeReader::findFunctionInStream( 5758 Function *F, 5759 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) { 5760 while (DeferredFunctionInfoIterator->second == 0) { 5761 // This is the fallback handling for the old format bitcode that 5762 // didn't contain the function index in the VST, or when we have 5763 // an anonymous function which would not have a VST entry. 5764 // Assert that we have one of those two cases. 5765 assert(VSTOffset == 0 || !F->hasName()); 5766 // Parse the next body in the stream and set its position in the 5767 // DeferredFunctionInfo map. 5768 if (Error Err = rememberAndSkipFunctionBodies()) 5769 return Err; 5770 } 5771 return Error::success(); 5772 } 5773 5774 //===----------------------------------------------------------------------===// 5775 // GVMaterializer implementation 5776 //===----------------------------------------------------------------------===// 5777 5778 Error BitcodeReader::materialize(GlobalValue *GV) { 5779 Function *F = dyn_cast<Function>(GV); 5780 // If it's not a function or is already material, ignore the request. 5781 if (!F || !F->isMaterializable()) 5782 return Error::success(); 5783 5784 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F); 5785 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!"); 5786 // If its position is recorded as 0, its body is somewhere in the stream 5787 // but we haven't seen it yet. 5788 if (DFII->second == 0) 5789 if (Error Err = findFunctionInStream(F, DFII)) 5790 return Err; 5791 5792 // Materialize metadata before parsing any function bodies. 5793 if (Error Err = materializeMetadata()) 5794 return Err; 5795 5796 // Move the bit stream to the saved position of the deferred function body. 5797 Stream.JumpToBit(DFII->second); 5798 5799 if (Error Err = parseFunctionBody(F)) 5800 return Err; 5801 F->setIsMaterializable(false); 5802 5803 if (StripDebugInfo) 5804 stripDebugInfo(*F); 5805 5806 // Upgrade any old intrinsic calls in the function. 5807 for (auto &I : UpgradedIntrinsics) { 5808 for (auto UI = I.first->materialized_user_begin(), UE = I.first->user_end(); 5809 UI != UE;) { 5810 User *U = *UI; 5811 ++UI; 5812 if (CallInst *CI = dyn_cast<CallInst>(U)) 5813 UpgradeIntrinsicCall(CI, I.second); 5814 } 5815 } 5816 5817 // Update calls to the remangled intrinsics 5818 for (auto &I : RemangledIntrinsics) 5819 for (auto UI = I.first->materialized_user_begin(), UE = I.first->user_end(); 5820 UI != UE;) 5821 // Don't expect any other users than call sites 5822 CallSite(*UI++).setCalledFunction(I.second); 5823 5824 // Finish fn->subprogram upgrade for materialized functions. 5825 if (DISubprogram *SP = FunctionsWithSPs.lookup(F)) 5826 F->setSubprogram(SP); 5827 5828 // Bring in any functions that this function forward-referenced via 5829 // blockaddresses. 5830 return materializeForwardReferencedFunctions(); 5831 } 5832 5833 Error BitcodeReader::materializeModule() { 5834 if (Error Err = materializeMetadata()) 5835 return Err; 5836 5837 // Promise to materialize all forward references. 5838 WillMaterializeAllForwardRefs = true; 5839 5840 // Iterate over the module, deserializing any functions that are still on 5841 // disk. 5842 for (Function &F : *TheModule) { 5843 if (Error Err = materialize(&F)) 5844 return Err; 5845 } 5846 // At this point, if there are any function bodies, parse the rest of 5847 // the bits in the module past the last function block we have recorded 5848 // through either lazy scanning or the VST. 5849 if (LastFunctionBlockBit || NextUnreadBit) 5850 if (Error Err = parseModule(LastFunctionBlockBit > NextUnreadBit 5851 ? LastFunctionBlockBit 5852 : NextUnreadBit)) 5853 return Err; 5854 5855 // Check that all block address forward references got resolved (as we 5856 // promised above). 5857 if (!BasicBlockFwdRefs.empty()) 5858 return error("Never resolved function from blockaddress"); 5859 5860 // Upgrade any intrinsic calls that slipped through (should not happen!) and 5861 // delete the old functions to clean up. We can't do this unless the entire 5862 // module is materialized because there could always be another function body 5863 // with calls to the old function. 5864 for (auto &I : UpgradedIntrinsics) { 5865 for (auto *U : I.first->users()) { 5866 if (CallInst *CI = dyn_cast<CallInst>(U)) 5867 UpgradeIntrinsicCall(CI, I.second); 5868 } 5869 if (!I.first->use_empty()) 5870 I.first->replaceAllUsesWith(I.second); 5871 I.first->eraseFromParent(); 5872 } 5873 UpgradedIntrinsics.clear(); 5874 // Do the same for remangled intrinsics 5875 for (auto &I : RemangledIntrinsics) { 5876 I.first->replaceAllUsesWith(I.second); 5877 I.first->eraseFromParent(); 5878 } 5879 RemangledIntrinsics.clear(); 5880 5881 UpgradeDebugInfo(*TheModule); 5882 5883 UpgradeModuleFlags(*TheModule); 5884 return Error::success(); 5885 } 5886 5887 std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes() const { 5888 return IdentifiedStructTypes; 5889 } 5890 5891 ModuleSummaryIndexBitcodeReader::ModuleSummaryIndexBitcodeReader( 5892 BitstreamCursor Cursor, bool CheckGlobalValSummaryPresenceOnly) 5893 : BitcodeReaderBase(std::move(Cursor)), 5894 CheckGlobalValSummaryPresenceOnly(CheckGlobalValSummaryPresenceOnly) {} 5895 5896 std::pair<GlobalValue::GUID, GlobalValue::GUID> 5897 ModuleSummaryIndexBitcodeReader::getGUIDFromValueId(unsigned ValueId) { 5898 auto VGI = ValueIdToCallGraphGUIDMap.find(ValueId); 5899 assert(VGI != ValueIdToCallGraphGUIDMap.end()); 5900 return VGI->second; 5901 } 5902 5903 // Specialized value symbol table parser used when reading module index 5904 // blocks where we don't actually create global values. The parsed information 5905 // is saved in the bitcode reader for use when later parsing summaries. 5906 Error ModuleSummaryIndexBitcodeReader::parseValueSymbolTable( 5907 uint64_t Offset, 5908 DenseMap<unsigned, GlobalValue::LinkageTypes> &ValueIdToLinkageMap) { 5909 assert(Offset > 0 && "Expected non-zero VST offset"); 5910 uint64_t CurrentBit = jumpToValueSymbolTable(Offset, Stream); 5911 5912 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID)) 5913 return error("Invalid record"); 5914 5915 SmallVector<uint64_t, 64> Record; 5916 5917 // Read all the records for this value table. 5918 SmallString<128> ValueName; 5919 5920 while (true) { 5921 BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 5922 5923 switch (Entry.Kind) { 5924 case BitstreamEntry::SubBlock: // Handled for us already. 5925 case BitstreamEntry::Error: 5926 return error("Malformed block"); 5927 case BitstreamEntry::EndBlock: 5928 // Done parsing VST, jump back to wherever we came from. 5929 Stream.JumpToBit(CurrentBit); 5930 return Error::success(); 5931 case BitstreamEntry::Record: 5932 // The interesting case. 5933 break; 5934 } 5935 5936 // Read a record. 5937 Record.clear(); 5938 switch (Stream.readRecord(Entry.ID, Record)) { 5939 default: // Default behavior: ignore (e.g. VST_CODE_BBENTRY records). 5940 break; 5941 case bitc::VST_CODE_ENTRY: { // VST_CODE_ENTRY: [valueid, namechar x N] 5942 if (convertToString(Record, 1, ValueName)) 5943 return error("Invalid record"); 5944 unsigned ValueID = Record[0]; 5945 assert(!SourceFileName.empty()); 5946 auto VLI = ValueIdToLinkageMap.find(ValueID); 5947 assert(VLI != ValueIdToLinkageMap.end() && 5948 "No linkage found for VST entry?"); 5949 auto Linkage = VLI->second; 5950 std::string GlobalId = 5951 GlobalValue::getGlobalIdentifier(ValueName, Linkage, SourceFileName); 5952 auto ValueGUID = GlobalValue::getGUID(GlobalId); 5953 auto OriginalNameID = ValueGUID; 5954 if (GlobalValue::isLocalLinkage(Linkage)) 5955 OriginalNameID = GlobalValue::getGUID(ValueName); 5956 if (PrintSummaryGUIDs) 5957 dbgs() << "GUID " << ValueGUID << "(" << OriginalNameID << ") is " 5958 << ValueName << "\n"; 5959 ValueIdToCallGraphGUIDMap[ValueID] = 5960 std::make_pair(ValueGUID, OriginalNameID); 5961 ValueName.clear(); 5962 break; 5963 } 5964 case bitc::VST_CODE_FNENTRY: { 5965 // VST_CODE_FNENTRY: [valueid, offset, namechar x N] 5966 if (convertToString(Record, 2, ValueName)) 5967 return error("Invalid record"); 5968 unsigned ValueID = Record[0]; 5969 assert(!SourceFileName.empty()); 5970 auto VLI = ValueIdToLinkageMap.find(ValueID); 5971 assert(VLI != ValueIdToLinkageMap.end() && 5972 "No linkage found for VST entry?"); 5973 auto Linkage = VLI->second; 5974 std::string FunctionGlobalId = GlobalValue::getGlobalIdentifier( 5975 ValueName, VLI->second, SourceFileName); 5976 auto FunctionGUID = GlobalValue::getGUID(FunctionGlobalId); 5977 auto OriginalNameID = FunctionGUID; 5978 if (GlobalValue::isLocalLinkage(Linkage)) 5979 OriginalNameID = GlobalValue::getGUID(ValueName); 5980 if (PrintSummaryGUIDs) 5981 dbgs() << "GUID " << FunctionGUID << "(" << OriginalNameID << ") is " 5982 << ValueName << "\n"; 5983 ValueIdToCallGraphGUIDMap[ValueID] = 5984 std::make_pair(FunctionGUID, OriginalNameID); 5985 5986 ValueName.clear(); 5987 break; 5988 } 5989 case bitc::VST_CODE_COMBINED_ENTRY: { 5990 // VST_CODE_COMBINED_ENTRY: [valueid, refguid] 5991 unsigned ValueID = Record[0]; 5992 GlobalValue::GUID RefGUID = Record[1]; 5993 // The "original name", which is the second value of the pair will be 5994 // overriden later by a FS_COMBINED_ORIGINAL_NAME in the combined index. 5995 ValueIdToCallGraphGUIDMap[ValueID] = std::make_pair(RefGUID, RefGUID); 5996 break; 5997 } 5998 } 5999 } 6000 } 6001 6002 // Parse just the blocks needed for building the index out of the module. 6003 // At the end of this routine the module Index is populated with a map 6004 // from global value id to GlobalValueSummary objects. 6005 Error ModuleSummaryIndexBitcodeReader::parseModule(StringRef ModulePath) { 6006 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID)) 6007 return error("Invalid record"); 6008 6009 SmallVector<uint64_t, 64> Record; 6010 DenseMap<unsigned, GlobalValue::LinkageTypes> ValueIdToLinkageMap; 6011 unsigned ValueId = 0; 6012 6013 // Read the index for this module. 6014 while (true) { 6015 BitstreamEntry Entry = Stream.advance(); 6016 6017 switch (Entry.Kind) { 6018 case BitstreamEntry::Error: 6019 return error("Malformed block"); 6020 case BitstreamEntry::EndBlock: 6021 return Error::success(); 6022 6023 case BitstreamEntry::SubBlock: 6024 if (CheckGlobalValSummaryPresenceOnly) { 6025 if (Entry.ID == bitc::GLOBALVAL_SUMMARY_BLOCK_ID) { 6026 SeenGlobalValSummary = true; 6027 // No need to parse the rest since we found the summary. 6028 return Error::success(); 6029 } 6030 if (Stream.SkipBlock()) 6031 return error("Invalid record"); 6032 continue; 6033 } 6034 switch (Entry.ID) { 6035 default: // Skip unknown content. 6036 if (Stream.SkipBlock()) 6037 return error("Invalid record"); 6038 break; 6039 case bitc::BLOCKINFO_BLOCK_ID: 6040 // Need to parse these to get abbrev ids (e.g. for VST) 6041 if (readBlockInfo()) 6042 return error("Malformed block"); 6043 break; 6044 case bitc::VALUE_SYMTAB_BLOCK_ID: 6045 // Should have been parsed earlier via VSTOffset, unless there 6046 // is no summary section. 6047 assert(((SeenValueSymbolTable && VSTOffset > 0) || 6048 !SeenGlobalValSummary) && 6049 "Expected early VST parse via VSTOffset record"); 6050 if (Stream.SkipBlock()) 6051 return error("Invalid record"); 6052 break; 6053 case bitc::GLOBALVAL_SUMMARY_BLOCK_ID: 6054 assert(!SeenValueSymbolTable && 6055 "Already read VST when parsing summary block?"); 6056 // We might not have a VST if there were no values in the 6057 // summary. An empty summary block generated when we are 6058 // performing ThinLTO compiles so we don't later invoke 6059 // the regular LTO process on them. 6060 if (VSTOffset > 0) { 6061 if (Error Err = parseValueSymbolTable(VSTOffset, ValueIdToLinkageMap)) 6062 return Err; 6063 SeenValueSymbolTable = true; 6064 } 6065 SeenGlobalValSummary = true; 6066 if (Error Err = parseEntireSummary(ModulePath)) 6067 return Err; 6068 break; 6069 case bitc::MODULE_STRTAB_BLOCK_ID: 6070 if (Error Err = parseModuleStringTable()) 6071 return Err; 6072 break; 6073 } 6074 continue; 6075 6076 case BitstreamEntry::Record: { 6077 Record.clear(); 6078 auto BitCode = Stream.readRecord(Entry.ID, Record); 6079 switch (BitCode) { 6080 default: 6081 break; // Default behavior, ignore unknown content. 6082 /// MODULE_CODE_SOURCE_FILENAME: [namechar x N] 6083 case bitc::MODULE_CODE_SOURCE_FILENAME: { 6084 SmallString<128> ValueName; 6085 if (convertToString(Record, 0, ValueName)) 6086 return error("Invalid record"); 6087 SourceFileName = ValueName.c_str(); 6088 break; 6089 } 6090 /// MODULE_CODE_HASH: [5*i32] 6091 case bitc::MODULE_CODE_HASH: { 6092 if (Record.size() != 5) 6093 return error("Invalid hash length " + Twine(Record.size()).str()); 6094 if (!TheIndex) 6095 break; 6096 if (TheIndex->modulePaths().empty()) 6097 // We always seed the index with the module. 6098 TheIndex->addModulePath(ModulePath, 0); 6099 if (TheIndex->modulePaths().size() != 1) 6100 return error("Don't expect multiple modules defined?"); 6101 auto &Hash = TheIndex->modulePaths().begin()->second.second; 6102 int Pos = 0; 6103 for (auto &Val : Record) { 6104 assert(!(Val >> 32) && "Unexpected high bits set"); 6105 Hash[Pos++] = Val; 6106 } 6107 break; 6108 } 6109 /// MODULE_CODE_VSTOFFSET: [offset] 6110 case bitc::MODULE_CODE_VSTOFFSET: 6111 if (Record.size() < 1) 6112 return error("Invalid record"); 6113 VSTOffset = Record[0]; 6114 break; 6115 // GLOBALVAR: [pointer type, isconst, initid, 6116 // linkage, alignment, section, visibility, threadlocal, 6117 // unnamed_addr, externally_initialized, dllstorageclass, 6118 // comdat] 6119 case bitc::MODULE_CODE_GLOBALVAR: { 6120 if (Record.size() < 6) 6121 return error("Invalid record"); 6122 uint64_t RawLinkage = Record[3]; 6123 GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage); 6124 ValueIdToLinkageMap[ValueId++] = Linkage; 6125 break; 6126 } 6127 // FUNCTION: [type, callingconv, isproto, linkage, paramattr, 6128 // alignment, section, visibility, gc, unnamed_addr, 6129 // prologuedata, dllstorageclass, comdat, prefixdata] 6130 case bitc::MODULE_CODE_FUNCTION: { 6131 if (Record.size() < 8) 6132 return error("Invalid record"); 6133 uint64_t RawLinkage = Record[3]; 6134 GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage); 6135 ValueIdToLinkageMap[ValueId++] = Linkage; 6136 break; 6137 } 6138 // ALIAS: [alias type, addrspace, aliasee val#, linkage, visibility, 6139 // dllstorageclass] 6140 case bitc::MODULE_CODE_ALIAS: { 6141 if (Record.size() < 6) 6142 return error("Invalid record"); 6143 uint64_t RawLinkage = Record[3]; 6144 GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage); 6145 ValueIdToLinkageMap[ValueId++] = Linkage; 6146 break; 6147 } 6148 } 6149 } 6150 continue; 6151 } 6152 } 6153 } 6154 6155 // Eagerly parse the entire summary block. This populates the GlobalValueSummary 6156 // objects in the index. 6157 Error ModuleSummaryIndexBitcodeReader::parseEntireSummary( 6158 StringRef ModulePath) { 6159 if (Stream.EnterSubBlock(bitc::GLOBALVAL_SUMMARY_BLOCK_ID)) 6160 return error("Invalid record"); 6161 SmallVector<uint64_t, 64> Record; 6162 6163 // Parse version 6164 { 6165 BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 6166 if (Entry.Kind != BitstreamEntry::Record) 6167 return error("Invalid Summary Block: record for version expected"); 6168 if (Stream.readRecord(Entry.ID, Record) != bitc::FS_VERSION) 6169 return error("Invalid Summary Block: version expected"); 6170 } 6171 const uint64_t Version = Record[0]; 6172 const bool IsOldProfileFormat = Version == 1; 6173 if (!IsOldProfileFormat && Version != 2) 6174 return error("Invalid summary version " + Twine(Version) + 6175 ", 1 or 2 expected"); 6176 Record.clear(); 6177 6178 // Keep around the last seen summary to be used when we see an optional 6179 // "OriginalName" attachement. 6180 GlobalValueSummary *LastSeenSummary = nullptr; 6181 bool Combined = false; 6182 6183 while (true) { 6184 BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 6185 6186 switch (Entry.Kind) { 6187 case BitstreamEntry::SubBlock: // Handled for us already. 6188 case BitstreamEntry::Error: 6189 return error("Malformed block"); 6190 case BitstreamEntry::EndBlock: 6191 // For a per-module index, remove any entries that still have empty 6192 // summaries. The VST parsing creates entries eagerly for all symbols, 6193 // but not all have associated summaries (e.g. it doesn't know how to 6194 // distinguish between VST_CODE_ENTRY for function declarations vs global 6195 // variables with initializers that end up with a summary). Remove those 6196 // entries now so that we don't need to rely on the combined index merger 6197 // to clean them up (especially since that may not run for the first 6198 // module's index if we merge into that). 6199 if (!Combined) 6200 TheIndex->removeEmptySummaryEntries(); 6201 return Error::success(); 6202 case BitstreamEntry::Record: 6203 // The interesting case. 6204 break; 6205 } 6206 6207 // Read a record. The record format depends on whether this 6208 // is a per-module index or a combined index file. In the per-module 6209 // case the records contain the associated value's ID for correlation 6210 // with VST entries. In the combined index the correlation is done 6211 // via the bitcode offset of the summary records (which were saved 6212 // in the combined index VST entries). The records also contain 6213 // information used for ThinLTO renaming and importing. 6214 Record.clear(); 6215 auto BitCode = Stream.readRecord(Entry.ID, Record); 6216 switch (BitCode) { 6217 default: // Default behavior: ignore. 6218 break; 6219 // FS_PERMODULE: [valueid, flags, instcount, numrefs, numrefs x valueid, 6220 // n x (valueid)] 6221 // FS_PERMODULE_PROFILE: [valueid, flags, instcount, numrefs, 6222 // numrefs x valueid, 6223 // n x (valueid, hotness)] 6224 case bitc::FS_PERMODULE: 6225 case bitc::FS_PERMODULE_PROFILE: { 6226 unsigned ValueID = Record[0]; 6227 uint64_t RawFlags = Record[1]; 6228 unsigned InstCount = Record[2]; 6229 unsigned NumRefs = Record[3]; 6230 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version); 6231 std::unique_ptr<FunctionSummary> FS = 6232 llvm::make_unique<FunctionSummary>(Flags, InstCount); 6233 // The module path string ref set in the summary must be owned by the 6234 // index's module string table. Since we don't have a module path 6235 // string table section in the per-module index, we create a single 6236 // module path string table entry with an empty (0) ID to take 6237 // ownership. 6238 FS->setModulePath(TheIndex->addModulePath(ModulePath, 0)->first()); 6239 static int RefListStartIndex = 4; 6240 int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs; 6241 assert(Record.size() >= RefListStartIndex + NumRefs && 6242 "Record size inconsistent with number of references"); 6243 for (unsigned I = 4, E = CallGraphEdgeStartIndex; I != E; ++I) { 6244 unsigned RefValueId = Record[I]; 6245 GlobalValue::GUID RefGUID = getGUIDFromValueId(RefValueId).first; 6246 FS->addRefEdge(RefGUID); 6247 } 6248 bool HasProfile = (BitCode == bitc::FS_PERMODULE_PROFILE); 6249 for (unsigned I = CallGraphEdgeStartIndex, E = Record.size(); I != E; 6250 ++I) { 6251 CalleeInfo::HotnessType Hotness; 6252 GlobalValue::GUID CalleeGUID; 6253 std::tie(CalleeGUID, Hotness) = 6254 readCallGraphEdge(Record, I, IsOldProfileFormat, HasProfile); 6255 FS->addCallGraphEdge(CalleeGUID, CalleeInfo(Hotness)); 6256 } 6257 auto GUID = getGUIDFromValueId(ValueID); 6258 FS->setOriginalName(GUID.second); 6259 TheIndex->addGlobalValueSummary(GUID.first, std::move(FS)); 6260 break; 6261 } 6262 // FS_ALIAS: [valueid, flags, valueid] 6263 // Aliases must be emitted (and parsed) after all FS_PERMODULE entries, as 6264 // they expect all aliasee summaries to be available. 6265 case bitc::FS_ALIAS: { 6266 unsigned ValueID = Record[0]; 6267 uint64_t RawFlags = Record[1]; 6268 unsigned AliaseeID = Record[2]; 6269 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version); 6270 std::unique_ptr<AliasSummary> AS = llvm::make_unique<AliasSummary>(Flags); 6271 // The module path string ref set in the summary must be owned by the 6272 // index's module string table. Since we don't have a module path 6273 // string table section in the per-module index, we create a single 6274 // module path string table entry with an empty (0) ID to take 6275 // ownership. 6276 AS->setModulePath(TheIndex->addModulePath(ModulePath, 0)->first()); 6277 6278 GlobalValue::GUID AliaseeGUID = getGUIDFromValueId(AliaseeID).first; 6279 auto *AliaseeSummary = TheIndex->getGlobalValueSummary(AliaseeGUID); 6280 if (!AliaseeSummary) 6281 return error("Alias expects aliasee summary to be parsed"); 6282 AS->setAliasee(AliaseeSummary); 6283 6284 auto GUID = getGUIDFromValueId(ValueID); 6285 AS->setOriginalName(GUID.second); 6286 TheIndex->addGlobalValueSummary(GUID.first, std::move(AS)); 6287 break; 6288 } 6289 // FS_PERMODULE_GLOBALVAR_INIT_REFS: [valueid, flags, n x valueid] 6290 case bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS: { 6291 unsigned ValueID = Record[0]; 6292 uint64_t RawFlags = Record[1]; 6293 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version); 6294 std::unique_ptr<GlobalVarSummary> FS = 6295 llvm::make_unique<GlobalVarSummary>(Flags); 6296 FS->setModulePath(TheIndex->addModulePath(ModulePath, 0)->first()); 6297 for (unsigned I = 2, E = Record.size(); I != E; ++I) { 6298 unsigned RefValueId = Record[I]; 6299 GlobalValue::GUID RefGUID = getGUIDFromValueId(RefValueId).first; 6300 FS->addRefEdge(RefGUID); 6301 } 6302 auto GUID = getGUIDFromValueId(ValueID); 6303 FS->setOriginalName(GUID.second); 6304 TheIndex->addGlobalValueSummary(GUID.first, std::move(FS)); 6305 break; 6306 } 6307 // FS_COMBINED: [valueid, modid, flags, instcount, numrefs, 6308 // numrefs x valueid, n x (valueid)] 6309 // FS_COMBINED_PROFILE: [valueid, modid, flags, instcount, numrefs, 6310 // numrefs x valueid, n x (valueid, hotness)] 6311 case bitc::FS_COMBINED: 6312 case bitc::FS_COMBINED_PROFILE: { 6313 unsigned ValueID = Record[0]; 6314 uint64_t ModuleId = Record[1]; 6315 uint64_t RawFlags = Record[2]; 6316 unsigned InstCount = Record[3]; 6317 unsigned NumRefs = Record[4]; 6318 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version); 6319 std::unique_ptr<FunctionSummary> FS = 6320 llvm::make_unique<FunctionSummary>(Flags, InstCount); 6321 LastSeenSummary = FS.get(); 6322 FS->setModulePath(ModuleIdMap[ModuleId]); 6323 static int RefListStartIndex = 5; 6324 int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs; 6325 assert(Record.size() >= RefListStartIndex + NumRefs && 6326 "Record size inconsistent with number of references"); 6327 for (unsigned I = RefListStartIndex, E = CallGraphEdgeStartIndex; I != E; 6328 ++I) { 6329 unsigned RefValueId = Record[I]; 6330 GlobalValue::GUID RefGUID = getGUIDFromValueId(RefValueId).first; 6331 FS->addRefEdge(RefGUID); 6332 } 6333 bool HasProfile = (BitCode == bitc::FS_COMBINED_PROFILE); 6334 for (unsigned I = CallGraphEdgeStartIndex, E = Record.size(); I != E; 6335 ++I) { 6336 CalleeInfo::HotnessType Hotness; 6337 GlobalValue::GUID CalleeGUID; 6338 std::tie(CalleeGUID, Hotness) = 6339 readCallGraphEdge(Record, I, IsOldProfileFormat, HasProfile); 6340 FS->addCallGraphEdge(CalleeGUID, CalleeInfo(Hotness)); 6341 } 6342 GlobalValue::GUID GUID = getGUIDFromValueId(ValueID).first; 6343 TheIndex->addGlobalValueSummary(GUID, std::move(FS)); 6344 Combined = true; 6345 break; 6346 } 6347 // FS_COMBINED_ALIAS: [valueid, modid, flags, valueid] 6348 // Aliases must be emitted (and parsed) after all FS_COMBINED entries, as 6349 // they expect all aliasee summaries to be available. 6350 case bitc::FS_COMBINED_ALIAS: { 6351 unsigned ValueID = Record[0]; 6352 uint64_t ModuleId = Record[1]; 6353 uint64_t RawFlags = Record[2]; 6354 unsigned AliaseeValueId = Record[3]; 6355 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version); 6356 std::unique_ptr<AliasSummary> AS = llvm::make_unique<AliasSummary>(Flags); 6357 LastSeenSummary = AS.get(); 6358 AS->setModulePath(ModuleIdMap[ModuleId]); 6359 6360 auto AliaseeGUID = getGUIDFromValueId(AliaseeValueId).first; 6361 auto AliaseeInModule = 6362 TheIndex->findSummaryInModule(AliaseeGUID, AS->modulePath()); 6363 if (!AliaseeInModule) 6364 return error("Alias expects aliasee summary to be parsed"); 6365 AS->setAliasee(AliaseeInModule); 6366 6367 GlobalValue::GUID GUID = getGUIDFromValueId(ValueID).first; 6368 TheIndex->addGlobalValueSummary(GUID, std::move(AS)); 6369 Combined = true; 6370 break; 6371 } 6372 // FS_COMBINED_GLOBALVAR_INIT_REFS: [valueid, modid, flags, n x valueid] 6373 case bitc::FS_COMBINED_GLOBALVAR_INIT_REFS: { 6374 unsigned ValueID = Record[0]; 6375 uint64_t ModuleId = Record[1]; 6376 uint64_t RawFlags = Record[2]; 6377 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version); 6378 std::unique_ptr<GlobalVarSummary> FS = 6379 llvm::make_unique<GlobalVarSummary>(Flags); 6380 LastSeenSummary = FS.get(); 6381 FS->setModulePath(ModuleIdMap[ModuleId]); 6382 for (unsigned I = 3, E = Record.size(); I != E; ++I) { 6383 unsigned RefValueId = Record[I]; 6384 GlobalValue::GUID RefGUID = getGUIDFromValueId(RefValueId).first; 6385 FS->addRefEdge(RefGUID); 6386 } 6387 GlobalValue::GUID GUID = getGUIDFromValueId(ValueID).first; 6388 TheIndex->addGlobalValueSummary(GUID, std::move(FS)); 6389 Combined = true; 6390 break; 6391 } 6392 // FS_COMBINED_ORIGINAL_NAME: [original_name] 6393 case bitc::FS_COMBINED_ORIGINAL_NAME: { 6394 uint64_t OriginalName = Record[0]; 6395 if (!LastSeenSummary) 6396 return error("Name attachment that does not follow a combined record"); 6397 LastSeenSummary->setOriginalName(OriginalName); 6398 // Reset the LastSeenSummary 6399 LastSeenSummary = nullptr; 6400 } 6401 } 6402 } 6403 llvm_unreachable("Exit infinite loop"); 6404 } 6405 6406 std::pair<GlobalValue::GUID, CalleeInfo::HotnessType> 6407 ModuleSummaryIndexBitcodeReader::readCallGraphEdge( 6408 const SmallVector<uint64_t, 64> &Record, unsigned int &I, 6409 const bool IsOldProfileFormat, const bool HasProfile) { 6410 6411 auto Hotness = CalleeInfo::HotnessType::Unknown; 6412 unsigned CalleeValueId = Record[I]; 6413 GlobalValue::GUID CalleeGUID = getGUIDFromValueId(CalleeValueId).first; 6414 if (IsOldProfileFormat) { 6415 I += 1; // Skip old callsitecount field 6416 if (HasProfile) 6417 I += 1; // Skip old profilecount field 6418 } else if (HasProfile) 6419 Hotness = static_cast<CalleeInfo::HotnessType>(Record[++I]); 6420 return {CalleeGUID, Hotness}; 6421 } 6422 6423 // Parse the module string table block into the Index. 6424 // This populates the ModulePathStringTable map in the index. 6425 Error ModuleSummaryIndexBitcodeReader::parseModuleStringTable() { 6426 if (Stream.EnterSubBlock(bitc::MODULE_STRTAB_BLOCK_ID)) 6427 return error("Invalid record"); 6428 6429 SmallVector<uint64_t, 64> Record; 6430 6431 SmallString<128> ModulePath; 6432 ModulePathStringTableTy::iterator LastSeenModulePath; 6433 6434 while (true) { 6435 BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 6436 6437 switch (Entry.Kind) { 6438 case BitstreamEntry::SubBlock: // Handled for us already. 6439 case BitstreamEntry::Error: 6440 return error("Malformed block"); 6441 case BitstreamEntry::EndBlock: 6442 return Error::success(); 6443 case BitstreamEntry::Record: 6444 // The interesting case. 6445 break; 6446 } 6447 6448 Record.clear(); 6449 switch (Stream.readRecord(Entry.ID, Record)) { 6450 default: // Default behavior: ignore. 6451 break; 6452 case bitc::MST_CODE_ENTRY: { 6453 // MST_ENTRY: [modid, namechar x N] 6454 uint64_t ModuleId = Record[0]; 6455 6456 if (convertToString(Record, 1, ModulePath)) 6457 return error("Invalid record"); 6458 6459 LastSeenModulePath = TheIndex->addModulePath(ModulePath, ModuleId); 6460 ModuleIdMap[ModuleId] = LastSeenModulePath->first(); 6461 6462 ModulePath.clear(); 6463 break; 6464 } 6465 /// MST_CODE_HASH: [5*i32] 6466 case bitc::MST_CODE_HASH: { 6467 if (Record.size() != 5) 6468 return error("Invalid hash length " + Twine(Record.size()).str()); 6469 if (LastSeenModulePath == TheIndex->modulePaths().end()) 6470 return error("Invalid hash that does not follow a module path"); 6471 int Pos = 0; 6472 for (auto &Val : Record) { 6473 assert(!(Val >> 32) && "Unexpected high bits set"); 6474 LastSeenModulePath->second.second[Pos++] = Val; 6475 } 6476 // Reset LastSeenModulePath to avoid overriding the hash unexpectedly. 6477 LastSeenModulePath = TheIndex->modulePaths().end(); 6478 break; 6479 } 6480 } 6481 } 6482 llvm_unreachable("Exit infinite loop"); 6483 } 6484 6485 // Parse the function info index from the bitcode streamer into the given index. 6486 Error ModuleSummaryIndexBitcodeReader::parseSummaryIndexInto( 6487 ModuleSummaryIndex *I, StringRef ModulePath) { 6488 TheIndex = I; 6489 6490 // We expect a number of well-defined blocks, though we don't necessarily 6491 // need to understand them all. 6492 while (true) { 6493 if (Stream.AtEndOfStream()) { 6494 // We didn't really read a proper Module block. 6495 return error("Malformed block"); 6496 } 6497 6498 BitstreamEntry Entry = 6499 Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs); 6500 6501 if (Entry.Kind != BitstreamEntry::SubBlock) 6502 return error("Malformed block"); 6503 6504 // If we see a MODULE_BLOCK, parse it to find the blocks needed for 6505 // building the function summary index. 6506 if (Entry.ID == bitc::MODULE_BLOCK_ID) 6507 return parseModule(ModulePath); 6508 6509 if (Stream.SkipBlock()) 6510 return error("Invalid record"); 6511 } 6512 } 6513 6514 namespace { 6515 6516 // FIXME: This class is only here to support the transition to llvm::Error. It 6517 // will be removed once this transition is complete. Clients should prefer to 6518 // deal with the Error value directly, rather than converting to error_code. 6519 class BitcodeErrorCategoryType : public std::error_category { 6520 const char *name() const noexcept override { 6521 return "llvm.bitcode"; 6522 } 6523 std::string message(int IE) const override { 6524 BitcodeError E = static_cast<BitcodeError>(IE); 6525 switch (E) { 6526 case BitcodeError::CorruptedBitcode: 6527 return "Corrupted bitcode"; 6528 } 6529 llvm_unreachable("Unknown error type!"); 6530 } 6531 }; 6532 6533 } // end anonymous namespace 6534 6535 static ManagedStatic<BitcodeErrorCategoryType> ErrorCategory; 6536 6537 const std::error_category &llvm::BitcodeErrorCategory() { 6538 return *ErrorCategory; 6539 } 6540 6541 //===----------------------------------------------------------------------===// 6542 // External interface 6543 //===----------------------------------------------------------------------===// 6544 6545 Expected<std::vector<BitcodeModule>> 6546 llvm::getBitcodeModuleList(MemoryBufferRef Buffer) { 6547 Expected<BitstreamCursor> StreamOrErr = initStream(Buffer); 6548 if (!StreamOrErr) 6549 return StreamOrErr.takeError(); 6550 BitstreamCursor &Stream = *StreamOrErr; 6551 6552 uint64_t IdentificationBit = -1ull; 6553 std::vector<BitcodeModule> Modules; 6554 while (true) { 6555 // We may be consuming bitcode from a client that leaves garbage at the end 6556 // of the bitcode stream (e.g. Apple's ar tool). If we are close enough to 6557 // the end that there cannot possibly be another module, stop looking. 6558 if (Stream.getCurrentByteNo() + 8 >= Stream.getBitcodeBytes().size()) 6559 return Modules; 6560 6561 BitstreamEntry Entry = Stream.advance(); 6562 switch (Entry.Kind) { 6563 case BitstreamEntry::EndBlock: 6564 case BitstreamEntry::Error: 6565 return error("Malformed block"); 6566 6567 case BitstreamEntry::SubBlock: 6568 if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID) 6569 IdentificationBit = Stream.GetCurrentBitNo(); 6570 else if (Entry.ID == bitc::MODULE_BLOCK_ID) 6571 Modules.push_back({Stream.getBitcodeBytes(), 6572 Buffer.getBufferIdentifier(), IdentificationBit, 6573 Stream.GetCurrentBitNo()}); 6574 6575 if (Stream.SkipBlock()) 6576 return error("Malformed block"); 6577 continue; 6578 case BitstreamEntry::Record: 6579 Stream.skipRecord(Entry.ID); 6580 continue; 6581 } 6582 } 6583 } 6584 6585 /// \brief Get a lazy one-at-time loading module from bitcode. 6586 /// 6587 /// This isn't always used in a lazy context. In particular, it's also used by 6588 /// \a parseModule(). If this is truly lazy, then we need to eagerly pull 6589 /// in forward-referenced functions from block address references. 6590 /// 6591 /// \param[in] MaterializeAll Set to \c true if we should materialize 6592 /// everything. 6593 Expected<std::unique_ptr<Module>> 6594 BitcodeModule::getModuleImpl(LLVMContext &Context, bool MaterializeAll, 6595 bool ShouldLazyLoadMetadata) { 6596 BitstreamCursor Stream(Buffer); 6597 6598 std::string ProducerIdentification; 6599 if (IdentificationBit != -1ull) { 6600 Stream.JumpToBit(IdentificationBit); 6601 Expected<std::string> ProducerIdentificationOrErr = 6602 readIdentificationBlock(Stream); 6603 if (!ProducerIdentificationOrErr) 6604 return ProducerIdentificationOrErr.takeError(); 6605 6606 ProducerIdentification = *ProducerIdentificationOrErr; 6607 } 6608 6609 Stream.JumpToBit(ModuleBit); 6610 auto *R = 6611 new BitcodeReader(std::move(Stream), ProducerIdentification, Context); 6612 6613 std::unique_ptr<Module> M = 6614 llvm::make_unique<Module>(ModuleIdentifier, Context); 6615 M->setMaterializer(R); 6616 6617 // Delay parsing Metadata if ShouldLazyLoadMetadata is true. 6618 if (Error Err = R->parseBitcodeInto(M.get(), ShouldLazyLoadMetadata)) 6619 return std::move(Err); 6620 6621 if (MaterializeAll) { 6622 // Read in the entire module, and destroy the BitcodeReader. 6623 if (Error Err = M->materializeAll()) 6624 return std::move(Err); 6625 } else { 6626 // Resolve forward references from blockaddresses. 6627 if (Error Err = R->materializeForwardReferencedFunctions()) 6628 return std::move(Err); 6629 } 6630 return std::move(M); 6631 } 6632 6633 Expected<std::unique_ptr<Module>> 6634 BitcodeModule::getLazyModule(LLVMContext &Context, 6635 bool ShouldLazyLoadMetadata) { 6636 return getModuleImpl(Context, false, ShouldLazyLoadMetadata); 6637 } 6638 6639 Expected<std::unique_ptr<Module>> 6640 llvm::getLazyBitcodeModule(MemoryBufferRef Buffer, 6641 LLVMContext &Context, bool ShouldLazyLoadMetadata) { 6642 Expected<std::vector<BitcodeModule>> MsOrErr = getBitcodeModuleList(Buffer); 6643 if (!MsOrErr) 6644 return MsOrErr.takeError(); 6645 6646 if (MsOrErr->size() != 1) 6647 return error("Expected a single module"); 6648 6649 return (*MsOrErr)[0].getLazyModule(Context, ShouldLazyLoadMetadata); 6650 } 6651 6652 Expected<std::unique_ptr<Module>> 6653 llvm::getOwningLazyBitcodeModule(std::unique_ptr<MemoryBuffer> &&Buffer, 6654 LLVMContext &Context, 6655 bool ShouldLazyLoadMetadata) { 6656 auto MOrErr = getLazyBitcodeModule(*Buffer, Context, ShouldLazyLoadMetadata); 6657 if (MOrErr) 6658 (*MOrErr)->setOwnedMemoryBuffer(std::move(Buffer)); 6659 return MOrErr; 6660 } 6661 6662 Expected<std::unique_ptr<Module>> 6663 BitcodeModule::parseModule(LLVMContext &Context) { 6664 return getModuleImpl(Context, true, false); 6665 // TODO: Restore the use-lists to the in-memory state when the bitcode was 6666 // written. We must defer until the Module has been fully materialized. 6667 } 6668 6669 Expected<std::unique_ptr<Module>> llvm::parseBitcodeFile(MemoryBufferRef Buffer, 6670 LLVMContext &Context) { 6671 Expected<std::vector<BitcodeModule>> MsOrErr = getBitcodeModuleList(Buffer); 6672 if (!MsOrErr) 6673 return MsOrErr.takeError(); 6674 6675 if (MsOrErr->size() != 1) 6676 return error("Expected a single module"); 6677 6678 return (*MsOrErr)[0].parseModule(Context); 6679 } 6680 6681 Expected<std::string> llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer) { 6682 Expected<BitstreamCursor> StreamOrErr = initStream(Buffer); 6683 if (!StreamOrErr) 6684 return StreamOrErr.takeError(); 6685 6686 return readTriple(*StreamOrErr); 6687 } 6688 6689 Expected<bool> llvm::isBitcodeContainingObjCCategory(MemoryBufferRef Buffer) { 6690 Expected<BitstreamCursor> StreamOrErr = initStream(Buffer); 6691 if (!StreamOrErr) 6692 return StreamOrErr.takeError(); 6693 6694 return hasObjCCategory(*StreamOrErr); 6695 } 6696 6697 Expected<std::string> llvm::getBitcodeProducerString(MemoryBufferRef Buffer) { 6698 Expected<BitstreamCursor> StreamOrErr = initStream(Buffer); 6699 if (!StreamOrErr) 6700 return StreamOrErr.takeError(); 6701 6702 return readIdentificationCode(*StreamOrErr); 6703 } 6704 6705 // Parse the specified bitcode buffer, returning the function info index. 6706 Expected<std::unique_ptr<ModuleSummaryIndex>> 6707 llvm::getModuleSummaryIndex(MemoryBufferRef Buffer) { 6708 Expected<BitstreamCursor> StreamOrErr = initStream(Buffer); 6709 if (!StreamOrErr) 6710 return StreamOrErr.takeError(); 6711 6712 ModuleSummaryIndexBitcodeReader R(std::move(*StreamOrErr)); 6713 6714 auto Index = llvm::make_unique<ModuleSummaryIndex>(); 6715 6716 if (Error Err = 6717 R.parseSummaryIndexInto(Index.get(), Buffer.getBufferIdentifier())) 6718 return std::move(Err); 6719 6720 return std::move(Index); 6721 } 6722 6723 // Check if the given bitcode buffer contains a global value summary block. 6724 Expected<bool> llvm::hasGlobalValueSummary(MemoryBufferRef Buffer) { 6725 Expected<BitstreamCursor> StreamOrErr = initStream(Buffer); 6726 if (!StreamOrErr) 6727 return StreamOrErr.takeError(); 6728 6729 ModuleSummaryIndexBitcodeReader R(std::move(*StreamOrErr), true); 6730 6731 if (Error Err = 6732 R.parseSummaryIndexInto(nullptr, Buffer.getBufferIdentifier())) 6733 return std::move(Err); 6734 6735 return R.foundGlobalValSummary(); 6736 } 6737