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