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