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