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