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