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