BitcodeReader.cpp revision ac80ade1580378e484e24c9f66d2fa5b058e5891
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 "BitcodeReader.h" 16#include "llvm/Constants.h" 17#include "llvm/DerivedTypes.h" 18#include "llvm/InlineAsm.h" 19#include "llvm/Instructions.h" 20#include "llvm/Module.h" 21#include "llvm/AutoUpgrade.h" 22#include "llvm/ADT/SmallString.h" 23#include "llvm/ADT/SmallVector.h" 24#include "llvm/Support/MathExtras.h" 25#include "llvm/Support/MemoryBuffer.h" 26#include "llvm/OperandTraits.h" 27using namespace llvm; 28 29void BitcodeReader::FreeState() { 30 delete Buffer; 31 Buffer = 0; 32 std::vector<PATypeHolder>().swap(TypeList); 33 ValueList.clear(); 34 35 std::vector<PAListPtr>().swap(ParamAttrs); 36 std::vector<BasicBlock*>().swap(FunctionBBs); 37 std::vector<Function*>().swap(FunctionsWithBodies); 38 DeferredFunctionInfo.clear(); 39} 40 41//===----------------------------------------------------------------------===// 42// Helper functions to implement forward reference resolution, etc. 43//===----------------------------------------------------------------------===// 44 45/// ConvertToString - Convert a string from a record into an std::string, return 46/// true on failure. 47template<typename StrTy> 48static bool ConvertToString(SmallVector<uint64_t, 64> &Record, unsigned Idx, 49 StrTy &Result) { 50 if (Idx > Record.size()) 51 return true; 52 53 for (unsigned i = Idx, e = Record.size(); i != e; ++i) 54 Result += (char)Record[i]; 55 return false; 56} 57 58static GlobalValue::LinkageTypes GetDecodedLinkage(unsigned Val) { 59 switch (Val) { 60 default: // Map unknown/new linkages to external 61 case 0: return GlobalValue::ExternalLinkage; 62 case 1: return GlobalValue::WeakLinkage; 63 case 2: return GlobalValue::AppendingLinkage; 64 case 3: return GlobalValue::InternalLinkage; 65 case 4: return GlobalValue::LinkOnceLinkage; 66 case 5: return GlobalValue::DLLImportLinkage; 67 case 6: return GlobalValue::DLLExportLinkage; 68 case 7: return GlobalValue::ExternalWeakLinkage; 69 } 70} 71 72static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned Val) { 73 switch (Val) { 74 default: // Map unknown visibilities to default. 75 case 0: return GlobalValue::DefaultVisibility; 76 case 1: return GlobalValue::HiddenVisibility; 77 case 2: return GlobalValue::ProtectedVisibility; 78 } 79} 80 81static int GetDecodedCastOpcode(unsigned Val) { 82 switch (Val) { 83 default: return -1; 84 case bitc::CAST_TRUNC : return Instruction::Trunc; 85 case bitc::CAST_ZEXT : return Instruction::ZExt; 86 case bitc::CAST_SEXT : return Instruction::SExt; 87 case bitc::CAST_FPTOUI : return Instruction::FPToUI; 88 case bitc::CAST_FPTOSI : return Instruction::FPToSI; 89 case bitc::CAST_UITOFP : return Instruction::UIToFP; 90 case bitc::CAST_SITOFP : return Instruction::SIToFP; 91 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc; 92 case bitc::CAST_FPEXT : return Instruction::FPExt; 93 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt; 94 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr; 95 case bitc::CAST_BITCAST : return Instruction::BitCast; 96 } 97} 98static int GetDecodedBinaryOpcode(unsigned Val, const Type *Ty) { 99 switch (Val) { 100 default: return -1; 101 case bitc::BINOP_ADD: return Instruction::Add; 102 case bitc::BINOP_SUB: return Instruction::Sub; 103 case bitc::BINOP_MUL: return Instruction::Mul; 104 case bitc::BINOP_UDIV: return Instruction::UDiv; 105 case bitc::BINOP_SDIV: 106 return Ty->isFPOrFPVector() ? Instruction::FDiv : Instruction::SDiv; 107 case bitc::BINOP_UREM: return Instruction::URem; 108 case bitc::BINOP_SREM: 109 return Ty->isFPOrFPVector() ? Instruction::FRem : Instruction::SRem; 110 case bitc::BINOP_SHL: return Instruction::Shl; 111 case bitc::BINOP_LSHR: return Instruction::LShr; 112 case bitc::BINOP_ASHR: return Instruction::AShr; 113 case bitc::BINOP_AND: return Instruction::And; 114 case bitc::BINOP_OR: return Instruction::Or; 115 case bitc::BINOP_XOR: return Instruction::Xor; 116 } 117} 118 119namespace llvm { 120namespace { 121 /// @brief A class for maintaining the slot number definition 122 /// as a placeholder for the actual definition for forward constants defs. 123 class ConstantPlaceHolder : public ConstantExpr { 124 ConstantPlaceHolder(); // DO NOT IMPLEMENT 125 void operator=(const ConstantPlaceHolder &); // DO NOT IMPLEMENT 126 public: 127 // allocate space for exactly one operand 128 void *operator new(size_t s) { 129 return User::operator new(s, 1); 130 } 131 explicit ConstantPlaceHolder(const Type *Ty) 132 : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) { 133 Op<0>() = UndefValue::get(Type::Int32Ty); 134 } 135 /// Provide fast operand accessors 136 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value); 137 }; 138} 139 140 141 // FIXME: can we inherit this from ConstantExpr? 142template <> 143struct OperandTraits<ConstantPlaceHolder> : FixedNumOperandTraits<1> { 144}; 145 146DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ConstantPlaceHolder, Value) 147} 148 149void BitcodeReaderValueList::resize(unsigned Desired) { 150 if (Desired > Capacity) { 151 // Since we expect many values to come from the bitcode file we better 152 // allocate the double amount, so that the array size grows exponentially 153 // at each reallocation. Also, add a small amount of 100 extra elements 154 // each time, to reallocate less frequently when the array is still small. 155 // 156 Capacity = Desired * 2 + 100; 157 Use *New = allocHungoffUses(Capacity); 158 Use *Old = OperandList; 159 unsigned Ops = getNumOperands(); 160 for (int i(Ops - 1); i >= 0; --i) 161 New[i] = Old[i].get(); 162 OperandList = New; 163 if (Old) Use::zap(Old, Old + Ops, true); 164 } 165} 166 167Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx, 168 const Type *Ty) { 169 if (Idx >= size()) { 170 // Insert a bunch of null values. 171 resize(Idx + 1); 172 NumOperands = Idx+1; 173 } 174 175 if (Value *V = OperandList[Idx]) { 176 assert(Ty == V->getType() && "Type mismatch in constant table!"); 177 return cast<Constant>(V); 178 } 179 180 // Create and return a placeholder, which will later be RAUW'd. 181 Constant *C = new ConstantPlaceHolder(Ty); 182 OperandList[Idx].init(C, this); 183 return C; 184} 185 186Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, const Type *Ty) { 187 if (Idx >= size()) { 188 // Insert a bunch of null values. 189 resize(Idx + 1); 190 NumOperands = Idx+1; 191 } 192 193 if (Value *V = OperandList[Idx]) { 194 assert((Ty == 0 || Ty == V->getType()) && "Type mismatch in value table!"); 195 return V; 196 } 197 198 // No type specified, must be invalid reference. 199 if (Ty == 0) return 0; 200 201 // Create and return a placeholder, which will later be RAUW'd. 202 Value *V = new Argument(Ty); 203 OperandList[Idx].init(V, this); 204 return V; 205} 206 207 208const Type *BitcodeReader::getTypeByID(unsigned ID, bool isTypeTable) { 209 // If the TypeID is in range, return it. 210 if (ID < TypeList.size()) 211 return TypeList[ID].get(); 212 if (!isTypeTable) return 0; 213 214 // The type table allows forward references. Push as many Opaque types as 215 // needed to get up to ID. 216 while (TypeList.size() <= ID) 217 TypeList.push_back(OpaqueType::get()); 218 return TypeList.back().get(); 219} 220 221//===----------------------------------------------------------------------===// 222// Functions for parsing blocks from the bitcode file 223//===----------------------------------------------------------------------===// 224 225bool BitcodeReader::ParseParamAttrBlock() { 226 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID)) 227 return Error("Malformed block record"); 228 229 if (!ParamAttrs.empty()) 230 return Error("Multiple PARAMATTR blocks found!"); 231 232 SmallVector<uint64_t, 64> Record; 233 234 SmallVector<ParamAttrsWithIndex, 8> Attrs; 235 236 // Read all the records. 237 while (1) { 238 unsigned Code = Stream.ReadCode(); 239 if (Code == bitc::END_BLOCK) { 240 if (Stream.ReadBlockEnd()) 241 return Error("Error at end of PARAMATTR block"); 242 return false; 243 } 244 245 if (Code == bitc::ENTER_SUBBLOCK) { 246 // No known subblocks, always skip them. 247 Stream.ReadSubBlockID(); 248 if (Stream.SkipBlock()) 249 return Error("Malformed block record"); 250 continue; 251 } 252 253 if (Code == bitc::DEFINE_ABBREV) { 254 Stream.ReadAbbrevRecord(); 255 continue; 256 } 257 258 // Read a record. 259 Record.clear(); 260 switch (Stream.ReadRecord(Code, Record)) { 261 default: // Default behavior: ignore. 262 break; 263 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [paramidx0, attr0, ...] 264 if (Record.size() & 1) 265 return Error("Invalid ENTRY record"); 266 267 for (unsigned i = 0, e = Record.size(); i != e; i += 2) { 268 if (Record[i+1] != ParamAttr::None) 269 Attrs.push_back(ParamAttrsWithIndex::get(Record[i], Record[i+1])); 270 } 271 272 ParamAttrs.push_back(PAListPtr::get(Attrs.begin(), Attrs.end())); 273 Attrs.clear(); 274 break; 275 } 276 } 277 } 278} 279 280 281bool BitcodeReader::ParseTypeTable() { 282 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID)) 283 return Error("Malformed block record"); 284 285 if (!TypeList.empty()) 286 return Error("Multiple TYPE_BLOCKs found!"); 287 288 SmallVector<uint64_t, 64> Record; 289 unsigned NumRecords = 0; 290 291 // Read all the records for this type table. 292 while (1) { 293 unsigned Code = Stream.ReadCode(); 294 if (Code == bitc::END_BLOCK) { 295 if (NumRecords != TypeList.size()) 296 return Error("Invalid type forward reference in TYPE_BLOCK"); 297 if (Stream.ReadBlockEnd()) 298 return Error("Error at end of type table block"); 299 return false; 300 } 301 302 if (Code == bitc::ENTER_SUBBLOCK) { 303 // No known subblocks, always skip them. 304 Stream.ReadSubBlockID(); 305 if (Stream.SkipBlock()) 306 return Error("Malformed block record"); 307 continue; 308 } 309 310 if (Code == bitc::DEFINE_ABBREV) { 311 Stream.ReadAbbrevRecord(); 312 continue; 313 } 314 315 // Read a record. 316 Record.clear(); 317 const Type *ResultTy = 0; 318 switch (Stream.ReadRecord(Code, Record)) { 319 default: // Default behavior: unknown type. 320 ResultTy = 0; 321 break; 322 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries] 323 // TYPE_CODE_NUMENTRY contains a count of the number of types in the 324 // type list. This allows us to reserve space. 325 if (Record.size() < 1) 326 return Error("Invalid TYPE_CODE_NUMENTRY record"); 327 TypeList.reserve(Record[0]); 328 continue; 329 case bitc::TYPE_CODE_VOID: // VOID 330 ResultTy = Type::VoidTy; 331 break; 332 case bitc::TYPE_CODE_FLOAT: // FLOAT 333 ResultTy = Type::FloatTy; 334 break; 335 case bitc::TYPE_CODE_DOUBLE: // DOUBLE 336 ResultTy = Type::DoubleTy; 337 break; 338 case bitc::TYPE_CODE_X86_FP80: // X86_FP80 339 ResultTy = Type::X86_FP80Ty; 340 break; 341 case bitc::TYPE_CODE_FP128: // FP128 342 ResultTy = Type::FP128Ty; 343 break; 344 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128 345 ResultTy = Type::PPC_FP128Ty; 346 break; 347 case bitc::TYPE_CODE_LABEL: // LABEL 348 ResultTy = Type::LabelTy; 349 break; 350 case bitc::TYPE_CODE_OPAQUE: // OPAQUE 351 ResultTy = 0; 352 break; 353 case bitc::TYPE_CODE_INTEGER: // INTEGER: [width] 354 if (Record.size() < 1) 355 return Error("Invalid Integer type record"); 356 357 ResultTy = IntegerType::get(Record[0]); 358 break; 359 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or 360 // [pointee type, address space] 361 if (Record.size() < 1) 362 return Error("Invalid POINTER type record"); 363 unsigned AddressSpace = 0; 364 if (Record.size() == 2) 365 AddressSpace = Record[1]; 366 ResultTy = PointerType::get(getTypeByID(Record[0], true), AddressSpace); 367 break; 368 } 369 case bitc::TYPE_CODE_FUNCTION: { 370 // FIXME: attrid is dead, remove it in LLVM 3.0 371 // FUNCTION: [vararg, attrid, retty, paramty x N] 372 if (Record.size() < 3) 373 return Error("Invalid FUNCTION type record"); 374 std::vector<const Type*> ArgTys; 375 for (unsigned i = 3, e = Record.size(); i != e; ++i) 376 ArgTys.push_back(getTypeByID(Record[i], true)); 377 378 ResultTy = FunctionType::get(getTypeByID(Record[2], true), ArgTys, 379 Record[0]); 380 break; 381 } 382 case bitc::TYPE_CODE_STRUCT: { // STRUCT: [ispacked, eltty x N] 383 if (Record.size() < 1) 384 return Error("Invalid STRUCT type record"); 385 std::vector<const Type*> EltTys; 386 for (unsigned i = 1, e = Record.size(); i != e; ++i) 387 EltTys.push_back(getTypeByID(Record[i], true)); 388 ResultTy = StructType::get(EltTys, Record[0]); 389 break; 390 } 391 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty] 392 if (Record.size() < 2) 393 return Error("Invalid ARRAY type record"); 394 ResultTy = ArrayType::get(getTypeByID(Record[1], true), Record[0]); 395 break; 396 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty] 397 if (Record.size() < 2) 398 return Error("Invalid VECTOR type record"); 399 ResultTy = VectorType::get(getTypeByID(Record[1], true), Record[0]); 400 break; 401 } 402 403 if (NumRecords == TypeList.size()) { 404 // If this is a new type slot, just append it. 405 TypeList.push_back(ResultTy ? ResultTy : OpaqueType::get()); 406 ++NumRecords; 407 } else if (ResultTy == 0) { 408 // Otherwise, this was forward referenced, so an opaque type was created, 409 // but the result type is actually just an opaque. Leave the one we 410 // created previously. 411 ++NumRecords; 412 } else { 413 // Otherwise, this was forward referenced, so an opaque type was created. 414 // Resolve the opaque type to the real type now. 415 assert(NumRecords < TypeList.size() && "Typelist imbalance"); 416 const OpaqueType *OldTy = cast<OpaqueType>(TypeList[NumRecords++].get()); 417 418 // Don't directly push the new type on the Tab. Instead we want to replace 419 // the opaque type we previously inserted with the new concrete value. The 420 // refinement from the abstract (opaque) type to the new type causes all 421 // uses of the abstract type to use the concrete type (NewTy). This will 422 // also cause the opaque type to be deleted. 423 const_cast<OpaqueType*>(OldTy)->refineAbstractTypeTo(ResultTy); 424 425 // This should have replaced the old opaque type with the new type in the 426 // value table... or with a preexisting type that was already in the 427 // system. Let's just make sure it did. 428 assert(TypeList[NumRecords-1].get() != OldTy && 429 "refineAbstractType didn't work!"); 430 } 431 } 432} 433 434 435bool BitcodeReader::ParseTypeSymbolTable() { 436 if (Stream.EnterSubBlock(bitc::TYPE_SYMTAB_BLOCK_ID)) 437 return Error("Malformed block record"); 438 439 SmallVector<uint64_t, 64> Record; 440 441 // Read all the records for this type table. 442 std::string TypeName; 443 while (1) { 444 unsigned Code = Stream.ReadCode(); 445 if (Code == bitc::END_BLOCK) { 446 if (Stream.ReadBlockEnd()) 447 return Error("Error at end of type symbol table block"); 448 return false; 449 } 450 451 if (Code == bitc::ENTER_SUBBLOCK) { 452 // No known subblocks, always skip them. 453 Stream.ReadSubBlockID(); 454 if (Stream.SkipBlock()) 455 return Error("Malformed block record"); 456 continue; 457 } 458 459 if (Code == bitc::DEFINE_ABBREV) { 460 Stream.ReadAbbrevRecord(); 461 continue; 462 } 463 464 // Read a record. 465 Record.clear(); 466 switch (Stream.ReadRecord(Code, Record)) { 467 default: // Default behavior: unknown type. 468 break; 469 case bitc::TST_CODE_ENTRY: // TST_ENTRY: [typeid, namechar x N] 470 if (ConvertToString(Record, 1, TypeName)) 471 return Error("Invalid TST_ENTRY record"); 472 unsigned TypeID = Record[0]; 473 if (TypeID >= TypeList.size()) 474 return Error("Invalid Type ID in TST_ENTRY record"); 475 476 TheModule->addTypeName(TypeName, TypeList[TypeID].get()); 477 TypeName.clear(); 478 break; 479 } 480 } 481} 482 483bool BitcodeReader::ParseValueSymbolTable() { 484 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID)) 485 return Error("Malformed block record"); 486 487 SmallVector<uint64_t, 64> Record; 488 489 // Read all the records for this value table. 490 SmallString<128> ValueName; 491 while (1) { 492 unsigned Code = Stream.ReadCode(); 493 if (Code == bitc::END_BLOCK) { 494 if (Stream.ReadBlockEnd()) 495 return Error("Error at end of value symbol table block"); 496 return false; 497 } 498 if (Code == bitc::ENTER_SUBBLOCK) { 499 // No known subblocks, always skip them. 500 Stream.ReadSubBlockID(); 501 if (Stream.SkipBlock()) 502 return Error("Malformed block record"); 503 continue; 504 } 505 506 if (Code == bitc::DEFINE_ABBREV) { 507 Stream.ReadAbbrevRecord(); 508 continue; 509 } 510 511 // Read a record. 512 Record.clear(); 513 switch (Stream.ReadRecord(Code, Record)) { 514 default: // Default behavior: unknown type. 515 break; 516 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N] 517 if (ConvertToString(Record, 1, ValueName)) 518 return Error("Invalid TST_ENTRY record"); 519 unsigned ValueID = Record[0]; 520 if (ValueID >= ValueList.size()) 521 return Error("Invalid Value ID in VST_ENTRY record"); 522 Value *V = ValueList[ValueID]; 523 524 V->setName(&ValueName[0], ValueName.size()); 525 ValueName.clear(); 526 break; 527 } 528 case bitc::VST_CODE_BBENTRY: { 529 if (ConvertToString(Record, 1, ValueName)) 530 return Error("Invalid VST_BBENTRY record"); 531 BasicBlock *BB = getBasicBlock(Record[0]); 532 if (BB == 0) 533 return Error("Invalid BB ID in VST_BBENTRY record"); 534 535 BB->setName(&ValueName[0], ValueName.size()); 536 ValueName.clear(); 537 break; 538 } 539 } 540 } 541} 542 543/// DecodeSignRotatedValue - Decode a signed value stored with the sign bit in 544/// the LSB for dense VBR encoding. 545static uint64_t DecodeSignRotatedValue(uint64_t V) { 546 if ((V & 1) == 0) 547 return V >> 1; 548 if (V != 1) 549 return -(V >> 1); 550 // There is no such thing as -0 with integers. "-0" really means MININT. 551 return 1ULL << 63; 552} 553 554/// ResolveGlobalAndAliasInits - Resolve all of the initializers for global 555/// values and aliases that we can. 556bool BitcodeReader::ResolveGlobalAndAliasInits() { 557 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist; 558 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist; 559 560 GlobalInitWorklist.swap(GlobalInits); 561 AliasInitWorklist.swap(AliasInits); 562 563 while (!GlobalInitWorklist.empty()) { 564 unsigned ValID = GlobalInitWorklist.back().second; 565 if (ValID >= ValueList.size()) { 566 // Not ready to resolve this yet, it requires something later in the file. 567 GlobalInits.push_back(GlobalInitWorklist.back()); 568 } else { 569 if (Constant *C = dyn_cast<Constant>(ValueList[ValID])) 570 GlobalInitWorklist.back().first->setInitializer(C); 571 else 572 return Error("Global variable initializer is not a constant!"); 573 } 574 GlobalInitWorklist.pop_back(); 575 } 576 577 while (!AliasInitWorklist.empty()) { 578 unsigned ValID = AliasInitWorklist.back().second; 579 if (ValID >= ValueList.size()) { 580 AliasInits.push_back(AliasInitWorklist.back()); 581 } else { 582 if (Constant *C = dyn_cast<Constant>(ValueList[ValID])) 583 AliasInitWorklist.back().first->setAliasee(C); 584 else 585 return Error("Alias initializer is not a constant!"); 586 } 587 AliasInitWorklist.pop_back(); 588 } 589 return false; 590} 591 592 593bool BitcodeReader::ParseConstants() { 594 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID)) 595 return Error("Malformed block record"); 596 597 SmallVector<uint64_t, 64> Record; 598 599 // Read all the records for this value table. 600 const Type *CurTy = Type::Int32Ty; 601 unsigned NextCstNo = ValueList.size(); 602 while (1) { 603 unsigned Code = Stream.ReadCode(); 604 if (Code == bitc::END_BLOCK) { 605 if (NextCstNo != ValueList.size()) 606 return Error("Invalid constant reference!"); 607 608 if (Stream.ReadBlockEnd()) 609 return Error("Error at end of constants block"); 610 return false; 611 } 612 613 if (Code == bitc::ENTER_SUBBLOCK) { 614 // No known subblocks, always skip them. 615 Stream.ReadSubBlockID(); 616 if (Stream.SkipBlock()) 617 return Error("Malformed block record"); 618 continue; 619 } 620 621 if (Code == bitc::DEFINE_ABBREV) { 622 Stream.ReadAbbrevRecord(); 623 continue; 624 } 625 626 // Read a record. 627 Record.clear(); 628 Value *V = 0; 629 switch (Stream.ReadRecord(Code, Record)) { 630 default: // Default behavior: unknown constant 631 case bitc::CST_CODE_UNDEF: // UNDEF 632 V = UndefValue::get(CurTy); 633 break; 634 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid] 635 if (Record.empty()) 636 return Error("Malformed CST_SETTYPE record"); 637 if (Record[0] >= TypeList.size()) 638 return Error("Invalid Type ID in CST_SETTYPE record"); 639 CurTy = TypeList[Record[0]]; 640 continue; // Skip the ValueList manipulation. 641 case bitc::CST_CODE_NULL: // NULL 642 V = Constant::getNullValue(CurTy); 643 break; 644 case bitc::CST_CODE_INTEGER: // INTEGER: [intval] 645 if (!isa<IntegerType>(CurTy) || Record.empty()) 646 return Error("Invalid CST_INTEGER record"); 647 V = ConstantInt::get(CurTy, DecodeSignRotatedValue(Record[0])); 648 break; 649 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval] 650 if (!isa<IntegerType>(CurTy) || Record.empty()) 651 return Error("Invalid WIDE_INTEGER record"); 652 653 unsigned NumWords = Record.size(); 654 SmallVector<uint64_t, 8> Words; 655 Words.resize(NumWords); 656 for (unsigned i = 0; i != NumWords; ++i) 657 Words[i] = DecodeSignRotatedValue(Record[i]); 658 V = ConstantInt::get(APInt(cast<IntegerType>(CurTy)->getBitWidth(), 659 NumWords, &Words[0])); 660 break; 661 } 662 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval] 663 if (Record.empty()) 664 return Error("Invalid FLOAT record"); 665 if (CurTy == Type::FloatTy) 666 V = ConstantFP::get(APFloat(APInt(32, (uint32_t)Record[0]))); 667 else if (CurTy == Type::DoubleTy) 668 V = ConstantFP::get(APFloat(APInt(64, Record[0]))); 669 else if (CurTy == Type::X86_FP80Ty) 670 V = ConstantFP::get(APFloat(APInt(80, 2, &Record[0]))); 671 else if (CurTy == Type::FP128Ty) 672 V = ConstantFP::get(APFloat(APInt(128, 2, &Record[0]), true)); 673 else if (CurTy == Type::PPC_FP128Ty) 674 V = ConstantFP::get(APFloat(APInt(128, 2, &Record[0]))); 675 else 676 V = UndefValue::get(CurTy); 677 break; 678 } 679 680 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number] 681 if (Record.empty()) 682 return Error("Invalid CST_AGGREGATE record"); 683 684 unsigned Size = Record.size(); 685 std::vector<Constant*> Elts; 686 687 if (const StructType *STy = dyn_cast<StructType>(CurTy)) { 688 for (unsigned i = 0; i != Size; ++i) 689 Elts.push_back(ValueList.getConstantFwdRef(Record[i], 690 STy->getElementType(i))); 691 V = ConstantStruct::get(STy, Elts); 692 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) { 693 const Type *EltTy = ATy->getElementType(); 694 for (unsigned i = 0; i != Size; ++i) 695 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy)); 696 V = ConstantArray::get(ATy, Elts); 697 } else if (const VectorType *VTy = dyn_cast<VectorType>(CurTy)) { 698 const Type *EltTy = VTy->getElementType(); 699 for (unsigned i = 0; i != Size; ++i) 700 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy)); 701 V = ConstantVector::get(Elts); 702 } else { 703 V = UndefValue::get(CurTy); 704 } 705 break; 706 } 707 case bitc::CST_CODE_STRING: { // STRING: [values] 708 if (Record.empty()) 709 return Error("Invalid CST_AGGREGATE record"); 710 711 const ArrayType *ATy = cast<ArrayType>(CurTy); 712 const Type *EltTy = ATy->getElementType(); 713 714 unsigned Size = Record.size(); 715 std::vector<Constant*> Elts; 716 for (unsigned i = 0; i != Size; ++i) 717 Elts.push_back(ConstantInt::get(EltTy, Record[i])); 718 V = ConstantArray::get(ATy, Elts); 719 break; 720 } 721 case bitc::CST_CODE_CSTRING: { // CSTRING: [values] 722 if (Record.empty()) 723 return Error("Invalid CST_AGGREGATE record"); 724 725 const ArrayType *ATy = cast<ArrayType>(CurTy); 726 const Type *EltTy = ATy->getElementType(); 727 728 unsigned Size = Record.size(); 729 std::vector<Constant*> Elts; 730 for (unsigned i = 0; i != Size; ++i) 731 Elts.push_back(ConstantInt::get(EltTy, Record[i])); 732 Elts.push_back(Constant::getNullValue(EltTy)); 733 V = ConstantArray::get(ATy, Elts); 734 break; 735 } 736 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval] 737 if (Record.size() < 3) return Error("Invalid CE_BINOP record"); 738 int Opc = GetDecodedBinaryOpcode(Record[0], CurTy); 739 if (Opc < 0) { 740 V = UndefValue::get(CurTy); // Unknown binop. 741 } else { 742 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy); 743 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy); 744 V = ConstantExpr::get(Opc, LHS, RHS); 745 } 746 break; 747 } 748 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval] 749 if (Record.size() < 3) return Error("Invalid CE_CAST record"); 750 int Opc = GetDecodedCastOpcode(Record[0]); 751 if (Opc < 0) { 752 V = UndefValue::get(CurTy); // Unknown cast. 753 } else { 754 const Type *OpTy = getTypeByID(Record[1]); 755 if (!OpTy) return Error("Invalid CE_CAST record"); 756 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy); 757 V = ConstantExpr::getCast(Opc, Op, CurTy); 758 } 759 break; 760 } 761 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands] 762 if (Record.size() & 1) return Error("Invalid CE_GEP record"); 763 SmallVector<Constant*, 16> Elts; 764 for (unsigned i = 0, e = Record.size(); i != e; i += 2) { 765 const Type *ElTy = getTypeByID(Record[i]); 766 if (!ElTy) return Error("Invalid CE_GEP record"); 767 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy)); 768 } 769 V = ConstantExpr::getGetElementPtr(Elts[0], &Elts[1], Elts.size()-1); 770 break; 771 } 772 case bitc::CST_CODE_CE_SELECT: // CE_SELECT: [opval#, opval#, opval#] 773 if (Record.size() < 3) return Error("Invalid CE_SELECT record"); 774 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0], 775 Type::Int1Ty), 776 ValueList.getConstantFwdRef(Record[1],CurTy), 777 ValueList.getConstantFwdRef(Record[2],CurTy)); 778 break; 779 case bitc::CST_CODE_CE_EXTRACTELT: { // CE_EXTRACTELT: [opty, opval, opval] 780 if (Record.size() < 3) return Error("Invalid CE_EXTRACTELT record"); 781 const VectorType *OpTy = 782 dyn_cast_or_null<VectorType>(getTypeByID(Record[0])); 783 if (OpTy == 0) return Error("Invalid CE_EXTRACTELT record"); 784 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy); 785 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], 786 OpTy->getElementType()); 787 V = ConstantExpr::getExtractElement(Op0, Op1); 788 break; 789 } 790 case bitc::CST_CODE_CE_INSERTELT: { // CE_INSERTELT: [opval, opval, opval] 791 const VectorType *OpTy = dyn_cast<VectorType>(CurTy); 792 if (Record.size() < 3 || OpTy == 0) 793 return Error("Invalid CE_INSERTELT record"); 794 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy); 795 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], 796 OpTy->getElementType()); 797 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], Type::Int32Ty); 798 V = ConstantExpr::getInsertElement(Op0, Op1, Op2); 799 break; 800 } 801 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval] 802 const VectorType *OpTy = dyn_cast<VectorType>(CurTy); 803 if (Record.size() < 3 || OpTy == 0) 804 return Error("Invalid CE_INSERTELT record"); 805 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy); 806 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy); 807 const Type *ShufTy=VectorType::get(Type::Int32Ty, OpTy->getNumElements()); 808 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy); 809 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2); 810 break; 811 } 812 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred] 813 if (Record.size() < 4) return Error("Invalid CE_CMP record"); 814 const Type *OpTy = getTypeByID(Record[0]); 815 if (OpTy == 0) return Error("Invalid CE_CMP record"); 816 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy); 817 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy); 818 819 if (OpTy->isFloatingPoint()) 820 V = ConstantExpr::getFCmp(Record[3], Op0, Op1); 821 else if (OpTy->isInteger()) 822 V = ConstantExpr::getICmp(Record[3], Op0, Op1); 823 else if (OpTy->isFPOrFPVector()) 824 V = ConstantExpr::getVFCmp(Record[3], Op0, Op1); 825 else 826 V = ConstantExpr::getVICmp(Record[3], Op0, Op1); 827 break; 828 } 829 case bitc::CST_CODE_INLINEASM: { 830 if (Record.size() < 2) return Error("Invalid INLINEASM record"); 831 std::string AsmStr, ConstrStr; 832 bool HasSideEffects = Record[0]; 833 unsigned AsmStrSize = Record[1]; 834 if (2+AsmStrSize >= Record.size()) 835 return Error("Invalid INLINEASM record"); 836 unsigned ConstStrSize = Record[2+AsmStrSize]; 837 if (3+AsmStrSize+ConstStrSize > Record.size()) 838 return Error("Invalid INLINEASM record"); 839 840 for (unsigned i = 0; i != AsmStrSize; ++i) 841 AsmStr += (char)Record[2+i]; 842 for (unsigned i = 0; i != ConstStrSize; ++i) 843 ConstrStr += (char)Record[3+AsmStrSize+i]; 844 const PointerType *PTy = cast<PointerType>(CurTy); 845 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()), 846 AsmStr, ConstrStr, HasSideEffects); 847 break; 848 } 849 } 850 851 ValueList.AssignValue(V, NextCstNo); 852 ++NextCstNo; 853 } 854} 855 856/// RememberAndSkipFunctionBody - When we see the block for a function body, 857/// remember where it is and then skip it. This lets us lazily deserialize the 858/// functions. 859bool BitcodeReader::RememberAndSkipFunctionBody() { 860 // Get the function we are talking about. 861 if (FunctionsWithBodies.empty()) 862 return Error("Insufficient function protos"); 863 864 Function *Fn = FunctionsWithBodies.back(); 865 FunctionsWithBodies.pop_back(); 866 867 // Save the current stream state. 868 uint64_t CurBit = Stream.GetCurrentBitNo(); 869 DeferredFunctionInfo[Fn] = std::make_pair(CurBit, Fn->getLinkage()); 870 871 // Set the functions linkage to GhostLinkage so we know it is lazily 872 // deserialized. 873 Fn->setLinkage(GlobalValue::GhostLinkage); 874 875 // Skip over the function block for now. 876 if (Stream.SkipBlock()) 877 return Error("Malformed block record"); 878 return false; 879} 880 881bool BitcodeReader::ParseModule(const std::string &ModuleID) { 882 // Reject multiple MODULE_BLOCK's in a single bitstream. 883 if (TheModule) 884 return Error("Multiple MODULE_BLOCKs in same stream"); 885 886 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID)) 887 return Error("Malformed block record"); 888 889 // Otherwise, create the module. 890 TheModule = new Module(ModuleID); 891 892 SmallVector<uint64_t, 64> Record; 893 std::vector<std::string> SectionTable; 894 std::vector<std::string> CollectorTable; 895 896 // Read all the records for this module. 897 while (!Stream.AtEndOfStream()) { 898 unsigned Code = Stream.ReadCode(); 899 if (Code == bitc::END_BLOCK) { 900 if (Stream.ReadBlockEnd()) 901 return Error("Error at end of module block"); 902 903 // Patch the initializers for globals and aliases up. 904 ResolveGlobalAndAliasInits(); 905 if (!GlobalInits.empty() || !AliasInits.empty()) 906 return Error("Malformed global initializer set"); 907 if (!FunctionsWithBodies.empty()) 908 return Error("Too few function bodies found"); 909 910 // Look for intrinsic functions which need to be upgraded at some point 911 for (Module::iterator FI = TheModule->begin(), FE = TheModule->end(); 912 FI != FE; ++FI) { 913 Function* NewFn; 914 if (UpgradeIntrinsicFunction(FI, NewFn)) 915 UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn)); 916 } 917 918 // Force deallocation of memory for these vectors to favor the client that 919 // want lazy deserialization. 920 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits); 921 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits); 922 std::vector<Function*>().swap(FunctionsWithBodies); 923 return false; 924 } 925 926 if (Code == bitc::ENTER_SUBBLOCK) { 927 switch (Stream.ReadSubBlockID()) { 928 default: // Skip unknown content. 929 if (Stream.SkipBlock()) 930 return Error("Malformed block record"); 931 break; 932 case bitc::BLOCKINFO_BLOCK_ID: 933 if (Stream.ReadBlockInfoBlock()) 934 return Error("Malformed BlockInfoBlock"); 935 break; 936 case bitc::PARAMATTR_BLOCK_ID: 937 if (ParseParamAttrBlock()) 938 return true; 939 break; 940 case bitc::TYPE_BLOCK_ID: 941 if (ParseTypeTable()) 942 return true; 943 break; 944 case bitc::TYPE_SYMTAB_BLOCK_ID: 945 if (ParseTypeSymbolTable()) 946 return true; 947 break; 948 case bitc::VALUE_SYMTAB_BLOCK_ID: 949 if (ParseValueSymbolTable()) 950 return true; 951 break; 952 case bitc::CONSTANTS_BLOCK_ID: 953 if (ParseConstants() || ResolveGlobalAndAliasInits()) 954 return true; 955 break; 956 case bitc::FUNCTION_BLOCK_ID: 957 // If this is the first function body we've seen, reverse the 958 // FunctionsWithBodies list. 959 if (!HasReversedFunctionsWithBodies) { 960 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end()); 961 HasReversedFunctionsWithBodies = true; 962 } 963 964 if (RememberAndSkipFunctionBody()) 965 return true; 966 break; 967 } 968 continue; 969 } 970 971 if (Code == bitc::DEFINE_ABBREV) { 972 Stream.ReadAbbrevRecord(); 973 continue; 974 } 975 976 // Read a record. 977 switch (Stream.ReadRecord(Code, Record)) { 978 default: break; // Default behavior, ignore unknown content. 979 case bitc::MODULE_CODE_VERSION: // VERSION: [version#] 980 if (Record.size() < 1) 981 return Error("Malformed MODULE_CODE_VERSION"); 982 // Only version #0 is supported so far. 983 if (Record[0] != 0) 984 return Error("Unknown bitstream version!"); 985 break; 986 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N] 987 std::string S; 988 if (ConvertToString(Record, 0, S)) 989 return Error("Invalid MODULE_CODE_TRIPLE record"); 990 TheModule->setTargetTriple(S); 991 break; 992 } 993 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N] 994 std::string S; 995 if (ConvertToString(Record, 0, S)) 996 return Error("Invalid MODULE_CODE_DATALAYOUT record"); 997 TheModule->setDataLayout(S); 998 break; 999 } 1000 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N] 1001 std::string S; 1002 if (ConvertToString(Record, 0, S)) 1003 return Error("Invalid MODULE_CODE_ASM record"); 1004 TheModule->setModuleInlineAsm(S); 1005 break; 1006 } 1007 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N] 1008 std::string S; 1009 if (ConvertToString(Record, 0, S)) 1010 return Error("Invalid MODULE_CODE_DEPLIB record"); 1011 TheModule->addLibrary(S); 1012 break; 1013 } 1014 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N] 1015 std::string S; 1016 if (ConvertToString(Record, 0, S)) 1017 return Error("Invalid MODULE_CODE_SECTIONNAME record"); 1018 SectionTable.push_back(S); 1019 break; 1020 } 1021 case bitc::MODULE_CODE_COLLECTORNAME: { // SECTIONNAME: [strchr x N] 1022 std::string S; 1023 if (ConvertToString(Record, 0, S)) 1024 return Error("Invalid MODULE_CODE_COLLECTORNAME record"); 1025 CollectorTable.push_back(S); 1026 break; 1027 } 1028 // GLOBALVAR: [pointer type, isconst, initid, 1029 // linkage, alignment, section, visibility, threadlocal] 1030 case bitc::MODULE_CODE_GLOBALVAR: { 1031 if (Record.size() < 6) 1032 return Error("Invalid MODULE_CODE_GLOBALVAR record"); 1033 const Type *Ty = getTypeByID(Record[0]); 1034 if (!isa<PointerType>(Ty)) 1035 return Error("Global not a pointer type!"); 1036 unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace(); 1037 Ty = cast<PointerType>(Ty)->getElementType(); 1038 1039 bool isConstant = Record[1]; 1040 GlobalValue::LinkageTypes Linkage = GetDecodedLinkage(Record[3]); 1041 unsigned Alignment = (1 << Record[4]) >> 1; 1042 std::string Section; 1043 if (Record[5]) { 1044 if (Record[5]-1 >= SectionTable.size()) 1045 return Error("Invalid section ID"); 1046 Section = SectionTable[Record[5]-1]; 1047 } 1048 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility; 1049 if (Record.size() > 6) 1050 Visibility = GetDecodedVisibility(Record[6]); 1051 bool isThreadLocal = false; 1052 if (Record.size() > 7) 1053 isThreadLocal = Record[7]; 1054 1055 GlobalVariable *NewGV = 1056 new GlobalVariable(Ty, isConstant, Linkage, 0, "", TheModule, 1057 isThreadLocal, AddressSpace); 1058 NewGV->setAlignment(Alignment); 1059 if (!Section.empty()) 1060 NewGV->setSection(Section); 1061 NewGV->setVisibility(Visibility); 1062 NewGV->setThreadLocal(isThreadLocal); 1063 1064 ValueList.push_back(NewGV); 1065 1066 // Remember which value to use for the global initializer. 1067 if (unsigned InitID = Record[2]) 1068 GlobalInits.push_back(std::make_pair(NewGV, InitID-1)); 1069 break; 1070 } 1071 // FUNCTION: [type, callingconv, isproto, linkage, paramattr, 1072 // alignment, section, visibility, collector] 1073 case bitc::MODULE_CODE_FUNCTION: { 1074 if (Record.size() < 8) 1075 return Error("Invalid MODULE_CODE_FUNCTION record"); 1076 const Type *Ty = getTypeByID(Record[0]); 1077 if (!isa<PointerType>(Ty)) 1078 return Error("Function not a pointer type!"); 1079 const FunctionType *FTy = 1080 dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType()); 1081 if (!FTy) 1082 return Error("Function not a pointer to function type!"); 1083 1084 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage, 1085 "", TheModule); 1086 1087 Func->setCallingConv(Record[1]); 1088 bool isProto = Record[2]; 1089 Func->setLinkage(GetDecodedLinkage(Record[3])); 1090 Func->setParamAttrs(getParamAttrs(Record[4])); 1091 1092 Func->setAlignment((1 << Record[5]) >> 1); 1093 if (Record[6]) { 1094 if (Record[6]-1 >= SectionTable.size()) 1095 return Error("Invalid section ID"); 1096 Func->setSection(SectionTable[Record[6]-1]); 1097 } 1098 Func->setVisibility(GetDecodedVisibility(Record[7])); 1099 if (Record.size() > 8 && Record[8]) { 1100 if (Record[8]-1 > CollectorTable.size()) 1101 return Error("Invalid collector ID"); 1102 Func->setCollector(CollectorTable[Record[8]-1].c_str()); 1103 } 1104 1105 ValueList.push_back(Func); 1106 1107 // If this is a function with a body, remember the prototype we are 1108 // creating now, so that we can match up the body with them later. 1109 if (!isProto) 1110 FunctionsWithBodies.push_back(Func); 1111 break; 1112 } 1113 // ALIAS: [alias type, aliasee val#, linkage] 1114 // ALIAS: [alias type, aliasee val#, linkage, visibility] 1115 case bitc::MODULE_CODE_ALIAS: { 1116 if (Record.size() < 3) 1117 return Error("Invalid MODULE_ALIAS record"); 1118 const Type *Ty = getTypeByID(Record[0]); 1119 if (!isa<PointerType>(Ty)) 1120 return Error("Function not a pointer type!"); 1121 1122 GlobalAlias *NewGA = new GlobalAlias(Ty, GetDecodedLinkage(Record[2]), 1123 "", 0, TheModule); 1124 // Old bitcode files didn't have visibility field. 1125 if (Record.size() > 3) 1126 NewGA->setVisibility(GetDecodedVisibility(Record[3])); 1127 ValueList.push_back(NewGA); 1128 AliasInits.push_back(std::make_pair(NewGA, Record[1])); 1129 break; 1130 } 1131 /// MODULE_CODE_PURGEVALS: [numvals] 1132 case bitc::MODULE_CODE_PURGEVALS: 1133 // Trim down the value list to the specified size. 1134 if (Record.size() < 1 || Record[0] > ValueList.size()) 1135 return Error("Invalid MODULE_PURGEVALS record"); 1136 ValueList.shrinkTo(Record[0]); 1137 break; 1138 } 1139 Record.clear(); 1140 } 1141 1142 return Error("Premature end of bitstream"); 1143} 1144 1145 1146bool BitcodeReader::ParseBitcode() { 1147 TheModule = 0; 1148 1149 if (Buffer->getBufferSize() & 3) 1150 return Error("Bitcode stream should be a multiple of 4 bytes in length"); 1151 1152 unsigned char *BufPtr = (unsigned char *)Buffer->getBufferStart(); 1153 Stream.init(BufPtr, BufPtr+Buffer->getBufferSize()); 1154 1155 // Sniff for the signature. 1156 if (Stream.Read(8) != 'B' || 1157 Stream.Read(8) != 'C' || 1158 Stream.Read(4) != 0x0 || 1159 Stream.Read(4) != 0xC || 1160 Stream.Read(4) != 0xE || 1161 Stream.Read(4) != 0xD) 1162 return Error("Invalid bitcode signature"); 1163 1164 // We expect a number of well-defined blocks, though we don't necessarily 1165 // need to understand them all. 1166 while (!Stream.AtEndOfStream()) { 1167 unsigned Code = Stream.ReadCode(); 1168 1169 if (Code != bitc::ENTER_SUBBLOCK) 1170 return Error("Invalid record at top-level"); 1171 1172 unsigned BlockID = Stream.ReadSubBlockID(); 1173 1174 // We only know the MODULE subblock ID. 1175 switch (BlockID) { 1176 case bitc::BLOCKINFO_BLOCK_ID: 1177 if (Stream.ReadBlockInfoBlock()) 1178 return Error("Malformed BlockInfoBlock"); 1179 break; 1180 case bitc::MODULE_BLOCK_ID: 1181 if (ParseModule(Buffer->getBufferIdentifier())) 1182 return true; 1183 break; 1184 default: 1185 if (Stream.SkipBlock()) 1186 return Error("Malformed block record"); 1187 break; 1188 } 1189 } 1190 1191 return false; 1192} 1193 1194 1195/// ParseFunctionBody - Lazily parse the specified function body block. 1196bool BitcodeReader::ParseFunctionBody(Function *F) { 1197 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID)) 1198 return Error("Malformed block record"); 1199 1200 unsigned ModuleValueListSize = ValueList.size(); 1201 1202 // Add all the function arguments to the value table. 1203 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I) 1204 ValueList.push_back(I); 1205 1206 unsigned NextValueNo = ValueList.size(); 1207 BasicBlock *CurBB = 0; 1208 unsigned CurBBNo = 0; 1209 1210 // Read all the records. 1211 SmallVector<uint64_t, 64> Record; 1212 while (1) { 1213 unsigned Code = Stream.ReadCode(); 1214 if (Code == bitc::END_BLOCK) { 1215 if (Stream.ReadBlockEnd()) 1216 return Error("Error at end of function block"); 1217 break; 1218 } 1219 1220 if (Code == bitc::ENTER_SUBBLOCK) { 1221 switch (Stream.ReadSubBlockID()) { 1222 default: // Skip unknown content. 1223 if (Stream.SkipBlock()) 1224 return Error("Malformed block record"); 1225 break; 1226 case bitc::CONSTANTS_BLOCK_ID: 1227 if (ParseConstants()) return true; 1228 NextValueNo = ValueList.size(); 1229 break; 1230 case bitc::VALUE_SYMTAB_BLOCK_ID: 1231 if (ParseValueSymbolTable()) return true; 1232 break; 1233 } 1234 continue; 1235 } 1236 1237 if (Code == bitc::DEFINE_ABBREV) { 1238 Stream.ReadAbbrevRecord(); 1239 continue; 1240 } 1241 1242 // Read a record. 1243 Record.clear(); 1244 Instruction *I = 0; 1245 switch (Stream.ReadRecord(Code, Record)) { 1246 default: // Default behavior: reject 1247 return Error("Unknown instruction"); 1248 case bitc::FUNC_CODE_DECLAREBLOCKS: // DECLAREBLOCKS: [nblocks] 1249 if (Record.size() < 1 || Record[0] == 0) 1250 return Error("Invalid DECLAREBLOCKS record"); 1251 // Create all the basic blocks for the function. 1252 FunctionBBs.resize(Record[0]); 1253 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i) 1254 FunctionBBs[i] = BasicBlock::Create("", F); 1255 CurBB = FunctionBBs[0]; 1256 continue; 1257 1258 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode] 1259 unsigned OpNum = 0; 1260 Value *LHS, *RHS; 1261 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) || 1262 getValue(Record, OpNum, LHS->getType(), RHS) || 1263 OpNum+1 != Record.size()) 1264 return Error("Invalid BINOP record"); 1265 1266 int Opc = GetDecodedBinaryOpcode(Record[OpNum], LHS->getType()); 1267 if (Opc == -1) return Error("Invalid BINOP record"); 1268 I = BinaryOperator::create((Instruction::BinaryOps)Opc, LHS, RHS); 1269 break; 1270 } 1271 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc] 1272 unsigned OpNum = 0; 1273 Value *Op; 1274 if (getValueTypePair(Record, OpNum, NextValueNo, Op) || 1275 OpNum+2 != Record.size()) 1276 return Error("Invalid CAST record"); 1277 1278 const Type *ResTy = getTypeByID(Record[OpNum]); 1279 int Opc = GetDecodedCastOpcode(Record[OpNum+1]); 1280 if (Opc == -1 || ResTy == 0) 1281 return Error("Invalid CAST record"); 1282 I = CastInst::create((Instruction::CastOps)Opc, Op, ResTy); 1283 break; 1284 } 1285 case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands] 1286 unsigned OpNum = 0; 1287 Value *BasePtr; 1288 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr)) 1289 return Error("Invalid GEP record"); 1290 1291 SmallVector<Value*, 16> GEPIdx; 1292 while (OpNum != Record.size()) { 1293 Value *Op; 1294 if (getValueTypePair(Record, OpNum, NextValueNo, Op)) 1295 return Error("Invalid GEP record"); 1296 GEPIdx.push_back(Op); 1297 } 1298 1299 I = GetElementPtrInst::Create(BasePtr, GEPIdx.begin(), GEPIdx.end()); 1300 break; 1301 } 1302 1303 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval] 1304 unsigned OpNum = 0; 1305 Value *TrueVal, *FalseVal, *Cond; 1306 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) || 1307 getValue(Record, OpNum, TrueVal->getType(), FalseVal) || 1308 getValue(Record, OpNum, Type::Int1Ty, Cond)) 1309 return Error("Invalid SELECT record"); 1310 1311 I = SelectInst::Create(Cond, TrueVal, FalseVal); 1312 break; 1313 } 1314 1315 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval] 1316 unsigned OpNum = 0; 1317 Value *Vec, *Idx; 1318 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) || 1319 getValue(Record, OpNum, Type::Int32Ty, Idx)) 1320 return Error("Invalid EXTRACTELT record"); 1321 I = new ExtractElementInst(Vec, Idx); 1322 break; 1323 } 1324 1325 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval] 1326 unsigned OpNum = 0; 1327 Value *Vec, *Elt, *Idx; 1328 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) || 1329 getValue(Record, OpNum, 1330 cast<VectorType>(Vec->getType())->getElementType(), Elt) || 1331 getValue(Record, OpNum, Type::Int32Ty, Idx)) 1332 return Error("Invalid INSERTELT record"); 1333 I = InsertElementInst::Create(Vec, Elt, Idx); 1334 break; 1335 } 1336 1337 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval] 1338 unsigned OpNum = 0; 1339 Value *Vec1, *Vec2, *Mask; 1340 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) || 1341 getValue(Record, OpNum, Vec1->getType(), Vec2)) 1342 return Error("Invalid SHUFFLEVEC record"); 1343 1344 const Type *MaskTy = 1345 VectorType::get(Type::Int32Ty, 1346 cast<VectorType>(Vec1->getType())->getNumElements()); 1347 1348 if (getValue(Record, OpNum, MaskTy, Mask)) 1349 return Error("Invalid SHUFFLEVEC record"); 1350 I = new ShuffleVectorInst(Vec1, Vec2, Mask); 1351 break; 1352 } 1353 1354 case bitc::FUNC_CODE_INST_CMP: { // CMP: [opty, opval, opval, pred] 1355 unsigned OpNum = 0; 1356 Value *LHS, *RHS; 1357 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) || 1358 getValue(Record, OpNum, LHS->getType(), RHS) || 1359 OpNum+1 != Record.size()) 1360 return Error("Invalid CMP record"); 1361 1362 if (LHS->getType()->isInteger()) 1363 I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS); 1364 else if (LHS->getType()->isFloatingPoint()) 1365 I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS); 1366 else if (LHS->getType()->isFPOrFPVector()) 1367 I = new VFCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS); 1368 else 1369 I = new VICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS); 1370 break; 1371 } 1372 case bitc::FUNC_CODE_INST_GETRESULT: { // GETRESULT: [ty, val, n] 1373 if (Record.size() != 2) 1374 return Error("Invalid GETRESULT record"); 1375 unsigned OpNum = 0; 1376 Value *Op; 1377 getValueTypePair(Record, OpNum, NextValueNo, Op); 1378 unsigned Index = Record[1]; 1379 I = new GetResultInst(Op, Index); 1380 break; 1381 } 1382 1383 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>] 1384 { 1385 unsigned Size = Record.size(); 1386 if (Size == 0) { 1387 I = ReturnInst::Create(); 1388 break; 1389 } else { 1390 unsigned OpNum = 0; 1391 SmallVector<Value *,4> Vs; 1392 do { 1393 Value *Op = NULL; 1394 if (getValueTypePair(Record, OpNum, NextValueNo, Op)) 1395 return Error("Invalid RET record"); 1396 Vs.push_back(Op); 1397 } while(OpNum != Record.size()); 1398 1399 // SmallVector Vs has at least one element. 1400 I = ReturnInst::Create(&Vs[0], Vs.size()); 1401 break; 1402 } 1403 } 1404 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#] 1405 if (Record.size() != 1 && Record.size() != 3) 1406 return Error("Invalid BR record"); 1407 BasicBlock *TrueDest = getBasicBlock(Record[0]); 1408 if (TrueDest == 0) 1409 return Error("Invalid BR record"); 1410 1411 if (Record.size() == 1) 1412 I = BranchInst::Create(TrueDest); 1413 else { 1414 BasicBlock *FalseDest = getBasicBlock(Record[1]); 1415 Value *Cond = getFnValueByID(Record[2], Type::Int1Ty); 1416 if (FalseDest == 0 || Cond == 0) 1417 return Error("Invalid BR record"); 1418 I = BranchInst::Create(TrueDest, FalseDest, Cond); 1419 } 1420 break; 1421 } 1422 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, opval, n, n x ops] 1423 if (Record.size() < 3 || (Record.size() & 1) == 0) 1424 return Error("Invalid SWITCH record"); 1425 const Type *OpTy = getTypeByID(Record[0]); 1426 Value *Cond = getFnValueByID(Record[1], OpTy); 1427 BasicBlock *Default = getBasicBlock(Record[2]); 1428 if (OpTy == 0 || Cond == 0 || Default == 0) 1429 return Error("Invalid SWITCH record"); 1430 unsigned NumCases = (Record.size()-3)/2; 1431 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases); 1432 for (unsigned i = 0, e = NumCases; i != e; ++i) { 1433 ConstantInt *CaseVal = 1434 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy)); 1435 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]); 1436 if (CaseVal == 0 || DestBB == 0) { 1437 delete SI; 1438 return Error("Invalid SWITCH record!"); 1439 } 1440 SI->addCase(CaseVal, DestBB); 1441 } 1442 I = SI; 1443 break; 1444 } 1445 1446 case bitc::FUNC_CODE_INST_INVOKE: { 1447 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...] 1448 if (Record.size() < 4) return Error("Invalid INVOKE record"); 1449 PAListPtr PAL = getParamAttrs(Record[0]); 1450 unsigned CCInfo = Record[1]; 1451 BasicBlock *NormalBB = getBasicBlock(Record[2]); 1452 BasicBlock *UnwindBB = getBasicBlock(Record[3]); 1453 1454 unsigned OpNum = 4; 1455 Value *Callee; 1456 if (getValueTypePair(Record, OpNum, NextValueNo, Callee)) 1457 return Error("Invalid INVOKE record"); 1458 1459 const PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType()); 1460 const FunctionType *FTy = !CalleeTy ? 0 : 1461 dyn_cast<FunctionType>(CalleeTy->getElementType()); 1462 1463 // Check that the right number of fixed parameters are here. 1464 if (FTy == 0 || NormalBB == 0 || UnwindBB == 0 || 1465 Record.size() < OpNum+FTy->getNumParams()) 1466 return Error("Invalid INVOKE record"); 1467 1468 SmallVector<Value*, 16> Ops; 1469 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) { 1470 Ops.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i))); 1471 if (Ops.back() == 0) return Error("Invalid INVOKE record"); 1472 } 1473 1474 if (!FTy->isVarArg()) { 1475 if (Record.size() != OpNum) 1476 return Error("Invalid INVOKE record"); 1477 } else { 1478 // Read type/value pairs for varargs params. 1479 while (OpNum != Record.size()) { 1480 Value *Op; 1481 if (getValueTypePair(Record, OpNum, NextValueNo, Op)) 1482 return Error("Invalid INVOKE record"); 1483 Ops.push_back(Op); 1484 } 1485 } 1486 1487 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops.begin(), Ops.end()); 1488 cast<InvokeInst>(I)->setCallingConv(CCInfo); 1489 cast<InvokeInst>(I)->setParamAttrs(PAL); 1490 break; 1491 } 1492 case bitc::FUNC_CODE_INST_UNWIND: // UNWIND 1493 I = new UnwindInst(); 1494 break; 1495 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE 1496 I = new UnreachableInst(); 1497 break; 1498 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...] 1499 if (Record.size() < 1 || ((Record.size()-1)&1)) 1500 return Error("Invalid PHI record"); 1501 const Type *Ty = getTypeByID(Record[0]); 1502 if (!Ty) return Error("Invalid PHI record"); 1503 1504 PHINode *PN = PHINode::Create(Ty); 1505 PN->reserveOperandSpace((Record.size()-1)/2); 1506 1507 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) { 1508 Value *V = getFnValueByID(Record[1+i], Ty); 1509 BasicBlock *BB = getBasicBlock(Record[2+i]); 1510 if (!V || !BB) return Error("Invalid PHI record"); 1511 PN->addIncoming(V, BB); 1512 } 1513 I = PN; 1514 break; 1515 } 1516 1517 case bitc::FUNC_CODE_INST_MALLOC: { // MALLOC: [instty, op, align] 1518 if (Record.size() < 3) 1519 return Error("Invalid MALLOC record"); 1520 const PointerType *Ty = 1521 dyn_cast_or_null<PointerType>(getTypeByID(Record[0])); 1522 Value *Size = getFnValueByID(Record[1], Type::Int32Ty); 1523 unsigned Align = Record[2]; 1524 if (!Ty || !Size) return Error("Invalid MALLOC record"); 1525 I = new MallocInst(Ty->getElementType(), Size, (1 << Align) >> 1); 1526 break; 1527 } 1528 case bitc::FUNC_CODE_INST_FREE: { // FREE: [op, opty] 1529 unsigned OpNum = 0; 1530 Value *Op; 1531 if (getValueTypePair(Record, OpNum, NextValueNo, Op) || 1532 OpNum != Record.size()) 1533 return Error("Invalid FREE record"); 1534 I = new FreeInst(Op); 1535 break; 1536 } 1537 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, op, align] 1538 if (Record.size() < 3) 1539 return Error("Invalid ALLOCA record"); 1540 const PointerType *Ty = 1541 dyn_cast_or_null<PointerType>(getTypeByID(Record[0])); 1542 Value *Size = getFnValueByID(Record[1], Type::Int32Ty); 1543 unsigned Align = Record[2]; 1544 if (!Ty || !Size) return Error("Invalid ALLOCA record"); 1545 I = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1); 1546 break; 1547 } 1548 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol] 1549 unsigned OpNum = 0; 1550 Value *Op; 1551 if (getValueTypePair(Record, OpNum, NextValueNo, Op) || 1552 OpNum+2 != Record.size()) 1553 return Error("Invalid LOAD record"); 1554 1555 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1); 1556 break; 1557 } 1558 case bitc::FUNC_CODE_INST_STORE2: { // STORE2:[ptrty, ptr, val, align, vol] 1559 unsigned OpNum = 0; 1560 Value *Val, *Ptr; 1561 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) || 1562 getValue(Record, OpNum, 1563 cast<PointerType>(Ptr->getType())->getElementType(), Val) || 1564 OpNum+2 != Record.size()) 1565 return Error("Invalid STORE record"); 1566 1567 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1); 1568 break; 1569 } 1570 case bitc::FUNC_CODE_INST_STORE: { // STORE:[val, valty, ptr, align, vol] 1571 // FIXME: Legacy form of store instruction. Should be removed in LLVM 3.0. 1572 unsigned OpNum = 0; 1573 Value *Val, *Ptr; 1574 if (getValueTypePair(Record, OpNum, NextValueNo, Val) || 1575 getValue(Record, OpNum, PointerType::getUnqual(Val->getType()), Ptr)|| 1576 OpNum+2 != Record.size()) 1577 return Error("Invalid STORE record"); 1578 1579 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1); 1580 break; 1581 } 1582 case bitc::FUNC_CODE_INST_CALL: { 1583 // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...] 1584 if (Record.size() < 3) 1585 return Error("Invalid CALL record"); 1586 1587 PAListPtr PAL = getParamAttrs(Record[0]); 1588 unsigned CCInfo = Record[1]; 1589 1590 unsigned OpNum = 2; 1591 Value *Callee; 1592 if (getValueTypePair(Record, OpNum, NextValueNo, Callee)) 1593 return Error("Invalid CALL record"); 1594 1595 const PointerType *OpTy = dyn_cast<PointerType>(Callee->getType()); 1596 const FunctionType *FTy = 0; 1597 if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType()); 1598 if (!FTy || Record.size() < FTy->getNumParams()+OpNum) 1599 return Error("Invalid CALL record"); 1600 1601 SmallVector<Value*, 16> Args; 1602 // Read the fixed params. 1603 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) { 1604 if (FTy->getParamType(i)->getTypeID()==Type::LabelTyID) 1605 Args.push_back(getBasicBlock(Record[OpNum])); 1606 else 1607 Args.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i))); 1608 if (Args.back() == 0) return Error("Invalid CALL record"); 1609 } 1610 1611 // Read type/value pairs for varargs params. 1612 if (!FTy->isVarArg()) { 1613 if (OpNum != Record.size()) 1614 return Error("Invalid CALL record"); 1615 } else { 1616 while (OpNum != Record.size()) { 1617 Value *Op; 1618 if (getValueTypePair(Record, OpNum, NextValueNo, Op)) 1619 return Error("Invalid CALL record"); 1620 Args.push_back(Op); 1621 } 1622 } 1623 1624 I = CallInst::Create(Callee, Args.begin(), Args.end()); 1625 cast<CallInst>(I)->setCallingConv(CCInfo>>1); 1626 cast<CallInst>(I)->setTailCall(CCInfo & 1); 1627 cast<CallInst>(I)->setParamAttrs(PAL); 1628 break; 1629 } 1630 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty] 1631 if (Record.size() < 3) 1632 return Error("Invalid VAARG record"); 1633 const Type *OpTy = getTypeByID(Record[0]); 1634 Value *Op = getFnValueByID(Record[1], OpTy); 1635 const Type *ResTy = getTypeByID(Record[2]); 1636 if (!OpTy || !Op || !ResTy) 1637 return Error("Invalid VAARG record"); 1638 I = new VAArgInst(Op, ResTy); 1639 break; 1640 } 1641 } 1642 1643 // Add instruction to end of current BB. If there is no current BB, reject 1644 // this file. 1645 if (CurBB == 0) { 1646 delete I; 1647 return Error("Invalid instruction with no BB"); 1648 } 1649 CurBB->getInstList().push_back(I); 1650 1651 // If this was a terminator instruction, move to the next block. 1652 if (isa<TerminatorInst>(I)) { 1653 ++CurBBNo; 1654 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : 0; 1655 } 1656 1657 // Non-void values get registered in the value table for future use. 1658 if (I && I->getType() != Type::VoidTy) 1659 ValueList.AssignValue(I, NextValueNo++); 1660 } 1661 1662 // Check the function list for unresolved values. 1663 if (Argument *A = dyn_cast<Argument>(ValueList.back())) { 1664 if (A->getParent() == 0) { 1665 // We found at least one unresolved value. Nuke them all to avoid leaks. 1666 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){ 1667 if ((A = dyn_cast<Argument>(ValueList.back())) && A->getParent() == 0) { 1668 A->replaceAllUsesWith(UndefValue::get(A->getType())); 1669 delete A; 1670 } 1671 } 1672 return Error("Never resolved value found in function!"); 1673 } 1674 } 1675 1676 // Trim the value list down to the size it was before we parsed this function. 1677 ValueList.shrinkTo(ModuleValueListSize); 1678 std::vector<BasicBlock*>().swap(FunctionBBs); 1679 1680 return false; 1681} 1682 1683//===----------------------------------------------------------------------===// 1684// ModuleProvider implementation 1685//===----------------------------------------------------------------------===// 1686 1687 1688bool BitcodeReader::materializeFunction(Function *F, std::string *ErrInfo) { 1689 // If it already is material, ignore the request. 1690 if (!F->hasNotBeenReadFromBitcode()) return false; 1691 1692 DenseMap<Function*, std::pair<uint64_t, unsigned> >::iterator DFII = 1693 DeferredFunctionInfo.find(F); 1694 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!"); 1695 1696 // Move the bit stream to the saved position of the deferred function body and 1697 // restore the real linkage type for the function. 1698 Stream.JumpToBit(DFII->second.first); 1699 F->setLinkage((GlobalValue::LinkageTypes)DFII->second.second); 1700 1701 if (ParseFunctionBody(F)) { 1702 if (ErrInfo) *ErrInfo = ErrorString; 1703 return true; 1704 } 1705 1706 // Upgrade any old intrinsic calls in the function. 1707 for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(), 1708 E = UpgradedIntrinsics.end(); I != E; ++I) { 1709 if (I->first != I->second) { 1710 for (Value::use_iterator UI = I->first->use_begin(), 1711 UE = I->first->use_end(); UI != UE; ) { 1712 if (CallInst* CI = dyn_cast<CallInst>(*UI++)) 1713 UpgradeIntrinsicCall(CI, I->second); 1714 } 1715 } 1716 } 1717 1718 return false; 1719} 1720 1721void BitcodeReader::dematerializeFunction(Function *F) { 1722 // If this function isn't materialized, or if it is a proto, this is a noop. 1723 if (F->hasNotBeenReadFromBitcode() || F->isDeclaration()) 1724 return; 1725 1726 assert(DeferredFunctionInfo.count(F) && "No info to read function later?"); 1727 1728 // Just forget the function body, we can remat it later. 1729 F->deleteBody(); 1730 F->setLinkage(GlobalValue::GhostLinkage); 1731} 1732 1733 1734Module *BitcodeReader::materializeModule(std::string *ErrInfo) { 1735 for (DenseMap<Function*, std::pair<uint64_t, unsigned> >::iterator I = 1736 DeferredFunctionInfo.begin(), E = DeferredFunctionInfo.end(); I != E; 1737 ++I) { 1738 Function *F = I->first; 1739 if (F->hasNotBeenReadFromBitcode() && 1740 materializeFunction(F, ErrInfo)) 1741 return 0; 1742 } 1743 1744 // Upgrade any intrinsic calls that slipped through (should not happen!) and 1745 // delete the old functions to clean up. We can't do this unless the entire 1746 // module is materialized because there could always be another function body 1747 // with calls to the old function. 1748 for (std::vector<std::pair<Function*, Function*> >::iterator I = 1749 UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) { 1750 if (I->first != I->second) { 1751 for (Value::use_iterator UI = I->first->use_begin(), 1752 UE = I->first->use_end(); UI != UE; ) { 1753 if (CallInst* CI = dyn_cast<CallInst>(*UI++)) 1754 UpgradeIntrinsicCall(CI, I->second); 1755 } 1756 ValueList.replaceUsesOfWith(I->first, I->second); 1757 I->first->eraseFromParent(); 1758 } 1759 } 1760 std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics); 1761 1762 return TheModule; 1763} 1764 1765 1766/// This method is provided by the parent ModuleProvde class and overriden 1767/// here. It simply releases the module from its provided and frees up our 1768/// state. 1769/// @brief Release our hold on the generated module 1770Module *BitcodeReader::releaseModule(std::string *ErrInfo) { 1771 // Since we're losing control of this Module, we must hand it back complete 1772 Module *M = ModuleProvider::releaseModule(ErrInfo); 1773 FreeState(); 1774 return M; 1775} 1776 1777 1778//===----------------------------------------------------------------------===// 1779// External interface 1780//===----------------------------------------------------------------------===// 1781 1782/// getBitcodeModuleProvider - lazy function-at-a-time loading from a file. 1783/// 1784ModuleProvider *llvm::getBitcodeModuleProvider(MemoryBuffer *Buffer, 1785 std::string *ErrMsg) { 1786 BitcodeReader *R = new BitcodeReader(Buffer); 1787 if (R->ParseBitcode()) { 1788 if (ErrMsg) 1789 *ErrMsg = R->getErrorString(); 1790 1791 // Don't let the BitcodeReader dtor delete 'Buffer'. 1792 R->releaseMemoryBuffer(); 1793 delete R; 1794 return 0; 1795 } 1796 return R; 1797} 1798 1799/// ParseBitcodeFile - Read the specified bitcode file, returning the module. 1800/// If an error occurs, return null and fill in *ErrMsg if non-null. 1801Module *llvm::ParseBitcodeFile(MemoryBuffer *Buffer, std::string *ErrMsg){ 1802 BitcodeReader *R; 1803 R = static_cast<BitcodeReader*>(getBitcodeModuleProvider(Buffer, ErrMsg)); 1804 if (!R) return 0; 1805 1806 // Read in the entire module. 1807 Module *M = R->materializeModule(ErrMsg); 1808 1809 // Don't let the BitcodeReader dtor delete 'Buffer', regardless of whether 1810 // there was an error. 1811 R->releaseMemoryBuffer(); 1812 1813 // If there was no error, tell ModuleProvider not to delete it when its dtor 1814 // is run. 1815 if (M) 1816 M = R->releaseModule(ErrMsg); 1817 1818 delete R; 1819 return M; 1820} 1821