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