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