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