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