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 // This header defines the BitcodeReader class. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "llvm/Bitcode/ReaderWriter.h" 15 #include "BitReader_2_7.h" 16 #include "llvm/ADT/STLExtras.h" 17 #include "llvm/ADT/SmallString.h" 18 #include "llvm/ADT/SmallVector.h" 19 #include "llvm/IR/AutoUpgrade.h" 20 #include "llvm/IR/Constants.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/Support/ManagedStatic.h" 31 #include "llvm/Support/MathExtras.h" 32 #include "llvm/Support/MemoryBuffer.h" 33 34 using namespace llvm; 35 using namespace llvm_2_7; 36 37 #define METADATA_NODE_2_7 2 38 #define METADATA_FN_NODE_2_7 3 39 #define METADATA_NAMED_NODE_2_7 5 40 #define METADATA_ATTACHMENT_2_7 7 41 #define FUNC_CODE_INST_UNWIND_2_7 14 42 #define FUNC_CODE_INST_MALLOC_2_7 17 43 #define FUNC_CODE_INST_FREE_2_7 18 44 #define FUNC_CODE_INST_STORE_2_7 21 45 #define FUNC_CODE_INST_CALL_2_7 22 46 #define FUNC_CODE_INST_GETRESULT_2_7 25 47 #define FUNC_CODE_DEBUG_LOC_2_7 32 48 49 #define TYPE_BLOCK_ID_OLD_3_0 10 50 #define TYPE_SYMTAB_BLOCK_ID_OLD_3_0 13 51 #define TYPE_CODE_STRUCT_OLD_3_0 10 52 53 namespace { 54 55 void StripDebugInfoOfFunction(Module* M, const char* name) { 56 if (Function* FuncStart = M->getFunction(name)) { 57 while (!FuncStart->use_empty()) { 58 cast<CallInst>(*FuncStart->use_begin())->eraseFromParent(); 59 } 60 FuncStart->eraseFromParent(); 61 } 62 } 63 64 /// This function strips all debug info intrinsics, except for llvm.dbg.declare. 65 /// If an llvm.dbg.declare intrinsic is invalid, then this function simply 66 /// strips that use. 67 void CheckDebugInfoIntrinsics(Module *M) { 68 StripDebugInfoOfFunction(M, "llvm.dbg.func.start"); 69 StripDebugInfoOfFunction(M, "llvm.dbg.stoppoint"); 70 StripDebugInfoOfFunction(M, "llvm.dbg.region.start"); 71 StripDebugInfoOfFunction(M, "llvm.dbg.region.end"); 72 73 if (Function *Declare = M->getFunction("llvm.dbg.declare")) { 74 if (!Declare->use_empty()) { 75 DbgDeclareInst *DDI = cast<DbgDeclareInst>(*Declare->use_begin()); 76 if (!isa<MDNode>(ValueAsMetadata::get(DDI->getArgOperand(0))) || 77 !isa<MDNode>(ValueAsMetadata::get(DDI->getArgOperand(1)))) { 78 while (!Declare->use_empty()) { 79 CallInst *CI = cast<CallInst>(*Declare->use_begin()); 80 CI->eraseFromParent(); 81 } 82 Declare->eraseFromParent(); 83 } 84 } 85 } 86 } 87 88 //===----------------------------------------------------------------------===// 89 // BitcodeReaderValueList Class 90 //===----------------------------------------------------------------------===// 91 92 class BitcodeReaderValueList { 93 std::vector<WeakVH> ValuePtrs; 94 95 /// ResolveConstants - As we resolve forward-referenced constants, we add 96 /// information about them to this vector. This allows us to resolve them in 97 /// bulk instead of resolving each reference at a time. See the code in 98 /// ResolveConstantForwardRefs for more information about this. 99 /// 100 /// The key of this vector is the placeholder constant, the value is the slot 101 /// number that holds the resolved value. 102 typedef std::vector<std::pair<Constant*, unsigned> > ResolveConstantsTy; 103 ResolveConstantsTy ResolveConstants; 104 LLVMContext &Context; 105 public: 106 BitcodeReaderValueList(LLVMContext &C) : Context(C) {} 107 ~BitcodeReaderValueList() { 108 assert(ResolveConstants.empty() && "Constants not resolved?"); 109 } 110 111 // vector compatibility methods 112 unsigned size() const { return ValuePtrs.size(); } 113 void resize(unsigned N) { ValuePtrs.resize(N); } 114 void push_back(Value *V) { 115 ValuePtrs.push_back(V); 116 } 117 118 void clear() { 119 assert(ResolveConstants.empty() && "Constants not resolved?"); 120 ValuePtrs.clear(); 121 } 122 123 Value *operator[](unsigned i) const { 124 assert(i < ValuePtrs.size()); 125 return ValuePtrs[i]; 126 } 127 128 Value *back() const { return ValuePtrs.back(); } 129 void pop_back() { ValuePtrs.pop_back(); } 130 bool empty() const { return ValuePtrs.empty(); } 131 void shrinkTo(unsigned N) { 132 assert(N <= size() && "Invalid shrinkTo request!"); 133 ValuePtrs.resize(N); 134 } 135 136 Constant *getConstantFwdRef(unsigned Idx, Type *Ty); 137 Value *getValueFwdRef(unsigned Idx, Type *Ty); 138 139 void AssignValue(Value *V, unsigned Idx); 140 141 /// ResolveConstantForwardRefs - Once all constants are read, this method bulk 142 /// resolves any forward references. 143 void ResolveConstantForwardRefs(); 144 }; 145 146 147 //===----------------------------------------------------------------------===// 148 // BitcodeReaderMDValueList Class 149 //===----------------------------------------------------------------------===// 150 151 class BitcodeReaderMDValueList { 152 unsigned NumFwdRefs; 153 bool AnyFwdRefs; 154 std::vector<TrackingMDRef> MDValuePtrs; 155 156 LLVMContext &Context; 157 public: 158 BitcodeReaderMDValueList(LLVMContext &C) 159 : NumFwdRefs(0), AnyFwdRefs(false), Context(C) {} 160 161 // vector compatibility methods 162 unsigned size() const { return MDValuePtrs.size(); } 163 void resize(unsigned N) { MDValuePtrs.resize(N); } 164 void push_back(Metadata *MD) { MDValuePtrs.emplace_back(MD); } 165 void clear() { MDValuePtrs.clear(); } 166 Metadata *back() const { return MDValuePtrs.back(); } 167 void pop_back() { MDValuePtrs.pop_back(); } 168 bool empty() const { return MDValuePtrs.empty(); } 169 170 Metadata *operator[](unsigned i) const { 171 assert(i < MDValuePtrs.size()); 172 return MDValuePtrs[i]; 173 } 174 175 void shrinkTo(unsigned N) { 176 assert(N <= size() && "Invalid shrinkTo request!"); 177 MDValuePtrs.resize(N); 178 } 179 180 Metadata *getValueFwdRef(unsigned Idx); 181 void AssignValue(Metadata *MD, unsigned Idx); 182 void tryToResolveCycles(); 183 }; 184 185 class BitcodeReader : public GVMaterializer { 186 LLVMContext &Context; 187 DiagnosticHandlerFunction DiagnosticHandler; 188 Module *TheModule; 189 std::unique_ptr<MemoryBuffer> Buffer; 190 std::unique_ptr<BitstreamReader> StreamFile; 191 BitstreamCursor Stream; 192 std::unique_ptr<DataStreamer> LazyStreamer; 193 uint64_t NextUnreadBit; 194 bool SeenValueSymbolTable; 195 196 std::vector<Type*> TypeList; 197 BitcodeReaderValueList ValueList; 198 BitcodeReaderMDValueList MDValueList; 199 SmallVector<Instruction *, 64> InstructionList; 200 201 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInits; 202 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInits; 203 204 /// MAttributes - The set of attributes by index. Index zero in the 205 /// file is for null, and is thus not represented here. As such all indices 206 /// are off by one. 207 std::vector<AttributeSet> MAttributes; 208 209 /// \brief The set of attribute groups. 210 std::map<unsigned, AttributeSet> MAttributeGroups; 211 212 /// FunctionBBs - While parsing a function body, this is a list of the basic 213 /// blocks for the function. 214 std::vector<BasicBlock*> FunctionBBs; 215 216 // When reading the module header, this list is populated with functions that 217 // have bodies later in the file. 218 std::vector<Function*> FunctionsWithBodies; 219 220 // When intrinsic functions are encountered which require upgrading they are 221 // stored here with their replacement function. 222 typedef std::vector<std::pair<Function*, Function*> > UpgradedIntrinsicMap; 223 UpgradedIntrinsicMap UpgradedIntrinsics; 224 225 // Map the bitcode's custom MDKind ID to the Module's MDKind ID. 226 DenseMap<unsigned, unsigned> MDKindMap; 227 228 // Several operations happen after the module header has been read, but 229 // before function bodies are processed. This keeps track of whether 230 // we've done this yet. 231 bool SeenFirstFunctionBody; 232 233 /// DeferredFunctionInfo - When function bodies are initially scanned, this 234 /// map contains info about where to find deferred function body in the 235 /// stream. 236 DenseMap<Function*, uint64_t> DeferredFunctionInfo; 237 238 /// BlockAddrFwdRefs - These are blockaddr references to basic blocks. These 239 /// are resolved lazily when functions are loaded. 240 typedef std::pair<unsigned, GlobalVariable*> BlockAddrRefTy; 241 DenseMap<Function*, std::vector<BlockAddrRefTy> > BlockAddrFwdRefs; 242 243 /// LLVM2_7MetadataDetected - True if metadata produced by LLVM 2.7 or 244 /// earlier was detected, in which case we behave slightly differently, 245 /// for compatibility. 246 /// FIXME: Remove in LLVM 3.0. 247 bool LLVM2_7MetadataDetected; 248 static const std::error_category &BitcodeErrorCategory(); 249 250 public: 251 std::error_code Error(BitcodeError E, const Twine &Message); 252 std::error_code Error(BitcodeError E); 253 std::error_code Error(const Twine &Message); 254 255 explicit BitcodeReader(MemoryBuffer *buffer, LLVMContext &C, 256 DiagnosticHandlerFunction DiagnosticHandler); 257 ~BitcodeReader() { FreeState(); } 258 259 void FreeState(); 260 261 void releaseBuffer(); 262 263 bool isDematerializable(const GlobalValue *GV) const; 264 std::error_code materialize(GlobalValue *GV) override; 265 std::error_code materializeModule() override; 266 std::vector<StructType *> getIdentifiedStructTypes() const override; 267 void dematerialize(GlobalValue *GV); 268 269 /// @brief Main interface to parsing a bitcode buffer. 270 /// @returns true if an error occurred. 271 std::error_code ParseBitcodeInto(Module *M); 272 273 /// @brief Cheap mechanism to just extract module triple 274 /// @returns true if an error occurred. 275 llvm::ErrorOr<std::string> parseTriple(); 276 277 static uint64_t decodeSignRotatedValue(uint64_t V); 278 279 /// Materialize any deferred Metadata block. 280 std::error_code materializeMetadata() override; 281 282 void setStripDebugInfo() override; 283 284 private: 285 std::vector<StructType *> IdentifiedStructTypes; 286 StructType *createIdentifiedStructType(LLVMContext &Context, StringRef Name); 287 StructType *createIdentifiedStructType(LLVMContext &Context); 288 289 Type *getTypeByID(unsigned ID); 290 Type *getTypeByIDOrNull(unsigned ID); 291 Value *getFnValueByID(unsigned ID, Type *Ty) { 292 if (Ty && Ty->isMetadataTy()) 293 return MetadataAsValue::get(Ty->getContext(), getFnMetadataByID(ID)); 294 return ValueList.getValueFwdRef(ID, Ty); 295 } 296 Metadata *getFnMetadataByID(unsigned ID) { 297 return MDValueList.getValueFwdRef(ID); 298 } 299 BasicBlock *getBasicBlock(unsigned ID) const { 300 if (ID >= FunctionBBs.size()) return nullptr; // Invalid ID 301 return FunctionBBs[ID]; 302 } 303 AttributeSet getAttributes(unsigned i) const { 304 if (i-1 < MAttributes.size()) 305 return MAttributes[i-1]; 306 return AttributeSet(); 307 } 308 309 /// getValueTypePair - Read a value/type pair out of the specified record from 310 /// slot 'Slot'. Increment Slot past the number of slots used in the record. 311 /// Return true on failure. 312 bool getValueTypePair(SmallVectorImpl<uint64_t> &Record, unsigned &Slot, 313 unsigned InstNum, Value *&ResVal) { 314 if (Slot == Record.size()) return true; 315 unsigned ValNo = (unsigned)Record[Slot++]; 316 if (ValNo < InstNum) { 317 // If this is not a forward reference, just return the value we already 318 // have. 319 ResVal = getFnValueByID(ValNo, nullptr); 320 return ResVal == nullptr; 321 } else if (Slot == Record.size()) { 322 return true; 323 } 324 325 unsigned TypeNo = (unsigned)Record[Slot++]; 326 ResVal = getFnValueByID(ValNo, getTypeByID(TypeNo)); 327 return ResVal == nullptr; 328 } 329 bool getValue(SmallVector<uint64_t, 64> &Record, unsigned &Slot, 330 Type *Ty, Value *&ResVal) { 331 if (Slot == Record.size()) return true; 332 unsigned ValNo = (unsigned)Record[Slot++]; 333 ResVal = getFnValueByID(ValNo, Ty); 334 return ResVal == 0; 335 } 336 337 338 std::error_code ParseModule(bool Resume); 339 std::error_code ParseAttributeBlock(); 340 std::error_code ParseTypeTable(); 341 std::error_code ParseOldTypeTable(); // FIXME: Remove in LLVM 3.1 342 std::error_code ParseTypeTableBody(); 343 344 std::error_code ParseOldTypeSymbolTable(); // FIXME: Remove in LLVM 3.1 345 std::error_code ParseValueSymbolTable(); 346 std::error_code ParseConstants(); 347 std::error_code RememberAndSkipFunctionBody(); 348 std::error_code ParseFunctionBody(Function *F); 349 std::error_code GlobalCleanup(); 350 std::error_code ResolveGlobalAndAliasInits(); 351 std::error_code ParseMetadata(); 352 std::error_code ParseMetadataAttachment(); 353 llvm::ErrorOr<std::string> parseModuleTriple(); 354 std::error_code InitStream(); 355 std::error_code InitStreamFromBuffer(); 356 std::error_code InitLazyStream(); 357 }; 358 } // end anonymous namespace 359 360 static std::error_code Error(DiagnosticHandlerFunction DiagnosticHandler, 361 std::error_code EC, const Twine &Message) { 362 BitcodeDiagnosticInfo DI(EC, DS_Error, Message); 363 DiagnosticHandler(DI); 364 return EC; 365 } 366 367 static std::error_code Error(DiagnosticHandlerFunction DiagnosticHandler, 368 std::error_code EC) { 369 return Error(DiagnosticHandler, EC, EC.message()); 370 } 371 372 std::error_code BitcodeReader::Error(BitcodeError E, const Twine &Message) { 373 return ::Error(DiagnosticHandler, make_error_code(E), Message); 374 } 375 376 std::error_code BitcodeReader::Error(const Twine &Message) { 377 return ::Error(DiagnosticHandler, 378 make_error_code(BitcodeError::CorruptedBitcode), Message); 379 } 380 381 std::error_code BitcodeReader::Error(BitcodeError E) { 382 return ::Error(DiagnosticHandler, make_error_code(E)); 383 } 384 385 static DiagnosticHandlerFunction getDiagHandler(DiagnosticHandlerFunction F, 386 LLVMContext &C) { 387 if (F) 388 return F; 389 return [&C](const DiagnosticInfo &DI) { C.diagnose(DI); }; 390 } 391 392 BitcodeReader::BitcodeReader(MemoryBuffer *buffer, LLVMContext &C, 393 DiagnosticHandlerFunction DiagnosticHandler) 394 : Context(C), DiagnosticHandler(getDiagHandler(DiagnosticHandler, C)), 395 TheModule(nullptr), Buffer(buffer), LazyStreamer(nullptr), 396 NextUnreadBit(0), SeenValueSymbolTable(false), ValueList(C), 397 MDValueList(C), SeenFirstFunctionBody(false), 398 LLVM2_7MetadataDetected(false) {} 399 400 401 void BitcodeReader::FreeState() { 402 Buffer = nullptr; 403 std::vector<Type*>().swap(TypeList); 404 ValueList.clear(); 405 MDValueList.clear(); 406 407 std::vector<AttributeSet>().swap(MAttributes); 408 std::vector<BasicBlock*>().swap(FunctionBBs); 409 std::vector<Function*>().swap(FunctionsWithBodies); 410 DeferredFunctionInfo.clear(); 411 MDKindMap.clear(); 412 } 413 414 //===----------------------------------------------------------------------===// 415 // Helper functions to implement forward reference resolution, etc. 416 //===----------------------------------------------------------------------===// 417 418 /// ConvertToString - Convert a string from a record into an std::string, return 419 /// true on failure. 420 template<typename StrTy> 421 static bool ConvertToString(ArrayRef<uint64_t> Record, unsigned Idx, 422 StrTy &Result) { 423 if (Idx > Record.size()) 424 return true; 425 426 for (unsigned i = Idx, e = Record.size(); i != e; ++i) 427 Result += (char)Record[i]; 428 return false; 429 } 430 431 static GlobalValue::LinkageTypes getDecodedLinkage(unsigned Val) { 432 switch (Val) { 433 default: // Map unknown/new linkages to external 434 case 0: 435 return GlobalValue::ExternalLinkage; 436 case 1: 437 return GlobalValue::WeakAnyLinkage; 438 case 2: 439 return GlobalValue::AppendingLinkage; 440 case 3: 441 return GlobalValue::InternalLinkage; 442 case 4: 443 return GlobalValue::LinkOnceAnyLinkage; 444 case 5: 445 return GlobalValue::ExternalLinkage; // Obsolete DLLImportLinkage 446 case 6: 447 return GlobalValue::ExternalLinkage; // Obsolete DLLExportLinkage 448 case 7: 449 return GlobalValue::ExternalWeakLinkage; 450 case 8: 451 return GlobalValue::CommonLinkage; 452 case 9: 453 return GlobalValue::PrivateLinkage; 454 case 10: 455 return GlobalValue::WeakODRLinkage; 456 case 11: 457 return GlobalValue::LinkOnceODRLinkage; 458 case 12: 459 return GlobalValue::AvailableExternallyLinkage; 460 case 13: 461 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateLinkage 462 case 14: 463 return GlobalValue::ExternalWeakLinkage; // Obsolete LinkerPrivateWeakLinkage 464 //ANDROID: convert LinkOnceODRAutoHideLinkage -> LinkOnceODRLinkage 465 case 15: 466 return GlobalValue::LinkOnceODRLinkage; 467 } 468 } 469 470 static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned Val) { 471 switch (Val) { 472 default: // Map unknown visibilities to default. 473 case 0: return GlobalValue::DefaultVisibility; 474 case 1: return GlobalValue::HiddenVisibility; 475 case 2: return GlobalValue::ProtectedVisibility; 476 } 477 } 478 479 static GlobalVariable::ThreadLocalMode GetDecodedThreadLocalMode(unsigned Val) { 480 switch (Val) { 481 case 0: return GlobalVariable::NotThreadLocal; 482 default: // Map unknown non-zero value to general dynamic. 483 case 1: return GlobalVariable::GeneralDynamicTLSModel; 484 case 2: return GlobalVariable::LocalDynamicTLSModel; 485 case 3: return GlobalVariable::InitialExecTLSModel; 486 case 4: return GlobalVariable::LocalExecTLSModel; 487 } 488 } 489 490 static int GetDecodedCastOpcode(unsigned Val) { 491 switch (Val) { 492 default: return -1; 493 case bitc::CAST_TRUNC : return Instruction::Trunc; 494 case bitc::CAST_ZEXT : return Instruction::ZExt; 495 case bitc::CAST_SEXT : return Instruction::SExt; 496 case bitc::CAST_FPTOUI : return Instruction::FPToUI; 497 case bitc::CAST_FPTOSI : return Instruction::FPToSI; 498 case bitc::CAST_UITOFP : return Instruction::UIToFP; 499 case bitc::CAST_SITOFP : return Instruction::SIToFP; 500 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc; 501 case bitc::CAST_FPEXT : return Instruction::FPExt; 502 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt; 503 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr; 504 case bitc::CAST_BITCAST : return Instruction::BitCast; 505 } 506 } 507 static int GetDecodedBinaryOpcode(unsigned Val, Type *Ty) { 508 switch (Val) { 509 default: return -1; 510 case bitc::BINOP_ADD: 511 return Ty->isFPOrFPVectorTy() ? Instruction::FAdd : Instruction::Add; 512 case bitc::BINOP_SUB: 513 return Ty->isFPOrFPVectorTy() ? Instruction::FSub : Instruction::Sub; 514 case bitc::BINOP_MUL: 515 return Ty->isFPOrFPVectorTy() ? Instruction::FMul : Instruction::Mul; 516 case bitc::BINOP_UDIV: return Instruction::UDiv; 517 case bitc::BINOP_SDIV: 518 return Ty->isFPOrFPVectorTy() ? Instruction::FDiv : Instruction::SDiv; 519 case bitc::BINOP_UREM: return Instruction::URem; 520 case bitc::BINOP_SREM: 521 return Ty->isFPOrFPVectorTy() ? Instruction::FRem : Instruction::SRem; 522 case bitc::BINOP_SHL: return Instruction::Shl; 523 case bitc::BINOP_LSHR: return Instruction::LShr; 524 case bitc::BINOP_ASHR: return Instruction::AShr; 525 case bitc::BINOP_AND: return Instruction::And; 526 case bitc::BINOP_OR: return Instruction::Or; 527 case bitc::BINOP_XOR: return Instruction::Xor; 528 } 529 } 530 531 namespace llvm { 532 namespace { 533 /// @brief A class for maintaining the slot number definition 534 /// as a placeholder for the actual definition for forward constants defs. 535 class ConstantPlaceHolder : public ConstantExpr { 536 void operator=(const ConstantPlaceHolder &) = delete; 537 public: 538 // allocate space for exactly one operand 539 void *operator new(size_t s) { 540 return User::operator new(s, 1); 541 } 542 explicit ConstantPlaceHolder(Type *Ty, LLVMContext& Context) 543 : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) { 544 Op<0>() = UndefValue::get(Type::getInt32Ty(Context)); 545 } 546 547 /// @brief Methods to support type inquiry through isa, cast, and dyn_cast. 548 static bool classof(const Value *V) { 549 return isa<ConstantExpr>(V) && 550 cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1; 551 } 552 553 554 /// Provide fast operand accessors 555 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value); 556 }; 557 } 558 559 // FIXME: can we inherit this from ConstantExpr? 560 template <> 561 struct OperandTraits<ConstantPlaceHolder> : 562 public FixedNumOperandTraits<ConstantPlaceHolder, 1> { 563 }; 564 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ConstantPlaceHolder, Value) 565 } 566 567 568 void BitcodeReaderValueList::AssignValue(Value *V, unsigned Idx) { 569 if (Idx == size()) { 570 push_back(V); 571 return; 572 } 573 574 if (Idx >= size()) 575 resize(Idx+1); 576 577 WeakVH &OldV = ValuePtrs[Idx]; 578 if (!OldV) { 579 OldV = V; 580 return; 581 } 582 583 // Handle constants and non-constants (e.g. instrs) differently for 584 // efficiency. 585 if (Constant *PHC = dyn_cast<Constant>(&*OldV)) { 586 ResolveConstants.push_back(std::make_pair(PHC, Idx)); 587 OldV = V; 588 } else { 589 // If there was a forward reference to this value, replace it. 590 Value *PrevVal = OldV; 591 OldV->replaceAllUsesWith(V); 592 delete PrevVal; 593 } 594 } 595 596 597 Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx, 598 Type *Ty) { 599 if (Idx >= size()) 600 resize(Idx + 1); 601 602 if (Value *V = ValuePtrs[Idx]) { 603 assert(Ty == V->getType() && "Type mismatch in constant table!"); 604 return cast<Constant>(V); 605 } 606 607 // Create and return a placeholder, which will later be RAUW'd. 608 Constant *C = new ConstantPlaceHolder(Ty, Context); 609 ValuePtrs[Idx] = C; 610 return C; 611 } 612 613 Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, Type *Ty) { 614 if (Idx >= size()) 615 resize(Idx + 1); 616 617 if (Value *V = ValuePtrs[Idx]) { 618 assert((!Ty || Ty == V->getType()) && "Type mismatch in value table!"); 619 return V; 620 } 621 622 // No type specified, must be invalid reference. 623 if (!Ty) return nullptr; 624 625 // Create and return a placeholder, which will later be RAUW'd. 626 Value *V = new Argument(Ty); 627 ValuePtrs[Idx] = V; 628 return V; 629 } 630 631 /// ResolveConstantForwardRefs - Once all constants are read, this method bulk 632 /// resolves any forward references. The idea behind this is that we sometimes 633 /// get constants (such as large arrays) which reference *many* forward ref 634 /// constants. Replacing each of these causes a lot of thrashing when 635 /// building/reuniquing the constant. Instead of doing this, we look at all the 636 /// uses and rewrite all the place holders at once for any constant that uses 637 /// a placeholder. 638 void BitcodeReaderValueList::ResolveConstantForwardRefs() { 639 // Sort the values by-pointer so that they are efficient to look up with a 640 // binary search. 641 std::sort(ResolveConstants.begin(), ResolveConstants.end()); 642 643 SmallVector<Constant*, 64> NewOps; 644 645 while (!ResolveConstants.empty()) { 646 Value *RealVal = operator[](ResolveConstants.back().second); 647 Constant *Placeholder = ResolveConstants.back().first; 648 ResolveConstants.pop_back(); 649 650 // Loop over all users of the placeholder, updating them to reference the 651 // new value. If they reference more than one placeholder, update them all 652 // at once. 653 while (!Placeholder->use_empty()) { 654 auto UI = Placeholder->user_begin(); 655 User *U = *UI; 656 657 // If the using object isn't uniqued, just update the operands. This 658 // handles instructions and initializers for global variables. 659 if (!isa<Constant>(U) || isa<GlobalValue>(U)) { 660 UI.getUse().set(RealVal); 661 continue; 662 } 663 664 // Otherwise, we have a constant that uses the placeholder. Replace that 665 // constant with a new constant that has *all* placeholder uses updated. 666 Constant *UserC = cast<Constant>(U); 667 for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end(); 668 I != E; ++I) { 669 Value *NewOp; 670 if (!isa<ConstantPlaceHolder>(*I)) { 671 // Not a placeholder reference. 672 NewOp = *I; 673 } else if (*I == Placeholder) { 674 // Common case is that it just references this one placeholder. 675 NewOp = RealVal; 676 } else { 677 // Otherwise, look up the placeholder in ResolveConstants. 678 ResolveConstantsTy::iterator It = 679 std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(), 680 std::pair<Constant*, unsigned>(cast<Constant>(*I), 681 0)); 682 assert(It != ResolveConstants.end() && It->first == *I); 683 NewOp = operator[](It->second); 684 } 685 686 NewOps.push_back(cast<Constant>(NewOp)); 687 } 688 689 // Make the new constant. 690 Constant *NewC; 691 if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) { 692 NewC = ConstantArray::get(UserCA->getType(), NewOps); 693 } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) { 694 NewC = ConstantStruct::get(UserCS->getType(), NewOps); 695 } else if (isa<ConstantVector>(UserC)) { 696 NewC = ConstantVector::get(NewOps); 697 } else { 698 assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr."); 699 NewC = cast<ConstantExpr>(UserC)->getWithOperands(NewOps); 700 } 701 702 UserC->replaceAllUsesWith(NewC); 703 UserC->destroyConstant(); 704 NewOps.clear(); 705 } 706 707 // Update all ValueHandles, they should be the only users at this point. 708 Placeholder->replaceAllUsesWith(RealVal); 709 delete Placeholder; 710 } 711 } 712 713 void BitcodeReaderMDValueList::AssignValue(Metadata *MD, unsigned Idx) { 714 if (Idx == size()) { 715 push_back(MD); 716 return; 717 } 718 719 if (Idx >= size()) 720 resize(Idx+1); 721 722 TrackingMDRef &OldMD = MDValuePtrs[Idx]; 723 if (!OldMD) { 724 OldMD.reset(MD); 725 return; 726 } 727 728 // If there was a forward reference to this value, replace it. 729 TempMDTuple PrevMD(cast<MDTuple>(OldMD.get())); 730 PrevMD->replaceAllUsesWith(MD); 731 --NumFwdRefs; 732 } 733 734 Metadata *BitcodeReaderMDValueList::getValueFwdRef(unsigned Idx) { 735 if (Idx >= size()) 736 resize(Idx + 1); 737 738 if (Metadata *MD = MDValuePtrs[Idx]) 739 return MD; 740 741 // Create and return a placeholder, which will later be RAUW'd. 742 AnyFwdRefs = true; 743 ++NumFwdRefs; 744 Metadata *MD = MDNode::getTemporary(Context, None).release(); 745 MDValuePtrs[Idx].reset(MD); 746 return MD; 747 } 748 749 void BitcodeReaderMDValueList::tryToResolveCycles() { 750 if (!AnyFwdRefs) 751 // Nothing to do. 752 return; 753 754 if (NumFwdRefs) 755 // Still forward references... can't resolve cycles. 756 return; 757 758 // Resolve any cycles. 759 for (auto &MD : MDValuePtrs) { 760 auto *N = dyn_cast_or_null<MDNode>(MD); 761 if (!N) 762 continue; 763 764 assert(!N->isTemporary() && "Unexpected forward reference"); 765 N->resolveCycles(); 766 } 767 } 768 769 Type *BitcodeReader::getTypeByID(unsigned ID) { 770 // The type table size is always specified correctly. 771 if (ID >= TypeList.size()) 772 return nullptr; 773 774 if (Type *Ty = TypeList[ID]) 775 return Ty; 776 777 // If we have a forward reference, the only possible case is when it is to a 778 // named struct. Just create a placeholder for now. 779 return TypeList[ID] = createIdentifiedStructType(Context); 780 } 781 782 StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context, 783 StringRef Name) { 784 auto *Ret = StructType::create(Context, Name); 785 IdentifiedStructTypes.push_back(Ret); 786 return Ret; 787 } 788 789 StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context) { 790 auto *Ret = StructType::create(Context); 791 IdentifiedStructTypes.push_back(Ret); 792 return Ret; 793 } 794 795 796 /// FIXME: Remove in LLVM 3.1, only used by ParseOldTypeTable. 797 Type *BitcodeReader::getTypeByIDOrNull(unsigned ID) { 798 if (ID >= TypeList.size()) 799 TypeList.resize(ID+1); 800 801 return TypeList[ID]; 802 } 803 804 //===----------------------------------------------------------------------===// 805 // Functions for parsing blocks from the bitcode file 806 //===----------------------------------------------------------------------===// 807 808 809 /// \brief This fills an AttrBuilder object with the LLVM attributes that have 810 /// been decoded from the given integer. This function must stay in sync with 811 /// 'encodeLLVMAttributesForBitcode'. 812 static void decodeLLVMAttributesForBitcode(AttrBuilder &B, 813 uint64_t EncodedAttrs) { 814 // FIXME: Remove in 4.0. 815 816 // The alignment is stored as a 16-bit raw value from bits 31--16. We shift 817 // the bits above 31 down by 11 bits. 818 unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16; 819 assert((!Alignment || isPowerOf2_32(Alignment)) && 820 "Alignment must be a power of two."); 821 822 if (Alignment) 823 B.addAlignmentAttr(Alignment); 824 B.addRawValue(((EncodedAttrs & (0xfffffULL << 32)) >> 11) | 825 (EncodedAttrs & 0xffff)); 826 } 827 828 std::error_code BitcodeReader::ParseAttributeBlock() { 829 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID)) 830 return Error("Invalid record"); 831 832 if (!MAttributes.empty()) 833 return Error("Invalid multiple blocks"); 834 835 SmallVector<uint64_t, 64> Record; 836 837 SmallVector<AttributeSet, 8> Attrs; 838 839 // Read all the records. 840 while (1) { 841 BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 842 843 switch (Entry.Kind) { 844 case BitstreamEntry::SubBlock: // Handled for us already. 845 case BitstreamEntry::Error: 846 return Error("Malformed block"); 847 case BitstreamEntry::EndBlock: 848 return std::error_code(); 849 case BitstreamEntry::Record: 850 // The interesting case. 851 break; 852 } 853 854 // Read a record. 855 Record.clear(); 856 switch (Stream.readRecord(Entry.ID, Record)) { 857 default: // Default behavior: ignore. 858 break; 859 case bitc::PARAMATTR_CODE_ENTRY_OLD: { // ENTRY: [paramidx0, attr0, ...] 860 if (Record.size() & 1) 861 return Error("Invalid record"); 862 863 for (unsigned i = 0, e = Record.size(); i != e; i += 2) { 864 AttrBuilder B; 865 decodeLLVMAttributesForBitcode(B, Record[i+1]); 866 Attrs.push_back(AttributeSet::get(Context, Record[i], B)); 867 } 868 869 MAttributes.push_back(AttributeSet::get(Context, Attrs)); 870 Attrs.clear(); 871 break; 872 } 873 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [attrgrp0, attrgrp1, ...] 874 for (unsigned i = 0, e = Record.size(); i != e; ++i) 875 Attrs.push_back(MAttributeGroups[Record[i]]); 876 877 MAttributes.push_back(AttributeSet::get(Context, Attrs)); 878 Attrs.clear(); 879 break; 880 } 881 } 882 } 883 } 884 885 886 std::error_code BitcodeReader::ParseTypeTable() { 887 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW)) 888 return Error("Invalid record"); 889 890 return ParseTypeTableBody(); 891 } 892 893 std::error_code BitcodeReader::ParseTypeTableBody() { 894 if (!TypeList.empty()) 895 return Error("Invalid multiple blocks"); 896 897 SmallVector<uint64_t, 64> Record; 898 unsigned NumRecords = 0; 899 900 SmallString<64> TypeName; 901 902 // Read all the records for this type table. 903 while (1) { 904 BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 905 906 switch (Entry.Kind) { 907 case BitstreamEntry::SubBlock: // Handled for us already. 908 case BitstreamEntry::Error: 909 return Error("Malformed block"); 910 case BitstreamEntry::EndBlock: 911 if (NumRecords != TypeList.size()) 912 return Error("Malformed block"); 913 return std::error_code(); 914 case BitstreamEntry::Record: 915 // The interesting case. 916 break; 917 } 918 919 // Read a record. 920 Record.clear(); 921 Type *ResultTy = nullptr; 922 switch (Stream.readRecord(Entry.ID, Record)) { 923 default: 924 return Error("Invalid value"); 925 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries] 926 // TYPE_CODE_NUMENTRY contains a count of the number of types in the 927 // type list. This allows us to reserve space. 928 if (Record.size() < 1) 929 return Error("Invalid record"); 930 TypeList.resize(Record[0]); 931 continue; 932 case bitc::TYPE_CODE_VOID: // VOID 933 ResultTy = Type::getVoidTy(Context); 934 break; 935 case bitc::TYPE_CODE_HALF: // HALF 936 ResultTy = Type::getHalfTy(Context); 937 break; 938 case bitc::TYPE_CODE_FLOAT: // FLOAT 939 ResultTy = Type::getFloatTy(Context); 940 break; 941 case bitc::TYPE_CODE_DOUBLE: // DOUBLE 942 ResultTy = Type::getDoubleTy(Context); 943 break; 944 case bitc::TYPE_CODE_X86_FP80: // X86_FP80 945 ResultTy = Type::getX86_FP80Ty(Context); 946 break; 947 case bitc::TYPE_CODE_FP128: // FP128 948 ResultTy = Type::getFP128Ty(Context); 949 break; 950 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128 951 ResultTy = Type::getPPC_FP128Ty(Context); 952 break; 953 case bitc::TYPE_CODE_LABEL: // LABEL 954 ResultTy = Type::getLabelTy(Context); 955 break; 956 case bitc::TYPE_CODE_METADATA: // METADATA 957 ResultTy = Type::getMetadataTy(Context); 958 break; 959 case bitc::TYPE_CODE_X86_MMX: // X86_MMX 960 ResultTy = Type::getX86_MMXTy(Context); 961 break; 962 case bitc::TYPE_CODE_INTEGER: // INTEGER: [width] 963 if (Record.size() < 1) 964 return Error("Invalid record"); 965 966 ResultTy = IntegerType::get(Context, Record[0]); 967 break; 968 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or 969 // [pointee type, address space] 970 if (Record.size() < 1) 971 return Error("Invalid record"); 972 unsigned AddressSpace = 0; 973 if (Record.size() == 2) 974 AddressSpace = Record[1]; 975 ResultTy = getTypeByID(Record[0]); 976 if (!ResultTy) 977 return Error("Invalid type"); 978 ResultTy = PointerType::get(ResultTy, AddressSpace); 979 break; 980 } 981 case bitc::TYPE_CODE_FUNCTION_OLD: { 982 // FIXME: attrid is dead, remove it in LLVM 4.0 983 // FUNCTION: [vararg, attrid, retty, paramty x N] 984 if (Record.size() < 3) 985 return Error("Invalid record"); 986 SmallVector<Type*, 8> ArgTys; 987 for (unsigned i = 3, e = Record.size(); i != e; ++i) { 988 if (Type *T = getTypeByID(Record[i])) 989 ArgTys.push_back(T); 990 else 991 break; 992 } 993 994 ResultTy = getTypeByID(Record[2]); 995 if (!ResultTy || ArgTys.size() < Record.size()-3) 996 return Error("Invalid type"); 997 998 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]); 999 break; 1000 } 1001 case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N] 1002 if (Record.size() < 1) 1003 return Error("Invalid record"); 1004 SmallVector<Type*, 8> EltTys; 1005 for (unsigned i = 1, e = Record.size(); i != e; ++i) { 1006 if (Type *T = getTypeByID(Record[i])) 1007 EltTys.push_back(T); 1008 else 1009 break; 1010 } 1011 if (EltTys.size() != Record.size()-1) 1012 return Error("Invalid type"); 1013 ResultTy = StructType::get(Context, EltTys, Record[0]); 1014 break; 1015 } 1016 case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N] 1017 if (ConvertToString(Record, 0, TypeName)) 1018 return Error("Invalid record"); 1019 continue; 1020 1021 case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N] 1022 if (Record.size() < 1) 1023 return Error("Invalid record"); 1024 1025 if (NumRecords >= TypeList.size()) 1026 return Error("Invalid TYPE table"); 1027 1028 // Check to see if this was forward referenced, if so fill in the temp. 1029 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]); 1030 if (Res) { 1031 Res->setName(TypeName); 1032 TypeList[NumRecords] = nullptr; 1033 } else // Otherwise, create a new struct. 1034 Res = createIdentifiedStructType(Context, TypeName); 1035 TypeName.clear(); 1036 1037 SmallVector<Type*, 8> EltTys; 1038 for (unsigned i = 1, e = Record.size(); i != e; ++i) { 1039 if (Type *T = getTypeByID(Record[i])) 1040 EltTys.push_back(T); 1041 else 1042 break; 1043 } 1044 if (EltTys.size() != Record.size()-1) 1045 return Error("Invalid record"); 1046 Res->setBody(EltTys, Record[0]); 1047 ResultTy = Res; 1048 break; 1049 } 1050 case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: [] 1051 if (Record.size() != 1) 1052 return Error("Invalid record"); 1053 1054 if (NumRecords >= TypeList.size()) 1055 return Error("Invalid TYPE table"); 1056 1057 // Check to see if this was forward referenced, if so fill in the temp. 1058 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]); 1059 if (Res) { 1060 Res->setName(TypeName); 1061 TypeList[NumRecords] = nullptr; 1062 } else // Otherwise, create a new struct with no body. 1063 Res = createIdentifiedStructType(Context, TypeName); 1064 TypeName.clear(); 1065 ResultTy = Res; 1066 break; 1067 } 1068 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty] 1069 if (Record.size() < 2) 1070 return Error("Invalid record"); 1071 if ((ResultTy = getTypeByID(Record[1]))) 1072 ResultTy = ArrayType::get(ResultTy, Record[0]); 1073 else 1074 return Error("Invalid type"); 1075 break; 1076 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty] 1077 if (Record.size() < 2) 1078 return Error("Invalid record"); 1079 if ((ResultTy = getTypeByID(Record[1]))) 1080 ResultTy = VectorType::get(ResultTy, Record[0]); 1081 else 1082 return Error("Invalid type"); 1083 break; 1084 } 1085 1086 if (NumRecords >= TypeList.size()) 1087 return Error("Invalid TYPE table"); 1088 assert(ResultTy && "Didn't read a type?"); 1089 assert(!TypeList[NumRecords] && "Already read type?"); 1090 TypeList[NumRecords++] = ResultTy; 1091 } 1092 } 1093 1094 // FIXME: Remove in LLVM 3.1 1095 std::error_code BitcodeReader::ParseOldTypeTable() { 1096 if (Stream.EnterSubBlock(TYPE_BLOCK_ID_OLD_3_0)) 1097 return Error("Malformed block"); 1098 1099 if (!TypeList.empty()) 1100 return Error("Invalid TYPE table"); 1101 1102 1103 // While horrible, we have no good ordering of types in the bc file. Just 1104 // iteratively parse types out of the bc file in multiple passes until we get 1105 // them all. Do this by saving a cursor for the start of the type block. 1106 BitstreamCursor StartOfTypeBlockCursor(Stream); 1107 1108 unsigned NumTypesRead = 0; 1109 1110 SmallVector<uint64_t, 64> Record; 1111 RestartScan: 1112 unsigned NextTypeID = 0; 1113 bool ReadAnyTypes = false; 1114 1115 // Read all the records for this type table. 1116 while (1) { 1117 unsigned Code = Stream.ReadCode(); 1118 if (Code == bitc::END_BLOCK) { 1119 if (NextTypeID != TypeList.size()) 1120 return Error("Invalid TYPE table"); 1121 1122 // If we haven't read all of the types yet, iterate again. 1123 if (NumTypesRead != TypeList.size()) { 1124 // If we didn't successfully read any types in this pass, then we must 1125 // have an unhandled forward reference. 1126 if (!ReadAnyTypes) 1127 return Error("Invalid TYPE table"); 1128 1129 Stream = StartOfTypeBlockCursor; 1130 goto RestartScan; 1131 } 1132 1133 if (Stream.ReadBlockEnd()) 1134 return Error("Invalid TYPE table"); 1135 return std::error_code(); 1136 } 1137 1138 if (Code == bitc::ENTER_SUBBLOCK) { 1139 // No known subblocks, always skip them. 1140 Stream.ReadSubBlockID(); 1141 if (Stream.SkipBlock()) 1142 return Error("Malformed block"); 1143 continue; 1144 } 1145 1146 if (Code == bitc::DEFINE_ABBREV) { 1147 Stream.ReadAbbrevRecord(); 1148 continue; 1149 } 1150 1151 // Read a record. 1152 Record.clear(); 1153 Type *ResultTy = nullptr; 1154 switch (Stream.readRecord(Code, Record)) { 1155 default: return Error("Invalid TYPE table"); 1156 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries] 1157 // TYPE_CODE_NUMENTRY contains a count of the number of types in the 1158 // type list. This allows us to reserve space. 1159 if (Record.size() < 1) 1160 return Error("Invalid TYPE table"); 1161 TypeList.resize(Record[0]); 1162 continue; 1163 case bitc::TYPE_CODE_VOID: // VOID 1164 ResultTy = Type::getVoidTy(Context); 1165 break; 1166 case bitc::TYPE_CODE_FLOAT: // FLOAT 1167 ResultTy = Type::getFloatTy(Context); 1168 break; 1169 case bitc::TYPE_CODE_DOUBLE: // DOUBLE 1170 ResultTy = Type::getDoubleTy(Context); 1171 break; 1172 case bitc::TYPE_CODE_X86_FP80: // X86_FP80 1173 ResultTy = Type::getX86_FP80Ty(Context); 1174 break; 1175 case bitc::TYPE_CODE_FP128: // FP128 1176 ResultTy = Type::getFP128Ty(Context); 1177 break; 1178 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128 1179 ResultTy = Type::getPPC_FP128Ty(Context); 1180 break; 1181 case bitc::TYPE_CODE_LABEL: // LABEL 1182 ResultTy = Type::getLabelTy(Context); 1183 break; 1184 case bitc::TYPE_CODE_METADATA: // METADATA 1185 ResultTy = Type::getMetadataTy(Context); 1186 break; 1187 case bitc::TYPE_CODE_X86_MMX: // X86_MMX 1188 ResultTy = Type::getX86_MMXTy(Context); 1189 break; 1190 case bitc::TYPE_CODE_INTEGER: // INTEGER: [width] 1191 if (Record.size() < 1) 1192 return Error("Invalid TYPE table"); 1193 ResultTy = IntegerType::get(Context, Record[0]); 1194 break; 1195 case bitc::TYPE_CODE_OPAQUE: // OPAQUE 1196 if (NextTypeID < TypeList.size() && TypeList[NextTypeID] == 0) 1197 ResultTy = StructType::create(Context, ""); 1198 break; 1199 case TYPE_CODE_STRUCT_OLD_3_0: {// STRUCT_OLD 1200 if (NextTypeID >= TypeList.size()) break; 1201 // If we already read it, don't reprocess. 1202 if (TypeList[NextTypeID] && 1203 !cast<StructType>(TypeList[NextTypeID])->isOpaque()) 1204 break; 1205 1206 // Set a type. 1207 if (TypeList[NextTypeID] == 0) 1208 TypeList[NextTypeID] = StructType::create(Context, ""); 1209 1210 std::vector<Type*> EltTys; 1211 for (unsigned i = 1, e = Record.size(); i != e; ++i) { 1212 if (Type *Elt = getTypeByIDOrNull(Record[i])) 1213 EltTys.push_back(Elt); 1214 else 1215 break; 1216 } 1217 1218 if (EltTys.size() != Record.size()-1) 1219 break; // Not all elements are ready. 1220 1221 cast<StructType>(TypeList[NextTypeID])->setBody(EltTys, Record[0]); 1222 ResultTy = TypeList[NextTypeID]; 1223 TypeList[NextTypeID] = 0; 1224 break; 1225 } 1226 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or 1227 // [pointee type, address space] 1228 if (Record.size() < 1) 1229 return Error("Invalid TYPE table"); 1230 unsigned AddressSpace = 0; 1231 if (Record.size() == 2) 1232 AddressSpace = Record[1]; 1233 if ((ResultTy = getTypeByIDOrNull(Record[0]))) 1234 ResultTy = PointerType::get(ResultTy, AddressSpace); 1235 break; 1236 } 1237 case bitc::TYPE_CODE_FUNCTION_OLD: { 1238 // FIXME: attrid is dead, remove it in LLVM 3.0 1239 // FUNCTION: [vararg, attrid, retty, paramty x N] 1240 if (Record.size() < 3) 1241 return Error("Invalid TYPE table"); 1242 std::vector<Type*> ArgTys; 1243 for (unsigned i = 3, e = Record.size(); i != e; ++i) { 1244 if (Type *Elt = getTypeByIDOrNull(Record[i])) 1245 ArgTys.push_back(Elt); 1246 else 1247 break; 1248 } 1249 if (ArgTys.size()+3 != Record.size()) 1250 break; // Something was null. 1251 if ((ResultTy = getTypeByIDOrNull(Record[2]))) 1252 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]); 1253 break; 1254 } 1255 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty] 1256 if (Record.size() < 2) 1257 return Error("Invalid TYPE table"); 1258 if ((ResultTy = getTypeByIDOrNull(Record[1]))) 1259 ResultTy = ArrayType::get(ResultTy, Record[0]); 1260 break; 1261 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty] 1262 if (Record.size() < 2) 1263 return Error("Invalid TYPE table"); 1264 if ((ResultTy = getTypeByIDOrNull(Record[1]))) 1265 ResultTy = VectorType::get(ResultTy, Record[0]); 1266 break; 1267 } 1268 1269 if (NextTypeID >= TypeList.size()) 1270 return Error("Invalid TYPE table"); 1271 1272 if (ResultTy && TypeList[NextTypeID] == 0) { 1273 ++NumTypesRead; 1274 ReadAnyTypes = true; 1275 1276 TypeList[NextTypeID] = ResultTy; 1277 } 1278 1279 ++NextTypeID; 1280 } 1281 } 1282 1283 1284 std::error_code BitcodeReader::ParseOldTypeSymbolTable() { 1285 if (Stream.EnterSubBlock(TYPE_SYMTAB_BLOCK_ID_OLD_3_0)) 1286 return Error("Malformed block"); 1287 1288 SmallVector<uint64_t, 64> Record; 1289 1290 // Read all the records for this type table. 1291 std::string TypeName; 1292 while (1) { 1293 unsigned Code = Stream.ReadCode(); 1294 if (Code == bitc::END_BLOCK) { 1295 if (Stream.ReadBlockEnd()) 1296 return Error("Malformed block"); 1297 return std::error_code(); 1298 } 1299 1300 if (Code == bitc::ENTER_SUBBLOCK) { 1301 // No known subblocks, always skip them. 1302 Stream.ReadSubBlockID(); 1303 if (Stream.SkipBlock()) 1304 return Error("Malformed block"); 1305 continue; 1306 } 1307 1308 if (Code == bitc::DEFINE_ABBREV) { 1309 Stream.ReadAbbrevRecord(); 1310 continue; 1311 } 1312 1313 // Read a record. 1314 Record.clear(); 1315 switch (Stream.readRecord(Code, Record)) { 1316 default: // Default behavior: unknown type. 1317 break; 1318 case bitc::TST_CODE_ENTRY: // TST_ENTRY: [typeid, namechar x N] 1319 if (ConvertToString(Record, 1, TypeName)) 1320 return Error("Invalid record"); 1321 unsigned TypeID = Record[0]; 1322 if (TypeID >= TypeList.size()) 1323 return Error("Invalid record"); 1324 1325 // Only apply the type name to a struct type with no name. 1326 if (StructType *STy = dyn_cast<StructType>(TypeList[TypeID])) 1327 if (!STy->isLiteral() && !STy->hasName()) 1328 STy->setName(TypeName); 1329 TypeName.clear(); 1330 break; 1331 } 1332 } 1333 } 1334 1335 std::error_code BitcodeReader::ParseValueSymbolTable() { 1336 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID)) 1337 return Error("Invalid record"); 1338 1339 SmallVector<uint64_t, 64> Record; 1340 1341 // Read all the records for this value table. 1342 SmallString<128> ValueName; 1343 while (1) { 1344 unsigned Code = Stream.ReadCode(); 1345 if (Code == bitc::END_BLOCK) { 1346 if (Stream.ReadBlockEnd()) 1347 return Error("Malformed block"); 1348 return std::error_code(); 1349 } 1350 if (Code == bitc::ENTER_SUBBLOCK) { 1351 // No known subblocks, always skip them. 1352 Stream.ReadSubBlockID(); 1353 if (Stream.SkipBlock()) 1354 return Error("Malformed block"); 1355 continue; 1356 } 1357 1358 if (Code == bitc::DEFINE_ABBREV) { 1359 Stream.ReadAbbrevRecord(); 1360 continue; 1361 } 1362 1363 // Read a record. 1364 Record.clear(); 1365 switch (Stream.readRecord(Code, Record)) { 1366 default: // Default behavior: unknown type. 1367 break; 1368 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N] 1369 if (ConvertToString(Record, 1, ValueName)) 1370 return Error("Invalid record"); 1371 unsigned ValueID = Record[0]; 1372 if (ValueID >= ValueList.size()) 1373 return Error("Invalid record"); 1374 Value *V = ValueList[ValueID]; 1375 1376 V->setName(StringRef(ValueName.data(), ValueName.size())); 1377 ValueName.clear(); 1378 break; 1379 } 1380 case bitc::VST_CODE_BBENTRY: { 1381 if (ConvertToString(Record, 1, ValueName)) 1382 return Error("Invalid record"); 1383 BasicBlock *BB = getBasicBlock(Record[0]); 1384 if (!BB) 1385 return Error("Invalid record"); 1386 1387 BB->setName(StringRef(ValueName.data(), ValueName.size())); 1388 ValueName.clear(); 1389 break; 1390 } 1391 } 1392 } 1393 } 1394 1395 std::error_code BitcodeReader::ParseMetadata() { 1396 unsigned NextMDValueNo = MDValueList.size(); 1397 1398 if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID)) 1399 return Error("Invalid record"); 1400 1401 SmallVector<uint64_t, 64> Record; 1402 1403 // Read all the records. 1404 while (1) { 1405 unsigned Code = Stream.ReadCode(); 1406 if (Code == bitc::END_BLOCK) { 1407 if (Stream.ReadBlockEnd()) 1408 return Error("Malformed block"); 1409 return std::error_code(); 1410 } 1411 1412 if (Code == bitc::ENTER_SUBBLOCK) { 1413 // No known subblocks, always skip them. 1414 Stream.ReadSubBlockID(); 1415 if (Stream.SkipBlock()) 1416 return Error("Malformed block"); 1417 continue; 1418 } 1419 1420 if (Code == bitc::DEFINE_ABBREV) { 1421 Stream.ReadAbbrevRecord(); 1422 continue; 1423 } 1424 1425 bool IsFunctionLocal = false; 1426 // Read a record. 1427 Record.clear(); 1428 Code = Stream.readRecord(Code, Record); 1429 switch (Code) { 1430 default: // Default behavior: ignore. 1431 break; 1432 case bitc::METADATA_NAME: { 1433 // Read named of the named metadata. 1434 unsigned NameLength = Record.size(); 1435 SmallString<8> Name; 1436 Name.resize(NameLength); 1437 for (unsigned i = 0; i != NameLength; ++i) 1438 Name[i] = Record[i]; 1439 Record.clear(); 1440 Code = Stream.ReadCode(); 1441 1442 // METADATA_NAME is always followed by METADATA_NAMED_NODE. 1443 unsigned NextBitCode = Stream.readRecord(Code, Record); 1444 if (NextBitCode == METADATA_NAMED_NODE_2_7) { 1445 LLVM2_7MetadataDetected = true; 1446 } else if (NextBitCode != bitc::METADATA_NAMED_NODE) { 1447 assert(!"Invalid Named Metadata record."); (void)NextBitCode; 1448 } 1449 1450 // Read named metadata elements. 1451 unsigned Size = Record.size(); 1452 NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name); 1453 for (unsigned i = 0; i != Size; ++i) { 1454 MDNode *MD = dyn_cast_or_null<MDNode>(MDValueList.getValueFwdRef(Record[i])); 1455 if (!MD) 1456 return Error("Invalid record"); 1457 NMD->addOperand(MD); 1458 } 1459 1460 if (LLVM2_7MetadataDetected) { 1461 MDValueList.AssignValue(0, NextMDValueNo++); 1462 } 1463 break; 1464 } 1465 case METADATA_FN_NODE_2_7: 1466 case bitc::METADATA_OLD_FN_NODE: 1467 IsFunctionLocal = true; 1468 // fall-through 1469 case METADATA_NODE_2_7: 1470 case bitc::METADATA_OLD_NODE: { 1471 if (Code == METADATA_FN_NODE_2_7 || 1472 Code == METADATA_NODE_2_7) { 1473 LLVM2_7MetadataDetected = true; 1474 } 1475 1476 if (Record.size() % 2 == 1) 1477 return Error("Invalid record"); 1478 1479 unsigned Size = Record.size(); 1480 SmallVector<Metadata *, 8> Elts; 1481 for (unsigned i = 0; i != Size; i += 2) { 1482 Type *Ty = getTypeByID(Record[i]); 1483 if (!Ty) 1484 return Error("Invalid record"); 1485 if (Ty->isMetadataTy()) 1486 Elts.push_back(MDValueList.getValueFwdRef(Record[i+1])); 1487 else if (!Ty->isVoidTy()) { 1488 auto *MD = 1489 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[i + 1], Ty)); 1490 assert(isa<ConstantAsMetadata>(MD) && 1491 "Expected non-function-local metadata"); 1492 Elts.push_back(MD); 1493 } else 1494 Elts.push_back(nullptr); 1495 } 1496 MDValueList.AssignValue(MDNode::get(Context, Elts), NextMDValueNo++); 1497 break; 1498 } 1499 case bitc::METADATA_STRING: { 1500 std::string String(Record.begin(), Record.end()); 1501 llvm::UpgradeMDStringConstant(String); 1502 Metadata *MD = MDString::get(Context, String); 1503 MDValueList.AssignValue(MD, NextMDValueNo++); 1504 break; 1505 } 1506 case bitc::METADATA_KIND: { 1507 if (Record.size() < 2) 1508 return Error("Invalid record"); 1509 1510 unsigned Kind = Record[0]; 1511 SmallString<8> Name(Record.begin()+1, Record.end()); 1512 1513 unsigned NewKind = TheModule->getMDKindID(Name.str()); 1514 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second) 1515 return Error("Conflicting METADATA_KIND records"); 1516 break; 1517 } 1518 } 1519 } 1520 } 1521 1522 /// decodeSignRotatedValue - Decode a signed value stored with the sign bit in 1523 /// the LSB for dense VBR encoding. 1524 uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) { 1525 if ((V & 1) == 0) 1526 return V >> 1; 1527 if (V != 1) 1528 return -(V >> 1); 1529 // There is no such thing as -0 with integers. "-0" really means MININT. 1530 return 1ULL << 63; 1531 } 1532 1533 // FIXME: Delete this in LLVM 4.0 and just assert that the aliasee is a 1534 // GlobalObject. 1535 static GlobalObject & 1536 getGlobalObjectInExpr(const DenseMap<GlobalAlias *, Constant *> &Map, 1537 Constant &C) { 1538 auto *GO = dyn_cast<GlobalObject>(&C); 1539 if (GO) 1540 return *GO; 1541 1542 auto *GA = dyn_cast<GlobalAlias>(&C); 1543 if (GA) 1544 return getGlobalObjectInExpr(Map, *Map.find(GA)->second); 1545 1546 auto &CE = cast<ConstantExpr>(C); 1547 assert(CE.getOpcode() == Instruction::BitCast || 1548 CE.getOpcode() == Instruction::GetElementPtr || 1549 CE.getOpcode() == Instruction::AddrSpaceCast); 1550 if (CE.getOpcode() == Instruction::GetElementPtr) 1551 assert(cast<GEPOperator>(CE).hasAllZeroIndices()); 1552 return getGlobalObjectInExpr(Map, *CE.getOperand(0)); 1553 } 1554 1555 /// ResolveGlobalAndAliasInits - Resolve all of the initializers for global 1556 /// values and aliases that we can. 1557 std::error_code BitcodeReader::ResolveGlobalAndAliasInits() { 1558 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist; 1559 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist; 1560 1561 GlobalInitWorklist.swap(GlobalInits); 1562 AliasInitWorklist.swap(AliasInits); 1563 1564 while (!GlobalInitWorklist.empty()) { 1565 unsigned ValID = GlobalInitWorklist.back().second; 1566 if (ValID >= ValueList.size()) { 1567 // Not ready to resolve this yet, it requires something later in the file. 1568 GlobalInits.push_back(GlobalInitWorklist.back()); 1569 } else { 1570 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID])) 1571 GlobalInitWorklist.back().first->setInitializer(C); 1572 else 1573 return Error("Expected a constant"); 1574 } 1575 GlobalInitWorklist.pop_back(); 1576 } 1577 1578 // FIXME: Delete this in LLVM 4.0 1579 // Older versions of llvm could write an alias pointing to another. We cannot 1580 // construct those aliases, so we first collect an alias to aliasee expression 1581 // and then compute the actual aliasee. 1582 DenseMap<GlobalAlias *, Constant *> AliasInit; 1583 1584 while (!AliasInitWorklist.empty()) { 1585 unsigned ValID = AliasInitWorklist.back().second; 1586 if (ValID >= ValueList.size()) { 1587 AliasInits.push_back(AliasInitWorklist.back()); 1588 } else { 1589 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID])) 1590 AliasInit.insert(std::make_pair(AliasInitWorklist.back().first, C)); 1591 else 1592 return Error("Expected a constant"); 1593 } 1594 AliasInitWorklist.pop_back(); 1595 } 1596 1597 for (auto &Pair : AliasInit) { 1598 auto &GO = getGlobalObjectInExpr(AliasInit, *Pair.second); 1599 Pair.first->setAliasee(&GO); 1600 } 1601 1602 return std::error_code(); 1603 } 1604 1605 static APInt ReadWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) { 1606 SmallVector<uint64_t, 8> Words(Vals.size()); 1607 std::transform(Vals.begin(), Vals.end(), Words.begin(), 1608 BitcodeReader::decodeSignRotatedValue); 1609 1610 return APInt(TypeBits, Words); 1611 } 1612 1613 std::error_code BitcodeReader::ParseConstants() { 1614 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID)) 1615 return Error("Invalid record"); 1616 1617 SmallVector<uint64_t, 64> Record; 1618 1619 // Read all the records for this value table. 1620 Type *CurTy = Type::getInt32Ty(Context); 1621 unsigned NextCstNo = ValueList.size(); 1622 while (1) { 1623 BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 1624 1625 switch (Entry.Kind) { 1626 case BitstreamEntry::SubBlock: // Handled for us already. 1627 case BitstreamEntry::Error: 1628 return Error("Malformed block"); 1629 case BitstreamEntry::EndBlock: 1630 if (NextCstNo != ValueList.size()) 1631 return Error("Invalid constant reference"); 1632 1633 // Once all the constants have been read, go through and resolve forward 1634 // references. 1635 ValueList.ResolveConstantForwardRefs(); 1636 return std::error_code(); 1637 case BitstreamEntry::Record: 1638 // The interesting case. 1639 break; 1640 } 1641 1642 // Read a record. 1643 Record.clear(); 1644 Value *V = nullptr; 1645 unsigned BitCode = Stream.readRecord(Entry.ID, Record); 1646 switch (BitCode) { 1647 default: // Default behavior: unknown constant 1648 case bitc::CST_CODE_UNDEF: // UNDEF 1649 V = UndefValue::get(CurTy); 1650 break; 1651 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid] 1652 if (Record.empty()) 1653 return Error("Invalid record"); 1654 if (Record[0] >= TypeList.size()) 1655 return Error("Invalid record"); 1656 CurTy = TypeList[Record[0]]; 1657 continue; // Skip the ValueList manipulation. 1658 case bitc::CST_CODE_NULL: // NULL 1659 V = Constant::getNullValue(CurTy); 1660 break; 1661 case bitc::CST_CODE_INTEGER: // INTEGER: [intval] 1662 if (!CurTy->isIntegerTy() || Record.empty()) 1663 return Error("Invalid record"); 1664 V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0])); 1665 break; 1666 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval] 1667 if (!CurTy->isIntegerTy() || Record.empty()) 1668 return Error("Invalid record"); 1669 1670 APInt VInt = ReadWideAPInt(Record, 1671 cast<IntegerType>(CurTy)->getBitWidth()); 1672 V = ConstantInt::get(Context, VInt); 1673 1674 break; 1675 } 1676 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval] 1677 if (Record.empty()) 1678 return Error("Invalid record"); 1679 if (CurTy->isHalfTy()) 1680 V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf, 1681 APInt(16, (uint16_t)Record[0]))); 1682 else if (CurTy->isFloatTy()) 1683 V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle, 1684 APInt(32, (uint32_t)Record[0]))); 1685 else if (CurTy->isDoubleTy()) 1686 V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble, 1687 APInt(64, Record[0]))); 1688 else if (CurTy->isX86_FP80Ty()) { 1689 // Bits are not stored the same way as a normal i80 APInt, compensate. 1690 uint64_t Rearrange[2]; 1691 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16); 1692 Rearrange[1] = Record[0] >> 48; 1693 V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended, 1694 APInt(80, Rearrange))); 1695 } else if (CurTy->isFP128Ty()) 1696 V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad, 1697 APInt(128, Record))); 1698 else if (CurTy->isPPC_FP128Ty()) 1699 V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble, 1700 APInt(128, Record))); 1701 else 1702 V = UndefValue::get(CurTy); 1703 break; 1704 } 1705 1706 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number] 1707 if (Record.empty()) 1708 return Error("Invalid record"); 1709 1710 unsigned Size = Record.size(); 1711 SmallVector<Constant*, 16> Elts; 1712 1713 if (StructType *STy = dyn_cast<StructType>(CurTy)) { 1714 for (unsigned i = 0; i != Size; ++i) 1715 Elts.push_back(ValueList.getConstantFwdRef(Record[i], 1716 STy->getElementType(i))); 1717 V = ConstantStruct::get(STy, Elts); 1718 } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) { 1719 Type *EltTy = ATy->getElementType(); 1720 for (unsigned i = 0; i != Size; ++i) 1721 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy)); 1722 V = ConstantArray::get(ATy, Elts); 1723 } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) { 1724 Type *EltTy = VTy->getElementType(); 1725 for (unsigned i = 0; i != Size; ++i) 1726 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy)); 1727 V = ConstantVector::get(Elts); 1728 } else { 1729 V = UndefValue::get(CurTy); 1730 } 1731 break; 1732 } 1733 case bitc::CST_CODE_STRING: { // STRING: [values] 1734 if (Record.empty()) 1735 return Error("Invalid record"); 1736 1737 ArrayType *ATy = cast<ArrayType>(CurTy); 1738 Type *EltTy = ATy->getElementType(); 1739 1740 unsigned Size = Record.size(); 1741 std::vector<Constant*> Elts; 1742 for (unsigned i = 0; i != Size; ++i) 1743 Elts.push_back(ConstantInt::get(EltTy, Record[i])); 1744 V = ConstantArray::get(ATy, Elts); 1745 break; 1746 } 1747 case bitc::CST_CODE_CSTRING: { // CSTRING: [values] 1748 if (Record.empty()) 1749 return Error("Invalid record"); 1750 1751 ArrayType *ATy = cast<ArrayType>(CurTy); 1752 Type *EltTy = ATy->getElementType(); 1753 1754 unsigned Size = Record.size(); 1755 std::vector<Constant*> Elts; 1756 for (unsigned i = 0; i != Size; ++i) 1757 Elts.push_back(ConstantInt::get(EltTy, Record[i])); 1758 Elts.push_back(Constant::getNullValue(EltTy)); 1759 V = ConstantArray::get(ATy, Elts); 1760 break; 1761 } 1762 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval] 1763 if (Record.size() < 3) 1764 return Error("Invalid record"); 1765 int Opc = GetDecodedBinaryOpcode(Record[0], CurTy); 1766 if (Opc < 0) { 1767 V = UndefValue::get(CurTy); // Unknown binop. 1768 } else { 1769 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy); 1770 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy); 1771 unsigned Flags = 0; 1772 if (Record.size() >= 4) { 1773 if (Opc == Instruction::Add || 1774 Opc == Instruction::Sub || 1775 Opc == Instruction::Mul || 1776 Opc == Instruction::Shl) { 1777 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP)) 1778 Flags |= OverflowingBinaryOperator::NoSignedWrap; 1779 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP)) 1780 Flags |= OverflowingBinaryOperator::NoUnsignedWrap; 1781 } else if (Opc == Instruction::SDiv || 1782 Opc == Instruction::UDiv || 1783 Opc == Instruction::LShr || 1784 Opc == Instruction::AShr) { 1785 if (Record[3] & (1 << bitc::PEO_EXACT)) 1786 Flags |= SDivOperator::IsExact; 1787 } 1788 } 1789 V = ConstantExpr::get(Opc, LHS, RHS, Flags); 1790 } 1791 break; 1792 } 1793 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval] 1794 if (Record.size() < 3) 1795 return Error("Invalid record"); 1796 int Opc = GetDecodedCastOpcode(Record[0]); 1797 if (Opc < 0) { 1798 V = UndefValue::get(CurTy); // Unknown cast. 1799 } else { 1800 Type *OpTy = getTypeByID(Record[1]); 1801 if (!OpTy) 1802 return Error("Invalid record"); 1803 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy); 1804 V = ConstantExpr::getCast(Opc, Op, CurTy); 1805 } 1806 break; 1807 } 1808 case bitc::CST_CODE_CE_INBOUNDS_GEP: 1809 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands] 1810 Type *PointeeType = nullptr; 1811 if (Record.size() & 1) 1812 return Error("Invalid record"); 1813 SmallVector<Constant*, 16> Elts; 1814 for (unsigned i = 0, e = Record.size(); i != e; i += 2) { 1815 Type *ElTy = getTypeByID(Record[i]); 1816 if (!ElTy) 1817 return Error("Invalid record"); 1818 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy)); 1819 } 1820 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end()); 1821 V = ConstantExpr::getGetElementPtr(PointeeType, Elts[0], Indices, 1822 BitCode == 1823 bitc::CST_CODE_CE_INBOUNDS_GEP); 1824 break; 1825 } 1826 case bitc::CST_CODE_CE_SELECT: // CE_SELECT: [opval#, opval#, opval#] 1827 if (Record.size() < 3) 1828 return Error("Invalid record"); 1829 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0], 1830 Type::getInt1Ty(Context)), 1831 ValueList.getConstantFwdRef(Record[1],CurTy), 1832 ValueList.getConstantFwdRef(Record[2],CurTy)); 1833 break; 1834 case bitc::CST_CODE_CE_EXTRACTELT: { // CE_EXTRACTELT: [opty, opval, opval] 1835 if (Record.size() < 3) 1836 return Error("Invalid record"); 1837 VectorType *OpTy = 1838 dyn_cast_or_null<VectorType>(getTypeByID(Record[0])); 1839 if (!OpTy) 1840 return Error("Invalid record"); 1841 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy); 1842 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context)); 1843 V = ConstantExpr::getExtractElement(Op0, Op1); 1844 break; 1845 } 1846 case bitc::CST_CODE_CE_INSERTELT: { // CE_INSERTELT: [opval, opval, opval] 1847 VectorType *OpTy = dyn_cast<VectorType>(CurTy); 1848 if (Record.size() < 3 || !OpTy) 1849 return Error("Invalid record"); 1850 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy); 1851 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], 1852 OpTy->getElementType()); 1853 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context)); 1854 V = ConstantExpr::getInsertElement(Op0, Op1, Op2); 1855 break; 1856 } 1857 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval] 1858 VectorType *OpTy = dyn_cast<VectorType>(CurTy); 1859 if (Record.size() < 3 || !OpTy) 1860 return Error("Invalid record"); 1861 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy); 1862 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy); 1863 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context), 1864 OpTy->getNumElements()); 1865 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy); 1866 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2); 1867 break; 1868 } 1869 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval] 1870 VectorType *RTy = dyn_cast<VectorType>(CurTy); 1871 VectorType *OpTy = 1872 dyn_cast_or_null<VectorType>(getTypeByID(Record[0])); 1873 if (Record.size() < 4 || !RTy || !OpTy) 1874 return Error("Invalid record"); 1875 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy); 1876 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy); 1877 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context), 1878 RTy->getNumElements()); 1879 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy); 1880 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2); 1881 break; 1882 } 1883 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred] 1884 if (Record.size() < 4) 1885 return Error("Invalid record"); 1886 Type *OpTy = getTypeByID(Record[0]); 1887 if (!OpTy) 1888 return Error("Invalid record"); 1889 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy); 1890 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy); 1891 1892 if (OpTy->isFPOrFPVectorTy()) 1893 V = ConstantExpr::getFCmp(Record[3], Op0, Op1); 1894 else 1895 V = ConstantExpr::getICmp(Record[3], Op0, Op1); 1896 break; 1897 } 1898 case bitc::CST_CODE_INLINEASM: 1899 case bitc::CST_CODE_INLINEASM_OLD: { 1900 if (Record.size() < 2) 1901 return Error("Invalid record"); 1902 std::string AsmStr, ConstrStr; 1903 bool HasSideEffects = Record[0] & 1; 1904 bool IsAlignStack = Record[0] >> 1; 1905 unsigned AsmStrSize = Record[1]; 1906 if (2+AsmStrSize >= Record.size()) 1907 return Error("Invalid record"); 1908 unsigned ConstStrSize = Record[2+AsmStrSize]; 1909 if (3+AsmStrSize+ConstStrSize > Record.size()) 1910 return Error("Invalid record"); 1911 1912 for (unsigned i = 0; i != AsmStrSize; ++i) 1913 AsmStr += (char)Record[2+i]; 1914 for (unsigned i = 0; i != ConstStrSize; ++i) 1915 ConstrStr += (char)Record[3+AsmStrSize+i]; 1916 PointerType *PTy = cast<PointerType>(CurTy); 1917 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()), 1918 AsmStr, ConstrStr, HasSideEffects, IsAlignStack); 1919 break; 1920 } 1921 case bitc::CST_CODE_BLOCKADDRESS:{ 1922 if (Record.size() < 3) 1923 return Error("Invalid record"); 1924 Type *FnTy = getTypeByID(Record[0]); 1925 if (!FnTy) 1926 return Error("Invalid record"); 1927 Function *Fn = 1928 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy)); 1929 if (!Fn) 1930 return Error("Invalid record"); 1931 1932 GlobalVariable *FwdRef = new GlobalVariable(*Fn->getParent(), 1933 Type::getInt8Ty(Context), 1934 false, GlobalValue::InternalLinkage, 1935 0, ""); 1936 BlockAddrFwdRefs[Fn].push_back(std::make_pair(Record[2], FwdRef)); 1937 V = FwdRef; 1938 break; 1939 } 1940 } 1941 1942 ValueList.AssignValue(V, NextCstNo); 1943 ++NextCstNo; 1944 } 1945 1946 if (NextCstNo != ValueList.size()) 1947 return Error("Invalid constant reference"); 1948 1949 if (Stream.ReadBlockEnd()) 1950 return Error("Expected a constant"); 1951 1952 // Once all the constants have been read, go through and resolve forward 1953 // references. 1954 ValueList.ResolveConstantForwardRefs(); 1955 return std::error_code(); 1956 } 1957 1958 std::error_code BitcodeReader::materializeMetadata() { 1959 return std::error_code(); 1960 } 1961 1962 void BitcodeReader::setStripDebugInfo() { } 1963 1964 /// RememberAndSkipFunctionBody - When we see the block for a function body, 1965 /// remember where it is and then skip it. This lets us lazily deserialize the 1966 /// functions. 1967 std::error_code BitcodeReader::RememberAndSkipFunctionBody() { 1968 // Get the function we are talking about. 1969 if (FunctionsWithBodies.empty()) 1970 return Error("Insufficient function protos"); 1971 1972 Function *Fn = FunctionsWithBodies.back(); 1973 FunctionsWithBodies.pop_back(); 1974 1975 // Save the current stream state. 1976 uint64_t CurBit = Stream.GetCurrentBitNo(); 1977 DeferredFunctionInfo[Fn] = CurBit; 1978 1979 // Skip over the function block for now. 1980 if (Stream.SkipBlock()) 1981 return Error("Invalid record"); 1982 return std::error_code(); 1983 } 1984 1985 std::error_code BitcodeReader::GlobalCleanup() { 1986 // Patch the initializers for globals and aliases up. 1987 ResolveGlobalAndAliasInits(); 1988 if (!GlobalInits.empty() || !AliasInits.empty()) 1989 return Error("Malformed global initializer set"); 1990 1991 // Look for intrinsic functions which need to be upgraded at some point 1992 for (Module::iterator FI = TheModule->begin(), FE = TheModule->end(); 1993 FI != FE; ++FI) { 1994 Function *NewFn; 1995 if (UpgradeIntrinsicFunction(&*FI, NewFn)) 1996 UpgradedIntrinsics.push_back(std::make_pair(&*FI, NewFn)); 1997 } 1998 1999 // Look for global variables which need to be renamed. 2000 for (Module::global_iterator 2001 GI = TheModule->global_begin(), GE = TheModule->global_end(); 2002 GI != GE; GI++) { 2003 GlobalVariable *GV = &*GI; 2004 UpgradeGlobalVariable(&*GV); 2005 } 2006 2007 // Force deallocation of memory for these vectors to favor the client that 2008 // want lazy deserialization. 2009 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits); 2010 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits); 2011 return std::error_code(); 2012 } 2013 2014 std::error_code BitcodeReader::ParseModule(bool Resume) { 2015 if (Resume) 2016 Stream.JumpToBit(NextUnreadBit); 2017 else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID)) 2018 return Error("Invalid record"); 2019 2020 SmallVector<uint64_t, 64> Record; 2021 std::vector<std::string> SectionTable; 2022 std::vector<std::string> GCTable; 2023 2024 // Read all the records for this module. 2025 while (!Stream.AtEndOfStream()) { 2026 unsigned Code = Stream.ReadCode(); 2027 if (Code == bitc::END_BLOCK) { 2028 if (Stream.ReadBlockEnd()) 2029 return Error("Malformed block"); 2030 2031 // Patch the initializers for globals and aliases up. 2032 ResolveGlobalAndAliasInits(); 2033 if (!GlobalInits.empty() || !AliasInits.empty()) 2034 return Error("Malformed global initializer set"); 2035 if (!FunctionsWithBodies.empty()) 2036 return Error("Insufficient function protos"); 2037 2038 // Look for intrinsic functions which need to be upgraded at some point 2039 for (Module::iterator FI = TheModule->begin(), FE = TheModule->end(); 2040 FI != FE; ++FI) { 2041 Function* NewFn; 2042 if (UpgradeIntrinsicFunction(&*FI, NewFn)) 2043 UpgradedIntrinsics.push_back(std::make_pair(&*FI, NewFn)); 2044 } 2045 2046 // Look for global variables which need to be renamed. 2047 for (Module::global_iterator 2048 GI = TheModule->global_begin(), GE = TheModule->global_end(); 2049 GI != GE; ++GI) 2050 UpgradeGlobalVariable(&*GI); 2051 2052 // Force deallocation of memory for these vectors to favor the client that 2053 // want lazy deserialization. 2054 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits); 2055 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits); 2056 std::vector<Function*>().swap(FunctionsWithBodies); 2057 return std::error_code(); 2058 } 2059 2060 if (Code == bitc::ENTER_SUBBLOCK) { 2061 switch (Stream.ReadSubBlockID()) { 2062 default: // Skip unknown content. 2063 if (Stream.SkipBlock()) 2064 return Error("Invalid record"); 2065 break; 2066 case bitc::BLOCKINFO_BLOCK_ID: 2067 if (Stream.ReadBlockInfoBlock()) 2068 return Error("Malformed block"); 2069 break; 2070 case bitc::PARAMATTR_BLOCK_ID: 2071 if (std::error_code EC = ParseAttributeBlock()) 2072 return EC; 2073 break; 2074 case bitc::TYPE_BLOCK_ID_NEW: 2075 if (std::error_code EC = ParseTypeTable()) 2076 return EC; 2077 break; 2078 case TYPE_BLOCK_ID_OLD_3_0: 2079 if (std::error_code EC = ParseOldTypeTable()) 2080 return EC; 2081 break; 2082 case TYPE_SYMTAB_BLOCK_ID_OLD_3_0: 2083 if (std::error_code EC = ParseOldTypeSymbolTable()) 2084 return EC; 2085 break; 2086 case bitc::VALUE_SYMTAB_BLOCK_ID: 2087 if (std::error_code EC = ParseValueSymbolTable()) 2088 return EC; 2089 SeenValueSymbolTable = true; 2090 break; 2091 case bitc::CONSTANTS_BLOCK_ID: 2092 if (std::error_code EC = ParseConstants()) 2093 return EC; 2094 if (std::error_code EC = ResolveGlobalAndAliasInits()) 2095 return EC; 2096 break; 2097 case bitc::METADATA_BLOCK_ID: 2098 if (std::error_code EC = ParseMetadata()) 2099 return EC; 2100 break; 2101 case bitc::FUNCTION_BLOCK_ID: 2102 // If this is the first function body we've seen, reverse the 2103 // FunctionsWithBodies list. 2104 if (!SeenFirstFunctionBody) { 2105 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end()); 2106 if (std::error_code EC = GlobalCleanup()) 2107 return EC; 2108 SeenFirstFunctionBody = true; 2109 } 2110 2111 if (std::error_code EC = RememberAndSkipFunctionBody()) 2112 return EC; 2113 // For streaming bitcode, suspend parsing when we reach the function 2114 // bodies. Subsequent materialization calls will resume it when 2115 // necessary. For streaming, the function bodies must be at the end of 2116 // the bitcode. If the bitcode file is old, the symbol table will be 2117 // at the end instead and will not have been seen yet. In this case, 2118 // just finish the parse now. 2119 if (LazyStreamer && SeenValueSymbolTable) { 2120 NextUnreadBit = Stream.GetCurrentBitNo(); 2121 return std::error_code(); 2122 } 2123 break; 2124 break; 2125 } 2126 continue; 2127 } 2128 2129 if (Code == bitc::DEFINE_ABBREV) { 2130 Stream.ReadAbbrevRecord(); 2131 continue; 2132 } 2133 2134 // Read a record. 2135 switch (Stream.readRecord(Code, Record)) { 2136 default: break; // Default behavior, ignore unknown content. 2137 case bitc::MODULE_CODE_VERSION: { // VERSION: [version#] 2138 if (Record.size() < 1) 2139 return Error("Invalid record"); 2140 // Only version #0 is supported so far. 2141 if (Record[0] != 0) 2142 return Error("Invalid value"); 2143 break; 2144 } 2145 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N] 2146 std::string S; 2147 if (ConvertToString(Record, 0, S)) 2148 return Error("Invalid record"); 2149 TheModule->setTargetTriple(S); 2150 break; 2151 } 2152 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N] 2153 std::string S; 2154 if (ConvertToString(Record, 0, S)) 2155 return Error("Invalid record"); 2156 TheModule->setDataLayout(S); 2157 break; 2158 } 2159 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N] 2160 std::string S; 2161 if (ConvertToString(Record, 0, S)) 2162 return Error("Invalid record"); 2163 TheModule->setModuleInlineAsm(S); 2164 break; 2165 } 2166 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N] 2167 std::string S; 2168 if (ConvertToString(Record, 0, S)) 2169 return Error("Invalid record"); 2170 // ANDROID: Ignore value, since we never used it anyways. 2171 // TheModule->addLibrary(S); 2172 break; 2173 } 2174 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N] 2175 std::string S; 2176 if (ConvertToString(Record, 0, S)) 2177 return Error("Invalid record"); 2178 SectionTable.push_back(S); 2179 break; 2180 } 2181 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N] 2182 std::string S; 2183 if (ConvertToString(Record, 0, S)) 2184 return Error("Invalid record"); 2185 GCTable.push_back(S); 2186 break; 2187 } 2188 // GLOBALVAR: [pointer type, isconst, initid, 2189 // linkage, alignment, section, visibility, threadlocal, 2190 // unnamed_addr] 2191 case bitc::MODULE_CODE_GLOBALVAR: { 2192 if (Record.size() < 6) 2193 return Error("Invalid record"); 2194 Type *Ty = getTypeByID(Record[0]); 2195 if (!Ty) 2196 return Error("Invalid record"); 2197 if (!Ty->isPointerTy()) 2198 return Error("Invalid type for value"); 2199 unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace(); 2200 Ty = cast<PointerType>(Ty)->getElementType(); 2201 2202 bool isConstant = Record[1]; 2203 uint64_t RawLinkage = Record[3]; 2204 GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage); 2205 unsigned Alignment = (1 << Record[4]) >> 1; 2206 std::string Section; 2207 if (Record[5]) { 2208 if (Record[5]-1 >= SectionTable.size()) 2209 return Error("Invalid ID"); 2210 Section = SectionTable[Record[5]-1]; 2211 } 2212 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility; 2213 if (Record.size() > 6) 2214 Visibility = GetDecodedVisibility(Record[6]); 2215 2216 GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal; 2217 if (Record.size() > 7) 2218 TLM = GetDecodedThreadLocalMode(Record[7]); 2219 2220 bool UnnamedAddr = false; 2221 if (Record.size() > 8) 2222 UnnamedAddr = Record[8]; 2223 2224 GlobalVariable *NewGV = 2225 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, "", nullptr, 2226 TLM, AddressSpace); 2227 NewGV->setAlignment(Alignment); 2228 if (!Section.empty()) 2229 NewGV->setSection(Section); 2230 NewGV->setVisibility(Visibility); 2231 NewGV->setUnnamedAddr(UnnamedAddr); 2232 2233 ValueList.push_back(NewGV); 2234 2235 // Remember which value to use for the global initializer. 2236 if (unsigned InitID = Record[2]) 2237 GlobalInits.push_back(std::make_pair(NewGV, InitID-1)); 2238 break; 2239 } 2240 // FUNCTION: [type, callingconv, isproto, linkage, paramattr, 2241 // alignment, section, visibility, gc, unnamed_addr] 2242 case bitc::MODULE_CODE_FUNCTION: { 2243 if (Record.size() < 8) 2244 return Error("Invalid record"); 2245 Type *Ty = getTypeByID(Record[0]); 2246 if (!Ty) 2247 return Error("Invalid record"); 2248 if (!Ty->isPointerTy()) 2249 return Error("Invalid type for value"); 2250 FunctionType *FTy = 2251 dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType()); 2252 if (!FTy) 2253 return Error("Invalid type for value"); 2254 2255 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage, 2256 "", TheModule); 2257 2258 Func->setCallingConv(static_cast<CallingConv::ID>(Record[1])); 2259 bool isProto = Record[2]; 2260 uint64_t RawLinkage = Record[3]; 2261 Func->setLinkage(getDecodedLinkage(RawLinkage)); 2262 Func->setAttributes(getAttributes(Record[4])); 2263 2264 Func->setAlignment((1 << Record[5]) >> 1); 2265 if (Record[6]) { 2266 if (Record[6]-1 >= SectionTable.size()) 2267 return Error("Invalid ID"); 2268 Func->setSection(SectionTable[Record[6]-1]); 2269 } 2270 Func->setVisibility(GetDecodedVisibility(Record[7])); 2271 if (Record.size() > 8 && Record[8]) { 2272 if (Record[8]-1 > GCTable.size()) 2273 return Error("Invalid ID"); 2274 Func->setGC(GCTable[Record[8]-1].c_str()); 2275 } 2276 bool UnnamedAddr = false; 2277 if (Record.size() > 9) 2278 UnnamedAddr = Record[9]; 2279 Func->setUnnamedAddr(UnnamedAddr); 2280 ValueList.push_back(Func); 2281 2282 // If this is a function with a body, remember the prototype we are 2283 // creating now, so that we can match up the body with them later. 2284 if (!isProto) { 2285 Func->setIsMaterializable(true); 2286 FunctionsWithBodies.push_back(Func); 2287 if (LazyStreamer) 2288 DeferredFunctionInfo[Func] = 0; 2289 } 2290 break; 2291 } 2292 // ALIAS: [alias type, aliasee val#, linkage] 2293 // ALIAS: [alias type, aliasee val#, linkage, visibility] 2294 case bitc::MODULE_CODE_ALIAS_OLD: { 2295 if (Record.size() < 3) 2296 return Error("Invalid record"); 2297 Type *Ty = getTypeByID(Record[0]); 2298 if (!Ty) 2299 return Error("Invalid record"); 2300 auto *PTy = dyn_cast<PointerType>(Ty); 2301 if (!PTy) 2302 return Error("Invalid type for value"); 2303 2304 auto *NewGA = 2305 GlobalAlias::create(PTy->getElementType(), PTy->getAddressSpace(), 2306 getDecodedLinkage(Record[2]), "", TheModule); 2307 // Old bitcode files didn't have visibility field. 2308 if (Record.size() > 3) 2309 NewGA->setVisibility(GetDecodedVisibility(Record[3])); 2310 ValueList.push_back(NewGA); 2311 AliasInits.push_back(std::make_pair(NewGA, Record[1])); 2312 break; 2313 } 2314 /// MODULE_CODE_PURGEVALS: [numvals] 2315 case bitc::MODULE_CODE_PURGEVALS: 2316 // Trim down the value list to the specified size. 2317 if (Record.size() < 1 || Record[0] > ValueList.size()) 2318 return Error("Invalid record"); 2319 ValueList.shrinkTo(Record[0]); 2320 break; 2321 } 2322 Record.clear(); 2323 } 2324 2325 return Error("Invalid bitcode signature"); 2326 } 2327 2328 std::error_code BitcodeReader::ParseBitcodeInto(Module *M) { 2329 TheModule = nullptr; 2330 2331 if (std::error_code EC = InitStream()) 2332 return EC; 2333 2334 // Sniff for the signature. 2335 if (Stream.Read(8) != 'B' || 2336 Stream.Read(8) != 'C' || 2337 Stream.Read(4) != 0x0 || 2338 Stream.Read(4) != 0xC || 2339 Stream.Read(4) != 0xE || 2340 Stream.Read(4) != 0xD) 2341 return Error("Invalid bitcode signature"); 2342 2343 // We expect a number of well-defined blocks, though we don't necessarily 2344 // need to understand them all. 2345 while (1) { 2346 if (Stream.AtEndOfStream()) 2347 return std::error_code(); 2348 2349 BitstreamEntry Entry = 2350 Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs); 2351 2352 switch (Entry.Kind) { 2353 case BitstreamEntry::Error: 2354 return Error("Malformed block"); 2355 case BitstreamEntry::EndBlock: 2356 return std::error_code(); 2357 2358 case BitstreamEntry::SubBlock: 2359 switch (Entry.ID) { 2360 case bitc::BLOCKINFO_BLOCK_ID: 2361 if (Stream.ReadBlockInfoBlock()) 2362 return Error("Malformed block"); 2363 break; 2364 case bitc::MODULE_BLOCK_ID: 2365 // Reject multiple MODULE_BLOCK's in a single bitstream. 2366 if (TheModule) 2367 return Error("Invalid multiple blocks"); 2368 TheModule = M; 2369 if (std::error_code EC = ParseModule(false)) 2370 return EC; 2371 if (LazyStreamer) 2372 return std::error_code(); 2373 break; 2374 default: 2375 if (Stream.SkipBlock()) 2376 return Error("Invalid record"); 2377 break; 2378 } 2379 continue; 2380 case BitstreamEntry::Record: 2381 // There should be no records in the top-level of blocks. 2382 2383 // The ranlib in Xcode 4 will align archive members by appending newlines 2384 // to the end of them. If this file size is a multiple of 4 but not 8, we 2385 // have to read and ignore these final 4 bytes :-( 2386 if (Stream.getAbbrevIDWidth() == 2 && Entry.ID == 2 && 2387 Stream.Read(6) == 2 && Stream.Read(24) == 0xa0a0a && 2388 Stream.AtEndOfStream()) 2389 return std::error_code(); 2390 2391 return Error("Invalid record"); 2392 } 2393 } 2394 } 2395 2396 llvm::ErrorOr<std::string> BitcodeReader::parseModuleTriple() { 2397 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID)) 2398 return Error("Invalid record"); 2399 2400 SmallVector<uint64_t, 64> Record; 2401 2402 std::string Triple; 2403 // Read all the records for this module. 2404 while (1) { 2405 BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 2406 2407 switch (Entry.Kind) { 2408 case BitstreamEntry::SubBlock: // Handled for us already. 2409 case BitstreamEntry::Error: 2410 return Error("Malformed block"); 2411 case BitstreamEntry::EndBlock: 2412 return Triple; 2413 case BitstreamEntry::Record: 2414 // The interesting case. 2415 break; 2416 } 2417 2418 // Read a record. 2419 switch (Stream.readRecord(Entry.ID, Record)) { 2420 default: break; // Default behavior, ignore unknown content. 2421 case bitc::MODULE_CODE_VERSION: // VERSION: [version#] 2422 if (Record.size() < 1) 2423 return Error("Invalid record"); 2424 // Only version #0 is supported so far. 2425 if (Record[0] != 0) 2426 return Error("Invalid record"); 2427 break; 2428 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N] 2429 std::string S; 2430 if (ConvertToString(Record, 0, S)) 2431 return Error("Invalid record"); 2432 Triple = S; 2433 break; 2434 } 2435 } 2436 Record.clear(); 2437 } 2438 2439 return Error("Invalid bitcode signature"); 2440 } 2441 2442 llvm::ErrorOr<std::string> BitcodeReader::parseTriple() { 2443 if (std::error_code EC = InitStream()) 2444 return EC; 2445 2446 // Sniff for the signature. 2447 if (Stream.Read(8) != 'B' || 2448 Stream.Read(8) != 'C' || 2449 Stream.Read(4) != 0x0 || 2450 Stream.Read(4) != 0xC || 2451 Stream.Read(4) != 0xE || 2452 Stream.Read(4) != 0xD) 2453 return Error("Invalid bitcode signature"); 2454 2455 // We expect a number of well-defined blocks, though we don't necessarily 2456 // need to understand them all. 2457 while (1) { 2458 BitstreamEntry Entry = Stream.advance(); 2459 2460 switch (Entry.Kind) { 2461 case BitstreamEntry::Error: 2462 return Error("Malformed block"); 2463 case BitstreamEntry::EndBlock: 2464 return std::error_code(); 2465 2466 case BitstreamEntry::SubBlock: 2467 if (Entry.ID == bitc::MODULE_BLOCK_ID) 2468 return parseModuleTriple(); 2469 2470 // Ignore other sub-blocks. 2471 if (Stream.SkipBlock()) 2472 return Error("Malformed block"); 2473 continue; 2474 2475 case BitstreamEntry::Record: 2476 Stream.skipRecord(Entry.ID); 2477 continue; 2478 } 2479 } 2480 } 2481 2482 /// ParseMetadataAttachment - Parse metadata attachments. 2483 std::error_code BitcodeReader::ParseMetadataAttachment() { 2484 if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID)) 2485 return Error("Invalid record"); 2486 2487 SmallVector<uint64_t, 64> Record; 2488 while (1) { 2489 BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 2490 2491 switch (Entry.Kind) { 2492 case BitstreamEntry::SubBlock: // Handled for us already. 2493 case BitstreamEntry::Error: 2494 return Error("Malformed block"); 2495 case BitstreamEntry::EndBlock: 2496 return std::error_code(); 2497 case BitstreamEntry::Record: 2498 // The interesting case. 2499 break; 2500 } 2501 2502 // Read a metadata attachment record. 2503 Record.clear(); 2504 switch (Stream.readRecord(Entry.ID, Record)) { 2505 default: // Default behavior: ignore. 2506 break; 2507 case METADATA_ATTACHMENT_2_7: 2508 LLVM2_7MetadataDetected = true; 2509 case bitc::METADATA_ATTACHMENT: { 2510 unsigned RecordLength = Record.size(); 2511 if (Record.empty() || (RecordLength - 1) % 2 == 1) 2512 return Error("Invalid record"); 2513 Instruction *Inst = InstructionList[Record[0]]; 2514 for (unsigned i = 1; i != RecordLength; i = i+2) { 2515 unsigned Kind = Record[i]; 2516 DenseMap<unsigned, unsigned>::iterator I = 2517 MDKindMap.find(Kind); 2518 if (I == MDKindMap.end()) 2519 return Error("Invalid ID"); 2520 Metadata *Node = MDValueList.getValueFwdRef(Record[i + 1]); 2521 Inst->setMetadata(I->second, cast<MDNode>(Node)); 2522 } 2523 break; 2524 } 2525 } 2526 } 2527 } 2528 2529 /// ParseFunctionBody - Lazily parse the specified function body block. 2530 std::error_code BitcodeReader::ParseFunctionBody(Function *F) { 2531 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID)) 2532 return Error("Invalid record"); 2533 2534 InstructionList.clear(); 2535 unsigned ModuleValueListSize = ValueList.size(); 2536 unsigned ModuleMDValueListSize = MDValueList.size(); 2537 2538 // Add all the function arguments to the value table. 2539 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I) 2540 ValueList.push_back(&*I); 2541 2542 unsigned NextValueNo = ValueList.size(); 2543 BasicBlock *CurBB = nullptr; 2544 unsigned CurBBNo = 0; 2545 2546 DebugLoc LastLoc; 2547 2548 // Read all the records. 2549 SmallVector<uint64_t, 64> Record; 2550 while (1) { 2551 unsigned Code = Stream.ReadCode(); 2552 if (Code == bitc::END_BLOCK) { 2553 if (Stream.ReadBlockEnd()) 2554 return Error("Malformed block"); 2555 break; 2556 } 2557 2558 if (Code == bitc::ENTER_SUBBLOCK) { 2559 switch (Stream.ReadSubBlockID()) { 2560 default: // Skip unknown content. 2561 if (Stream.SkipBlock()) 2562 return Error("Invalid record"); 2563 break; 2564 case bitc::CONSTANTS_BLOCK_ID: 2565 if (std::error_code EC = ParseConstants()) 2566 return EC; 2567 NextValueNo = ValueList.size(); 2568 break; 2569 case bitc::VALUE_SYMTAB_BLOCK_ID: 2570 if (std::error_code EC = ParseValueSymbolTable()) 2571 return EC; 2572 break; 2573 case bitc::METADATA_ATTACHMENT_ID: 2574 if (std::error_code EC = ParseMetadataAttachment()) 2575 return EC; 2576 break; 2577 case bitc::METADATA_BLOCK_ID: 2578 if (std::error_code EC = ParseMetadata()) 2579 return EC; 2580 break; 2581 } 2582 continue; 2583 } 2584 2585 if (Code == bitc::DEFINE_ABBREV) { 2586 Stream.ReadAbbrevRecord(); 2587 continue; 2588 } 2589 2590 // Read a record. 2591 Record.clear(); 2592 Instruction *I = nullptr; 2593 unsigned BitCode = Stream.readRecord(Code, Record); 2594 switch (BitCode) { 2595 default: // Default behavior: reject 2596 return Error("Invalid value"); 2597 case bitc::FUNC_CODE_DECLAREBLOCKS: // DECLAREBLOCKS: [nblocks] 2598 if (Record.size() < 1 || Record[0] == 0) 2599 return Error("Invalid record"); 2600 // Create all the basic blocks for the function. 2601 FunctionBBs.resize(Record[0]); 2602 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i) 2603 FunctionBBs[i] = BasicBlock::Create(Context, "", F); 2604 CurBB = FunctionBBs[0]; 2605 continue; 2606 2607 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN 2608 // This record indicates that the last instruction is at the same 2609 // location as the previous instruction with a location. 2610 I = nullptr; 2611 2612 // Get the last instruction emitted. 2613 if (CurBB && !CurBB->empty()) 2614 I = &CurBB->back(); 2615 else if (CurBBNo && FunctionBBs[CurBBNo-1] && 2616 !FunctionBBs[CurBBNo-1]->empty()) 2617 I = &FunctionBBs[CurBBNo-1]->back(); 2618 2619 if (!I) 2620 return Error("Invalid record"); 2621 I->setDebugLoc(LastLoc); 2622 I = nullptr; 2623 continue; 2624 2625 case FUNC_CODE_DEBUG_LOC_2_7: 2626 LLVM2_7MetadataDetected = true; 2627 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia] 2628 I = nullptr; // Get the last instruction emitted. 2629 if (CurBB && !CurBB->empty()) 2630 I = &CurBB->back(); 2631 else if (CurBBNo && FunctionBBs[CurBBNo-1] && 2632 !FunctionBBs[CurBBNo-1]->empty()) 2633 I = &FunctionBBs[CurBBNo-1]->back(); 2634 if (!I || Record.size() < 4) 2635 return Error("Invalid record"); 2636 2637 unsigned Line = Record[0], Col = Record[1]; 2638 unsigned ScopeID = Record[2], IAID = Record[3]; 2639 2640 MDNode *Scope = nullptr, *IA = nullptr; 2641 if (ScopeID) Scope = cast<MDNode>(MDValueList.getValueFwdRef(ScopeID-1)); 2642 if (IAID) IA = cast<MDNode>(MDValueList.getValueFwdRef(IAID-1)); 2643 LastLoc = DebugLoc::get(Line, Col, Scope, IA); 2644 I->setDebugLoc(LastLoc); 2645 I = nullptr; 2646 continue; 2647 } 2648 2649 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode] 2650 unsigned OpNum = 0; 2651 Value *LHS, *RHS; 2652 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) || 2653 getValue(Record, OpNum, LHS->getType(), RHS) || 2654 OpNum+1 > Record.size()) 2655 return Error("Invalid record"); 2656 2657 int Opc = GetDecodedBinaryOpcode(Record[OpNum++], LHS->getType()); 2658 if (Opc == -1) 2659 return Error("Invalid record"); 2660 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS); 2661 InstructionList.push_back(I); 2662 if (OpNum < Record.size()) { 2663 if (Opc == Instruction::Add || 2664 Opc == Instruction::Sub || 2665 Opc == Instruction::Mul || 2666 Opc == Instruction::Shl) { 2667 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP)) 2668 cast<BinaryOperator>(I)->setHasNoSignedWrap(true); 2669 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP)) 2670 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true); 2671 } else if (Opc == Instruction::SDiv || 2672 Opc == Instruction::UDiv || 2673 Opc == Instruction::LShr || 2674 Opc == Instruction::AShr) { 2675 if (Record[OpNum] & (1 << bitc::PEO_EXACT)) 2676 cast<BinaryOperator>(I)->setIsExact(true); 2677 } 2678 } 2679 break; 2680 } 2681 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc] 2682 unsigned OpNum = 0; 2683 Value *Op; 2684 if (getValueTypePair(Record, OpNum, NextValueNo, Op) || 2685 OpNum+2 != Record.size()) 2686 return Error("Invalid record"); 2687 2688 Type *ResTy = getTypeByID(Record[OpNum]); 2689 int Opc = GetDecodedCastOpcode(Record[OpNum+1]); 2690 if (Opc == -1 || !ResTy) 2691 return Error("Invalid record"); 2692 I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy); 2693 InstructionList.push_back(I); 2694 break; 2695 } 2696 case bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD: 2697 case bitc::FUNC_CODE_INST_GEP_OLD: // GEP: [n x operands] 2698 case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands] 2699 unsigned OpNum = 0; 2700 2701 Type *Ty; 2702 bool InBounds; 2703 2704 if (BitCode == bitc::FUNC_CODE_INST_GEP) { 2705 InBounds = Record[OpNum++]; 2706 Ty = getTypeByID(Record[OpNum++]); 2707 } else { 2708 InBounds = BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD; 2709 Ty = nullptr; 2710 } 2711 2712 Value *BasePtr; 2713 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr)) 2714 return Error("Invalid record"); 2715 2716 if (Ty && 2717 Ty != 2718 cast<SequentialType>(BasePtr->getType()->getScalarType()) 2719 ->getElementType()) 2720 return Error( 2721 "Explicit gep type does not match pointee type of pointer operand"); 2722 2723 SmallVector<Value*, 16> GEPIdx; 2724 while (OpNum != Record.size()) { 2725 Value *Op; 2726 if (getValueTypePair(Record, OpNum, NextValueNo, Op)) 2727 return Error("Invalid record"); 2728 GEPIdx.push_back(Op); 2729 } 2730 2731 I = GetElementPtrInst::Create(Ty, BasePtr, GEPIdx); 2732 2733 InstructionList.push_back(I); 2734 if (InBounds) 2735 cast<GetElementPtrInst>(I)->setIsInBounds(true); 2736 break; 2737 } 2738 2739 case bitc::FUNC_CODE_INST_EXTRACTVAL: { 2740 // EXTRACTVAL: [opty, opval, n x indices] 2741 unsigned OpNum = 0; 2742 Value *Agg; 2743 if (getValueTypePair(Record, OpNum, NextValueNo, Agg)) 2744 return Error("Invalid record"); 2745 2746 SmallVector<unsigned, 4> EXTRACTVALIdx; 2747 for (unsigned RecSize = Record.size(); 2748 OpNum != RecSize; ++OpNum) { 2749 uint64_t Index = Record[OpNum]; 2750 if ((unsigned)Index != Index) 2751 return Error("Invalid value"); 2752 EXTRACTVALIdx.push_back((unsigned)Index); 2753 } 2754 2755 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx); 2756 InstructionList.push_back(I); 2757 break; 2758 } 2759 2760 case bitc::FUNC_CODE_INST_INSERTVAL: { 2761 // INSERTVAL: [opty, opval, opty, opval, n x indices] 2762 unsigned OpNum = 0; 2763 Value *Agg; 2764 if (getValueTypePair(Record, OpNum, NextValueNo, Agg)) 2765 return Error("Invalid record"); 2766 Value *Val; 2767 if (getValueTypePair(Record, OpNum, NextValueNo, Val)) 2768 return Error("Invalid record"); 2769 2770 SmallVector<unsigned, 4> INSERTVALIdx; 2771 for (unsigned RecSize = Record.size(); 2772 OpNum != RecSize; ++OpNum) { 2773 uint64_t Index = Record[OpNum]; 2774 if ((unsigned)Index != Index) 2775 return Error("Invalid value"); 2776 INSERTVALIdx.push_back((unsigned)Index); 2777 } 2778 2779 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx); 2780 InstructionList.push_back(I); 2781 break; 2782 } 2783 2784 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval] 2785 // obsolete form of select 2786 // handles select i1 ... in old bitcode 2787 unsigned OpNum = 0; 2788 Value *TrueVal, *FalseVal, *Cond; 2789 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) || 2790 getValue(Record, OpNum, TrueVal->getType(), FalseVal) || 2791 getValue(Record, OpNum, Type::getInt1Ty(Context), Cond)) 2792 return Error("Invalid record"); 2793 2794 I = SelectInst::Create(Cond, TrueVal, FalseVal); 2795 InstructionList.push_back(I); 2796 break; 2797 } 2798 2799 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred] 2800 // new form of select 2801 // handles select i1 or select [N x i1] 2802 unsigned OpNum = 0; 2803 Value *TrueVal, *FalseVal, *Cond; 2804 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) || 2805 getValue(Record, OpNum, TrueVal->getType(), FalseVal) || 2806 getValueTypePair(Record, OpNum, NextValueNo, Cond)) 2807 return Error("Invalid record"); 2808 2809 // select condition can be either i1 or [N x i1] 2810 if (VectorType* vector_type = 2811 dyn_cast<VectorType>(Cond->getType())) { 2812 // expect <n x i1> 2813 if (vector_type->getElementType() != Type::getInt1Ty(Context)) 2814 return Error("Invalid type for value"); 2815 } else { 2816 // expect i1 2817 if (Cond->getType() != Type::getInt1Ty(Context)) 2818 return Error("Invalid type for value"); 2819 } 2820 2821 I = SelectInst::Create(Cond, TrueVal, FalseVal); 2822 InstructionList.push_back(I); 2823 break; 2824 } 2825 2826 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval] 2827 unsigned OpNum = 0; 2828 Value *Vec, *Idx; 2829 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) || 2830 getValue(Record, OpNum, Type::getInt32Ty(Context), Idx)) 2831 return Error("Invalid record"); 2832 I = ExtractElementInst::Create(Vec, Idx); 2833 InstructionList.push_back(I); 2834 break; 2835 } 2836 2837 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval] 2838 unsigned OpNum = 0; 2839 Value *Vec, *Elt, *Idx; 2840 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) || 2841 getValue(Record, OpNum, 2842 cast<VectorType>(Vec->getType())->getElementType(), Elt) || 2843 getValue(Record, OpNum, Type::getInt32Ty(Context), Idx)) 2844 return Error("Invalid record"); 2845 I = InsertElementInst::Create(Vec, Elt, Idx); 2846 InstructionList.push_back(I); 2847 break; 2848 } 2849 2850 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval] 2851 unsigned OpNum = 0; 2852 Value *Vec1, *Vec2, *Mask; 2853 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) || 2854 getValue(Record, OpNum, Vec1->getType(), Vec2)) 2855 return Error("Invalid record"); 2856 2857 if (getValueTypePair(Record, OpNum, NextValueNo, Mask)) 2858 return Error("Invalid record"); 2859 I = new ShuffleVectorInst(Vec1, Vec2, Mask); 2860 InstructionList.push_back(I); 2861 break; 2862 } 2863 2864 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred] 2865 // Old form of ICmp/FCmp returning bool 2866 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were 2867 // both legal on vectors but had different behaviour. 2868 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred] 2869 // FCmp/ICmp returning bool or vector of bool 2870 2871 unsigned OpNum = 0; 2872 Value *LHS, *RHS; 2873 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) || 2874 getValue(Record, OpNum, LHS->getType(), RHS) || 2875 OpNum+1 != Record.size()) 2876 return Error("Invalid record"); 2877 2878 if (LHS->getType()->isFPOrFPVectorTy()) 2879 I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS); 2880 else 2881 I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS); 2882 InstructionList.push_back(I); 2883 break; 2884 } 2885 2886 case FUNC_CODE_INST_GETRESULT_2_7: { 2887 if (Record.size() != 2) { 2888 return Error("Invalid record"); 2889 } 2890 unsigned OpNum = 0; 2891 Value *Op; 2892 getValueTypePair(Record, OpNum, NextValueNo, Op); 2893 unsigned Index = Record[1]; 2894 I = ExtractValueInst::Create(Op, Index); 2895 InstructionList.push_back(I); 2896 break; 2897 } 2898 2899 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>] 2900 { 2901 unsigned Size = Record.size(); 2902 if (Size == 0) { 2903 I = ReturnInst::Create(Context); 2904 InstructionList.push_back(I); 2905 break; 2906 } 2907 2908 unsigned OpNum = 0; 2909 Value *Op = nullptr; 2910 if (getValueTypePair(Record, OpNum, NextValueNo, Op)) 2911 return Error("Invalid record"); 2912 if (OpNum != Record.size()) 2913 return Error("Invalid record"); 2914 2915 I = ReturnInst::Create(Context, Op); 2916 InstructionList.push_back(I); 2917 break; 2918 } 2919 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#] 2920 if (Record.size() != 1 && Record.size() != 3) 2921 return Error("Invalid record"); 2922 BasicBlock *TrueDest = getBasicBlock(Record[0]); 2923 if (!TrueDest) 2924 return Error("Invalid record"); 2925 2926 if (Record.size() == 1) { 2927 I = BranchInst::Create(TrueDest); 2928 InstructionList.push_back(I); 2929 } 2930 else { 2931 BasicBlock *FalseDest = getBasicBlock(Record[1]); 2932 Value *Cond = getFnValueByID(Record[2], Type::getInt1Ty(Context)); 2933 if (!FalseDest || !Cond) 2934 return Error("Invalid record"); 2935 I = BranchInst::Create(TrueDest, FalseDest, Cond); 2936 InstructionList.push_back(I); 2937 } 2938 break; 2939 } 2940 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...] 2941 if (Record.size() < 3 || (Record.size() & 1) == 0) 2942 return Error("Invalid record"); 2943 Type *OpTy = getTypeByID(Record[0]); 2944 Value *Cond = getFnValueByID(Record[1], OpTy); 2945 BasicBlock *Default = getBasicBlock(Record[2]); 2946 if (!OpTy || !Cond || !Default) 2947 return Error("Invalid record"); 2948 unsigned NumCases = (Record.size()-3)/2; 2949 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases); 2950 InstructionList.push_back(SI); 2951 for (unsigned i = 0, e = NumCases; i != e; ++i) { 2952 ConstantInt *CaseVal = 2953 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy)); 2954 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]); 2955 if (!CaseVal || !DestBB) { 2956 delete SI; 2957 return Error("Invalid record"); 2958 } 2959 SI->addCase(CaseVal, DestBB); 2960 } 2961 I = SI; 2962 break; 2963 } 2964 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...] 2965 if (Record.size() < 2) 2966 return Error("Invalid record"); 2967 Type *OpTy = getTypeByID(Record[0]); 2968 Value *Address = getFnValueByID(Record[1], OpTy); 2969 if (!OpTy || !Address) 2970 return Error("Invalid record"); 2971 unsigned NumDests = Record.size()-2; 2972 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests); 2973 InstructionList.push_back(IBI); 2974 for (unsigned i = 0, e = NumDests; i != e; ++i) { 2975 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) { 2976 IBI->addDestination(DestBB); 2977 } else { 2978 delete IBI; 2979 return Error("Invalid record"); 2980 } 2981 } 2982 I = IBI; 2983 break; 2984 } 2985 2986 case bitc::FUNC_CODE_INST_INVOKE: { 2987 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...] 2988 if (Record.size() < 4) 2989 return Error("Invalid record"); 2990 AttributeSet PAL = getAttributes(Record[0]); 2991 unsigned CCInfo = Record[1]; 2992 BasicBlock *NormalBB = getBasicBlock(Record[2]); 2993 BasicBlock *UnwindBB = getBasicBlock(Record[3]); 2994 2995 unsigned OpNum = 4; 2996 Value *Callee; 2997 if (getValueTypePair(Record, OpNum, NextValueNo, Callee)) 2998 return Error("Invalid record"); 2999 3000 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType()); 3001 FunctionType *FTy = !CalleeTy ? nullptr : 3002 dyn_cast<FunctionType>(CalleeTy->getElementType()); 3003 3004 // Check that the right number of fixed parameters are here. 3005 if (!FTy || !NormalBB || !UnwindBB || 3006 Record.size() < OpNum+FTy->getNumParams()) 3007 return Error("Invalid record"); 3008 3009 SmallVector<Value*, 16> Ops; 3010 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) { 3011 Ops.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i))); 3012 if (!Ops.back()) 3013 return Error("Invalid record"); 3014 } 3015 3016 if (!FTy->isVarArg()) { 3017 if (Record.size() != OpNum) 3018 return Error("Invalid record"); 3019 } else { 3020 // Read type/value pairs for varargs params. 3021 while (OpNum != Record.size()) { 3022 Value *Op; 3023 if (getValueTypePair(Record, OpNum, NextValueNo, Op)) 3024 return Error("Invalid record"); 3025 Ops.push_back(Op); 3026 } 3027 } 3028 3029 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops); 3030 InstructionList.push_back(I); 3031 cast<InvokeInst>(I)->setCallingConv( 3032 static_cast<CallingConv::ID>(CCInfo)); 3033 cast<InvokeInst>(I)->setAttributes(PAL); 3034 break; 3035 } 3036 case FUNC_CODE_INST_UNWIND_2_7: { // UNWIND_OLD 3037 // 'unwind' instruction has been removed in LLVM 3.1 3038 // Replace 'unwind' with 'landingpad' and 'resume'. 3039 Type *ExnTy = StructType::get(Type::getInt8PtrTy(Context), 3040 Type::getInt32Ty(Context), nullptr); 3041 3042 LandingPadInst *LP = LandingPadInst::Create(ExnTy, 1); 3043 LP->setCleanup(true); 3044 3045 CurBB->getInstList().push_back(LP); 3046 I = ResumeInst::Create(LP); 3047 InstructionList.push_back(I); 3048 break; 3049 } 3050 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE 3051 I = new UnreachableInst(Context); 3052 InstructionList.push_back(I); 3053 break; 3054 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...] 3055 if (Record.size() < 1 || ((Record.size()-1)&1)) 3056 return Error("Invalid record"); 3057 Type *Ty = getTypeByID(Record[0]); 3058 if (!Ty) 3059 return Error("Invalid record"); 3060 3061 PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2); 3062 InstructionList.push_back(PN); 3063 3064 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) { 3065 Value *V = getFnValueByID(Record[1+i], Ty); 3066 BasicBlock *BB = getBasicBlock(Record[2+i]); 3067 if (!V || !BB) 3068 return Error("Invalid record"); 3069 PN->addIncoming(V, BB); 3070 } 3071 I = PN; 3072 break; 3073 } 3074 3075 case FUNC_CODE_INST_MALLOC_2_7: { // MALLOC: [instty, op, align] 3076 // Autoupgrade malloc instruction to malloc call. 3077 // FIXME: Remove in LLVM 3.0. 3078 if (Record.size() < 3) { 3079 return Error("Invalid record"); 3080 } 3081 PointerType *Ty = 3082 dyn_cast_or_null<PointerType>(getTypeByID(Record[0])); 3083 Value *Size = getFnValueByID(Record[1], Type::getInt32Ty(Context)); 3084 if (!Ty || !Size) 3085 return Error("Invalid record"); 3086 if (!CurBB) 3087 return Error("Invalid instruction with no BB"); 3088 Type *Int32Ty = IntegerType::getInt32Ty(CurBB->getContext()); 3089 Constant *AllocSize = ConstantExpr::getSizeOf(Ty->getElementType()); 3090 AllocSize = ConstantExpr::getTruncOrBitCast(AllocSize, Int32Ty); 3091 I = CallInst::CreateMalloc(CurBB, Int32Ty, Ty->getElementType(), 3092 AllocSize, Size, nullptr); 3093 InstructionList.push_back(I); 3094 break; 3095 } 3096 case FUNC_CODE_INST_FREE_2_7: { // FREE: [op, opty] 3097 unsigned OpNum = 0; 3098 Value *Op; 3099 if (getValueTypePair(Record, OpNum, NextValueNo, Op) || 3100 OpNum != Record.size()) { 3101 return Error("Invalid record"); 3102 } 3103 if (!CurBB) 3104 return Error("Invalid instruction with no BB"); 3105 I = CallInst::CreateFree(Op, CurBB); 3106 InstructionList.push_back(I); 3107 break; 3108 } 3109 3110 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align] 3111 // For backward compatibility, tolerate a lack of an opty, and use i32. 3112 // Remove this in LLVM 3.0. 3113 if (Record.size() < 3 || Record.size() > 4) { 3114 return Error("Invalid record"); 3115 } 3116 unsigned OpNum = 0; 3117 PointerType *Ty = 3118 dyn_cast_or_null<PointerType>(getTypeByID(Record[OpNum++])); 3119 Type *OpTy = Record.size() == 4 ? getTypeByID(Record[OpNum++]) : 3120 Type::getInt32Ty(Context); 3121 Value *Size = getFnValueByID(Record[OpNum++], OpTy); 3122 unsigned Align = Record[OpNum++]; 3123 if (!Ty || !Size) 3124 return Error("Invalid record"); 3125 I = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1); 3126 InstructionList.push_back(I); 3127 break; 3128 } 3129 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol] 3130 unsigned OpNum = 0; 3131 Value *Op; 3132 if (getValueTypePair(Record, OpNum, NextValueNo, Op) || 3133 OpNum+2 != Record.size()) 3134 return Error("Invalid record"); 3135 3136 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1); 3137 InstructionList.push_back(I); 3138 break; 3139 } 3140 case bitc::FUNC_CODE_INST_STORE_OLD: { // STORE2:[ptrty, ptr, val, align, vol] 3141 unsigned OpNum = 0; 3142 Value *Val, *Ptr; 3143 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) || 3144 getValue(Record, OpNum, 3145 cast<PointerType>(Ptr->getType())->getElementType(), Val) || 3146 OpNum+2 != Record.size()) 3147 return Error("Invalid record"); 3148 3149 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1); 3150 InstructionList.push_back(I); 3151 break; 3152 } 3153 case FUNC_CODE_INST_STORE_2_7: { 3154 unsigned OpNum = 0; 3155 Value *Val, *Ptr; 3156 if (getValueTypePair(Record, OpNum, NextValueNo, Val) || 3157 getValue(Record, OpNum, 3158 PointerType::getUnqual(Val->getType()), Ptr)|| 3159 OpNum+2 != Record.size()) { 3160 return Error("Invalid record"); 3161 } 3162 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1); 3163 InstructionList.push_back(I); 3164 break; 3165 } 3166 case FUNC_CODE_INST_CALL_2_7: 3167 LLVM2_7MetadataDetected = true; 3168 case bitc::FUNC_CODE_INST_CALL: { 3169 // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...] 3170 if (Record.size() < 3) 3171 return Error("Invalid record"); 3172 3173 AttributeSet PAL = getAttributes(Record[0]); 3174 unsigned CCInfo = Record[1]; 3175 3176 unsigned OpNum = 2; 3177 Value *Callee; 3178 if (getValueTypePair(Record, OpNum, NextValueNo, Callee)) 3179 return Error("Invalid record"); 3180 3181 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType()); 3182 FunctionType *FTy = nullptr; 3183 if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType()); 3184 if (!FTy || Record.size() < FTy->getNumParams()+OpNum) 3185 return Error("Invalid record"); 3186 3187 SmallVector<Value*, 16> Args; 3188 // Read the fixed params. 3189 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) { 3190 if (FTy->getParamType(i)->isLabelTy()) 3191 Args.push_back(getBasicBlock(Record[OpNum])); 3192 else 3193 Args.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i))); 3194 if (!Args.back()) 3195 return Error("Invalid record"); 3196 } 3197 3198 // Read type/value pairs for varargs params. 3199 if (!FTy->isVarArg()) { 3200 if (OpNum != Record.size()) 3201 return Error("Invalid record"); 3202 } else { 3203 while (OpNum != Record.size()) { 3204 Value *Op; 3205 if (getValueTypePair(Record, OpNum, NextValueNo, Op)) 3206 return Error("Invalid record"); 3207 Args.push_back(Op); 3208 } 3209 } 3210 3211 I = CallInst::Create(Callee, Args); 3212 InstructionList.push_back(I); 3213 cast<CallInst>(I)->setCallingConv( 3214 static_cast<CallingConv::ID>(CCInfo>>1)); 3215 cast<CallInst>(I)->setTailCall(CCInfo & 1); 3216 cast<CallInst>(I)->setAttributes(PAL); 3217 break; 3218 } 3219 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty] 3220 if (Record.size() < 3) 3221 return Error("Invalid record"); 3222 Type *OpTy = getTypeByID(Record[0]); 3223 Value *Op = getFnValueByID(Record[1], OpTy); 3224 Type *ResTy = getTypeByID(Record[2]); 3225 if (!OpTy || !Op || !ResTy) 3226 return Error("Invalid record"); 3227 I = new VAArgInst(Op, ResTy); 3228 InstructionList.push_back(I); 3229 break; 3230 } 3231 } 3232 3233 // Add instruction to end of current BB. If there is no current BB, reject 3234 // this file. 3235 if (!CurBB) { 3236 delete I; 3237 return Error("Invalid instruction with no BB"); 3238 } 3239 CurBB->getInstList().push_back(I); 3240 3241 // If this was a terminator instruction, move to the next block. 3242 if (isa<TerminatorInst>(I)) { 3243 ++CurBBNo; 3244 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr; 3245 } 3246 3247 // Non-void values get registered in the value table for future use. 3248 if (I && !I->getType()->isVoidTy()) 3249 ValueList.AssignValue(I, NextValueNo++); 3250 } 3251 3252 // Check the function list for unresolved values. 3253 if (Argument *A = dyn_cast<Argument>(ValueList.back())) { 3254 if (!A->getParent()) { 3255 // We found at least one unresolved value. Nuke them all to avoid leaks. 3256 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){ 3257 if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) { 3258 A->replaceAllUsesWith(UndefValue::get(A->getType())); 3259 delete A; 3260 } 3261 } 3262 return Error("Never resolved value found in function"); 3263 } 3264 } 3265 3266 // FIXME: Check for unresolved forward-declared metadata references 3267 // and clean up leaks. 3268 3269 // See if anything took the address of blocks in this function. If so, 3270 // resolve them now. 3271 DenseMap<Function*, std::vector<BlockAddrRefTy> >::iterator BAFRI = 3272 BlockAddrFwdRefs.find(F); 3273 if (BAFRI != BlockAddrFwdRefs.end()) { 3274 std::vector<BlockAddrRefTy> &RefList = BAFRI->second; 3275 for (unsigned i = 0, e = RefList.size(); i != e; ++i) { 3276 unsigned BlockIdx = RefList[i].first; 3277 if (BlockIdx >= FunctionBBs.size()) 3278 return Error("Invalid ID"); 3279 3280 GlobalVariable *FwdRef = RefList[i].second; 3281 FwdRef->replaceAllUsesWith(BlockAddress::get(F, FunctionBBs[BlockIdx])); 3282 FwdRef->eraseFromParent(); 3283 } 3284 3285 BlockAddrFwdRefs.erase(BAFRI); 3286 } 3287 3288 unsigned NewMDValueListSize = MDValueList.size(); 3289 // Trim the value list down to the size it was before we parsed this function. 3290 ValueList.shrinkTo(ModuleValueListSize); 3291 MDValueList.shrinkTo(ModuleMDValueListSize); 3292 3293 if (LLVM2_7MetadataDetected) { 3294 MDValueList.resize(NewMDValueListSize); 3295 } 3296 3297 std::vector<BasicBlock*>().swap(FunctionBBs); 3298 return std::error_code(); 3299 } 3300 3301 //===----------------------------------------------------------------------===// 3302 // GVMaterializer implementation 3303 //===----------------------------------------------------------------------===// 3304 3305 void BitcodeReader::releaseBuffer() { Buffer.release(); } 3306 3307 std::error_code BitcodeReader::materialize(GlobalValue *GV) { 3308 if (std::error_code EC = materializeMetadata()) 3309 return EC; 3310 3311 Function *F = dyn_cast<Function>(GV); 3312 // If it's not a function or is already material, ignore the request. 3313 if (!F || !F->isMaterializable()) 3314 return std::error_code(); 3315 3316 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F); 3317 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!"); 3318 3319 // Move the bit stream to the saved position of the deferred function body. 3320 Stream.JumpToBit(DFII->second); 3321 3322 if (std::error_code EC = ParseFunctionBody(F)) 3323 return EC; 3324 F->setIsMaterializable(false); 3325 3326 // Upgrade any old intrinsic calls in the function. 3327 for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(), 3328 E = UpgradedIntrinsics.end(); I != E; ++I) { 3329 if (I->first != I->second) { 3330 for (auto UI = I->first->user_begin(), UE = I->first->user_end(); 3331 UI != UE;) { 3332 if (CallInst* CI = dyn_cast<CallInst>(*UI++)) 3333 UpgradeIntrinsicCall(CI, I->second); 3334 } 3335 } 3336 } 3337 3338 return std::error_code(); 3339 } 3340 3341 bool BitcodeReader::isDematerializable(const GlobalValue *GV) const { 3342 const Function *F = dyn_cast<Function>(GV); 3343 if (!F || F->isDeclaration()) 3344 return false; 3345 return DeferredFunctionInfo.count(const_cast<Function*>(F)); 3346 } 3347 3348 void BitcodeReader::dematerialize(GlobalValue *GV) { 3349 Function *F = dyn_cast<Function>(GV); 3350 // If this function isn't dematerializable, this is a noop. 3351 if (!F || !isDematerializable(F)) 3352 return; 3353 3354 assert(DeferredFunctionInfo.count(F) && "No info to read function later?"); 3355 3356 // Just forget the function body, we can remat it later. 3357 F->deleteBody(); 3358 F->setIsMaterializable(true); 3359 } 3360 3361 std::error_code BitcodeReader::materializeModule() { 3362 // Iterate over the module, deserializing any functions that are still on 3363 // disk. 3364 for (Module::iterator F = TheModule->begin(), E = TheModule->end(); 3365 F != E; ++F) { 3366 if (std::error_code EC = materialize(&*F)) 3367 return EC; 3368 } 3369 // At this point, if there are any function bodies, the current bit is 3370 // pointing to the END_BLOCK record after them. Now make sure the rest 3371 // of the bits in the module have been read. 3372 if (NextUnreadBit) 3373 ParseModule(true); 3374 3375 // Upgrade any intrinsic calls that slipped through (should not happen!) and 3376 // delete the old functions to clean up. We can't do this unless the entire 3377 // module is materialized because there could always be another function body 3378 // with calls to the old function. 3379 for (std::vector<std::pair<Function*, Function*> >::iterator I = 3380 UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) { 3381 if (I->first != I->second) { 3382 for (auto UI = I->first->user_begin(), UE = I->first->user_end(); 3383 UI != UE;) { 3384 if (CallInst* CI = dyn_cast<CallInst>(*UI++)) 3385 UpgradeIntrinsicCall(CI, I->second); 3386 } 3387 if (!I->first->use_empty()) 3388 I->first->replaceAllUsesWith(I->second); 3389 I->first->eraseFromParent(); 3390 } 3391 } 3392 std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics); 3393 3394 // Check debug info intrinsics. 3395 CheckDebugInfoIntrinsics(TheModule); 3396 3397 return std::error_code(); 3398 } 3399 3400 std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes() const { 3401 return IdentifiedStructTypes; 3402 } 3403 3404 std::error_code BitcodeReader::InitStream() { 3405 if (LazyStreamer) 3406 return InitLazyStream(); 3407 return InitStreamFromBuffer(); 3408 } 3409 3410 std::error_code BitcodeReader::InitStreamFromBuffer() { 3411 const unsigned char *BufPtr = (const unsigned char*)Buffer->getBufferStart(); 3412 const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize(); 3413 3414 if (Buffer->getBufferSize() & 3) 3415 return Error("Invalid bitcode signature"); 3416 3417 // If we have a wrapper header, parse it and ignore the non-bc file contents. 3418 // The magic number is 0x0B17C0DE stored in little endian. 3419 if (isBitcodeWrapper(BufPtr, BufEnd)) 3420 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true)) 3421 return Error("Invalid bitcode wrapper header"); 3422 3423 StreamFile.reset(new BitstreamReader(BufPtr, BufEnd)); 3424 Stream.init(&*StreamFile); 3425 3426 return std::error_code(); 3427 } 3428 3429 std::error_code BitcodeReader::InitLazyStream() { 3430 // Check and strip off the bitcode wrapper; BitstreamReader expects never to 3431 // see it. 3432 auto OwnedBytes = llvm::make_unique<StreamingMemoryObject>( 3433 std::move(LazyStreamer)); 3434 StreamingMemoryObject &Bytes = *OwnedBytes; 3435 StreamFile = llvm::make_unique<BitstreamReader>(std::move(OwnedBytes)); 3436 Stream.init(&*StreamFile); 3437 3438 unsigned char buf[16]; 3439 if (Bytes.readBytes(buf, 16, 0) != 16) 3440 return Error("Invalid bitcode signature"); 3441 3442 if (!isBitcode(buf, buf + 16)) 3443 return Error("Invalid bitcode signature"); 3444 3445 if (isBitcodeWrapper(buf, buf + 4)) { 3446 const unsigned char *bitcodeStart = buf; 3447 const unsigned char *bitcodeEnd = buf + 16; 3448 SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false); 3449 Bytes.dropLeadingBytes(bitcodeStart - buf); 3450 Bytes.setKnownObjectSize(bitcodeEnd - bitcodeStart); 3451 } 3452 return std::error_code(); 3453 } 3454 3455 namespace { 3456 class BitcodeErrorCategoryType : public std::error_category { 3457 const char *name() const LLVM_NOEXCEPT override { 3458 return "llvm.bitcode"; 3459 } 3460 std::string message(int IE) const override { 3461 BitcodeError E = static_cast<BitcodeError>(IE); 3462 switch (E) { 3463 case BitcodeError::InvalidBitcodeSignature: 3464 return "Invalid bitcode signature"; 3465 case BitcodeError::CorruptedBitcode: 3466 return "Corrupted bitcode"; 3467 } 3468 llvm_unreachable("Unknown error type!"); 3469 } 3470 }; 3471 } 3472 3473 static ManagedStatic<BitcodeErrorCategoryType> ErrorCategory; 3474 3475 const std::error_category &BitcodeReader::BitcodeErrorCategory() { 3476 return *ErrorCategory; 3477 } 3478 3479 //===----------------------------------------------------------------------===// 3480 // External interface 3481 //===----------------------------------------------------------------------===// 3482 3483 /// getLazyBitcodeModule - lazy function-at-a-time loading from a file. 3484 /// 3485 static llvm::ErrorOr<llvm::Module *> 3486 getLazyBitcodeModuleImpl(std::unique_ptr<MemoryBuffer> &&Buffer, 3487 LLVMContext &Context, bool WillMaterializeAll, 3488 DiagnosticHandlerFunction DiagnosticHandler) { 3489 Module *M = new Module(Buffer->getBufferIdentifier(), Context); 3490 BitcodeReader *R = 3491 new BitcodeReader(Buffer.get(), Context, DiagnosticHandler); 3492 M->setMaterializer(R); 3493 3494 auto cleanupOnError = [&](std::error_code EC) { 3495 R->releaseBuffer(); // Never take ownership on error. 3496 delete M; // Also deletes R. 3497 return EC; 3498 }; 3499 3500 if (std::error_code EC = R->ParseBitcodeInto(M)) 3501 return cleanupOnError(EC); 3502 3503 Buffer.release(); // The BitcodeReader owns it now. 3504 return M; 3505 } 3506 3507 llvm::ErrorOr<Module *> 3508 llvm_2_7::getLazyBitcodeModule(std::unique_ptr<MemoryBuffer> &&Buffer, 3509 LLVMContext &Context, 3510 DiagnosticHandlerFunction DiagnosticHandler) { 3511 return getLazyBitcodeModuleImpl(std::move(Buffer), Context, false, 3512 DiagnosticHandler); 3513 } 3514 3515 /// ParseBitcodeFile - Read the specified bitcode file, returning the module. 3516 /// If an error occurs, return null and fill in *ErrMsg if non-null. 3517 llvm::ErrorOr<llvm::Module *> 3518 llvm_2_7::parseBitcodeFile(MemoryBufferRef Buffer, LLVMContext &Context, 3519 DiagnosticHandlerFunction DiagnosticHandler) { 3520 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false); 3521 ErrorOr<Module *> ModuleOrErr = getLazyBitcodeModuleImpl( 3522 std::move(Buf), Context, true, DiagnosticHandler); 3523 if (!ModuleOrErr) 3524 return ModuleOrErr; 3525 Module *M = ModuleOrErr.get(); 3526 // Read in the entire module, and destroy the BitcodeReader. 3527 if (std::error_code EC = M->materializeAll()) { 3528 delete M; 3529 return EC; 3530 } 3531 3532 return M; 3533 } 3534 3535 std::string 3536 llvm_2_7::getBitcodeTargetTriple(MemoryBufferRef Buffer, LLVMContext &Context, 3537 DiagnosticHandlerFunction DiagnosticHandler) { 3538 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false); 3539 auto R = llvm::make_unique<BitcodeReader>(Buf.release(), Context, 3540 DiagnosticHandler); 3541 ErrorOr<std::string> Triple = R->parseTriple(); 3542 if (Triple.getError()) 3543 return ""; 3544 return Triple.get(); 3545 } 3546