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