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