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