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