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