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