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