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