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