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