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