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