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