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