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 /// 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, 1954 Record[0] || Record[8], // All definitions should be distinct. 1955 (Context, getMDOrNull(Record[1]), getMDString(Record[2]), 1956 getMDString(Record[3]), getMDOrNull(Record[4]), Record[5], 1957 getMDOrNull(Record[6]), Record[7], Record[8], Record[9], 1958 getMDOrNull(Record[10]), Record[11], Record[12], Record[13], 1959 Record[14], getMDOrNull(Record[15]), getMDOrNull(Record[16]), 1960 getMDOrNull(Record[17]), getMDOrNull(Record[18]))), 1961 NextMDValueNo++); 1962 break; 1963 } 1964 case bitc::METADATA_LEXICAL_BLOCK: { 1965 if (Record.size() != 5) 1966 return error("Invalid record"); 1967 1968 MDValueList.assignValue( 1969 GET_OR_DISTINCT(DILexicalBlock, Record[0], 1970 (Context, getMDOrNull(Record[1]), 1971 getMDOrNull(Record[2]), Record[3], Record[4])), 1972 NextMDValueNo++); 1973 break; 1974 } 1975 case bitc::METADATA_LEXICAL_BLOCK_FILE: { 1976 if (Record.size() != 4) 1977 return error("Invalid record"); 1978 1979 MDValueList.assignValue( 1980 GET_OR_DISTINCT(DILexicalBlockFile, Record[0], 1981 (Context, getMDOrNull(Record[1]), 1982 getMDOrNull(Record[2]), Record[3])), 1983 NextMDValueNo++); 1984 break; 1985 } 1986 case bitc::METADATA_NAMESPACE: { 1987 if (Record.size() != 5) 1988 return error("Invalid record"); 1989 1990 MDValueList.assignValue( 1991 GET_OR_DISTINCT(DINamespace, Record[0], 1992 (Context, getMDOrNull(Record[1]), 1993 getMDOrNull(Record[2]), getMDString(Record[3]), 1994 Record[4])), 1995 NextMDValueNo++); 1996 break; 1997 } 1998 case bitc::METADATA_TEMPLATE_TYPE: { 1999 if (Record.size() != 3) 2000 return error("Invalid record"); 2001 2002 MDValueList.assignValue(GET_OR_DISTINCT(DITemplateTypeParameter, 2003 Record[0], 2004 (Context, getMDString(Record[1]), 2005 getMDOrNull(Record[2]))), 2006 NextMDValueNo++); 2007 break; 2008 } 2009 case bitc::METADATA_TEMPLATE_VALUE: { 2010 if (Record.size() != 5) 2011 return error("Invalid record"); 2012 2013 MDValueList.assignValue( 2014 GET_OR_DISTINCT(DITemplateValueParameter, Record[0], 2015 (Context, Record[1], getMDString(Record[2]), 2016 getMDOrNull(Record[3]), getMDOrNull(Record[4]))), 2017 NextMDValueNo++); 2018 break; 2019 } 2020 case bitc::METADATA_GLOBAL_VAR: { 2021 if (Record.size() != 11) 2022 return error("Invalid record"); 2023 2024 MDValueList.assignValue( 2025 GET_OR_DISTINCT(DIGlobalVariable, Record[0], 2026 (Context, getMDOrNull(Record[1]), 2027 getMDString(Record[2]), getMDString(Record[3]), 2028 getMDOrNull(Record[4]), Record[5], 2029 getMDOrNull(Record[6]), Record[7], Record[8], 2030 getMDOrNull(Record[9]), getMDOrNull(Record[10]))), 2031 NextMDValueNo++); 2032 break; 2033 } 2034 case bitc::METADATA_LOCAL_VAR: { 2035 // 10th field is for the obseleted 'inlinedAt:' field. 2036 if (Record.size() < 8 || Record.size() > 10) 2037 return error("Invalid record"); 2038 2039 // 2nd field used to be an artificial tag, either DW_TAG_auto_variable or 2040 // DW_TAG_arg_variable. 2041 bool HasTag = Record.size() > 8; 2042 MDValueList.assignValue( 2043 GET_OR_DISTINCT(DILocalVariable, Record[0], 2044 (Context, getMDOrNull(Record[1 + HasTag]), 2045 getMDString(Record[2 + HasTag]), 2046 getMDOrNull(Record[3 + HasTag]), Record[4 + HasTag], 2047 getMDOrNull(Record[5 + HasTag]), Record[6 + HasTag], 2048 Record[7 + HasTag])), 2049 NextMDValueNo++); 2050 break; 2051 } 2052 case bitc::METADATA_EXPRESSION: { 2053 if (Record.size() < 1) 2054 return error("Invalid record"); 2055 2056 MDValueList.assignValue( 2057 GET_OR_DISTINCT(DIExpression, Record[0], 2058 (Context, makeArrayRef(Record).slice(1))), 2059 NextMDValueNo++); 2060 break; 2061 } 2062 case bitc::METADATA_OBJC_PROPERTY: { 2063 if (Record.size() != 8) 2064 return error("Invalid record"); 2065 2066 MDValueList.assignValue( 2067 GET_OR_DISTINCT(DIObjCProperty, Record[0], 2068 (Context, getMDString(Record[1]), 2069 getMDOrNull(Record[2]), Record[3], 2070 getMDString(Record[4]), getMDString(Record[5]), 2071 Record[6], getMDOrNull(Record[7]))), 2072 NextMDValueNo++); 2073 break; 2074 } 2075 case bitc::METADATA_IMPORTED_ENTITY: { 2076 if (Record.size() != 6) 2077 return error("Invalid record"); 2078 2079 MDValueList.assignValue( 2080 GET_OR_DISTINCT(DIImportedEntity, Record[0], 2081 (Context, Record[1], getMDOrNull(Record[2]), 2082 getMDOrNull(Record[3]), Record[4], 2083 getMDString(Record[5]))), 2084 NextMDValueNo++); 2085 break; 2086 } 2087 case bitc::METADATA_STRING: { 2088 std::string String(Record.begin(), Record.end()); 2089 llvm::UpgradeMDStringConstant(String); 2090 Metadata *MD = MDString::get(Context, String); 2091 MDValueList.assignValue(MD, NextMDValueNo++); 2092 break; 2093 } 2094 case bitc::METADATA_KIND: { 2095 if (Record.size() < 2) 2096 return error("Invalid record"); 2097 2098 unsigned Kind = Record[0]; 2099 SmallString<8> Name(Record.begin()+1, Record.end()); 2100 2101 unsigned NewKind = TheModule->getMDKindID(Name.str()); 2102 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second) 2103 return error("Conflicting METADATA_KIND records"); 2104 break; 2105 } 2106 } 2107 } 2108 #undef GET_OR_DISTINCT 2109 } 2110 2111 /// Decode a signed value stored with the sign bit in the LSB for dense VBR 2112 /// encoding. 2113 uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) { 2114 if ((V & 1) == 0) 2115 return V >> 1; 2116 if (V != 1) 2117 return -(V >> 1); 2118 // There is no such thing as -0 with integers. "-0" really means MININT. 2119 return 1ULL << 63; 2120 } 2121 2122 /// Resolve all of the initializers for global values and aliases that we can. 2123 std::error_code BitcodeReader::resolveGlobalAndAliasInits() { 2124 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist; 2125 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist; 2126 std::vector<std::pair<Function*, unsigned> > FunctionPrefixWorklist; 2127 std::vector<std::pair<Function*, unsigned> > FunctionPrologueWorklist; 2128 std::vector<std::pair<Function*, unsigned> > FunctionPersonalityFnWorklist; 2129 2130 GlobalInitWorklist.swap(GlobalInits); 2131 AliasInitWorklist.swap(AliasInits); 2132 FunctionPrefixWorklist.swap(FunctionPrefixes); 2133 FunctionPrologueWorklist.swap(FunctionPrologues); 2134 FunctionPersonalityFnWorklist.swap(FunctionPersonalityFns); 2135 2136 while (!GlobalInitWorklist.empty()) { 2137 unsigned ValID = GlobalInitWorklist.back().second; 2138 if (ValID >= ValueList.size()) { 2139 // Not ready to resolve this yet, it requires something later in the file. 2140 GlobalInits.push_back(GlobalInitWorklist.back()); 2141 } else { 2142 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID])) 2143 GlobalInitWorklist.back().first->setInitializer(C); 2144 else 2145 return error("Expected a constant"); 2146 } 2147 GlobalInitWorklist.pop_back(); 2148 } 2149 2150 while (!AliasInitWorklist.empty()) { 2151 unsigned ValID = AliasInitWorklist.back().second; 2152 if (ValID >= ValueList.size()) { 2153 AliasInits.push_back(AliasInitWorklist.back()); 2154 } else { 2155 Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]); 2156 if (!C) 2157 return error("Expected a constant"); 2158 GlobalAlias *Alias = AliasInitWorklist.back().first; 2159 if (C->getType() != Alias->getType()) 2160 return error("Alias and aliasee types don't match"); 2161 Alias->setAliasee(C); 2162 } 2163 AliasInitWorklist.pop_back(); 2164 } 2165 2166 while (!FunctionPrefixWorklist.empty()) { 2167 unsigned ValID = FunctionPrefixWorklist.back().second; 2168 if (ValID >= ValueList.size()) { 2169 FunctionPrefixes.push_back(FunctionPrefixWorklist.back()); 2170 } else { 2171 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID])) 2172 FunctionPrefixWorklist.back().first->setPrefixData(C); 2173 else 2174 return error("Expected a constant"); 2175 } 2176 FunctionPrefixWorklist.pop_back(); 2177 } 2178 2179 while (!FunctionPrologueWorklist.empty()) { 2180 unsigned ValID = FunctionPrologueWorklist.back().second; 2181 if (ValID >= ValueList.size()) { 2182 FunctionPrologues.push_back(FunctionPrologueWorklist.back()); 2183 } else { 2184 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID])) 2185 FunctionPrologueWorklist.back().first->setPrologueData(C); 2186 else 2187 return error("Expected a constant"); 2188 } 2189 FunctionPrologueWorklist.pop_back(); 2190 } 2191 2192 while (!FunctionPersonalityFnWorklist.empty()) { 2193 unsigned ValID = FunctionPersonalityFnWorklist.back().second; 2194 if (ValID >= ValueList.size()) { 2195 FunctionPersonalityFns.push_back(FunctionPersonalityFnWorklist.back()); 2196 } else { 2197 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID])) 2198 FunctionPersonalityFnWorklist.back().first->setPersonalityFn(C); 2199 else 2200 return error("Expected a constant"); 2201 } 2202 FunctionPersonalityFnWorklist.pop_back(); 2203 } 2204 2205 return std::error_code(); 2206 } 2207 2208 static APInt readWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) { 2209 SmallVector<uint64_t, 8> Words(Vals.size()); 2210 std::transform(Vals.begin(), Vals.end(), Words.begin(), 2211 BitcodeReader::decodeSignRotatedValue); 2212 2213 return APInt(TypeBits, Words); 2214 } 2215 2216 std::error_code BitcodeReader::parseConstants() { 2217 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID)) 2218 return error("Invalid record"); 2219 2220 SmallVector<uint64_t, 64> Record; 2221 2222 // Read all the records for this value table. 2223 Type *CurTy = Type::getInt32Ty(Context); 2224 unsigned NextCstNo = ValueList.size(); 2225 while (1) { 2226 BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 2227 2228 switch (Entry.Kind) { 2229 case BitstreamEntry::SubBlock: // Handled for us already. 2230 case BitstreamEntry::Error: 2231 return error("Malformed block"); 2232 case BitstreamEntry::EndBlock: 2233 if (NextCstNo != ValueList.size()) 2234 return error("Invalid ronstant reference"); 2235 2236 // Once all the constants have been read, go through and resolve forward 2237 // references. 2238 ValueList.resolveConstantForwardRefs(); 2239 return std::error_code(); 2240 case BitstreamEntry::Record: 2241 // The interesting case. 2242 break; 2243 } 2244 2245 // Read a record. 2246 Record.clear(); 2247 Value *V = nullptr; 2248 unsigned BitCode = Stream.readRecord(Entry.ID, Record); 2249 switch (BitCode) { 2250 default: // Default behavior: unknown constant 2251 case bitc::CST_CODE_UNDEF: // UNDEF 2252 V = UndefValue::get(CurTy); 2253 break; 2254 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid] 2255 if (Record.empty()) 2256 return error("Invalid record"); 2257 if (Record[0] >= TypeList.size() || !TypeList[Record[0]]) 2258 return error("Invalid record"); 2259 CurTy = TypeList[Record[0]]; 2260 continue; // Skip the ValueList manipulation. 2261 case bitc::CST_CODE_NULL: // NULL 2262 V = Constant::getNullValue(CurTy); 2263 break; 2264 case bitc::CST_CODE_INTEGER: // INTEGER: [intval] 2265 if (!CurTy->isIntegerTy() || Record.empty()) 2266 return error("Invalid record"); 2267 V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0])); 2268 break; 2269 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval] 2270 if (!CurTy->isIntegerTy() || Record.empty()) 2271 return error("Invalid record"); 2272 2273 APInt VInt = 2274 readWideAPInt(Record, cast<IntegerType>(CurTy)->getBitWidth()); 2275 V = ConstantInt::get(Context, VInt); 2276 2277 break; 2278 } 2279 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval] 2280 if (Record.empty()) 2281 return error("Invalid record"); 2282 if (CurTy->isHalfTy()) 2283 V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf, 2284 APInt(16, (uint16_t)Record[0]))); 2285 else if (CurTy->isFloatTy()) 2286 V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle, 2287 APInt(32, (uint32_t)Record[0]))); 2288 else if (CurTy->isDoubleTy()) 2289 V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble, 2290 APInt(64, Record[0]))); 2291 else if (CurTy->isX86_FP80Ty()) { 2292 // Bits are not stored the same way as a normal i80 APInt, compensate. 2293 uint64_t Rearrange[2]; 2294 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16); 2295 Rearrange[1] = Record[0] >> 48; 2296 V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended, 2297 APInt(80, Rearrange))); 2298 } else if (CurTy->isFP128Ty()) 2299 V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad, 2300 APInt(128, Record))); 2301 else if (CurTy->isPPC_FP128Ty()) 2302 V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble, 2303 APInt(128, Record))); 2304 else 2305 V = UndefValue::get(CurTy); 2306 break; 2307 } 2308 2309 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number] 2310 if (Record.empty()) 2311 return error("Invalid record"); 2312 2313 unsigned Size = Record.size(); 2314 SmallVector<Constant*, 16> Elts; 2315 2316 if (StructType *STy = dyn_cast<StructType>(CurTy)) { 2317 for (unsigned i = 0; i != Size; ++i) 2318 Elts.push_back(ValueList.getConstantFwdRef(Record[i], 2319 STy->getElementType(i))); 2320 V = ConstantStruct::get(STy, Elts); 2321 } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) { 2322 Type *EltTy = ATy->getElementType(); 2323 for (unsigned i = 0; i != Size; ++i) 2324 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy)); 2325 V = ConstantArray::get(ATy, Elts); 2326 } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) { 2327 Type *EltTy = VTy->getElementType(); 2328 for (unsigned i = 0; i != Size; ++i) 2329 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy)); 2330 V = ConstantVector::get(Elts); 2331 } else { 2332 V = UndefValue::get(CurTy); 2333 } 2334 break; 2335 } 2336 case bitc::CST_CODE_STRING: // STRING: [values] 2337 case bitc::CST_CODE_CSTRING: { // CSTRING: [values] 2338 if (Record.empty()) 2339 return error("Invalid record"); 2340 2341 SmallString<16> Elts(Record.begin(), Record.end()); 2342 V = ConstantDataArray::getString(Context, Elts, 2343 BitCode == bitc::CST_CODE_CSTRING); 2344 break; 2345 } 2346 case bitc::CST_CODE_DATA: {// DATA: [n x value] 2347 if (Record.empty()) 2348 return error("Invalid record"); 2349 2350 Type *EltTy = cast<SequentialType>(CurTy)->getElementType(); 2351 unsigned Size = Record.size(); 2352 2353 if (EltTy->isIntegerTy(8)) { 2354 SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end()); 2355 if (isa<VectorType>(CurTy)) 2356 V = ConstantDataVector::get(Context, Elts); 2357 else 2358 V = ConstantDataArray::get(Context, Elts); 2359 } else if (EltTy->isIntegerTy(16)) { 2360 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end()); 2361 if (isa<VectorType>(CurTy)) 2362 V = ConstantDataVector::get(Context, Elts); 2363 else 2364 V = ConstantDataArray::get(Context, Elts); 2365 } else if (EltTy->isIntegerTy(32)) { 2366 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end()); 2367 if (isa<VectorType>(CurTy)) 2368 V = ConstantDataVector::get(Context, Elts); 2369 else 2370 V = ConstantDataArray::get(Context, Elts); 2371 } else if (EltTy->isIntegerTy(64)) { 2372 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end()); 2373 if (isa<VectorType>(CurTy)) 2374 V = ConstantDataVector::get(Context, Elts); 2375 else 2376 V = ConstantDataArray::get(Context, Elts); 2377 } else if (EltTy->isFloatTy()) { 2378 SmallVector<float, 16> Elts(Size); 2379 std::transform(Record.begin(), Record.end(), Elts.begin(), BitsToFloat); 2380 if (isa<VectorType>(CurTy)) 2381 V = ConstantDataVector::get(Context, Elts); 2382 else 2383 V = ConstantDataArray::get(Context, Elts); 2384 } else if (EltTy->isDoubleTy()) { 2385 SmallVector<double, 16> Elts(Size); 2386 std::transform(Record.begin(), Record.end(), Elts.begin(), 2387 BitsToDouble); 2388 if (isa<VectorType>(CurTy)) 2389 V = ConstantDataVector::get(Context, Elts); 2390 else 2391 V = ConstantDataArray::get(Context, Elts); 2392 } else { 2393 return error("Invalid type for value"); 2394 } 2395 break; 2396 } 2397 2398 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval] 2399 if (Record.size() < 3) 2400 return error("Invalid record"); 2401 int Opc = getDecodedBinaryOpcode(Record[0], CurTy); 2402 if (Opc < 0) { 2403 V = UndefValue::get(CurTy); // Unknown binop. 2404 } else { 2405 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy); 2406 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy); 2407 unsigned Flags = 0; 2408 if (Record.size() >= 4) { 2409 if (Opc == Instruction::Add || 2410 Opc == Instruction::Sub || 2411 Opc == Instruction::Mul || 2412 Opc == Instruction::Shl) { 2413 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP)) 2414 Flags |= OverflowingBinaryOperator::NoSignedWrap; 2415 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP)) 2416 Flags |= OverflowingBinaryOperator::NoUnsignedWrap; 2417 } else if (Opc == Instruction::SDiv || 2418 Opc == Instruction::UDiv || 2419 Opc == Instruction::LShr || 2420 Opc == Instruction::AShr) { 2421 if (Record[3] & (1 << bitc::PEO_EXACT)) 2422 Flags |= SDivOperator::IsExact; 2423 } 2424 } 2425 V = ConstantExpr::get(Opc, LHS, RHS, Flags); 2426 } 2427 break; 2428 } 2429 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval] 2430 if (Record.size() < 3) 2431 return error("Invalid record"); 2432 int Opc = getDecodedCastOpcode(Record[0]); 2433 if (Opc < 0) { 2434 V = UndefValue::get(CurTy); // Unknown cast. 2435 } else { 2436 Type *OpTy = getTypeByID(Record[1]); 2437 if (!OpTy) 2438 return error("Invalid record"); 2439 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy); 2440 V = UpgradeBitCastExpr(Opc, Op, CurTy); 2441 if (!V) V = ConstantExpr::getCast(Opc, Op, CurTy); 2442 } 2443 break; 2444 } 2445 case bitc::CST_CODE_CE_INBOUNDS_GEP: 2446 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands] 2447 unsigned OpNum = 0; 2448 Type *PointeeType = nullptr; 2449 if (Record.size() % 2) 2450 PointeeType = getTypeByID(Record[OpNum++]); 2451 SmallVector<Constant*, 16> Elts; 2452 while (OpNum != Record.size()) { 2453 Type *ElTy = getTypeByID(Record[OpNum++]); 2454 if (!ElTy) 2455 return error("Invalid record"); 2456 Elts.push_back(ValueList.getConstantFwdRef(Record[OpNum++], ElTy)); 2457 } 2458 2459 if (PointeeType && 2460 PointeeType != 2461 cast<SequentialType>(Elts[0]->getType()->getScalarType()) 2462 ->getElementType()) 2463 return error("Explicit gep operator type does not match pointee type " 2464 "of pointer operand"); 2465 2466 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end()); 2467 V = ConstantExpr::getGetElementPtr(PointeeType, Elts[0], Indices, 2468 BitCode == 2469 bitc::CST_CODE_CE_INBOUNDS_GEP); 2470 break; 2471 } 2472 case bitc::CST_CODE_CE_SELECT: { // CE_SELECT: [opval#, opval#, opval#] 2473 if (Record.size() < 3) 2474 return error("Invalid record"); 2475 2476 Type *SelectorTy = Type::getInt1Ty(Context); 2477 2478 // The selector might be an i1 or an <n x i1> 2479 // Get the type from the ValueList before getting a forward ref. 2480 if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) 2481 if (Value *V = ValueList[Record[0]]) 2482 if (SelectorTy != V->getType()) 2483 SelectorTy = VectorType::get(SelectorTy, VTy->getNumElements()); 2484 2485 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0], 2486 SelectorTy), 2487 ValueList.getConstantFwdRef(Record[1],CurTy), 2488 ValueList.getConstantFwdRef(Record[2],CurTy)); 2489 break; 2490 } 2491 case bitc::CST_CODE_CE_EXTRACTELT 2492 : { // CE_EXTRACTELT: [opty, opval, opty, opval] 2493 if (Record.size() < 3) 2494 return error("Invalid record"); 2495 VectorType *OpTy = 2496 dyn_cast_or_null<VectorType>(getTypeByID(Record[0])); 2497 if (!OpTy) 2498 return error("Invalid record"); 2499 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy); 2500 Constant *Op1 = nullptr; 2501 if (Record.size() == 4) { 2502 Type *IdxTy = getTypeByID(Record[2]); 2503 if (!IdxTy) 2504 return error("Invalid record"); 2505 Op1 = ValueList.getConstantFwdRef(Record[3], IdxTy); 2506 } else // TODO: Remove with llvm 4.0 2507 Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context)); 2508 if (!Op1) 2509 return error("Invalid record"); 2510 V = ConstantExpr::getExtractElement(Op0, Op1); 2511 break; 2512 } 2513 case bitc::CST_CODE_CE_INSERTELT 2514 : { // CE_INSERTELT: [opval, opval, opty, opval] 2515 VectorType *OpTy = dyn_cast<VectorType>(CurTy); 2516 if (Record.size() < 3 || !OpTy) 2517 return error("Invalid record"); 2518 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy); 2519 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], 2520 OpTy->getElementType()); 2521 Constant *Op2 = nullptr; 2522 if (Record.size() == 4) { 2523 Type *IdxTy = getTypeByID(Record[2]); 2524 if (!IdxTy) 2525 return error("Invalid record"); 2526 Op2 = ValueList.getConstantFwdRef(Record[3], IdxTy); 2527 } else // TODO: Remove with llvm 4.0 2528 Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context)); 2529 if (!Op2) 2530 return error("Invalid record"); 2531 V = ConstantExpr::getInsertElement(Op0, Op1, Op2); 2532 break; 2533 } 2534 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval] 2535 VectorType *OpTy = dyn_cast<VectorType>(CurTy); 2536 if (Record.size() < 3 || !OpTy) 2537 return error("Invalid record"); 2538 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy); 2539 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy); 2540 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context), 2541 OpTy->getNumElements()); 2542 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy); 2543 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2); 2544 break; 2545 } 2546 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval] 2547 VectorType *RTy = dyn_cast<VectorType>(CurTy); 2548 VectorType *OpTy = 2549 dyn_cast_or_null<VectorType>(getTypeByID(Record[0])); 2550 if (Record.size() < 4 || !RTy || !OpTy) 2551 return error("Invalid record"); 2552 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy); 2553 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy); 2554 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context), 2555 RTy->getNumElements()); 2556 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy); 2557 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2); 2558 break; 2559 } 2560 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred] 2561 if (Record.size() < 4) 2562 return error("Invalid record"); 2563 Type *OpTy = getTypeByID(Record[0]); 2564 if (!OpTy) 2565 return error("Invalid record"); 2566 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy); 2567 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy); 2568 2569 if (OpTy->isFPOrFPVectorTy()) 2570 V = ConstantExpr::getFCmp(Record[3], Op0, Op1); 2571 else 2572 V = ConstantExpr::getICmp(Record[3], Op0, Op1); 2573 break; 2574 } 2575 // This maintains backward compatibility, pre-asm dialect keywords. 2576 // FIXME: Remove with the 4.0 release. 2577 case bitc::CST_CODE_INLINEASM_OLD: { 2578 if (Record.size() < 2) 2579 return error("Invalid record"); 2580 std::string AsmStr, ConstrStr; 2581 bool HasSideEffects = Record[0] & 1; 2582 bool IsAlignStack = Record[0] >> 1; 2583 unsigned AsmStrSize = Record[1]; 2584 if (2+AsmStrSize >= Record.size()) 2585 return error("Invalid record"); 2586 unsigned ConstStrSize = Record[2+AsmStrSize]; 2587 if (3+AsmStrSize+ConstStrSize > Record.size()) 2588 return error("Invalid record"); 2589 2590 for (unsigned i = 0; i != AsmStrSize; ++i) 2591 AsmStr += (char)Record[2+i]; 2592 for (unsigned i = 0; i != ConstStrSize; ++i) 2593 ConstrStr += (char)Record[3+AsmStrSize+i]; 2594 PointerType *PTy = cast<PointerType>(CurTy); 2595 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()), 2596 AsmStr, ConstrStr, HasSideEffects, IsAlignStack); 2597 break; 2598 } 2599 // This version adds support for the asm dialect keywords (e.g., 2600 // inteldialect). 2601 case bitc::CST_CODE_INLINEASM: { 2602 if (Record.size() < 2) 2603 return error("Invalid record"); 2604 std::string AsmStr, ConstrStr; 2605 bool HasSideEffects = Record[0] & 1; 2606 bool IsAlignStack = (Record[0] >> 1) & 1; 2607 unsigned AsmDialect = Record[0] >> 2; 2608 unsigned AsmStrSize = Record[1]; 2609 if (2+AsmStrSize >= Record.size()) 2610 return error("Invalid record"); 2611 unsigned ConstStrSize = Record[2+AsmStrSize]; 2612 if (3+AsmStrSize+ConstStrSize > Record.size()) 2613 return error("Invalid record"); 2614 2615 for (unsigned i = 0; i != AsmStrSize; ++i) 2616 AsmStr += (char)Record[2+i]; 2617 for (unsigned i = 0; i != ConstStrSize; ++i) 2618 ConstrStr += (char)Record[3+AsmStrSize+i]; 2619 PointerType *PTy = cast<PointerType>(CurTy); 2620 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()), 2621 AsmStr, ConstrStr, HasSideEffects, IsAlignStack, 2622 InlineAsm::AsmDialect(AsmDialect)); 2623 break; 2624 } 2625 case bitc::CST_CODE_BLOCKADDRESS:{ 2626 if (Record.size() < 3) 2627 return error("Invalid record"); 2628 Type *FnTy = getTypeByID(Record[0]); 2629 if (!FnTy) 2630 return error("Invalid record"); 2631 Function *Fn = 2632 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy)); 2633 if (!Fn) 2634 return error("Invalid record"); 2635 2636 // Don't let Fn get dematerialized. 2637 BlockAddressesTaken.insert(Fn); 2638 2639 // If the function is already parsed we can insert the block address right 2640 // away. 2641 BasicBlock *BB; 2642 unsigned BBID = Record[2]; 2643 if (!BBID) 2644 // Invalid reference to entry block. 2645 return error("Invalid ID"); 2646 if (!Fn->empty()) { 2647 Function::iterator BBI = Fn->begin(), BBE = Fn->end(); 2648 for (size_t I = 0, E = BBID; I != E; ++I) { 2649 if (BBI == BBE) 2650 return error("Invalid ID"); 2651 ++BBI; 2652 } 2653 BB = BBI; 2654 } else { 2655 // Otherwise insert a placeholder and remember it so it can be inserted 2656 // when the function is parsed. 2657 auto &FwdBBs = BasicBlockFwdRefs[Fn]; 2658 if (FwdBBs.empty()) 2659 BasicBlockFwdRefQueue.push_back(Fn); 2660 if (FwdBBs.size() < BBID + 1) 2661 FwdBBs.resize(BBID + 1); 2662 if (!FwdBBs[BBID]) 2663 FwdBBs[BBID] = BasicBlock::Create(Context); 2664 BB = FwdBBs[BBID]; 2665 } 2666 V = BlockAddress::get(Fn, BB); 2667 break; 2668 } 2669 } 2670 2671 if (ValueList.assignValue(V, NextCstNo)) 2672 return error("Invalid forward reference"); 2673 ++NextCstNo; 2674 } 2675 } 2676 2677 std::error_code BitcodeReader::parseUseLists() { 2678 if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID)) 2679 return error("Invalid record"); 2680 2681 // Read all the records. 2682 SmallVector<uint64_t, 64> Record; 2683 while (1) { 2684 BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 2685 2686 switch (Entry.Kind) { 2687 case BitstreamEntry::SubBlock: // Handled for us already. 2688 case BitstreamEntry::Error: 2689 return error("Malformed block"); 2690 case BitstreamEntry::EndBlock: 2691 return std::error_code(); 2692 case BitstreamEntry::Record: 2693 // The interesting case. 2694 break; 2695 } 2696 2697 // Read a use list record. 2698 Record.clear(); 2699 bool IsBB = false; 2700 switch (Stream.readRecord(Entry.ID, Record)) { 2701 default: // Default behavior: unknown type. 2702 break; 2703 case bitc::USELIST_CODE_BB: 2704 IsBB = true; 2705 // fallthrough 2706 case bitc::USELIST_CODE_DEFAULT: { 2707 unsigned RecordLength = Record.size(); 2708 if (RecordLength < 3) 2709 // Records should have at least an ID and two indexes. 2710 return error("Invalid record"); 2711 unsigned ID = Record.back(); 2712 Record.pop_back(); 2713 2714 Value *V; 2715 if (IsBB) { 2716 assert(ID < FunctionBBs.size() && "Basic block not found"); 2717 V = FunctionBBs[ID]; 2718 } else 2719 V = ValueList[ID]; 2720 unsigned NumUses = 0; 2721 SmallDenseMap<const Use *, unsigned, 16> Order; 2722 for (const Use &U : V->uses()) { 2723 if (++NumUses > Record.size()) 2724 break; 2725 Order[&U] = Record[NumUses - 1]; 2726 } 2727 if (Order.size() != Record.size() || NumUses > Record.size()) 2728 // Mismatches can happen if the functions are being materialized lazily 2729 // (out-of-order), or a value has been upgraded. 2730 break; 2731 2732 V->sortUseList([&](const Use &L, const Use &R) { 2733 return Order.lookup(&L) < Order.lookup(&R); 2734 }); 2735 break; 2736 } 2737 } 2738 } 2739 } 2740 2741 /// When we see the block for metadata, remember where it is and then skip it. 2742 /// This lets us lazily deserialize the metadata. 2743 std::error_code BitcodeReader::rememberAndSkipMetadata() { 2744 // Save the current stream state. 2745 uint64_t CurBit = Stream.GetCurrentBitNo(); 2746 DeferredMetadataInfo.push_back(CurBit); 2747 2748 // Skip over the block for now. 2749 if (Stream.SkipBlock()) 2750 return error("Invalid record"); 2751 return std::error_code(); 2752 } 2753 2754 std::error_code BitcodeReader::materializeMetadata() { 2755 for (uint64_t BitPos : DeferredMetadataInfo) { 2756 // Move the bit stream to the saved position. 2757 Stream.JumpToBit(BitPos); 2758 if (std::error_code EC = parseMetadata()) 2759 return EC; 2760 } 2761 DeferredMetadataInfo.clear(); 2762 return std::error_code(); 2763 } 2764 2765 void BitcodeReader::setStripDebugInfo() { StripDebugInfo = true; } 2766 2767 /// When we see the block for a function body, remember where it is and then 2768 /// skip it. This lets us lazily deserialize the functions. 2769 std::error_code BitcodeReader::rememberAndSkipFunctionBody() { 2770 // Get the function we are talking about. 2771 if (FunctionsWithBodies.empty()) 2772 return error("Insufficient function protos"); 2773 2774 Function *Fn = FunctionsWithBodies.back(); 2775 FunctionsWithBodies.pop_back(); 2776 2777 // Save the current stream state. 2778 uint64_t CurBit = Stream.GetCurrentBitNo(); 2779 DeferredFunctionInfo[Fn] = CurBit; 2780 2781 // Skip over the function block for now. 2782 if (Stream.SkipBlock()) 2783 return error("Invalid record"); 2784 return std::error_code(); 2785 } 2786 2787 std::error_code BitcodeReader::globalCleanup() { 2788 // Patch the initializers for globals and aliases up. 2789 resolveGlobalAndAliasInits(); 2790 if (!GlobalInits.empty() || !AliasInits.empty()) 2791 return error("Malformed global initializer set"); 2792 2793 // Look for intrinsic functions which need to be upgraded at some point 2794 for (Function &F : *TheModule) { 2795 Function *NewFn; 2796 if (UpgradeIntrinsicFunction(&F, NewFn)) 2797 UpgradedIntrinsics[&F] = NewFn; 2798 } 2799 2800 // Look for global variables which need to be renamed. 2801 for (GlobalVariable &GV : TheModule->globals()) 2802 UpgradeGlobalVariable(&GV); 2803 2804 // Force deallocation of memory for these vectors to favor the client that 2805 // want lazy deserialization. 2806 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits); 2807 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits); 2808 return std::error_code(); 2809 } 2810 2811 std::error_code BitcodeReader::parseModule(bool Resume, 2812 bool ShouldLazyLoadMetadata) { 2813 if (Resume) 2814 Stream.JumpToBit(NextUnreadBit); 2815 else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID)) 2816 return error("Invalid record"); 2817 2818 SmallVector<uint64_t, 64> Record; 2819 std::vector<std::string> SectionTable; 2820 std::vector<std::string> GCTable; 2821 2822 // Read all the records for this module. 2823 while (1) { 2824 BitstreamEntry Entry = Stream.advance(); 2825 2826 switch (Entry.Kind) { 2827 case BitstreamEntry::Error: 2828 return error("Malformed block"); 2829 case BitstreamEntry::EndBlock: 2830 return globalCleanup(); 2831 2832 case BitstreamEntry::SubBlock: 2833 switch (Entry.ID) { 2834 default: // Skip unknown content. 2835 if (Stream.SkipBlock()) 2836 return error("Invalid record"); 2837 break; 2838 case bitc::BLOCKINFO_BLOCK_ID: 2839 if (Stream.ReadBlockInfoBlock()) 2840 return error("Malformed block"); 2841 break; 2842 case bitc::PARAMATTR_BLOCK_ID: 2843 if (std::error_code EC = parseAttributeBlock()) 2844 return EC; 2845 break; 2846 case bitc::PARAMATTR_GROUP_BLOCK_ID: 2847 if (std::error_code EC = parseAttributeGroupBlock()) 2848 return EC; 2849 break; 2850 case bitc::TYPE_BLOCK_ID_NEW: 2851 if (std::error_code EC = parseTypeTable()) 2852 return EC; 2853 break; 2854 case bitc::VALUE_SYMTAB_BLOCK_ID: 2855 if (std::error_code EC = parseValueSymbolTable()) 2856 return EC; 2857 SeenValueSymbolTable = true; 2858 break; 2859 case bitc::CONSTANTS_BLOCK_ID: 2860 if (std::error_code EC = parseConstants()) 2861 return EC; 2862 if (std::error_code EC = resolveGlobalAndAliasInits()) 2863 return EC; 2864 break; 2865 case bitc::METADATA_BLOCK_ID: 2866 if (ShouldLazyLoadMetadata && !IsMetadataMaterialized) { 2867 if (std::error_code EC = rememberAndSkipMetadata()) 2868 return EC; 2869 break; 2870 } 2871 assert(DeferredMetadataInfo.empty() && "Unexpected deferred metadata"); 2872 if (std::error_code EC = parseMetadata()) 2873 return EC; 2874 break; 2875 case bitc::FUNCTION_BLOCK_ID: 2876 // If this is the first function body we've seen, reverse the 2877 // FunctionsWithBodies list. 2878 if (!SeenFirstFunctionBody) { 2879 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end()); 2880 if (std::error_code EC = globalCleanup()) 2881 return EC; 2882 SeenFirstFunctionBody = true; 2883 } 2884 2885 if (std::error_code EC = rememberAndSkipFunctionBody()) 2886 return EC; 2887 // Suspend parsing when we reach the function bodies. Subsequent 2888 // materialization calls will resume it when necessary. If the bitcode 2889 // file is old, the symbol table will be at the end instead and will not 2890 // have been seen yet. In this case, just finish the parse now. 2891 if (SeenValueSymbolTable) { 2892 NextUnreadBit = Stream.GetCurrentBitNo(); 2893 return std::error_code(); 2894 } 2895 break; 2896 case bitc::USELIST_BLOCK_ID: 2897 if (std::error_code EC = parseUseLists()) 2898 return EC; 2899 break; 2900 } 2901 continue; 2902 2903 case BitstreamEntry::Record: 2904 // The interesting case. 2905 break; 2906 } 2907 2908 2909 // Read a record. 2910 switch (Stream.readRecord(Entry.ID, Record)) { 2911 default: break; // Default behavior, ignore unknown content. 2912 case bitc::MODULE_CODE_VERSION: { // VERSION: [version#] 2913 if (Record.size() < 1) 2914 return error("Invalid record"); 2915 // Only version #0 and #1 are supported so far. 2916 unsigned module_version = Record[0]; 2917 switch (module_version) { 2918 default: 2919 return error("Invalid value"); 2920 case 0: 2921 UseRelativeIDs = false; 2922 break; 2923 case 1: 2924 UseRelativeIDs = true; 2925 break; 2926 } 2927 break; 2928 } 2929 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N] 2930 std::string S; 2931 if (convertToString(Record, 0, S)) 2932 return error("Invalid record"); 2933 TheModule->setTargetTriple(S); 2934 break; 2935 } 2936 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N] 2937 std::string S; 2938 if (convertToString(Record, 0, S)) 2939 return error("Invalid record"); 2940 TheModule->setDataLayout(S); 2941 break; 2942 } 2943 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N] 2944 std::string S; 2945 if (convertToString(Record, 0, S)) 2946 return error("Invalid record"); 2947 TheModule->setModuleInlineAsm(S); 2948 break; 2949 } 2950 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N] 2951 // FIXME: Remove in 4.0. 2952 std::string S; 2953 if (convertToString(Record, 0, S)) 2954 return error("Invalid record"); 2955 // Ignore value. 2956 break; 2957 } 2958 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N] 2959 std::string S; 2960 if (convertToString(Record, 0, S)) 2961 return error("Invalid record"); 2962 SectionTable.push_back(S); 2963 break; 2964 } 2965 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N] 2966 std::string S; 2967 if (convertToString(Record, 0, S)) 2968 return error("Invalid record"); 2969 GCTable.push_back(S); 2970 break; 2971 } 2972 case bitc::MODULE_CODE_COMDAT: { // COMDAT: [selection_kind, name] 2973 if (Record.size() < 2) 2974 return error("Invalid record"); 2975 Comdat::SelectionKind SK = getDecodedComdatSelectionKind(Record[0]); 2976 unsigned ComdatNameSize = Record[1]; 2977 std::string ComdatName; 2978 ComdatName.reserve(ComdatNameSize); 2979 for (unsigned i = 0; i != ComdatNameSize; ++i) 2980 ComdatName += (char)Record[2 + i]; 2981 Comdat *C = TheModule->getOrInsertComdat(ComdatName); 2982 C->setSelectionKind(SK); 2983 ComdatList.push_back(C); 2984 break; 2985 } 2986 // GLOBALVAR: [pointer type, isconst, initid, 2987 // linkage, alignment, section, visibility, threadlocal, 2988 // unnamed_addr, externally_initialized, dllstorageclass, 2989 // comdat] 2990 case bitc::MODULE_CODE_GLOBALVAR: { 2991 if (Record.size() < 6) 2992 return error("Invalid record"); 2993 Type *Ty = getTypeByID(Record[0]); 2994 if (!Ty) 2995 return error("Invalid record"); 2996 bool isConstant = Record[1] & 1; 2997 bool explicitType = Record[1] & 2; 2998 unsigned AddressSpace; 2999 if (explicitType) { 3000 AddressSpace = Record[1] >> 2; 3001 } else { 3002 if (!Ty->isPointerTy()) 3003 return error("Invalid type for value"); 3004 AddressSpace = cast<PointerType>(Ty)->getAddressSpace(); 3005 Ty = cast<PointerType>(Ty)->getElementType(); 3006 } 3007 3008 uint64_t RawLinkage = Record[3]; 3009 GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage); 3010 unsigned Alignment; 3011 if (std::error_code EC = parseAlignmentValue(Record[4], Alignment)) 3012 return EC; 3013 std::string Section; 3014 if (Record[5]) { 3015 if (Record[5]-1 >= SectionTable.size()) 3016 return error("Invalid ID"); 3017 Section = SectionTable[Record[5]-1]; 3018 } 3019 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility; 3020 // Local linkage must have default visibility. 3021 if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage)) 3022 // FIXME: Change to an error if non-default in 4.0. 3023 Visibility = getDecodedVisibility(Record[6]); 3024 3025 GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal; 3026 if (Record.size() > 7) 3027 TLM = getDecodedThreadLocalMode(Record[7]); 3028 3029 bool UnnamedAddr = false; 3030 if (Record.size() > 8) 3031 UnnamedAddr = Record[8]; 3032 3033 bool ExternallyInitialized = false; 3034 if (Record.size() > 9) 3035 ExternallyInitialized = Record[9]; 3036 3037 GlobalVariable *NewGV = 3038 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, "", nullptr, 3039 TLM, AddressSpace, ExternallyInitialized); 3040 NewGV->setAlignment(Alignment); 3041 if (!Section.empty()) 3042 NewGV->setSection(Section); 3043 NewGV->setVisibility(Visibility); 3044 NewGV->setUnnamedAddr(UnnamedAddr); 3045 3046 if (Record.size() > 10) 3047 NewGV->setDLLStorageClass(getDecodedDLLStorageClass(Record[10])); 3048 else 3049 upgradeDLLImportExportLinkage(NewGV, RawLinkage); 3050 3051 ValueList.push_back(NewGV); 3052 3053 // Remember which value to use for the global initializer. 3054 if (unsigned InitID = Record[2]) 3055 GlobalInits.push_back(std::make_pair(NewGV, InitID-1)); 3056 3057 if (Record.size() > 11) { 3058 if (unsigned ComdatID = Record[11]) { 3059 if (ComdatID > ComdatList.size()) 3060 return error("Invalid global variable comdat ID"); 3061 NewGV->setComdat(ComdatList[ComdatID - 1]); 3062 } 3063 } else if (hasImplicitComdat(RawLinkage)) { 3064 NewGV->setComdat(reinterpret_cast<Comdat *>(1)); 3065 } 3066 break; 3067 } 3068 // FUNCTION: [type, callingconv, isproto, linkage, paramattr, 3069 // alignment, section, visibility, gc, unnamed_addr, 3070 // prologuedata, dllstorageclass, comdat, prefixdata] 3071 case bitc::MODULE_CODE_FUNCTION: { 3072 if (Record.size() < 8) 3073 return error("Invalid record"); 3074 Type *Ty = getTypeByID(Record[0]); 3075 if (!Ty) 3076 return error("Invalid record"); 3077 if (auto *PTy = dyn_cast<PointerType>(Ty)) 3078 Ty = PTy->getElementType(); 3079 auto *FTy = dyn_cast<FunctionType>(Ty); 3080 if (!FTy) 3081 return error("Invalid type for value"); 3082 3083 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage, 3084 "", TheModule); 3085 3086 Func->setCallingConv(static_cast<CallingConv::ID>(Record[1])); 3087 bool isProto = Record[2]; 3088 uint64_t RawLinkage = Record[3]; 3089 Func->setLinkage(getDecodedLinkage(RawLinkage)); 3090 Func->setAttributes(getAttributes(Record[4])); 3091 3092 unsigned Alignment; 3093 if (std::error_code EC = parseAlignmentValue(Record[5], Alignment)) 3094 return EC; 3095 Func->setAlignment(Alignment); 3096 if (Record[6]) { 3097 if (Record[6]-1 >= SectionTable.size()) 3098 return error("Invalid ID"); 3099 Func->setSection(SectionTable[Record[6]-1]); 3100 } 3101 // Local linkage must have default visibility. 3102 if (!Func->hasLocalLinkage()) 3103 // FIXME: Change to an error if non-default in 4.0. 3104 Func->setVisibility(getDecodedVisibility(Record[7])); 3105 if (Record.size() > 8 && Record[8]) { 3106 if (Record[8]-1 >= GCTable.size()) 3107 return error("Invalid ID"); 3108 Func->setGC(GCTable[Record[8]-1].c_str()); 3109 } 3110 bool UnnamedAddr = false; 3111 if (Record.size() > 9) 3112 UnnamedAddr = Record[9]; 3113 Func->setUnnamedAddr(UnnamedAddr); 3114 if (Record.size() > 10 && Record[10] != 0) 3115 FunctionPrologues.push_back(std::make_pair(Func, Record[10]-1)); 3116 3117 if (Record.size() > 11) 3118 Func->setDLLStorageClass(getDecodedDLLStorageClass(Record[11])); 3119 else 3120 upgradeDLLImportExportLinkage(Func, RawLinkage); 3121 3122 if (Record.size() > 12) { 3123 if (unsigned ComdatID = Record[12]) { 3124 if (ComdatID > ComdatList.size()) 3125 return error("Invalid function comdat ID"); 3126 Func->setComdat(ComdatList[ComdatID - 1]); 3127 } 3128 } else if (hasImplicitComdat(RawLinkage)) { 3129 Func->setComdat(reinterpret_cast<Comdat *>(1)); 3130 } 3131 3132 if (Record.size() > 13 && Record[13] != 0) 3133 FunctionPrefixes.push_back(std::make_pair(Func, Record[13]-1)); 3134 3135 if (Record.size() > 14 && Record[14] != 0) 3136 FunctionPersonalityFns.push_back(std::make_pair(Func, Record[14] - 1)); 3137 3138 ValueList.push_back(Func); 3139 3140 // If this is a function with a body, remember the prototype we are 3141 // creating now, so that we can match up the body with them later. 3142 if (!isProto) { 3143 Func->setIsMaterializable(true); 3144 FunctionsWithBodies.push_back(Func); 3145 DeferredFunctionInfo[Func] = 0; 3146 } 3147 break; 3148 } 3149 // ALIAS: [alias type, aliasee val#, linkage] 3150 // ALIAS: [alias type, aliasee val#, linkage, visibility, dllstorageclass] 3151 case bitc::MODULE_CODE_ALIAS: { 3152 if (Record.size() < 3) 3153 return error("Invalid record"); 3154 Type *Ty = getTypeByID(Record[0]); 3155 if (!Ty) 3156 return error("Invalid record"); 3157 auto *PTy = dyn_cast<PointerType>(Ty); 3158 if (!PTy) 3159 return error("Invalid type for value"); 3160 3161 auto *NewGA = 3162 GlobalAlias::create(PTy, getDecodedLinkage(Record[2]), "", TheModule); 3163 // Old bitcode files didn't have visibility field. 3164 // Local linkage must have default visibility. 3165 if (Record.size() > 3 && !NewGA->hasLocalLinkage()) 3166 // FIXME: Change to an error if non-default in 4.0. 3167 NewGA->setVisibility(getDecodedVisibility(Record[3])); 3168 if (Record.size() > 4) 3169 NewGA->setDLLStorageClass(getDecodedDLLStorageClass(Record[4])); 3170 else 3171 upgradeDLLImportExportLinkage(NewGA, Record[2]); 3172 if (Record.size() > 5) 3173 NewGA->setThreadLocalMode(getDecodedThreadLocalMode(Record[5])); 3174 if (Record.size() > 6) 3175 NewGA->setUnnamedAddr(Record[6]); 3176 ValueList.push_back(NewGA); 3177 AliasInits.push_back(std::make_pair(NewGA, Record[1])); 3178 break; 3179 } 3180 /// MODULE_CODE_PURGEVALS: [numvals] 3181 case bitc::MODULE_CODE_PURGEVALS: 3182 // Trim down the value list to the specified size. 3183 if (Record.size() < 1 || Record[0] > ValueList.size()) 3184 return error("Invalid record"); 3185 ValueList.shrinkTo(Record[0]); 3186 break; 3187 } 3188 Record.clear(); 3189 } 3190 } 3191 3192 std::error_code 3193 BitcodeReader::parseBitcodeInto(std::unique_ptr<DataStreamer> Streamer, 3194 Module *M, bool ShouldLazyLoadMetadata) { 3195 TheModule = M; 3196 3197 if (std::error_code EC = initStream(std::move(Streamer))) 3198 return EC; 3199 3200 // Sniff for the signature. 3201 if (Stream.Read(8) != 'B' || 3202 Stream.Read(8) != 'C' || 3203 Stream.Read(4) != 0x0 || 3204 Stream.Read(4) != 0xC || 3205 Stream.Read(4) != 0xE || 3206 Stream.Read(4) != 0xD) 3207 return error("Invalid bitcode signature"); 3208 3209 // We expect a number of well-defined blocks, though we don't necessarily 3210 // need to understand them all. 3211 while (1) { 3212 if (Stream.AtEndOfStream()) { 3213 // We didn't really read a proper Module. 3214 return error("Malformed IR file"); 3215 } 3216 3217 BitstreamEntry Entry = 3218 Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs); 3219 3220 if (Entry.Kind != BitstreamEntry::SubBlock) 3221 return error("Malformed block"); 3222 3223 if (Entry.ID == bitc::MODULE_BLOCK_ID) 3224 return parseModule(false, ShouldLazyLoadMetadata); 3225 3226 if (Stream.SkipBlock()) 3227 return error("Invalid record"); 3228 } 3229 } 3230 3231 ErrorOr<std::string> BitcodeReader::parseModuleTriple() { 3232 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID)) 3233 return error("Invalid record"); 3234 3235 SmallVector<uint64_t, 64> Record; 3236 3237 std::string Triple; 3238 // Read all the records for this module. 3239 while (1) { 3240 BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 3241 3242 switch (Entry.Kind) { 3243 case BitstreamEntry::SubBlock: // Handled for us already. 3244 case BitstreamEntry::Error: 3245 return error("Malformed block"); 3246 case BitstreamEntry::EndBlock: 3247 return Triple; 3248 case BitstreamEntry::Record: 3249 // The interesting case. 3250 break; 3251 } 3252 3253 // Read a record. 3254 switch (Stream.readRecord(Entry.ID, Record)) { 3255 default: break; // Default behavior, ignore unknown content. 3256 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N] 3257 std::string S; 3258 if (convertToString(Record, 0, S)) 3259 return error("Invalid record"); 3260 Triple = S; 3261 break; 3262 } 3263 } 3264 Record.clear(); 3265 } 3266 llvm_unreachable("Exit infinite loop"); 3267 } 3268 3269 ErrorOr<std::string> BitcodeReader::parseTriple() { 3270 if (std::error_code EC = initStream(nullptr)) 3271 return EC; 3272 3273 // Sniff for the signature. 3274 if (Stream.Read(8) != 'B' || 3275 Stream.Read(8) != 'C' || 3276 Stream.Read(4) != 0x0 || 3277 Stream.Read(4) != 0xC || 3278 Stream.Read(4) != 0xE || 3279 Stream.Read(4) != 0xD) 3280 return error("Invalid bitcode signature"); 3281 3282 // We expect a number of well-defined blocks, though we don't necessarily 3283 // need to understand them all. 3284 while (1) { 3285 BitstreamEntry Entry = Stream.advance(); 3286 3287 switch (Entry.Kind) { 3288 case BitstreamEntry::Error: 3289 return error("Malformed block"); 3290 case BitstreamEntry::EndBlock: 3291 return std::error_code(); 3292 3293 case BitstreamEntry::SubBlock: 3294 if (Entry.ID == bitc::MODULE_BLOCK_ID) 3295 return parseModuleTriple(); 3296 3297 // Ignore other sub-blocks. 3298 if (Stream.SkipBlock()) 3299 return error("Malformed block"); 3300 continue; 3301 3302 case BitstreamEntry::Record: 3303 Stream.skipRecord(Entry.ID); 3304 continue; 3305 } 3306 } 3307 } 3308 3309 /// Parse metadata attachments. 3310 std::error_code BitcodeReader::parseMetadataAttachment(Function &F) { 3311 if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID)) 3312 return error("Invalid record"); 3313 3314 SmallVector<uint64_t, 64> Record; 3315 while (1) { 3316 BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 3317 3318 switch (Entry.Kind) { 3319 case BitstreamEntry::SubBlock: // Handled for us already. 3320 case BitstreamEntry::Error: 3321 return error("Malformed block"); 3322 case BitstreamEntry::EndBlock: 3323 return std::error_code(); 3324 case BitstreamEntry::Record: 3325 // The interesting case. 3326 break; 3327 } 3328 3329 // Read a metadata attachment record. 3330 Record.clear(); 3331 switch (Stream.readRecord(Entry.ID, Record)) { 3332 default: // Default behavior: ignore. 3333 break; 3334 case bitc::METADATA_ATTACHMENT: { 3335 unsigned RecordLength = Record.size(); 3336 if (Record.empty()) 3337 return error("Invalid record"); 3338 if (RecordLength % 2 == 0) { 3339 // A function attachment. 3340 for (unsigned I = 0; I != RecordLength; I += 2) { 3341 auto K = MDKindMap.find(Record[I]); 3342 if (K == MDKindMap.end()) 3343 return error("Invalid ID"); 3344 Metadata *MD = MDValueList.getValueFwdRef(Record[I + 1]); 3345 F.setMetadata(K->second, cast<MDNode>(MD)); 3346 } 3347 continue; 3348 } 3349 3350 // An instruction attachment. 3351 Instruction *Inst = InstructionList[Record[0]]; 3352 for (unsigned i = 1; i != RecordLength; i = i+2) { 3353 unsigned Kind = Record[i]; 3354 DenseMap<unsigned, unsigned>::iterator I = 3355 MDKindMap.find(Kind); 3356 if (I == MDKindMap.end()) 3357 return error("Invalid ID"); 3358 Metadata *Node = MDValueList.getValueFwdRef(Record[i + 1]); 3359 if (isa<LocalAsMetadata>(Node)) 3360 // Drop the attachment. This used to be legal, but there's no 3361 // upgrade path. 3362 break; 3363 Inst->setMetadata(I->second, cast<MDNode>(Node)); 3364 if (I->second == LLVMContext::MD_tbaa) 3365 InstsWithTBAATag.push_back(Inst); 3366 } 3367 break; 3368 } 3369 } 3370 } 3371 } 3372 3373 static std::error_code typeCheckLoadStoreInst(DiagnosticHandlerFunction DH, 3374 Type *ValType, Type *PtrType) { 3375 if (!isa<PointerType>(PtrType)) 3376 return error(DH, "Load/Store operand is not a pointer type"); 3377 Type *ElemType = cast<PointerType>(PtrType)->getElementType(); 3378 3379 if (ValType && ValType != ElemType) 3380 return error(DH, "Explicit load/store type does not match pointee type of " 3381 "pointer operand"); 3382 if (!PointerType::isLoadableOrStorableType(ElemType)) 3383 return error(DH, "Cannot load/store from pointer"); 3384 return std::error_code(); 3385 } 3386 3387 /// Lazily parse the specified function body block. 3388 std::error_code BitcodeReader::parseFunctionBody(Function *F) { 3389 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID)) 3390 return error("Invalid record"); 3391 3392 InstructionList.clear(); 3393 unsigned ModuleValueListSize = ValueList.size(); 3394 unsigned ModuleMDValueListSize = MDValueList.size(); 3395 3396 // Add all the function arguments to the value table. 3397 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I) 3398 ValueList.push_back(I); 3399 3400 unsigned NextValueNo = ValueList.size(); 3401 BasicBlock *CurBB = nullptr; 3402 unsigned CurBBNo = 0; 3403 3404 DebugLoc LastLoc; 3405 auto getLastInstruction = [&]() -> Instruction * { 3406 if (CurBB && !CurBB->empty()) 3407 return &CurBB->back(); 3408 else if (CurBBNo && FunctionBBs[CurBBNo - 1] && 3409 !FunctionBBs[CurBBNo - 1]->empty()) 3410 return &FunctionBBs[CurBBNo - 1]->back(); 3411 return nullptr; 3412 }; 3413 3414 // Read all the records. 3415 SmallVector<uint64_t, 64> Record; 3416 while (1) { 3417 BitstreamEntry Entry = Stream.advance(); 3418 3419 switch (Entry.Kind) { 3420 case BitstreamEntry::Error: 3421 return error("Malformed block"); 3422 case BitstreamEntry::EndBlock: 3423 goto OutOfRecordLoop; 3424 3425 case BitstreamEntry::SubBlock: 3426 switch (Entry.ID) { 3427 default: // Skip unknown content. 3428 if (Stream.SkipBlock()) 3429 return error("Invalid record"); 3430 break; 3431 case bitc::CONSTANTS_BLOCK_ID: 3432 if (std::error_code EC = parseConstants()) 3433 return EC; 3434 NextValueNo = ValueList.size(); 3435 break; 3436 case bitc::VALUE_SYMTAB_BLOCK_ID: 3437 if (std::error_code EC = parseValueSymbolTable()) 3438 return EC; 3439 break; 3440 case bitc::METADATA_ATTACHMENT_ID: 3441 if (std::error_code EC = parseMetadataAttachment(*F)) 3442 return EC; 3443 break; 3444 case bitc::METADATA_BLOCK_ID: 3445 if (std::error_code EC = parseMetadata()) 3446 return EC; 3447 break; 3448 case bitc::USELIST_BLOCK_ID: 3449 if (std::error_code EC = parseUseLists()) 3450 return EC; 3451 break; 3452 } 3453 continue; 3454 3455 case BitstreamEntry::Record: 3456 // The interesting case. 3457 break; 3458 } 3459 3460 // Read a record. 3461 Record.clear(); 3462 Instruction *I = nullptr; 3463 unsigned BitCode = Stream.readRecord(Entry.ID, Record); 3464 switch (BitCode) { 3465 default: // Default behavior: reject 3466 return error("Invalid value"); 3467 case bitc::FUNC_CODE_DECLAREBLOCKS: { // DECLAREBLOCKS: [nblocks] 3468 if (Record.size() < 1 || Record[0] == 0) 3469 return error("Invalid record"); 3470 // Create all the basic blocks for the function. 3471 FunctionBBs.resize(Record[0]); 3472 3473 // See if anything took the address of blocks in this function. 3474 auto BBFRI = BasicBlockFwdRefs.find(F); 3475 if (BBFRI == BasicBlockFwdRefs.end()) { 3476 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i) 3477 FunctionBBs[i] = BasicBlock::Create(Context, "", F); 3478 } else { 3479 auto &BBRefs = BBFRI->second; 3480 // Check for invalid basic block references. 3481 if (BBRefs.size() > FunctionBBs.size()) 3482 return error("Invalid ID"); 3483 assert(!BBRefs.empty() && "Unexpected empty array"); 3484 assert(!BBRefs.front() && "Invalid reference to entry block"); 3485 for (unsigned I = 0, E = FunctionBBs.size(), RE = BBRefs.size(); I != E; 3486 ++I) 3487 if (I < RE && BBRefs[I]) { 3488 BBRefs[I]->insertInto(F); 3489 FunctionBBs[I] = BBRefs[I]; 3490 } else { 3491 FunctionBBs[I] = BasicBlock::Create(Context, "", F); 3492 } 3493 3494 // Erase from the table. 3495 BasicBlockFwdRefs.erase(BBFRI); 3496 } 3497 3498 CurBB = FunctionBBs[0]; 3499 continue; 3500 } 3501 3502 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN 3503 // This record indicates that the last instruction is at the same 3504 // location as the previous instruction with a location. 3505 I = getLastInstruction(); 3506 3507 if (!I) 3508 return error("Invalid record"); 3509 I->setDebugLoc(LastLoc); 3510 I = nullptr; 3511 continue; 3512 3513 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia] 3514 I = getLastInstruction(); 3515 if (!I || Record.size() < 4) 3516 return error("Invalid record"); 3517 3518 unsigned Line = Record[0], Col = Record[1]; 3519 unsigned ScopeID = Record[2], IAID = Record[3]; 3520 3521 MDNode *Scope = nullptr, *IA = nullptr; 3522 if (ScopeID) Scope = cast<MDNode>(MDValueList.getValueFwdRef(ScopeID-1)); 3523 if (IAID) IA = cast<MDNode>(MDValueList.getValueFwdRef(IAID-1)); 3524 LastLoc = DebugLoc::get(Line, Col, Scope, IA); 3525 I->setDebugLoc(LastLoc); 3526 I = nullptr; 3527 continue; 3528 } 3529 3530 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode] 3531 unsigned OpNum = 0; 3532 Value *LHS, *RHS; 3533 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) || 3534 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) || 3535 OpNum+1 > Record.size()) 3536 return error("Invalid record"); 3537 3538 int Opc = getDecodedBinaryOpcode(Record[OpNum++], LHS->getType()); 3539 if (Opc == -1) 3540 return error("Invalid record"); 3541 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS); 3542 InstructionList.push_back(I); 3543 if (OpNum < Record.size()) { 3544 if (Opc == Instruction::Add || 3545 Opc == Instruction::Sub || 3546 Opc == Instruction::Mul || 3547 Opc == Instruction::Shl) { 3548 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP)) 3549 cast<BinaryOperator>(I)->setHasNoSignedWrap(true); 3550 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP)) 3551 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true); 3552 } else if (Opc == Instruction::SDiv || 3553 Opc == Instruction::UDiv || 3554 Opc == Instruction::LShr || 3555 Opc == Instruction::AShr) { 3556 if (Record[OpNum] & (1 << bitc::PEO_EXACT)) 3557 cast<BinaryOperator>(I)->setIsExact(true); 3558 } else if (isa<FPMathOperator>(I)) { 3559 FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]); 3560 if (FMF.any()) 3561 I->setFastMathFlags(FMF); 3562 } 3563 3564 } 3565 break; 3566 } 3567 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc] 3568 unsigned OpNum = 0; 3569 Value *Op; 3570 if (getValueTypePair(Record, OpNum, NextValueNo, Op) || 3571 OpNum+2 != Record.size()) 3572 return error("Invalid record"); 3573 3574 Type *ResTy = getTypeByID(Record[OpNum]); 3575 int Opc = getDecodedCastOpcode(Record[OpNum + 1]); 3576 if (Opc == -1 || !ResTy) 3577 return error("Invalid record"); 3578 Instruction *Temp = nullptr; 3579 if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) { 3580 if (Temp) { 3581 InstructionList.push_back(Temp); 3582 CurBB->getInstList().push_back(Temp); 3583 } 3584 } else { 3585 I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy); 3586 } 3587 InstructionList.push_back(I); 3588 break; 3589 } 3590 case bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD: 3591 case bitc::FUNC_CODE_INST_GEP_OLD: 3592 case bitc::FUNC_CODE_INST_GEP: { // GEP: type, [n x operands] 3593 unsigned OpNum = 0; 3594 3595 Type *Ty; 3596 bool InBounds; 3597 3598 if (BitCode == bitc::FUNC_CODE_INST_GEP) { 3599 InBounds = Record[OpNum++]; 3600 Ty = getTypeByID(Record[OpNum++]); 3601 } else { 3602 InBounds = BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD; 3603 Ty = nullptr; 3604 } 3605 3606 Value *BasePtr; 3607 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr)) 3608 return error("Invalid record"); 3609 3610 if (!Ty) 3611 Ty = cast<SequentialType>(BasePtr->getType()->getScalarType()) 3612 ->getElementType(); 3613 else if (Ty != 3614 cast<SequentialType>(BasePtr->getType()->getScalarType()) 3615 ->getElementType()) 3616 return error( 3617 "Explicit gep type does not match pointee type of pointer operand"); 3618 3619 SmallVector<Value*, 16> GEPIdx; 3620 while (OpNum != Record.size()) { 3621 Value *Op; 3622 if (getValueTypePair(Record, OpNum, NextValueNo, Op)) 3623 return error("Invalid record"); 3624 GEPIdx.push_back(Op); 3625 } 3626 3627 I = GetElementPtrInst::Create(Ty, BasePtr, GEPIdx); 3628 3629 InstructionList.push_back(I); 3630 if (InBounds) 3631 cast<GetElementPtrInst>(I)->setIsInBounds(true); 3632 break; 3633 } 3634 3635 case bitc::FUNC_CODE_INST_EXTRACTVAL: { 3636 // EXTRACTVAL: [opty, opval, n x indices] 3637 unsigned OpNum = 0; 3638 Value *Agg; 3639 if (getValueTypePair(Record, OpNum, NextValueNo, Agg)) 3640 return error("Invalid record"); 3641 3642 unsigned RecSize = Record.size(); 3643 if (OpNum == RecSize) 3644 return error("EXTRACTVAL: Invalid instruction with 0 indices"); 3645 3646 SmallVector<unsigned, 4> EXTRACTVALIdx; 3647 Type *CurTy = Agg->getType(); 3648 for (; OpNum != RecSize; ++OpNum) { 3649 bool IsArray = CurTy->isArrayTy(); 3650 bool IsStruct = CurTy->isStructTy(); 3651 uint64_t Index = Record[OpNum]; 3652 3653 if (!IsStruct && !IsArray) 3654 return error("EXTRACTVAL: Invalid type"); 3655 if ((unsigned)Index != Index) 3656 return error("Invalid value"); 3657 if (IsStruct && Index >= CurTy->subtypes().size()) 3658 return error("EXTRACTVAL: Invalid struct index"); 3659 if (IsArray && Index >= CurTy->getArrayNumElements()) 3660 return error("EXTRACTVAL: Invalid array index"); 3661 EXTRACTVALIdx.push_back((unsigned)Index); 3662 3663 if (IsStruct) 3664 CurTy = CurTy->subtypes()[Index]; 3665 else 3666 CurTy = CurTy->subtypes()[0]; 3667 } 3668 3669 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx); 3670 InstructionList.push_back(I); 3671 break; 3672 } 3673 3674 case bitc::FUNC_CODE_INST_INSERTVAL: { 3675 // INSERTVAL: [opty, opval, opty, opval, n x indices] 3676 unsigned OpNum = 0; 3677 Value *Agg; 3678 if (getValueTypePair(Record, OpNum, NextValueNo, Agg)) 3679 return error("Invalid record"); 3680 Value *Val; 3681 if (getValueTypePair(Record, OpNum, NextValueNo, Val)) 3682 return error("Invalid record"); 3683 3684 unsigned RecSize = Record.size(); 3685 if (OpNum == RecSize) 3686 return error("INSERTVAL: Invalid instruction with 0 indices"); 3687 3688 SmallVector<unsigned, 4> INSERTVALIdx; 3689 Type *CurTy = Agg->getType(); 3690 for (; OpNum != RecSize; ++OpNum) { 3691 bool IsArray = CurTy->isArrayTy(); 3692 bool IsStruct = CurTy->isStructTy(); 3693 uint64_t Index = Record[OpNum]; 3694 3695 if (!IsStruct && !IsArray) 3696 return error("INSERTVAL: Invalid type"); 3697 if ((unsigned)Index != Index) 3698 return error("Invalid value"); 3699 if (IsStruct && Index >= CurTy->subtypes().size()) 3700 return error("INSERTVAL: Invalid struct index"); 3701 if (IsArray && Index >= CurTy->getArrayNumElements()) 3702 return error("INSERTVAL: Invalid array index"); 3703 3704 INSERTVALIdx.push_back((unsigned)Index); 3705 if (IsStruct) 3706 CurTy = CurTy->subtypes()[Index]; 3707 else 3708 CurTy = CurTy->subtypes()[0]; 3709 } 3710 3711 if (CurTy != Val->getType()) 3712 return error("Inserted value type doesn't match aggregate type"); 3713 3714 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx); 3715 InstructionList.push_back(I); 3716 break; 3717 } 3718 3719 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval] 3720 // obsolete form of select 3721 // handles select i1 ... in old bitcode 3722 unsigned OpNum = 0; 3723 Value *TrueVal, *FalseVal, *Cond; 3724 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) || 3725 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) || 3726 popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond)) 3727 return error("Invalid record"); 3728 3729 I = SelectInst::Create(Cond, TrueVal, FalseVal); 3730 InstructionList.push_back(I); 3731 break; 3732 } 3733 3734 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred] 3735 // new form of select 3736 // handles select i1 or select [N x i1] 3737 unsigned OpNum = 0; 3738 Value *TrueVal, *FalseVal, *Cond; 3739 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) || 3740 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) || 3741 getValueTypePair(Record, OpNum, NextValueNo, Cond)) 3742 return error("Invalid record"); 3743 3744 // select condition can be either i1 or [N x i1] 3745 if (VectorType* vector_type = 3746 dyn_cast<VectorType>(Cond->getType())) { 3747 // expect <n x i1> 3748 if (vector_type->getElementType() != Type::getInt1Ty(Context)) 3749 return error("Invalid type for value"); 3750 } else { 3751 // expect i1 3752 if (Cond->getType() != Type::getInt1Ty(Context)) 3753 return error("Invalid type for value"); 3754 } 3755 3756 I = SelectInst::Create(Cond, TrueVal, FalseVal); 3757 InstructionList.push_back(I); 3758 break; 3759 } 3760 3761 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval] 3762 unsigned OpNum = 0; 3763 Value *Vec, *Idx; 3764 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) || 3765 getValueTypePair(Record, OpNum, NextValueNo, Idx)) 3766 return error("Invalid record"); 3767 if (!Vec->getType()->isVectorTy()) 3768 return error("Invalid type for value"); 3769 I = ExtractElementInst::Create(Vec, Idx); 3770 InstructionList.push_back(I); 3771 break; 3772 } 3773 3774 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval] 3775 unsigned OpNum = 0; 3776 Value *Vec, *Elt, *Idx; 3777 if (getValueTypePair(Record, OpNum, NextValueNo, Vec)) 3778 return error("Invalid record"); 3779 if (!Vec->getType()->isVectorTy()) 3780 return error("Invalid type for value"); 3781 if (popValue(Record, OpNum, NextValueNo, 3782 cast<VectorType>(Vec->getType())->getElementType(), Elt) || 3783 getValueTypePair(Record, OpNum, NextValueNo, Idx)) 3784 return error("Invalid record"); 3785 I = InsertElementInst::Create(Vec, Elt, Idx); 3786 InstructionList.push_back(I); 3787 break; 3788 } 3789 3790 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval] 3791 unsigned OpNum = 0; 3792 Value *Vec1, *Vec2, *Mask; 3793 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) || 3794 popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2)) 3795 return error("Invalid record"); 3796 3797 if (getValueTypePair(Record, OpNum, NextValueNo, Mask)) 3798 return error("Invalid record"); 3799 if (!Vec1->getType()->isVectorTy() || !Vec2->getType()->isVectorTy()) 3800 return error("Invalid type for value"); 3801 I = new ShuffleVectorInst(Vec1, Vec2, Mask); 3802 InstructionList.push_back(I); 3803 break; 3804 } 3805 3806 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred] 3807 // Old form of ICmp/FCmp returning bool 3808 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were 3809 // both legal on vectors but had different behaviour. 3810 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred] 3811 // FCmp/ICmp returning bool or vector of bool 3812 3813 unsigned OpNum = 0; 3814 Value *LHS, *RHS; 3815 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) || 3816 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS)) 3817 return error("Invalid record"); 3818 3819 unsigned PredVal = Record[OpNum]; 3820 bool IsFP = LHS->getType()->isFPOrFPVectorTy(); 3821 FastMathFlags FMF; 3822 if (IsFP && Record.size() > OpNum+1) 3823 FMF = getDecodedFastMathFlags(Record[++OpNum]); 3824 3825 if (OpNum+1 != Record.size()) 3826 return error("Invalid record"); 3827 3828 if (LHS->getType()->isFPOrFPVectorTy()) 3829 I = new FCmpInst((FCmpInst::Predicate)PredVal, LHS, RHS); 3830 else 3831 I = new ICmpInst((ICmpInst::Predicate)PredVal, LHS, RHS); 3832 3833 if (FMF.any()) 3834 I->setFastMathFlags(FMF); 3835 InstructionList.push_back(I); 3836 break; 3837 } 3838 3839 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>] 3840 { 3841 unsigned Size = Record.size(); 3842 if (Size == 0) { 3843 I = ReturnInst::Create(Context); 3844 InstructionList.push_back(I); 3845 break; 3846 } 3847 3848 unsigned OpNum = 0; 3849 Value *Op = nullptr; 3850 if (getValueTypePair(Record, OpNum, NextValueNo, Op)) 3851 return error("Invalid record"); 3852 if (OpNum != Record.size()) 3853 return error("Invalid record"); 3854 3855 I = ReturnInst::Create(Context, Op); 3856 InstructionList.push_back(I); 3857 break; 3858 } 3859 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#] 3860 if (Record.size() != 1 && Record.size() != 3) 3861 return error("Invalid record"); 3862 BasicBlock *TrueDest = getBasicBlock(Record[0]); 3863 if (!TrueDest) 3864 return error("Invalid record"); 3865 3866 if (Record.size() == 1) { 3867 I = BranchInst::Create(TrueDest); 3868 InstructionList.push_back(I); 3869 } 3870 else { 3871 BasicBlock *FalseDest = getBasicBlock(Record[1]); 3872 Value *Cond = getValue(Record, 2, NextValueNo, 3873 Type::getInt1Ty(Context)); 3874 if (!FalseDest || !Cond) 3875 return error("Invalid record"); 3876 I = BranchInst::Create(TrueDest, FalseDest, Cond); 3877 InstructionList.push_back(I); 3878 } 3879 break; 3880 } 3881 case bitc::FUNC_CODE_INST_CLEANUPRET: { // CLEANUPRET: [val] or [val,bb#] 3882 if (Record.size() != 1 && Record.size() != 2) 3883 return error("Invalid record"); 3884 unsigned Idx = 0; 3885 Value *CleanupPad = getValue(Record, Idx++, NextValueNo, 3886 Type::getTokenTy(Context), OC_CleanupPad); 3887 if (!CleanupPad) 3888 return error("Invalid record"); 3889 BasicBlock *UnwindDest = nullptr; 3890 if (Record.size() == 2) { 3891 UnwindDest = getBasicBlock(Record[Idx++]); 3892 if (!UnwindDest) 3893 return error("Invalid record"); 3894 } 3895 3896 I = CleanupReturnInst::Create(cast<CleanupPadInst>(CleanupPad), 3897 UnwindDest); 3898 InstructionList.push_back(I); 3899 break; 3900 } 3901 case bitc::FUNC_CODE_INST_CATCHRET: { // CATCHRET: [val,bb#] 3902 if (Record.size() != 2) 3903 return error("Invalid record"); 3904 unsigned Idx = 0; 3905 Value *CatchPad = getValue(Record, Idx++, NextValueNo, 3906 Type::getTokenTy(Context), OC_CatchPad); 3907 if (!CatchPad) 3908 return error("Invalid record"); 3909 BasicBlock *BB = getBasicBlock(Record[Idx++]); 3910 if (!BB) 3911 return error("Invalid record"); 3912 3913 I = CatchReturnInst::Create(cast<CatchPadInst>(CatchPad), BB); 3914 InstructionList.push_back(I); 3915 break; 3916 } 3917 case bitc::FUNC_CODE_INST_CATCHPAD: { // CATCHPAD: [bb#,bb#,num,(ty,val)*] 3918 if (Record.size() < 3) 3919 return error("Invalid record"); 3920 unsigned Idx = 0; 3921 BasicBlock *NormalBB = getBasicBlock(Record[Idx++]); 3922 if (!NormalBB) 3923 return error("Invalid record"); 3924 BasicBlock *UnwindBB = getBasicBlock(Record[Idx++]); 3925 if (!UnwindBB) 3926 return error("Invalid record"); 3927 unsigned NumArgOperands = Record[Idx++]; 3928 SmallVector<Value *, 2> Args; 3929 for (unsigned Op = 0; Op != NumArgOperands; ++Op) { 3930 Value *Val; 3931 if (getValueTypePair(Record, Idx, NextValueNo, Val)) 3932 return error("Invalid record"); 3933 Args.push_back(Val); 3934 } 3935 if (Record.size() != Idx) 3936 return error("Invalid record"); 3937 3938 I = CatchPadInst::Create(NormalBB, UnwindBB, Args); 3939 InstructionList.push_back(I); 3940 break; 3941 } 3942 case bitc::FUNC_CODE_INST_TERMINATEPAD: { // TERMINATEPAD: [bb#,num,(ty,val)*] 3943 if (Record.size() < 1) 3944 return error("Invalid record"); 3945 unsigned Idx = 0; 3946 bool HasUnwindDest = !!Record[Idx++]; 3947 BasicBlock *UnwindDest = nullptr; 3948 if (HasUnwindDest) { 3949 if (Idx == Record.size()) 3950 return error("Invalid record"); 3951 UnwindDest = getBasicBlock(Record[Idx++]); 3952 if (!UnwindDest) 3953 return error("Invalid record"); 3954 } 3955 unsigned NumArgOperands = Record[Idx++]; 3956 SmallVector<Value *, 2> Args; 3957 for (unsigned Op = 0; Op != NumArgOperands; ++Op) { 3958 Value *Val; 3959 if (getValueTypePair(Record, Idx, NextValueNo, Val)) 3960 return error("Invalid record"); 3961 Args.push_back(Val); 3962 } 3963 if (Record.size() != Idx) 3964 return error("Invalid record"); 3965 3966 I = TerminatePadInst::Create(Context, UnwindDest, Args); 3967 InstructionList.push_back(I); 3968 break; 3969 } 3970 case bitc::FUNC_CODE_INST_CLEANUPPAD: { // CLEANUPPAD: [num,(ty,val)*] 3971 if (Record.size() < 1) 3972 return error("Invalid record"); 3973 unsigned Idx = 0; 3974 unsigned NumArgOperands = Record[Idx++]; 3975 SmallVector<Value *, 2> Args; 3976 for (unsigned Op = 0; Op != NumArgOperands; ++Op) { 3977 Value *Val; 3978 if (getValueTypePair(Record, Idx, NextValueNo, Val)) 3979 return error("Invalid record"); 3980 Args.push_back(Val); 3981 } 3982 if (Record.size() != Idx) 3983 return error("Invalid record"); 3984 3985 I = CleanupPadInst::Create(Context, Args); 3986 InstructionList.push_back(I); 3987 break; 3988 } 3989 case bitc::FUNC_CODE_INST_CATCHENDPAD: { // CATCHENDPADINST: [bb#] or [] 3990 if (Record.size() > 1) 3991 return error("Invalid record"); 3992 BasicBlock *BB = nullptr; 3993 if (Record.size() == 1) { 3994 BB = getBasicBlock(Record[0]); 3995 if (!BB) 3996 return error("Invalid record"); 3997 } 3998 I = CatchEndPadInst::Create(Context, BB); 3999 InstructionList.push_back(I); 4000 break; 4001 } 4002 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...] 4003 // Check magic 4004 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) { 4005 // "New" SwitchInst format with case ranges. The changes to write this 4006 // format were reverted but we still recognize bitcode that uses it. 4007 // Hopefully someday we will have support for case ranges and can use 4008 // this format again. 4009 4010 Type *OpTy = getTypeByID(Record[1]); 4011 unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth(); 4012 4013 Value *Cond = getValue(Record, 2, NextValueNo, OpTy); 4014 BasicBlock *Default = getBasicBlock(Record[3]); 4015 if (!OpTy || !Cond || !Default) 4016 return error("Invalid record"); 4017 4018 unsigned NumCases = Record[4]; 4019 4020 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases); 4021 InstructionList.push_back(SI); 4022 4023 unsigned CurIdx = 5; 4024 for (unsigned i = 0; i != NumCases; ++i) { 4025 SmallVector<ConstantInt*, 1> CaseVals; 4026 unsigned NumItems = Record[CurIdx++]; 4027 for (unsigned ci = 0; ci != NumItems; ++ci) { 4028 bool isSingleNumber = Record[CurIdx++]; 4029 4030 APInt Low; 4031 unsigned ActiveWords = 1; 4032 if (ValueBitWidth > 64) 4033 ActiveWords = Record[CurIdx++]; 4034 Low = readWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords), 4035 ValueBitWidth); 4036 CurIdx += ActiveWords; 4037 4038 if (!isSingleNumber) { 4039 ActiveWords = 1; 4040 if (ValueBitWidth > 64) 4041 ActiveWords = Record[CurIdx++]; 4042 APInt High = readWideAPInt( 4043 makeArrayRef(&Record[CurIdx], ActiveWords), ValueBitWidth); 4044 CurIdx += ActiveWords; 4045 4046 // FIXME: It is not clear whether values in the range should be 4047 // compared as signed or unsigned values. The partially 4048 // implemented changes that used this format in the past used 4049 // unsigned comparisons. 4050 for ( ; Low.ule(High); ++Low) 4051 CaseVals.push_back(ConstantInt::get(Context, Low)); 4052 } else 4053 CaseVals.push_back(ConstantInt::get(Context, Low)); 4054 } 4055 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]); 4056 for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(), 4057 cve = CaseVals.end(); cvi != cve; ++cvi) 4058 SI->addCase(*cvi, DestBB); 4059 } 4060 I = SI; 4061 break; 4062 } 4063 4064 // Old SwitchInst format without case ranges. 4065 4066 if (Record.size() < 3 || (Record.size() & 1) == 0) 4067 return error("Invalid record"); 4068 Type *OpTy = getTypeByID(Record[0]); 4069 Value *Cond = getValue(Record, 1, NextValueNo, OpTy); 4070 BasicBlock *Default = getBasicBlock(Record[2]); 4071 if (!OpTy || !Cond || !Default) 4072 return error("Invalid record"); 4073 unsigned NumCases = (Record.size()-3)/2; 4074 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases); 4075 InstructionList.push_back(SI); 4076 for (unsigned i = 0, e = NumCases; i != e; ++i) { 4077 ConstantInt *CaseVal = 4078 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy)); 4079 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]); 4080 if (!CaseVal || !DestBB) { 4081 delete SI; 4082 return error("Invalid record"); 4083 } 4084 SI->addCase(CaseVal, DestBB); 4085 } 4086 I = SI; 4087 break; 4088 } 4089 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...] 4090 if (Record.size() < 2) 4091 return error("Invalid record"); 4092 Type *OpTy = getTypeByID(Record[0]); 4093 Value *Address = getValue(Record, 1, NextValueNo, OpTy); 4094 if (!OpTy || !Address) 4095 return error("Invalid record"); 4096 unsigned NumDests = Record.size()-2; 4097 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests); 4098 InstructionList.push_back(IBI); 4099 for (unsigned i = 0, e = NumDests; i != e; ++i) { 4100 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) { 4101 IBI->addDestination(DestBB); 4102 } else { 4103 delete IBI; 4104 return error("Invalid record"); 4105 } 4106 } 4107 I = IBI; 4108 break; 4109 } 4110 4111 case bitc::FUNC_CODE_INST_INVOKE: { 4112 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...] 4113 if (Record.size() < 4) 4114 return error("Invalid record"); 4115 unsigned OpNum = 0; 4116 AttributeSet PAL = getAttributes(Record[OpNum++]); 4117 unsigned CCInfo = Record[OpNum++]; 4118 BasicBlock *NormalBB = getBasicBlock(Record[OpNum++]); 4119 BasicBlock *UnwindBB = getBasicBlock(Record[OpNum++]); 4120 4121 FunctionType *FTy = nullptr; 4122 if (CCInfo >> 13 & 1 && 4123 !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++])))) 4124 return error("Explicit invoke type is not a function type"); 4125 4126 Value *Callee; 4127 if (getValueTypePair(Record, OpNum, NextValueNo, Callee)) 4128 return error("Invalid record"); 4129 4130 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType()); 4131 if (!CalleeTy) 4132 return error("Callee is not a pointer"); 4133 if (!FTy) { 4134 FTy = dyn_cast<FunctionType>(CalleeTy->getElementType()); 4135 if (!FTy) 4136 return error("Callee is not of pointer to function type"); 4137 } else if (CalleeTy->getElementType() != FTy) 4138 return error("Explicit invoke type does not match pointee type of " 4139 "callee operand"); 4140 if (Record.size() < FTy->getNumParams() + OpNum) 4141 return error("Insufficient operands to call"); 4142 4143 SmallVector<Value*, 16> Ops; 4144 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) { 4145 Ops.push_back(getValue(Record, OpNum, NextValueNo, 4146 FTy->getParamType(i))); 4147 if (!Ops.back()) 4148 return error("Invalid record"); 4149 } 4150 4151 if (!FTy->isVarArg()) { 4152 if (Record.size() != OpNum) 4153 return error("Invalid record"); 4154 } else { 4155 // Read type/value pairs for varargs params. 4156 while (OpNum != Record.size()) { 4157 Value *Op; 4158 if (getValueTypePair(Record, OpNum, NextValueNo, Op)) 4159 return error("Invalid record"); 4160 Ops.push_back(Op); 4161 } 4162 } 4163 4164 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops); 4165 InstructionList.push_back(I); 4166 cast<InvokeInst>(I) 4167 ->setCallingConv(static_cast<CallingConv::ID>(~(1U << 13) & CCInfo)); 4168 cast<InvokeInst>(I)->setAttributes(PAL); 4169 break; 4170 } 4171 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval] 4172 unsigned Idx = 0; 4173 Value *Val = nullptr; 4174 if (getValueTypePair(Record, Idx, NextValueNo, Val)) 4175 return error("Invalid record"); 4176 I = ResumeInst::Create(Val); 4177 InstructionList.push_back(I); 4178 break; 4179 } 4180 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE 4181 I = new UnreachableInst(Context); 4182 InstructionList.push_back(I); 4183 break; 4184 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...] 4185 if (Record.size() < 1 || ((Record.size()-1)&1)) 4186 return error("Invalid record"); 4187 Type *Ty = getTypeByID(Record[0]); 4188 if (!Ty) 4189 return error("Invalid record"); 4190 4191 PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2); 4192 InstructionList.push_back(PN); 4193 4194 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) { 4195 Value *V; 4196 // With the new function encoding, it is possible that operands have 4197 // negative IDs (for forward references). Use a signed VBR 4198 // representation to keep the encoding small. 4199 if (UseRelativeIDs) 4200 V = getValueSigned(Record, 1+i, NextValueNo, Ty); 4201 else 4202 V = getValue(Record, 1+i, NextValueNo, Ty); 4203 BasicBlock *BB = getBasicBlock(Record[2+i]); 4204 if (!V || !BB) 4205 return error("Invalid record"); 4206 PN->addIncoming(V, BB); 4207 } 4208 I = PN; 4209 break; 4210 } 4211 4212 case bitc::FUNC_CODE_INST_LANDINGPAD: 4213 case bitc::FUNC_CODE_INST_LANDINGPAD_OLD: { 4214 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?] 4215 unsigned Idx = 0; 4216 if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD) { 4217 if (Record.size() < 3) 4218 return error("Invalid record"); 4219 } else { 4220 assert(BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD); 4221 if (Record.size() < 4) 4222 return error("Invalid record"); 4223 } 4224 Type *Ty = getTypeByID(Record[Idx++]); 4225 if (!Ty) 4226 return error("Invalid record"); 4227 if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD) { 4228 Value *PersFn = nullptr; 4229 if (getValueTypePair(Record, Idx, NextValueNo, PersFn)) 4230 return error("Invalid record"); 4231 4232 if (!F->hasPersonalityFn()) 4233 F->setPersonalityFn(cast<Constant>(PersFn)); 4234 else if (F->getPersonalityFn() != cast<Constant>(PersFn)) 4235 return error("Personality function mismatch"); 4236 } 4237 4238 bool IsCleanup = !!Record[Idx++]; 4239 unsigned NumClauses = Record[Idx++]; 4240 LandingPadInst *LP = LandingPadInst::Create(Ty, NumClauses); 4241 LP->setCleanup(IsCleanup); 4242 for (unsigned J = 0; J != NumClauses; ++J) { 4243 LandingPadInst::ClauseType CT = 4244 LandingPadInst::ClauseType(Record[Idx++]); (void)CT; 4245 Value *Val; 4246 4247 if (getValueTypePair(Record, Idx, NextValueNo, Val)) { 4248 delete LP; 4249 return error("Invalid record"); 4250 } 4251 4252 assert((CT != LandingPadInst::Catch || 4253 !isa<ArrayType>(Val->getType())) && 4254 "Catch clause has a invalid type!"); 4255 assert((CT != LandingPadInst::Filter || 4256 isa<ArrayType>(Val->getType())) && 4257 "Filter clause has invalid type!"); 4258 LP->addClause(cast<Constant>(Val)); 4259 } 4260 4261 I = LP; 4262 InstructionList.push_back(I); 4263 break; 4264 } 4265 4266 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align] 4267 if (Record.size() != 4) 4268 return error("Invalid record"); 4269 uint64_t AlignRecord = Record[3]; 4270 const uint64_t InAllocaMask = uint64_t(1) << 5; 4271 const uint64_t ExplicitTypeMask = uint64_t(1) << 6; 4272 // Reserve bit 7 for SwiftError flag. 4273 // const uint64_t SwiftErrorMask = uint64_t(1) << 7; 4274 const uint64_t FlagMask = InAllocaMask | ExplicitTypeMask; 4275 bool InAlloca = AlignRecord & InAllocaMask; 4276 Type *Ty = getTypeByID(Record[0]); 4277 if ((AlignRecord & ExplicitTypeMask) == 0) { 4278 auto *PTy = dyn_cast_or_null<PointerType>(Ty); 4279 if (!PTy) 4280 return error("Old-style alloca with a non-pointer type"); 4281 Ty = PTy->getElementType(); 4282 } 4283 Type *OpTy = getTypeByID(Record[1]); 4284 Value *Size = getFnValueByID(Record[2], OpTy); 4285 unsigned Align; 4286 if (std::error_code EC = 4287 parseAlignmentValue(AlignRecord & ~FlagMask, Align)) { 4288 return EC; 4289 } 4290 if (!Ty || !Size) 4291 return error("Invalid record"); 4292 AllocaInst *AI = new AllocaInst(Ty, Size, Align); 4293 AI->setUsedWithInAlloca(InAlloca); 4294 I = AI; 4295 InstructionList.push_back(I); 4296 break; 4297 } 4298 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol] 4299 unsigned OpNum = 0; 4300 Value *Op; 4301 if (getValueTypePair(Record, OpNum, NextValueNo, Op) || 4302 (OpNum + 2 != Record.size() && OpNum + 3 != Record.size())) 4303 return error("Invalid record"); 4304 4305 Type *Ty = nullptr; 4306 if (OpNum + 3 == Record.size()) 4307 Ty = getTypeByID(Record[OpNum++]); 4308 if (std::error_code EC = 4309 typeCheckLoadStoreInst(DiagnosticHandler, Ty, Op->getType())) 4310 return EC; 4311 if (!Ty) 4312 Ty = cast<PointerType>(Op->getType())->getElementType(); 4313 4314 unsigned Align; 4315 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align)) 4316 return EC; 4317 I = new LoadInst(Ty, Op, "", Record[OpNum + 1], Align); 4318 4319 InstructionList.push_back(I); 4320 break; 4321 } 4322 case bitc::FUNC_CODE_INST_LOADATOMIC: { 4323 // LOADATOMIC: [opty, op, align, vol, ordering, synchscope] 4324 unsigned OpNum = 0; 4325 Value *Op; 4326 if (getValueTypePair(Record, OpNum, NextValueNo, Op) || 4327 (OpNum + 4 != Record.size() && OpNum + 5 != Record.size())) 4328 return error("Invalid record"); 4329 4330 Type *Ty = nullptr; 4331 if (OpNum + 5 == Record.size()) 4332 Ty = getTypeByID(Record[OpNum++]); 4333 if (std::error_code EC = 4334 typeCheckLoadStoreInst(DiagnosticHandler, Ty, Op->getType())) 4335 return EC; 4336 if (!Ty) 4337 Ty = cast<PointerType>(Op->getType())->getElementType(); 4338 4339 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]); 4340 if (Ordering == NotAtomic || Ordering == Release || 4341 Ordering == AcquireRelease) 4342 return error("Invalid record"); 4343 if (Ordering != NotAtomic && Record[OpNum] == 0) 4344 return error("Invalid record"); 4345 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]); 4346 4347 unsigned Align; 4348 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align)) 4349 return EC; 4350 I = new LoadInst(Op, "", Record[OpNum+1], Align, Ordering, SynchScope); 4351 4352 InstructionList.push_back(I); 4353 break; 4354 } 4355 case bitc::FUNC_CODE_INST_STORE: 4356 case bitc::FUNC_CODE_INST_STORE_OLD: { // STORE2:[ptrty, ptr, val, align, vol] 4357 unsigned OpNum = 0; 4358 Value *Val, *Ptr; 4359 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) || 4360 (BitCode == bitc::FUNC_CODE_INST_STORE 4361 ? getValueTypePair(Record, OpNum, NextValueNo, Val) 4362 : popValue(Record, OpNum, NextValueNo, 4363 cast<PointerType>(Ptr->getType())->getElementType(), 4364 Val)) || 4365 OpNum + 2 != Record.size()) 4366 return error("Invalid record"); 4367 4368 if (std::error_code EC = typeCheckLoadStoreInst( 4369 DiagnosticHandler, Val->getType(), Ptr->getType())) 4370 return EC; 4371 unsigned Align; 4372 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align)) 4373 return EC; 4374 I = new StoreInst(Val, Ptr, Record[OpNum+1], Align); 4375 InstructionList.push_back(I); 4376 break; 4377 } 4378 case bitc::FUNC_CODE_INST_STOREATOMIC: 4379 case bitc::FUNC_CODE_INST_STOREATOMIC_OLD: { 4380 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope] 4381 unsigned OpNum = 0; 4382 Value *Val, *Ptr; 4383 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) || 4384 (BitCode == bitc::FUNC_CODE_INST_STOREATOMIC 4385 ? getValueTypePair(Record, OpNum, NextValueNo, Val) 4386 : popValue(Record, OpNum, NextValueNo, 4387 cast<PointerType>(Ptr->getType())->getElementType(), 4388 Val)) || 4389 OpNum + 4 != Record.size()) 4390 return error("Invalid record"); 4391 4392 if (std::error_code EC = typeCheckLoadStoreInst( 4393 DiagnosticHandler, Val->getType(), Ptr->getType())) 4394 return EC; 4395 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]); 4396 if (Ordering == NotAtomic || Ordering == Acquire || 4397 Ordering == AcquireRelease) 4398 return error("Invalid record"); 4399 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]); 4400 if (Ordering != NotAtomic && Record[OpNum] == 0) 4401 return error("Invalid record"); 4402 4403 unsigned Align; 4404 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align)) 4405 return EC; 4406 I = new StoreInst(Val, Ptr, Record[OpNum+1], Align, Ordering, SynchScope); 4407 InstructionList.push_back(I); 4408 break; 4409 } 4410 case bitc::FUNC_CODE_INST_CMPXCHG_OLD: 4411 case bitc::FUNC_CODE_INST_CMPXCHG: { 4412 // CMPXCHG:[ptrty, ptr, cmp, new, vol, successordering, synchscope, 4413 // failureordering?, isweak?] 4414 unsigned OpNum = 0; 4415 Value *Ptr, *Cmp, *New; 4416 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) || 4417 (BitCode == bitc::FUNC_CODE_INST_CMPXCHG 4418 ? getValueTypePair(Record, OpNum, NextValueNo, Cmp) 4419 : popValue(Record, OpNum, NextValueNo, 4420 cast<PointerType>(Ptr->getType())->getElementType(), 4421 Cmp)) || 4422 popValue(Record, OpNum, NextValueNo, Cmp->getType(), New) || 4423 Record.size() < OpNum + 3 || Record.size() > OpNum + 5) 4424 return error("Invalid record"); 4425 AtomicOrdering SuccessOrdering = getDecodedOrdering(Record[OpNum + 1]); 4426 if (SuccessOrdering == NotAtomic || SuccessOrdering == Unordered) 4427 return error("Invalid record"); 4428 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 2]); 4429 4430 if (std::error_code EC = typeCheckLoadStoreInst( 4431 DiagnosticHandler, Cmp->getType(), Ptr->getType())) 4432 return EC; 4433 AtomicOrdering FailureOrdering; 4434 if (Record.size() < 7) 4435 FailureOrdering = 4436 AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering); 4437 else 4438 FailureOrdering = getDecodedOrdering(Record[OpNum + 3]); 4439 4440 I = new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering, FailureOrdering, 4441 SynchScope); 4442 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]); 4443 4444 if (Record.size() < 8) { 4445 // Before weak cmpxchgs existed, the instruction simply returned the 4446 // value loaded from memory, so bitcode files from that era will be 4447 // expecting the first component of a modern cmpxchg. 4448 CurBB->getInstList().push_back(I); 4449 I = ExtractValueInst::Create(I, 0); 4450 } else { 4451 cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum+4]); 4452 } 4453 4454 InstructionList.push_back(I); 4455 break; 4456 } 4457 case bitc::FUNC_CODE_INST_ATOMICRMW: { 4458 // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope] 4459 unsigned OpNum = 0; 4460 Value *Ptr, *Val; 4461 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) || 4462 popValue(Record, OpNum, NextValueNo, 4463 cast<PointerType>(Ptr->getType())->getElementType(), Val) || 4464 OpNum+4 != Record.size()) 4465 return error("Invalid record"); 4466 AtomicRMWInst::BinOp Operation = getDecodedRMWOperation(Record[OpNum]); 4467 if (Operation < AtomicRMWInst::FIRST_BINOP || 4468 Operation > AtomicRMWInst::LAST_BINOP) 4469 return error("Invalid record"); 4470 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]); 4471 if (Ordering == NotAtomic || Ordering == Unordered) 4472 return error("Invalid record"); 4473 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]); 4474 I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope); 4475 cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]); 4476 InstructionList.push_back(I); 4477 break; 4478 } 4479 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope] 4480 if (2 != Record.size()) 4481 return error("Invalid record"); 4482 AtomicOrdering Ordering = getDecodedOrdering(Record[0]); 4483 if (Ordering == NotAtomic || Ordering == Unordered || 4484 Ordering == Monotonic) 4485 return error("Invalid record"); 4486 SynchronizationScope SynchScope = getDecodedSynchScope(Record[1]); 4487 I = new FenceInst(Context, Ordering, SynchScope); 4488 InstructionList.push_back(I); 4489 break; 4490 } 4491 case bitc::FUNC_CODE_INST_CALL: { 4492 // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...] 4493 if (Record.size() < 3) 4494 return error("Invalid record"); 4495 4496 unsigned OpNum = 0; 4497 AttributeSet PAL = getAttributes(Record[OpNum++]); 4498 unsigned CCInfo = Record[OpNum++]; 4499 4500 FunctionType *FTy = nullptr; 4501 if (CCInfo >> 15 & 1 && 4502 !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++])))) 4503 return error("Explicit call type is not a function type"); 4504 4505 Value *Callee; 4506 if (getValueTypePair(Record, OpNum, NextValueNo, Callee)) 4507 return error("Invalid record"); 4508 4509 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType()); 4510 if (!OpTy) 4511 return error("Callee is not a pointer type"); 4512 if (!FTy) { 4513 FTy = dyn_cast<FunctionType>(OpTy->getElementType()); 4514 if (!FTy) 4515 return error("Callee is not of pointer to function type"); 4516 } else if (OpTy->getElementType() != FTy) 4517 return error("Explicit call type does not match pointee type of " 4518 "callee operand"); 4519 if (Record.size() < FTy->getNumParams() + OpNum) 4520 return error("Insufficient operands to call"); 4521 4522 SmallVector<Value*, 16> Args; 4523 // Read the fixed params. 4524 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) { 4525 if (FTy->getParamType(i)->isLabelTy()) 4526 Args.push_back(getBasicBlock(Record[OpNum])); 4527 else 4528 Args.push_back(getValue(Record, OpNum, NextValueNo, 4529 FTy->getParamType(i))); 4530 if (!Args.back()) 4531 return error("Invalid record"); 4532 } 4533 4534 // Read type/value pairs for varargs params. 4535 if (!FTy->isVarArg()) { 4536 if (OpNum != Record.size()) 4537 return error("Invalid record"); 4538 } else { 4539 while (OpNum != Record.size()) { 4540 Value *Op; 4541 if (getValueTypePair(Record, OpNum, NextValueNo, Op)) 4542 return error("Invalid record"); 4543 Args.push_back(Op); 4544 } 4545 } 4546 4547 I = CallInst::Create(FTy, Callee, Args); 4548 InstructionList.push_back(I); 4549 cast<CallInst>(I)->setCallingConv( 4550 static_cast<CallingConv::ID>((~(1U << 14) & CCInfo) >> 1)); 4551 CallInst::TailCallKind TCK = CallInst::TCK_None; 4552 if (CCInfo & 1) 4553 TCK = CallInst::TCK_Tail; 4554 if (CCInfo & (1 << 14)) 4555 TCK = CallInst::TCK_MustTail; 4556 cast<CallInst>(I)->setTailCallKind(TCK); 4557 cast<CallInst>(I)->setAttributes(PAL); 4558 break; 4559 } 4560 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty] 4561 if (Record.size() < 3) 4562 return error("Invalid record"); 4563 Type *OpTy = getTypeByID(Record[0]); 4564 Value *Op = getValue(Record, 1, NextValueNo, OpTy); 4565 Type *ResTy = getTypeByID(Record[2]); 4566 if (!OpTy || !Op || !ResTy) 4567 return error("Invalid record"); 4568 I = new VAArgInst(Op, ResTy); 4569 InstructionList.push_back(I); 4570 break; 4571 } 4572 } 4573 4574 // Add instruction to end of current BB. If there is no current BB, reject 4575 // this file. 4576 if (!CurBB) { 4577 delete I; 4578 return error("Invalid instruction with no BB"); 4579 } 4580 CurBB->getInstList().push_back(I); 4581 4582 // If this was a terminator instruction, move to the next block. 4583 if (isa<TerminatorInst>(I)) { 4584 ++CurBBNo; 4585 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr; 4586 } 4587 4588 // Non-void values get registered in the value table for future use. 4589 if (I && !I->getType()->isVoidTy()) 4590 if (ValueList.assignValue(I, NextValueNo++)) 4591 return error("Invalid forward reference"); 4592 } 4593 4594 OutOfRecordLoop: 4595 4596 // Check the function list for unresolved values. 4597 if (Argument *A = dyn_cast<Argument>(ValueList.back())) { 4598 if (!A->getParent()) { 4599 // We found at least one unresolved value. Nuke them all to avoid leaks. 4600 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){ 4601 if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) { 4602 A->replaceAllUsesWith(UndefValue::get(A->getType())); 4603 delete A; 4604 } 4605 } 4606 return error("Never resolved value found in function"); 4607 } 4608 } 4609 4610 // FIXME: Check for unresolved forward-declared metadata references 4611 // and clean up leaks. 4612 4613 // Trim the value list down to the size it was before we parsed this function. 4614 ValueList.shrinkTo(ModuleValueListSize); 4615 MDValueList.shrinkTo(ModuleMDValueListSize); 4616 std::vector<BasicBlock*>().swap(FunctionBBs); 4617 return std::error_code(); 4618 } 4619 4620 /// Find the function body in the bitcode stream 4621 std::error_code BitcodeReader::findFunctionInStream( 4622 Function *F, 4623 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) { 4624 while (DeferredFunctionInfoIterator->second == 0) { 4625 if (Stream.AtEndOfStream()) 4626 return error("Could not find function in stream"); 4627 // ParseModule will parse the next body in the stream and set its 4628 // position in the DeferredFunctionInfo map. 4629 if (std::error_code EC = parseModule(true)) 4630 return EC; 4631 } 4632 return std::error_code(); 4633 } 4634 4635 //===----------------------------------------------------------------------===// 4636 // GVMaterializer implementation 4637 //===----------------------------------------------------------------------===// 4638 4639 void BitcodeReader::releaseBuffer() { Buffer.release(); } 4640 4641 std::error_code BitcodeReader::materialize(GlobalValue *GV) { 4642 if (std::error_code EC = materializeMetadata()) 4643 return EC; 4644 4645 Function *F = dyn_cast<Function>(GV); 4646 // If it's not a function or is already material, ignore the request. 4647 if (!F || !F->isMaterializable()) 4648 return std::error_code(); 4649 4650 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F); 4651 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!"); 4652 // If its position is recorded as 0, its body is somewhere in the stream 4653 // but we haven't seen it yet. 4654 if (DFII->second == 0) 4655 if (std::error_code EC = findFunctionInStream(F, DFII)) 4656 return EC; 4657 4658 // Move the bit stream to the saved position of the deferred function body. 4659 Stream.JumpToBit(DFII->second); 4660 4661 if (std::error_code EC = parseFunctionBody(F)) 4662 return EC; 4663 F->setIsMaterializable(false); 4664 4665 if (StripDebugInfo) 4666 stripDebugInfo(*F); 4667 4668 // Upgrade any old intrinsic calls in the function. 4669 for (auto &I : UpgradedIntrinsics) { 4670 for (auto UI = I.first->user_begin(), UE = I.first->user_end(); UI != UE;) { 4671 User *U = *UI; 4672 ++UI; 4673 if (CallInst *CI = dyn_cast<CallInst>(U)) 4674 UpgradeIntrinsicCall(CI, I.second); 4675 } 4676 } 4677 4678 // Bring in any functions that this function forward-referenced via 4679 // blockaddresses. 4680 return materializeForwardReferencedFunctions(); 4681 } 4682 4683 bool BitcodeReader::isDematerializable(const GlobalValue *GV) const { 4684 const Function *F = dyn_cast<Function>(GV); 4685 if (!F || F->isDeclaration()) 4686 return false; 4687 4688 // Dematerializing F would leave dangling references that wouldn't be 4689 // reconnected on re-materialization. 4690 if (BlockAddressesTaken.count(F)) 4691 return false; 4692 4693 return DeferredFunctionInfo.count(const_cast<Function*>(F)); 4694 } 4695 4696 void BitcodeReader::dematerialize(GlobalValue *GV) { 4697 Function *F = dyn_cast<Function>(GV); 4698 // If this function isn't dematerializable, this is a noop. 4699 if (!F || !isDematerializable(F)) 4700 return; 4701 4702 assert(DeferredFunctionInfo.count(F) && "No info to read function later?"); 4703 4704 // Just forget the function body, we can remat it later. 4705 F->dropAllReferences(); 4706 F->setIsMaterializable(true); 4707 } 4708 4709 std::error_code BitcodeReader::materializeModule(Module *M) { 4710 assert(M == TheModule && 4711 "Can only Materialize the Module this BitcodeReader is attached to."); 4712 4713 if (std::error_code EC = materializeMetadata()) 4714 return EC; 4715 4716 // Promise to materialize all forward references. 4717 WillMaterializeAllForwardRefs = true; 4718 4719 // Iterate over the module, deserializing any functions that are still on 4720 // disk. 4721 for (Module::iterator F = TheModule->begin(), E = TheModule->end(); 4722 F != E; ++F) { 4723 if (std::error_code EC = materialize(F)) 4724 return EC; 4725 } 4726 // At this point, if there are any function bodies, the current bit is 4727 // pointing to the END_BLOCK record after them. Now make sure the rest 4728 // of the bits in the module have been read. 4729 if (NextUnreadBit) 4730 parseModule(true); 4731 4732 // Check that all block address forward references got resolved (as we 4733 // promised above). 4734 if (!BasicBlockFwdRefs.empty()) 4735 return error("Never resolved function from blockaddress"); 4736 4737 // Upgrade any intrinsic calls that slipped through (should not happen!) and 4738 // delete the old functions to clean up. We can't do this unless the entire 4739 // module is materialized because there could always be another function body 4740 // with calls to the old function. 4741 for (auto &I : UpgradedIntrinsics) { 4742 for (auto *U : I.first->users()) { 4743 if (CallInst *CI = dyn_cast<CallInst>(U)) 4744 UpgradeIntrinsicCall(CI, I.second); 4745 } 4746 if (!I.first->use_empty()) 4747 I.first->replaceAllUsesWith(I.second); 4748 I.first->eraseFromParent(); 4749 } 4750 UpgradedIntrinsics.clear(); 4751 4752 for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++) 4753 UpgradeInstWithTBAATag(InstsWithTBAATag[I]); 4754 4755 UpgradeDebugInfo(*M); 4756 return std::error_code(); 4757 } 4758 4759 std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes() const { 4760 return IdentifiedStructTypes; 4761 } 4762 4763 std::error_code 4764 BitcodeReader::initStream(std::unique_ptr<DataStreamer> Streamer) { 4765 if (Streamer) 4766 return initLazyStream(std::move(Streamer)); 4767 return initStreamFromBuffer(); 4768 } 4769 4770 std::error_code BitcodeReader::initStreamFromBuffer() { 4771 const unsigned char *BufPtr = (const unsigned char*)Buffer->getBufferStart(); 4772 const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize(); 4773 4774 if (Buffer->getBufferSize() & 3) 4775 return error("Invalid bitcode signature"); 4776 4777 // If we have a wrapper header, parse it and ignore the non-bc file contents. 4778 // The magic number is 0x0B17C0DE stored in little endian. 4779 if (isBitcodeWrapper(BufPtr, BufEnd)) 4780 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true)) 4781 return error("Invalid bitcode wrapper header"); 4782 4783 StreamFile.reset(new BitstreamReader(BufPtr, BufEnd)); 4784 Stream.init(&*StreamFile); 4785 4786 return std::error_code(); 4787 } 4788 4789 std::error_code 4790 BitcodeReader::initLazyStream(std::unique_ptr<DataStreamer> Streamer) { 4791 // Check and strip off the bitcode wrapper; BitstreamReader expects never to 4792 // see it. 4793 auto OwnedBytes = 4794 llvm::make_unique<StreamingMemoryObject>(std::move(Streamer)); 4795 StreamingMemoryObject &Bytes = *OwnedBytes; 4796 StreamFile = llvm::make_unique<BitstreamReader>(std::move(OwnedBytes)); 4797 Stream.init(&*StreamFile); 4798 4799 unsigned char buf[16]; 4800 if (Bytes.readBytes(buf, 16, 0) != 16) 4801 return error("Invalid bitcode signature"); 4802 4803 if (!isBitcode(buf, buf + 16)) 4804 return error("Invalid bitcode signature"); 4805 4806 if (isBitcodeWrapper(buf, buf + 4)) { 4807 const unsigned char *bitcodeStart = buf; 4808 const unsigned char *bitcodeEnd = buf + 16; 4809 SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false); 4810 Bytes.dropLeadingBytes(bitcodeStart - buf); 4811 Bytes.setKnownObjectSize(bitcodeEnd - bitcodeStart); 4812 } 4813 return std::error_code(); 4814 } 4815 4816 namespace { 4817 class BitcodeErrorCategoryType : public std::error_category { 4818 const char *name() const LLVM_NOEXCEPT override { 4819 return "llvm.bitcode"; 4820 } 4821 std::string message(int IE) const override { 4822 BitcodeError E = static_cast<BitcodeError>(IE); 4823 switch (E) { 4824 case BitcodeError::InvalidBitcodeSignature: 4825 return "Invalid bitcode signature"; 4826 case BitcodeError::CorruptedBitcode: 4827 return "Corrupted bitcode"; 4828 } 4829 llvm_unreachable("Unknown error type!"); 4830 } 4831 }; 4832 } 4833 4834 static ManagedStatic<BitcodeErrorCategoryType> ErrorCategory; 4835 4836 const std::error_category &llvm::BitcodeErrorCategory() { 4837 return *ErrorCategory; 4838 } 4839 4840 //===----------------------------------------------------------------------===// 4841 // External interface 4842 //===----------------------------------------------------------------------===// 4843 4844 static ErrorOr<std::unique_ptr<Module>> 4845 getBitcodeModuleImpl(std::unique_ptr<DataStreamer> Streamer, StringRef Name, 4846 BitcodeReader *R, LLVMContext &Context, 4847 bool MaterializeAll, bool ShouldLazyLoadMetadata) { 4848 std::unique_ptr<Module> M = make_unique<Module>(Name, Context); 4849 M->setMaterializer(R); 4850 4851 auto cleanupOnError = [&](std::error_code EC) { 4852 R->releaseBuffer(); // Never take ownership on error. 4853 return EC; 4854 }; 4855 4856 // Delay parsing Metadata if ShouldLazyLoadMetadata is true. 4857 if (std::error_code EC = R->parseBitcodeInto(std::move(Streamer), M.get(), 4858 ShouldLazyLoadMetadata)) 4859 return cleanupOnError(EC); 4860 4861 if (MaterializeAll) { 4862 // Read in the entire module, and destroy the BitcodeReader. 4863 if (std::error_code EC = M->materializeAllPermanently()) 4864 return cleanupOnError(EC); 4865 } else { 4866 // Resolve forward references from blockaddresses. 4867 if (std::error_code EC = R->materializeForwardReferencedFunctions()) 4868 return cleanupOnError(EC); 4869 } 4870 return std::move(M); 4871 } 4872 4873 /// \brief Get a lazy one-at-time loading module from bitcode. 4874 /// 4875 /// This isn't always used in a lazy context. In particular, it's also used by 4876 /// \a parseBitcodeFile(). If this is truly lazy, then we need to eagerly pull 4877 /// in forward-referenced functions from block address references. 4878 /// 4879 /// \param[in] MaterializeAll Set to \c true if we should materialize 4880 /// everything. 4881 static ErrorOr<std::unique_ptr<Module>> 4882 getLazyBitcodeModuleImpl(std::unique_ptr<MemoryBuffer> &&Buffer, 4883 LLVMContext &Context, bool MaterializeAll, 4884 DiagnosticHandlerFunction DiagnosticHandler, 4885 bool ShouldLazyLoadMetadata = false) { 4886 BitcodeReader *R = 4887 new BitcodeReader(Buffer.get(), Context, DiagnosticHandler); 4888 4889 ErrorOr<std::unique_ptr<Module>> Ret = 4890 getBitcodeModuleImpl(nullptr, Buffer->getBufferIdentifier(), R, Context, 4891 MaterializeAll, ShouldLazyLoadMetadata); 4892 if (!Ret) 4893 return Ret; 4894 4895 Buffer.release(); // The BitcodeReader owns it now. 4896 return Ret; 4897 } 4898 4899 ErrorOr<std::unique_ptr<Module>> llvm::getLazyBitcodeModule( 4900 std::unique_ptr<MemoryBuffer> &&Buffer, LLVMContext &Context, 4901 DiagnosticHandlerFunction DiagnosticHandler, bool ShouldLazyLoadMetadata) { 4902 return getLazyBitcodeModuleImpl(std::move(Buffer), Context, false, 4903 DiagnosticHandler, ShouldLazyLoadMetadata); 4904 } 4905 4906 ErrorOr<std::unique_ptr<Module>> llvm::getStreamedBitcodeModule( 4907 StringRef Name, std::unique_ptr<DataStreamer> Streamer, 4908 LLVMContext &Context, DiagnosticHandlerFunction DiagnosticHandler) { 4909 std::unique_ptr<Module> M = make_unique<Module>(Name, Context); 4910 BitcodeReader *R = new BitcodeReader(Context, DiagnosticHandler); 4911 4912 return getBitcodeModuleImpl(std::move(Streamer), Name, R, Context, false, 4913 false); 4914 } 4915 4916 ErrorOr<std::unique_ptr<Module>> 4917 llvm::parseBitcodeFile(MemoryBufferRef Buffer, LLVMContext &Context, 4918 DiagnosticHandlerFunction DiagnosticHandler) { 4919 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false); 4920 return getLazyBitcodeModuleImpl(std::move(Buf), Context, true, 4921 DiagnosticHandler); 4922 // TODO: Restore the use-lists to the in-memory state when the bitcode was 4923 // written. We must defer until the Module has been fully materialized. 4924 } 4925 4926 std::string 4927 llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer, LLVMContext &Context, 4928 DiagnosticHandlerFunction DiagnosticHandler) { 4929 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false); 4930 auto R = llvm::make_unique<BitcodeReader>(Buf.release(), Context, 4931 DiagnosticHandler); 4932 ErrorOr<std::string> Triple = R->parseTriple(); 4933 if (Triple.getError()) 4934 return ""; 4935 return Triple.get(); 4936 } 4937