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