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