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