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