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