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