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