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