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