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