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