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