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