BitcodeReader.cpp revision 734dde8e051d34ac34cc58eb31cf2e6fa3ac3f37
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/IntrinsicInst.h" 20#include "llvm/Module.h" 21#include "llvm/Operator.h" 22#include "llvm/AutoUpgrade.h" 23#include "llvm/ADT/SmallString.h" 24#include "llvm/ADT/SmallVector.h" 25#include "llvm/Support/DataStream.h" 26#include "llvm/Support/MathExtras.h" 27#include "llvm/Support/MemoryBuffer.h" 28#include "llvm/OperandTraits.h" 29using namespace llvm; 30 31enum { 32 SWITCH_INST_MAGIC = 0x4B5 // May 2012 => 1205 => Hex 33}; 34 35void BitcodeReader::materializeForwardReferencedFunctions() { 36 while (!BlockAddrFwdRefs.empty()) { 37 Function *F = BlockAddrFwdRefs.begin()->first; 38 F->Materialize(); 39 } 40} 41 42void BitcodeReader::FreeState() { 43 if (BufferOwned) 44 delete Buffer; 45 Buffer = 0; 46 std::vector<Type*>().swap(TypeList); 47 ValueList.clear(); 48 MDValueList.clear(); 49 50 std::vector<AttrListPtr>().swap(MAttributes); 51 std::vector<BasicBlock*>().swap(FunctionBBs); 52 std::vector<Function*>().swap(FunctionsWithBodies); 53 DeferredFunctionInfo.clear(); 54 MDKindMap.clear(); 55} 56 57//===----------------------------------------------------------------------===// 58// Helper functions to implement forward reference resolution, etc. 59//===----------------------------------------------------------------------===// 60 61/// ConvertToString - Convert a string from a record into an std::string, return 62/// true on failure. 63template<typename StrTy> 64static bool ConvertToString(SmallVector<uint64_t, 64> &Record, unsigned Idx, 65 StrTy &Result) { 66 if (Idx > Record.size()) 67 return true; 68 69 for (unsigned i = Idx, e = Record.size(); i != e; ++i) 70 Result += (char)Record[i]; 71 return false; 72} 73 74static GlobalValue::LinkageTypes GetDecodedLinkage(unsigned Val) { 75 switch (Val) { 76 default: // Map unknown/new linkages to external 77 case 0: return GlobalValue::ExternalLinkage; 78 case 1: return GlobalValue::WeakAnyLinkage; 79 case 2: return GlobalValue::AppendingLinkage; 80 case 3: return GlobalValue::InternalLinkage; 81 case 4: return GlobalValue::LinkOnceAnyLinkage; 82 case 5: return GlobalValue::DLLImportLinkage; 83 case 6: return GlobalValue::DLLExportLinkage; 84 case 7: return GlobalValue::ExternalWeakLinkage; 85 case 8: return GlobalValue::CommonLinkage; 86 case 9: return GlobalValue::PrivateLinkage; 87 case 10: return GlobalValue::WeakODRLinkage; 88 case 11: return GlobalValue::LinkOnceODRLinkage; 89 case 12: return GlobalValue::AvailableExternallyLinkage; 90 case 13: return GlobalValue::LinkerPrivateLinkage; 91 case 14: return GlobalValue::LinkerPrivateWeakLinkage; 92 case 15: return GlobalValue::LinkerPrivateWeakDefAutoLinkage; 93 } 94} 95 96static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned Val) { 97 switch (Val) { 98 default: // Map unknown visibilities to default. 99 case 0: return GlobalValue::DefaultVisibility; 100 case 1: return GlobalValue::HiddenVisibility; 101 case 2: return GlobalValue::ProtectedVisibility; 102 } 103} 104 105static int GetDecodedCastOpcode(unsigned Val) { 106 switch (Val) { 107 default: return -1; 108 case bitc::CAST_TRUNC : return Instruction::Trunc; 109 case bitc::CAST_ZEXT : return Instruction::ZExt; 110 case bitc::CAST_SEXT : return Instruction::SExt; 111 case bitc::CAST_FPTOUI : return Instruction::FPToUI; 112 case bitc::CAST_FPTOSI : return Instruction::FPToSI; 113 case bitc::CAST_UITOFP : return Instruction::UIToFP; 114 case bitc::CAST_SITOFP : return Instruction::SIToFP; 115 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc; 116 case bitc::CAST_FPEXT : return Instruction::FPExt; 117 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt; 118 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr; 119 case bitc::CAST_BITCAST : return Instruction::BitCast; 120 } 121} 122static int GetDecodedBinaryOpcode(unsigned Val, Type *Ty) { 123 switch (Val) { 124 default: return -1; 125 case bitc::BINOP_ADD: 126 return Ty->isFPOrFPVectorTy() ? Instruction::FAdd : Instruction::Add; 127 case bitc::BINOP_SUB: 128 return Ty->isFPOrFPVectorTy() ? Instruction::FSub : Instruction::Sub; 129 case bitc::BINOP_MUL: 130 return Ty->isFPOrFPVectorTy() ? Instruction::FMul : Instruction::Mul; 131 case bitc::BINOP_UDIV: return Instruction::UDiv; 132 case bitc::BINOP_SDIV: 133 return Ty->isFPOrFPVectorTy() ? Instruction::FDiv : Instruction::SDiv; 134 case bitc::BINOP_UREM: return Instruction::URem; 135 case bitc::BINOP_SREM: 136 return Ty->isFPOrFPVectorTy() ? Instruction::FRem : Instruction::SRem; 137 case bitc::BINOP_SHL: return Instruction::Shl; 138 case bitc::BINOP_LSHR: return Instruction::LShr; 139 case bitc::BINOP_ASHR: return Instruction::AShr; 140 case bitc::BINOP_AND: return Instruction::And; 141 case bitc::BINOP_OR: return Instruction::Or; 142 case bitc::BINOP_XOR: return Instruction::Xor; 143 } 144} 145 146static AtomicRMWInst::BinOp GetDecodedRMWOperation(unsigned Val) { 147 switch (Val) { 148 default: return AtomicRMWInst::BAD_BINOP; 149 case bitc::RMW_XCHG: return AtomicRMWInst::Xchg; 150 case bitc::RMW_ADD: return AtomicRMWInst::Add; 151 case bitc::RMW_SUB: return AtomicRMWInst::Sub; 152 case bitc::RMW_AND: return AtomicRMWInst::And; 153 case bitc::RMW_NAND: return AtomicRMWInst::Nand; 154 case bitc::RMW_OR: return AtomicRMWInst::Or; 155 case bitc::RMW_XOR: return AtomicRMWInst::Xor; 156 case bitc::RMW_MAX: return AtomicRMWInst::Max; 157 case bitc::RMW_MIN: return AtomicRMWInst::Min; 158 case bitc::RMW_UMAX: return AtomicRMWInst::UMax; 159 case bitc::RMW_UMIN: return AtomicRMWInst::UMin; 160 } 161} 162 163static AtomicOrdering GetDecodedOrdering(unsigned Val) { 164 switch (Val) { 165 case bitc::ORDERING_NOTATOMIC: return NotAtomic; 166 case bitc::ORDERING_UNORDERED: return Unordered; 167 case bitc::ORDERING_MONOTONIC: return Monotonic; 168 case bitc::ORDERING_ACQUIRE: return Acquire; 169 case bitc::ORDERING_RELEASE: return Release; 170 case bitc::ORDERING_ACQREL: return AcquireRelease; 171 default: // Map unknown orderings to sequentially-consistent. 172 case bitc::ORDERING_SEQCST: return SequentiallyConsistent; 173 } 174} 175 176static SynchronizationScope GetDecodedSynchScope(unsigned Val) { 177 switch (Val) { 178 case bitc::SYNCHSCOPE_SINGLETHREAD: return SingleThread; 179 default: // Map unknown scopes to cross-thread. 180 case bitc::SYNCHSCOPE_CROSSTHREAD: return CrossThread; 181 } 182} 183 184namespace llvm { 185namespace { 186 /// @brief A class for maintaining the slot number definition 187 /// as a placeholder for the actual definition for forward constants defs. 188 class ConstantPlaceHolder : public ConstantExpr { 189 void operator=(const ConstantPlaceHolder &); // DO NOT IMPLEMENT 190 public: 191 // allocate space for exactly one operand 192 void *operator new(size_t s) { 193 return User::operator new(s, 1); 194 } 195 explicit ConstantPlaceHolder(Type *Ty, LLVMContext& Context) 196 : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) { 197 Op<0>() = UndefValue::get(Type::getInt32Ty(Context)); 198 } 199 200 /// @brief Methods to support type inquiry through isa, cast, and dyn_cast. 201 //static inline bool classof(const ConstantPlaceHolder *) { return true; } 202 static bool classof(const Value *V) { 203 return isa<ConstantExpr>(V) && 204 cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1; 205 } 206 207 208 /// Provide fast operand accessors 209 //DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value); 210 }; 211} 212 213// FIXME: can we inherit this from ConstantExpr? 214template <> 215struct OperandTraits<ConstantPlaceHolder> : 216 public FixedNumOperandTraits<ConstantPlaceHolder, 1> { 217}; 218} 219 220 221void BitcodeReaderValueList::AssignValue(Value *V, unsigned Idx) { 222 if (Idx == size()) { 223 push_back(V); 224 return; 225 } 226 227 if (Idx >= size()) 228 resize(Idx+1); 229 230 WeakVH &OldV = ValuePtrs[Idx]; 231 if (OldV == 0) { 232 OldV = V; 233 return; 234 } 235 236 // Handle constants and non-constants (e.g. instrs) differently for 237 // efficiency. 238 if (Constant *PHC = dyn_cast<Constant>(&*OldV)) { 239 ResolveConstants.push_back(std::make_pair(PHC, Idx)); 240 OldV = V; 241 } else { 242 // If there was a forward reference to this value, replace it. 243 Value *PrevVal = OldV; 244 OldV->replaceAllUsesWith(V); 245 delete PrevVal; 246 } 247} 248 249 250Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx, 251 Type *Ty) { 252 if (Idx >= size()) 253 resize(Idx + 1); 254 255 if (Value *V = ValuePtrs[Idx]) { 256 assert(Ty == V->getType() && "Type mismatch in constant table!"); 257 return cast<Constant>(V); 258 } 259 260 // Create and return a placeholder, which will later be RAUW'd. 261 Constant *C = new ConstantPlaceHolder(Ty, Context); 262 ValuePtrs[Idx] = C; 263 return C; 264} 265 266Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, Type *Ty) { 267 if (Idx >= size()) 268 resize(Idx + 1); 269 270 if (Value *V = ValuePtrs[Idx]) { 271 assert((Ty == 0 || Ty == V->getType()) && "Type mismatch in value table!"); 272 return V; 273 } 274 275 // No type specified, must be invalid reference. 276 if (Ty == 0) return 0; 277 278 // Create and return a placeholder, which will later be RAUW'd. 279 Value *V = new Argument(Ty); 280 ValuePtrs[Idx] = V; 281 return V; 282} 283 284/// ResolveConstantForwardRefs - Once all constants are read, this method bulk 285/// resolves any forward references. The idea behind this is that we sometimes 286/// get constants (such as large arrays) which reference *many* forward ref 287/// constants. Replacing each of these causes a lot of thrashing when 288/// building/reuniquing the constant. Instead of doing this, we look at all the 289/// uses and rewrite all the place holders at once for any constant that uses 290/// a placeholder. 291void BitcodeReaderValueList::ResolveConstantForwardRefs() { 292 // Sort the values by-pointer so that they are efficient to look up with a 293 // binary search. 294 std::sort(ResolveConstants.begin(), ResolveConstants.end()); 295 296 SmallVector<Constant*, 64> NewOps; 297 298 while (!ResolveConstants.empty()) { 299 Value *RealVal = operator[](ResolveConstants.back().second); 300 Constant *Placeholder = ResolveConstants.back().first; 301 ResolveConstants.pop_back(); 302 303 // Loop over all users of the placeholder, updating them to reference the 304 // new value. If they reference more than one placeholder, update them all 305 // at once. 306 while (!Placeholder->use_empty()) { 307 Value::use_iterator UI = Placeholder->use_begin(); 308 User *U = *UI; 309 310 // If the using object isn't uniqued, just update the operands. This 311 // handles instructions and initializers for global variables. 312 if (!isa<Constant>(U) || isa<GlobalValue>(U)) { 313 UI.getUse().set(RealVal); 314 continue; 315 } 316 317 // Otherwise, we have a constant that uses the placeholder. Replace that 318 // constant with a new constant that has *all* placeholder uses updated. 319 Constant *UserC = cast<Constant>(U); 320 for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end(); 321 I != E; ++I) { 322 Value *NewOp; 323 if (!isa<ConstantPlaceHolder>(*I)) { 324 // Not a placeholder reference. 325 NewOp = *I; 326 } else if (*I == Placeholder) { 327 // Common case is that it just references this one placeholder. 328 NewOp = RealVal; 329 } else { 330 // Otherwise, look up the placeholder in ResolveConstants. 331 ResolveConstantsTy::iterator It = 332 std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(), 333 std::pair<Constant*, unsigned>(cast<Constant>(*I), 334 0)); 335 assert(It != ResolveConstants.end() && It->first == *I); 336 NewOp = operator[](It->second); 337 } 338 339 NewOps.push_back(cast<Constant>(NewOp)); 340 } 341 342 // Make the new constant. 343 Constant *NewC; 344 if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) { 345 NewC = ConstantArray::get(UserCA->getType(), NewOps); 346 } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) { 347 NewC = ConstantStruct::get(UserCS->getType(), NewOps); 348 } else if (isa<ConstantVector>(UserC)) { 349 NewC = ConstantVector::get(NewOps); 350 } else { 351 assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr."); 352 NewC = cast<ConstantExpr>(UserC)->getWithOperands(NewOps); 353 } 354 355 UserC->replaceAllUsesWith(NewC); 356 UserC->destroyConstant(); 357 NewOps.clear(); 358 } 359 360 // Update all ValueHandles, they should be the only users at this point. 361 Placeholder->replaceAllUsesWith(RealVal); 362 delete Placeholder; 363 } 364} 365 366void BitcodeReaderMDValueList::AssignValue(Value *V, unsigned Idx) { 367 if (Idx == size()) { 368 push_back(V); 369 return; 370 } 371 372 if (Idx >= size()) 373 resize(Idx+1); 374 375 WeakVH &OldV = MDValuePtrs[Idx]; 376 if (OldV == 0) { 377 OldV = V; 378 return; 379 } 380 381 // If there was a forward reference to this value, replace it. 382 MDNode *PrevVal = cast<MDNode>(OldV); 383 OldV->replaceAllUsesWith(V); 384 MDNode::deleteTemporary(PrevVal); 385 // Deleting PrevVal sets Idx value in MDValuePtrs to null. Set new 386 // value for Idx. 387 MDValuePtrs[Idx] = V; 388} 389 390Value *BitcodeReaderMDValueList::getValueFwdRef(unsigned Idx) { 391 if (Idx >= size()) 392 resize(Idx + 1); 393 394 if (Value *V = MDValuePtrs[Idx]) { 395 assert(V->getType()->isMetadataTy() && "Type mismatch in value table!"); 396 return V; 397 } 398 399 // Create and return a placeholder, which will later be RAUW'd. 400 Value *V = MDNode::getTemporary(Context, ArrayRef<Value*>()); 401 MDValuePtrs[Idx] = V; 402 return V; 403} 404 405Type *BitcodeReader::getTypeByID(unsigned ID) { 406 // The type table size is always specified correctly. 407 if (ID >= TypeList.size()) 408 return 0; 409 410 if (Type *Ty = TypeList[ID]) 411 return Ty; 412 413 // If we have a forward reference, the only possible case is when it is to a 414 // named struct. Just create a placeholder for now. 415 return TypeList[ID] = StructType::create(Context); 416} 417 418 419//===----------------------------------------------------------------------===// 420// Functions for parsing blocks from the bitcode file 421//===----------------------------------------------------------------------===// 422 423bool BitcodeReader::ParseAttributeBlock() { 424 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID)) 425 return Error("Malformed block record"); 426 427 if (!MAttributes.empty()) 428 return Error("Multiple PARAMATTR blocks found!"); 429 430 SmallVector<uint64_t, 64> Record; 431 432 SmallVector<AttributeWithIndex, 8> Attrs; 433 434 // Read all the records. 435 while (1) { 436 unsigned Code = Stream.ReadCode(); 437 if (Code == bitc::END_BLOCK) { 438 if (Stream.ReadBlockEnd()) 439 return Error("Error at end of PARAMATTR 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 switch (Stream.ReadRecord(Code, Record)) { 459 default: // Default behavior: ignore. 460 break; 461 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [paramidx0, attr0, ...] 462 if (Record.size() & 1) 463 return Error("Invalid ENTRY record"); 464 465 for (unsigned i = 0, e = Record.size(); i != e; i += 2) { 466 // FIXME: remove in LLVM 3.0 467 // The alignment is stored as a 16-bit raw value from bits 31--16. 468 // We shift the bits above 31 down by 11 bits. 469 470 unsigned Alignment = (Record[i+1] & (0xffffull << 16)) >> 16; 471 if (Alignment && !isPowerOf2_32(Alignment)) 472 return Error("Alignment is not a power of two."); 473 474 Attributes ReconstitutedAttr(Record[i+1] & 0xffff); 475 if (Alignment) 476 ReconstitutedAttr |= Attribute::constructAlignmentFromInt(Alignment); 477 ReconstitutedAttr |= 478 Attributes((Record[i+1] & (0xffffull << 32)) >> 11); 479 480 Record[i+1] = ReconstitutedAttr.Raw(); 481 } 482 483 for (unsigned i = 0, e = Record.size(); i != e; i += 2) { 484 if (Attributes(Record[i+1]) != Attribute::None) 485 Attrs.push_back(AttributeWithIndex::get(Record[i], 486 Attributes(Record[i+1]))); 487 } 488 489 MAttributes.push_back(AttrListPtr::get(Attrs.begin(), Attrs.end())); 490 Attrs.clear(); 491 break; 492 } 493 } 494 } 495} 496 497bool BitcodeReader::ParseTypeTable() { 498 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW)) 499 return Error("Malformed block record"); 500 501 return ParseTypeTableBody(); 502} 503 504bool BitcodeReader::ParseTypeTableBody() { 505 if (!TypeList.empty()) 506 return Error("Multiple TYPE_BLOCKs found!"); 507 508 SmallVector<uint64_t, 64> Record; 509 unsigned NumRecords = 0; 510 511 SmallString<64> TypeName; 512 513 // Read all the records for this type table. 514 while (1) { 515 unsigned Code = Stream.ReadCode(); 516 if (Code == bitc::END_BLOCK) { 517 if (NumRecords != TypeList.size()) 518 return Error("Invalid type forward reference in TYPE_BLOCK"); 519 if (Stream.ReadBlockEnd()) 520 return Error("Error at end of type table block"); 521 return false; 522 } 523 524 if (Code == bitc::ENTER_SUBBLOCK) { 525 // No known subblocks, always skip them. 526 Stream.ReadSubBlockID(); 527 if (Stream.SkipBlock()) 528 return Error("Malformed block record"); 529 continue; 530 } 531 532 if (Code == bitc::DEFINE_ABBREV) { 533 Stream.ReadAbbrevRecord(); 534 continue; 535 } 536 537 // Read a record. 538 Record.clear(); 539 Type *ResultTy = 0; 540 switch (Stream.ReadRecord(Code, Record)) { 541 default: return Error("unknown type in type table"); 542 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries] 543 // TYPE_CODE_NUMENTRY contains a count of the number of types in the 544 // type list. This allows us to reserve space. 545 if (Record.size() < 1) 546 return Error("Invalid TYPE_CODE_NUMENTRY record"); 547 TypeList.resize(Record[0]); 548 continue; 549 case bitc::TYPE_CODE_VOID: // VOID 550 ResultTy = Type::getVoidTy(Context); 551 break; 552 case bitc::TYPE_CODE_HALF: // HALF 553 ResultTy = Type::getHalfTy(Context); 554 break; 555 case bitc::TYPE_CODE_FLOAT: // FLOAT 556 ResultTy = Type::getFloatTy(Context); 557 break; 558 case bitc::TYPE_CODE_DOUBLE: // DOUBLE 559 ResultTy = Type::getDoubleTy(Context); 560 break; 561 case bitc::TYPE_CODE_X86_FP80: // X86_FP80 562 ResultTy = Type::getX86_FP80Ty(Context); 563 break; 564 case bitc::TYPE_CODE_FP128: // FP128 565 ResultTy = Type::getFP128Ty(Context); 566 break; 567 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128 568 ResultTy = Type::getPPC_FP128Ty(Context); 569 break; 570 case bitc::TYPE_CODE_LABEL: // LABEL 571 ResultTy = Type::getLabelTy(Context); 572 break; 573 case bitc::TYPE_CODE_METADATA: // METADATA 574 ResultTy = Type::getMetadataTy(Context); 575 break; 576 case bitc::TYPE_CODE_X86_MMX: // X86_MMX 577 ResultTy = Type::getX86_MMXTy(Context); 578 break; 579 case bitc::TYPE_CODE_INTEGER: // INTEGER: [width] 580 if (Record.size() < 1) 581 return Error("Invalid Integer type record"); 582 583 ResultTy = IntegerType::get(Context, Record[0]); 584 break; 585 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or 586 // [pointee type, address space] 587 if (Record.size() < 1) 588 return Error("Invalid POINTER type record"); 589 unsigned AddressSpace = 0; 590 if (Record.size() == 2) 591 AddressSpace = Record[1]; 592 ResultTy = getTypeByID(Record[0]); 593 if (ResultTy == 0) return Error("invalid element type in pointer type"); 594 ResultTy = PointerType::get(ResultTy, AddressSpace); 595 break; 596 } 597 case bitc::TYPE_CODE_FUNCTION: { 598 // FUNCTION: [vararg, retty, paramty x N] 599 if (Record.size() < 2) 600 return Error("Invalid FUNCTION type record"); 601 SmallVector<Type*, 8> ArgTys; 602 for (unsigned i = 2, e = Record.size(); i != e; ++i) { 603 if (Type *T = getTypeByID(Record[i])) 604 ArgTys.push_back(T); 605 else 606 break; 607 } 608 609 ResultTy = getTypeByID(Record[1]); 610 if (ResultTy == 0 || ArgTys.size() < Record.size()-2) 611 return Error("invalid type in function type"); 612 613 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]); 614 break; 615 } 616 case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N] 617 if (Record.size() < 1) 618 return Error("Invalid STRUCT type record"); 619 SmallVector<Type*, 8> EltTys; 620 for (unsigned i = 1, e = Record.size(); i != e; ++i) { 621 if (Type *T = getTypeByID(Record[i])) 622 EltTys.push_back(T); 623 else 624 break; 625 } 626 if (EltTys.size() != Record.size()-1) 627 return Error("invalid type in struct type"); 628 ResultTy = StructType::get(Context, EltTys, Record[0]); 629 break; 630 } 631 case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N] 632 if (ConvertToString(Record, 0, TypeName)) 633 return Error("Invalid STRUCT_NAME record"); 634 continue; 635 636 case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N] 637 if (Record.size() < 1) 638 return Error("Invalid STRUCT type record"); 639 640 if (NumRecords >= TypeList.size()) 641 return Error("invalid TYPE table"); 642 643 // Check to see if this was forward referenced, if so fill in the temp. 644 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]); 645 if (Res) { 646 Res->setName(TypeName); 647 TypeList[NumRecords] = 0; 648 } else // Otherwise, create a new struct. 649 Res = StructType::create(Context, TypeName); 650 TypeName.clear(); 651 652 SmallVector<Type*, 8> EltTys; 653 for (unsigned i = 1, e = Record.size(); i != e; ++i) { 654 if (Type *T = getTypeByID(Record[i])) 655 EltTys.push_back(T); 656 else 657 break; 658 } 659 if (EltTys.size() != Record.size()-1) 660 return Error("invalid STRUCT type record"); 661 Res->setBody(EltTys, Record[0]); 662 ResultTy = Res; 663 break; 664 } 665 case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: [] 666 if (Record.size() != 1) 667 return Error("Invalid OPAQUE type record"); 668 669 if (NumRecords >= TypeList.size()) 670 return Error("invalid TYPE table"); 671 672 // Check to see if this was forward referenced, if so fill in the temp. 673 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]); 674 if (Res) { 675 Res->setName(TypeName); 676 TypeList[NumRecords] = 0; 677 } else // Otherwise, create a new struct with no body. 678 Res = StructType::create(Context, TypeName); 679 TypeName.clear(); 680 ResultTy = Res; 681 break; 682 } 683 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty] 684 if (Record.size() < 2) 685 return Error("Invalid ARRAY type record"); 686 if ((ResultTy = getTypeByID(Record[1]))) 687 ResultTy = ArrayType::get(ResultTy, Record[0]); 688 else 689 return Error("Invalid ARRAY type element"); 690 break; 691 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty] 692 if (Record.size() < 2) 693 return Error("Invalid VECTOR type record"); 694 if ((ResultTy = getTypeByID(Record[1]))) 695 ResultTy = VectorType::get(ResultTy, Record[0]); 696 else 697 return Error("Invalid ARRAY type element"); 698 break; 699 } 700 701 if (NumRecords >= TypeList.size()) 702 return Error("invalid TYPE table"); 703 assert(ResultTy && "Didn't read a type?"); 704 assert(TypeList[NumRecords] == 0 && "Already read type?"); 705 TypeList[NumRecords++] = ResultTy; 706 } 707} 708 709bool BitcodeReader::ParseValueSymbolTable() { 710 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID)) 711 return Error("Malformed block record"); 712 713 SmallVector<uint64_t, 64> Record; 714 715 // Read all the records for this value table. 716 SmallString<128> ValueName; 717 while (1) { 718 unsigned Code = Stream.ReadCode(); 719 if (Code == bitc::END_BLOCK) { 720 if (Stream.ReadBlockEnd()) 721 return Error("Error at end of value symbol table block"); 722 return false; 723 } 724 if (Code == bitc::ENTER_SUBBLOCK) { 725 // No known subblocks, always skip them. 726 Stream.ReadSubBlockID(); 727 if (Stream.SkipBlock()) 728 return Error("Malformed block record"); 729 continue; 730 } 731 732 if (Code == bitc::DEFINE_ABBREV) { 733 Stream.ReadAbbrevRecord(); 734 continue; 735 } 736 737 // Read a record. 738 Record.clear(); 739 switch (Stream.ReadRecord(Code, Record)) { 740 default: // Default behavior: unknown type. 741 break; 742 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N] 743 if (ConvertToString(Record, 1, ValueName)) 744 return Error("Invalid VST_ENTRY record"); 745 unsigned ValueID = Record[0]; 746 if (ValueID >= ValueList.size()) 747 return Error("Invalid Value ID in VST_ENTRY record"); 748 Value *V = ValueList[ValueID]; 749 750 V->setName(StringRef(ValueName.data(), ValueName.size())); 751 ValueName.clear(); 752 break; 753 } 754 case bitc::VST_CODE_BBENTRY: { 755 if (ConvertToString(Record, 1, ValueName)) 756 return Error("Invalid VST_BBENTRY record"); 757 BasicBlock *BB = getBasicBlock(Record[0]); 758 if (BB == 0) 759 return Error("Invalid BB ID in VST_BBENTRY record"); 760 761 BB->setName(StringRef(ValueName.data(), ValueName.size())); 762 ValueName.clear(); 763 break; 764 } 765 } 766 } 767} 768 769bool BitcodeReader::ParseMetadata() { 770 unsigned NextMDValueNo = MDValueList.size(); 771 772 if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID)) 773 return Error("Malformed block record"); 774 775 SmallVector<uint64_t, 64> Record; 776 777 // Read all the records. 778 while (1) { 779 unsigned Code = Stream.ReadCode(); 780 if (Code == bitc::END_BLOCK) { 781 if (Stream.ReadBlockEnd()) 782 return Error("Error at end of PARAMATTR block"); 783 return false; 784 } 785 786 if (Code == bitc::ENTER_SUBBLOCK) { 787 // No known subblocks, always skip them. 788 Stream.ReadSubBlockID(); 789 if (Stream.SkipBlock()) 790 return Error("Malformed block record"); 791 continue; 792 } 793 794 if (Code == bitc::DEFINE_ABBREV) { 795 Stream.ReadAbbrevRecord(); 796 continue; 797 } 798 799 bool IsFunctionLocal = false; 800 // Read a record. 801 Record.clear(); 802 Code = Stream.ReadRecord(Code, Record); 803 switch (Code) { 804 default: // Default behavior: ignore. 805 break; 806 case bitc::METADATA_NAME: { 807 // Read named of the named metadata. 808 unsigned NameLength = Record.size(); 809 SmallString<8> Name; 810 Name.resize(NameLength); 811 for (unsigned i = 0; i != NameLength; ++i) 812 Name[i] = Record[i]; 813 Record.clear(); 814 Code = Stream.ReadCode(); 815 816 // METADATA_NAME is always followed by METADATA_NAMED_NODE. 817 unsigned NextBitCode = Stream.ReadRecord(Code, Record); 818 assert(NextBitCode == bitc::METADATA_NAMED_NODE); (void)NextBitCode; 819 820 // Read named metadata elements. 821 unsigned Size = Record.size(); 822 NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name); 823 for (unsigned i = 0; i != Size; ++i) { 824 MDNode *MD = dyn_cast<MDNode>(MDValueList.getValueFwdRef(Record[i])); 825 if (MD == 0) 826 return Error("Malformed metadata record"); 827 NMD->addOperand(MD); 828 } 829 break; 830 } 831 case bitc::METADATA_FN_NODE: 832 IsFunctionLocal = true; 833 // fall-through 834 case bitc::METADATA_NODE: { 835 if (Record.size() % 2 == 1) 836 return Error("Invalid METADATA_NODE record"); 837 838 unsigned Size = Record.size(); 839 SmallVector<Value*, 8> Elts; 840 for (unsigned i = 0; i != Size; i += 2) { 841 Type *Ty = getTypeByID(Record[i]); 842 if (!Ty) return Error("Invalid METADATA_NODE record"); 843 if (Ty->isMetadataTy()) 844 Elts.push_back(MDValueList.getValueFwdRef(Record[i+1])); 845 else if (!Ty->isVoidTy()) 846 Elts.push_back(ValueList.getValueFwdRef(Record[i+1], Ty)); 847 else 848 Elts.push_back(NULL); 849 } 850 Value *V = MDNode::getWhenValsUnresolved(Context, Elts, IsFunctionLocal); 851 IsFunctionLocal = false; 852 MDValueList.AssignValue(V, NextMDValueNo++); 853 break; 854 } 855 case bitc::METADATA_STRING: { 856 unsigned MDStringLength = Record.size(); 857 SmallString<8> String; 858 String.resize(MDStringLength); 859 for (unsigned i = 0; i != MDStringLength; ++i) 860 String[i] = Record[i]; 861 Value *V = MDString::get(Context, 862 StringRef(String.data(), String.size())); 863 MDValueList.AssignValue(V, NextMDValueNo++); 864 break; 865 } 866 case bitc::METADATA_KIND: { 867 unsigned RecordLength = Record.size(); 868 if (Record.empty() || RecordLength < 2) 869 return Error("Invalid METADATA_KIND record"); 870 SmallString<8> Name; 871 Name.resize(RecordLength-1); 872 unsigned Kind = Record[0]; 873 for (unsigned i = 1; i != RecordLength; ++i) 874 Name[i-1] = Record[i]; 875 876 unsigned NewKind = TheModule->getMDKindID(Name.str()); 877 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second) 878 return Error("Conflicting METADATA_KIND records"); 879 break; 880 } 881 } 882 } 883} 884 885/// DecodeSignRotatedValue - Decode a signed value stored with the sign bit in 886/// the LSB for dense VBR encoding. 887static uint64_t DecodeSignRotatedValue(uint64_t V) { 888 if ((V & 1) == 0) 889 return V >> 1; 890 if (V != 1) 891 return -(V >> 1); 892 // There is no such thing as -0 with integers. "-0" really means MININT. 893 return 1ULL << 63; 894} 895 896/// ResolveGlobalAndAliasInits - Resolve all of the initializers for global 897/// values and aliases that we can. 898bool BitcodeReader::ResolveGlobalAndAliasInits() { 899 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist; 900 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist; 901 902 GlobalInitWorklist.swap(GlobalInits); 903 AliasInitWorklist.swap(AliasInits); 904 905 while (!GlobalInitWorklist.empty()) { 906 unsigned ValID = GlobalInitWorklist.back().second; 907 if (ValID >= ValueList.size()) { 908 // Not ready to resolve this yet, it requires something later in the file. 909 GlobalInits.push_back(GlobalInitWorklist.back()); 910 } else { 911 if (Constant *C = dyn_cast<Constant>(ValueList[ValID])) 912 GlobalInitWorklist.back().first->setInitializer(C); 913 else 914 return Error("Global variable initializer is not a constant!"); 915 } 916 GlobalInitWorklist.pop_back(); 917 } 918 919 while (!AliasInitWorklist.empty()) { 920 unsigned ValID = AliasInitWorklist.back().second; 921 if (ValID >= ValueList.size()) { 922 AliasInits.push_back(AliasInitWorklist.back()); 923 } else { 924 if (Constant *C = dyn_cast<Constant>(ValueList[ValID])) 925 AliasInitWorklist.back().first->setAliasee(C); 926 else 927 return Error("Alias initializer is not a constant!"); 928 } 929 AliasInitWorklist.pop_back(); 930 } 931 return false; 932} 933 934APInt ReadWideAPInt(const uint64_t *Vals, unsigned ActiveWords, 935 unsigned TypeBits) { 936 SmallVector<uint64_t, 8> Words; 937 Words.resize(ActiveWords); 938 for (unsigned i = 0; i != ActiveWords; ++i) 939 Words[i] = DecodeSignRotatedValue(Vals[i]); 940 941 return APInt(TypeBits, Words); 942} 943 944bool BitcodeReader::ParseConstants() { 945 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID)) 946 return Error("Malformed block record"); 947 948 SmallVector<uint64_t, 64> Record; 949 950 // Read all the records for this value table. 951 Type *CurTy = Type::getInt32Ty(Context); 952 unsigned NextCstNo = ValueList.size(); 953 while (1) { 954 unsigned Code = Stream.ReadCode(); 955 if (Code == bitc::END_BLOCK) 956 break; 957 958 if (Code == bitc::ENTER_SUBBLOCK) { 959 // No known subblocks, always skip them. 960 Stream.ReadSubBlockID(); 961 if (Stream.SkipBlock()) 962 return Error("Malformed block record"); 963 continue; 964 } 965 966 if (Code == bitc::DEFINE_ABBREV) { 967 Stream.ReadAbbrevRecord(); 968 continue; 969 } 970 971 // Read a record. 972 Record.clear(); 973 Value *V = 0; 974 unsigned BitCode = Stream.ReadRecord(Code, Record); 975 switch (BitCode) { 976 default: // Default behavior: unknown constant 977 case bitc::CST_CODE_UNDEF: // UNDEF 978 V = UndefValue::get(CurTy); 979 break; 980 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid] 981 if (Record.empty()) 982 return Error("Malformed CST_SETTYPE record"); 983 if (Record[0] >= TypeList.size()) 984 return Error("Invalid Type ID in CST_SETTYPE record"); 985 CurTy = TypeList[Record[0]]; 986 continue; // Skip the ValueList manipulation. 987 case bitc::CST_CODE_NULL: // NULL 988 V = Constant::getNullValue(CurTy); 989 break; 990 case bitc::CST_CODE_INTEGER: // INTEGER: [intval] 991 if (!CurTy->isIntegerTy() || Record.empty()) 992 return Error("Invalid CST_INTEGER record"); 993 V = ConstantInt::get(CurTy, DecodeSignRotatedValue(Record[0])); 994 break; 995 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval] 996 if (!CurTy->isIntegerTy() || Record.empty()) 997 return Error("Invalid WIDE_INTEGER record"); 998 999 unsigned NumWords = Record.size(); 1000 1001 APInt VInt = ReadWideAPInt(&Record[0], NumWords, 1002 cast<IntegerType>(CurTy)->getBitWidth()); 1003 V = ConstantInt::get(Context, VInt); 1004 1005 break; 1006 } 1007 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval] 1008 if (Record.empty()) 1009 return Error("Invalid FLOAT record"); 1010 if (CurTy->isHalfTy()) 1011 V = ConstantFP::get(Context, APFloat(APInt(16, (uint16_t)Record[0]))); 1012 else if (CurTy->isFloatTy()) 1013 V = ConstantFP::get(Context, APFloat(APInt(32, (uint32_t)Record[0]))); 1014 else if (CurTy->isDoubleTy()) 1015 V = ConstantFP::get(Context, APFloat(APInt(64, Record[0]))); 1016 else if (CurTy->isX86_FP80Ty()) { 1017 // Bits are not stored the same way as a normal i80 APInt, compensate. 1018 uint64_t Rearrange[2]; 1019 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16); 1020 Rearrange[1] = Record[0] >> 48; 1021 V = ConstantFP::get(Context, APFloat(APInt(80, Rearrange))); 1022 } else if (CurTy->isFP128Ty()) 1023 V = ConstantFP::get(Context, APFloat(APInt(128, Record), true)); 1024 else if (CurTy->isPPC_FP128Ty()) 1025 V = ConstantFP::get(Context, APFloat(APInt(128, Record))); 1026 else 1027 V = UndefValue::get(CurTy); 1028 break; 1029 } 1030 1031 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number] 1032 if (Record.empty()) 1033 return Error("Invalid CST_AGGREGATE record"); 1034 1035 unsigned Size = Record.size(); 1036 SmallVector<Constant*, 16> Elts; 1037 1038 if (StructType *STy = dyn_cast<StructType>(CurTy)) { 1039 for (unsigned i = 0; i != Size; ++i) 1040 Elts.push_back(ValueList.getConstantFwdRef(Record[i], 1041 STy->getElementType(i))); 1042 V = ConstantStruct::get(STy, Elts); 1043 } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) { 1044 Type *EltTy = ATy->getElementType(); 1045 for (unsigned i = 0; i != Size; ++i) 1046 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy)); 1047 V = ConstantArray::get(ATy, Elts); 1048 } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) { 1049 Type *EltTy = VTy->getElementType(); 1050 for (unsigned i = 0; i != Size; ++i) 1051 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy)); 1052 V = ConstantVector::get(Elts); 1053 } else { 1054 V = UndefValue::get(CurTy); 1055 } 1056 break; 1057 } 1058 case bitc::CST_CODE_STRING: // STRING: [values] 1059 case bitc::CST_CODE_CSTRING: { // CSTRING: [values] 1060 if (Record.empty()) 1061 return Error("Invalid CST_STRING record"); 1062 1063 unsigned Size = Record.size(); 1064 SmallString<16> Elts; 1065 for (unsigned i = 0; i != Size; ++i) 1066 Elts.push_back(Record[i]); 1067 V = ConstantDataArray::getString(Context, Elts, 1068 BitCode == bitc::CST_CODE_CSTRING); 1069 break; 1070 } 1071 case bitc::CST_CODE_DATA: {// DATA: [n x value] 1072 if (Record.empty()) 1073 return Error("Invalid CST_DATA record"); 1074 1075 Type *EltTy = cast<SequentialType>(CurTy)->getElementType(); 1076 unsigned Size = Record.size(); 1077 1078 if (EltTy->isIntegerTy(8)) { 1079 SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end()); 1080 if (isa<VectorType>(CurTy)) 1081 V = ConstantDataVector::get(Context, Elts); 1082 else 1083 V = ConstantDataArray::get(Context, Elts); 1084 } else if (EltTy->isIntegerTy(16)) { 1085 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end()); 1086 if (isa<VectorType>(CurTy)) 1087 V = ConstantDataVector::get(Context, Elts); 1088 else 1089 V = ConstantDataArray::get(Context, Elts); 1090 } else if (EltTy->isIntegerTy(32)) { 1091 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end()); 1092 if (isa<VectorType>(CurTy)) 1093 V = ConstantDataVector::get(Context, Elts); 1094 else 1095 V = ConstantDataArray::get(Context, Elts); 1096 } else if (EltTy->isIntegerTy(64)) { 1097 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end()); 1098 if (isa<VectorType>(CurTy)) 1099 V = ConstantDataVector::get(Context, Elts); 1100 else 1101 V = ConstantDataArray::get(Context, Elts); 1102 } else if (EltTy->isFloatTy()) { 1103 SmallVector<float, 16> Elts; 1104 for (unsigned i = 0; i != Size; ++i) { 1105 union { uint32_t I; float F; }; 1106 I = Record[i]; 1107 Elts.push_back(F); 1108 } 1109 if (isa<VectorType>(CurTy)) 1110 V = ConstantDataVector::get(Context, Elts); 1111 else 1112 V = ConstantDataArray::get(Context, Elts); 1113 } else if (EltTy->isDoubleTy()) { 1114 SmallVector<double, 16> Elts; 1115 for (unsigned i = 0; i != Size; ++i) { 1116 union { uint64_t I; double F; }; 1117 I = Record[i]; 1118 Elts.push_back(F); 1119 } 1120 if (isa<VectorType>(CurTy)) 1121 V = ConstantDataVector::get(Context, Elts); 1122 else 1123 V = ConstantDataArray::get(Context, Elts); 1124 } else { 1125 return Error("Unknown element type in CE_DATA"); 1126 } 1127 break; 1128 } 1129 1130 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval] 1131 if (Record.size() < 3) return Error("Invalid CE_BINOP record"); 1132 int Opc = GetDecodedBinaryOpcode(Record[0], CurTy); 1133 if (Opc < 0) { 1134 V = UndefValue::get(CurTy); // Unknown binop. 1135 } else { 1136 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy); 1137 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy); 1138 unsigned Flags = 0; 1139 if (Record.size() >= 4) { 1140 if (Opc == Instruction::Add || 1141 Opc == Instruction::Sub || 1142 Opc == Instruction::Mul || 1143 Opc == Instruction::Shl) { 1144 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP)) 1145 Flags |= OverflowingBinaryOperator::NoSignedWrap; 1146 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP)) 1147 Flags |= OverflowingBinaryOperator::NoUnsignedWrap; 1148 } else if (Opc == Instruction::SDiv || 1149 Opc == Instruction::UDiv || 1150 Opc == Instruction::LShr || 1151 Opc == Instruction::AShr) { 1152 if (Record[3] & (1 << bitc::PEO_EXACT)) 1153 Flags |= SDivOperator::IsExact; 1154 } 1155 } 1156 V = ConstantExpr::get(Opc, LHS, RHS, Flags); 1157 } 1158 break; 1159 } 1160 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval] 1161 if (Record.size() < 3) return Error("Invalid CE_CAST record"); 1162 int Opc = GetDecodedCastOpcode(Record[0]); 1163 if (Opc < 0) { 1164 V = UndefValue::get(CurTy); // Unknown cast. 1165 } else { 1166 Type *OpTy = getTypeByID(Record[1]); 1167 if (!OpTy) return Error("Invalid CE_CAST record"); 1168 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy); 1169 V = ConstantExpr::getCast(Opc, Op, CurTy); 1170 } 1171 break; 1172 } 1173 case bitc::CST_CODE_CE_INBOUNDS_GEP: 1174 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands] 1175 if (Record.size() & 1) return Error("Invalid CE_GEP record"); 1176 SmallVector<Constant*, 16> Elts; 1177 for (unsigned i = 0, e = Record.size(); i != e; i += 2) { 1178 Type *ElTy = getTypeByID(Record[i]); 1179 if (!ElTy) return Error("Invalid CE_GEP record"); 1180 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy)); 1181 } 1182 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end()); 1183 V = ConstantExpr::getGetElementPtr(Elts[0], Indices, 1184 BitCode == 1185 bitc::CST_CODE_CE_INBOUNDS_GEP); 1186 break; 1187 } 1188 case bitc::CST_CODE_CE_SELECT: // CE_SELECT: [opval#, opval#, opval#] 1189 if (Record.size() < 3) return Error("Invalid CE_SELECT record"); 1190 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0], 1191 Type::getInt1Ty(Context)), 1192 ValueList.getConstantFwdRef(Record[1],CurTy), 1193 ValueList.getConstantFwdRef(Record[2],CurTy)); 1194 break; 1195 case bitc::CST_CODE_CE_EXTRACTELT: { // CE_EXTRACTELT: [opty, opval, opval] 1196 if (Record.size() < 3) return Error("Invalid CE_EXTRACTELT record"); 1197 VectorType *OpTy = 1198 dyn_cast_or_null<VectorType>(getTypeByID(Record[0])); 1199 if (OpTy == 0) return Error("Invalid CE_EXTRACTELT record"); 1200 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy); 1201 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context)); 1202 V = ConstantExpr::getExtractElement(Op0, Op1); 1203 break; 1204 } 1205 case bitc::CST_CODE_CE_INSERTELT: { // CE_INSERTELT: [opval, opval, opval] 1206 VectorType *OpTy = dyn_cast<VectorType>(CurTy); 1207 if (Record.size() < 3 || OpTy == 0) 1208 return Error("Invalid CE_INSERTELT record"); 1209 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy); 1210 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], 1211 OpTy->getElementType()); 1212 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context)); 1213 V = ConstantExpr::getInsertElement(Op0, Op1, Op2); 1214 break; 1215 } 1216 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval] 1217 VectorType *OpTy = dyn_cast<VectorType>(CurTy); 1218 if (Record.size() < 3 || OpTy == 0) 1219 return Error("Invalid CE_SHUFFLEVEC record"); 1220 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy); 1221 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy); 1222 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context), 1223 OpTy->getNumElements()); 1224 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy); 1225 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2); 1226 break; 1227 } 1228 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval] 1229 VectorType *RTy = dyn_cast<VectorType>(CurTy); 1230 VectorType *OpTy = 1231 dyn_cast_or_null<VectorType>(getTypeByID(Record[0])); 1232 if (Record.size() < 4 || RTy == 0 || OpTy == 0) 1233 return Error("Invalid CE_SHUFVEC_EX record"); 1234 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy); 1235 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy); 1236 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context), 1237 RTy->getNumElements()); 1238 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy); 1239 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2); 1240 break; 1241 } 1242 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred] 1243 if (Record.size() < 4) return Error("Invalid CE_CMP record"); 1244 Type *OpTy = getTypeByID(Record[0]); 1245 if (OpTy == 0) return Error("Invalid CE_CMP record"); 1246 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy); 1247 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy); 1248 1249 if (OpTy->isFPOrFPVectorTy()) 1250 V = ConstantExpr::getFCmp(Record[3], Op0, Op1); 1251 else 1252 V = ConstantExpr::getICmp(Record[3], Op0, Op1); 1253 break; 1254 } 1255 case bitc::CST_CODE_INLINEASM: { 1256 if (Record.size() < 2) return Error("Invalid INLINEASM record"); 1257 std::string AsmStr, ConstrStr; 1258 bool HasSideEffects = Record[0] & 1; 1259 bool IsAlignStack = Record[0] >> 1; 1260 unsigned AsmStrSize = Record[1]; 1261 if (2+AsmStrSize >= Record.size()) 1262 return Error("Invalid INLINEASM record"); 1263 unsigned ConstStrSize = Record[2+AsmStrSize]; 1264 if (3+AsmStrSize+ConstStrSize > Record.size()) 1265 return Error("Invalid INLINEASM record"); 1266 1267 for (unsigned i = 0; i != AsmStrSize; ++i) 1268 AsmStr += (char)Record[2+i]; 1269 for (unsigned i = 0; i != ConstStrSize; ++i) 1270 ConstrStr += (char)Record[3+AsmStrSize+i]; 1271 PointerType *PTy = cast<PointerType>(CurTy); 1272 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()), 1273 AsmStr, ConstrStr, HasSideEffects, IsAlignStack); 1274 break; 1275 } 1276 case bitc::CST_CODE_BLOCKADDRESS:{ 1277 if (Record.size() < 3) return Error("Invalid CE_BLOCKADDRESS record"); 1278 Type *FnTy = getTypeByID(Record[0]); 1279 if (FnTy == 0) return Error("Invalid CE_BLOCKADDRESS record"); 1280 Function *Fn = 1281 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy)); 1282 if (Fn == 0) return Error("Invalid CE_BLOCKADDRESS record"); 1283 1284 GlobalVariable *FwdRef = new GlobalVariable(*Fn->getParent(), 1285 Type::getInt8Ty(Context), 1286 false, GlobalValue::InternalLinkage, 1287 0, ""); 1288 BlockAddrFwdRefs[Fn].push_back(std::make_pair(Record[2], FwdRef)); 1289 V = FwdRef; 1290 break; 1291 } 1292 } 1293 1294 ValueList.AssignValue(V, NextCstNo); 1295 ++NextCstNo; 1296 } 1297 1298 if (NextCstNo != ValueList.size()) 1299 return Error("Invalid constant reference!"); 1300 1301 if (Stream.ReadBlockEnd()) 1302 return Error("Error at end of constants block"); 1303 1304 // Once all the constants have been read, go through and resolve forward 1305 // references. 1306 ValueList.ResolveConstantForwardRefs(); 1307 return false; 1308} 1309 1310bool BitcodeReader::ParseUseLists() { 1311 if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID)) 1312 return Error("Malformed block record"); 1313 1314 SmallVector<uint64_t, 64> Record; 1315 1316 // Read all the records. 1317 while (1) { 1318 unsigned Code = Stream.ReadCode(); 1319 if (Code == bitc::END_BLOCK) { 1320 if (Stream.ReadBlockEnd()) 1321 return Error("Error at end of use-list table block"); 1322 return false; 1323 } 1324 1325 if (Code == bitc::ENTER_SUBBLOCK) { 1326 // No known subblocks, always skip them. 1327 Stream.ReadSubBlockID(); 1328 if (Stream.SkipBlock()) 1329 return Error("Malformed block record"); 1330 continue; 1331 } 1332 1333 if (Code == bitc::DEFINE_ABBREV) { 1334 Stream.ReadAbbrevRecord(); 1335 continue; 1336 } 1337 1338 // Read a use list record. 1339 Record.clear(); 1340 switch (Stream.ReadRecord(Code, Record)) { 1341 default: // Default behavior: unknown type. 1342 break; 1343 case bitc::USELIST_CODE_ENTRY: { // USELIST_CODE_ENTRY: TBD. 1344 unsigned RecordLength = Record.size(); 1345 if (RecordLength < 1) 1346 return Error ("Invalid UseList reader!"); 1347 UseListRecords.push_back(Record); 1348 break; 1349 } 1350 } 1351 } 1352} 1353 1354/// RememberAndSkipFunctionBody - When we see the block for a function body, 1355/// remember where it is and then skip it. This lets us lazily deserialize the 1356/// functions. 1357bool BitcodeReader::RememberAndSkipFunctionBody() { 1358 // Get the function we are talking about. 1359 if (FunctionsWithBodies.empty()) 1360 return Error("Insufficient function protos"); 1361 1362 Function *Fn = FunctionsWithBodies.back(); 1363 FunctionsWithBodies.pop_back(); 1364 1365 // Save the current stream state. 1366 uint64_t CurBit = Stream.GetCurrentBitNo(); 1367 DeferredFunctionInfo[Fn] = CurBit; 1368 1369 // Skip over the function block for now. 1370 if (Stream.SkipBlock()) 1371 return Error("Malformed block record"); 1372 return false; 1373} 1374 1375bool BitcodeReader::GlobalCleanup() { 1376 // Patch the initializers for globals and aliases up. 1377 ResolveGlobalAndAliasInits(); 1378 if (!GlobalInits.empty() || !AliasInits.empty()) 1379 return Error("Malformed global initializer set"); 1380 1381 // Look for intrinsic functions which need to be upgraded at some point 1382 for (Module::iterator FI = TheModule->begin(), FE = TheModule->end(); 1383 FI != FE; ++FI) { 1384 Function *NewFn; 1385 if (UpgradeIntrinsicFunction(FI, NewFn)) 1386 UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn)); 1387 } 1388 1389 // Look for global variables which need to be renamed. 1390 for (Module::global_iterator 1391 GI = TheModule->global_begin(), GE = TheModule->global_end(); 1392 GI != GE; ++GI) 1393 UpgradeGlobalVariable(GI); 1394 // Force deallocation of memory for these vectors to favor the client that 1395 // want lazy deserialization. 1396 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits); 1397 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits); 1398 return false; 1399} 1400 1401bool BitcodeReader::ParseModule(bool Resume) { 1402 if (Resume) 1403 Stream.JumpToBit(NextUnreadBit); 1404 else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID)) 1405 return Error("Malformed block record"); 1406 1407 SmallVector<uint64_t, 64> Record; 1408 std::vector<std::string> SectionTable; 1409 std::vector<std::string> GCTable; 1410 1411 // Read all the records for this module. 1412 while (!Stream.AtEndOfStream()) { 1413 unsigned Code = Stream.ReadCode(); 1414 if (Code == bitc::END_BLOCK) { 1415 if (Stream.ReadBlockEnd()) 1416 return Error("Error at end of module block"); 1417 1418 return GlobalCleanup(); 1419 } 1420 1421 if (Code == bitc::ENTER_SUBBLOCK) { 1422 switch (Stream.ReadSubBlockID()) { 1423 default: // Skip unknown content. 1424 if (Stream.SkipBlock()) 1425 return Error("Malformed block record"); 1426 break; 1427 case bitc::BLOCKINFO_BLOCK_ID: 1428 if (Stream.ReadBlockInfoBlock()) 1429 return Error("Malformed BlockInfoBlock"); 1430 break; 1431 case bitc::PARAMATTR_BLOCK_ID: 1432 if (ParseAttributeBlock()) 1433 return true; 1434 break; 1435 case bitc::TYPE_BLOCK_ID_NEW: 1436 if (ParseTypeTable()) 1437 return true; 1438 break; 1439 case bitc::VALUE_SYMTAB_BLOCK_ID: 1440 if (ParseValueSymbolTable()) 1441 return true; 1442 SeenValueSymbolTable = true; 1443 break; 1444 case bitc::CONSTANTS_BLOCK_ID: 1445 if (ParseConstants() || ResolveGlobalAndAliasInits()) 1446 return true; 1447 break; 1448 case bitc::METADATA_BLOCK_ID: 1449 if (ParseMetadata()) 1450 return true; 1451 break; 1452 case bitc::FUNCTION_BLOCK_ID: 1453 // If this is the first function body we've seen, reverse the 1454 // FunctionsWithBodies list. 1455 if (!SeenFirstFunctionBody) { 1456 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end()); 1457 if (GlobalCleanup()) 1458 return true; 1459 SeenFirstFunctionBody = true; 1460 } 1461 1462 if (RememberAndSkipFunctionBody()) 1463 return true; 1464 // For streaming bitcode, suspend parsing when we reach the function 1465 // bodies. Subsequent materialization calls will resume it when 1466 // necessary. For streaming, the function bodies must be at the end of 1467 // the bitcode. If the bitcode file is old, the symbol table will be 1468 // at the end instead and will not have been seen yet. In this case, 1469 // just finish the parse now. 1470 if (LazyStreamer && SeenValueSymbolTable) { 1471 NextUnreadBit = Stream.GetCurrentBitNo(); 1472 return false; 1473 } 1474 break; 1475 case bitc::USELIST_BLOCK_ID: 1476 if (ParseUseLists()) 1477 return true; 1478 break; 1479 } 1480 continue; 1481 } 1482 1483 if (Code == bitc::DEFINE_ABBREV) { 1484 Stream.ReadAbbrevRecord(); 1485 continue; 1486 } 1487 1488 // Read a record. 1489 switch (Stream.ReadRecord(Code, Record)) { 1490 default: break; // Default behavior, ignore unknown content. 1491 case bitc::MODULE_CODE_VERSION: // VERSION: [version#] 1492 if (Record.size() < 1) 1493 return Error("Malformed MODULE_CODE_VERSION"); 1494 // Only version #0 is supported so far. 1495 if (Record[0] != 0) 1496 return Error("Unknown bitstream version!"); 1497 break; 1498 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N] 1499 std::string S; 1500 if (ConvertToString(Record, 0, S)) 1501 return Error("Invalid MODULE_CODE_TRIPLE record"); 1502 TheModule->setTargetTriple(S); 1503 break; 1504 } 1505 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N] 1506 std::string S; 1507 if (ConvertToString(Record, 0, S)) 1508 return Error("Invalid MODULE_CODE_DATALAYOUT record"); 1509 TheModule->setDataLayout(S); 1510 break; 1511 } 1512 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N] 1513 std::string S; 1514 if (ConvertToString(Record, 0, S)) 1515 return Error("Invalid MODULE_CODE_ASM record"); 1516 TheModule->setModuleInlineAsm(S); 1517 break; 1518 } 1519 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N] 1520 std::string S; 1521 if (ConvertToString(Record, 0, S)) 1522 return Error("Invalid MODULE_CODE_DEPLIB record"); 1523 TheModule->addLibrary(S); 1524 break; 1525 } 1526 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N] 1527 std::string S; 1528 if (ConvertToString(Record, 0, S)) 1529 return Error("Invalid MODULE_CODE_SECTIONNAME record"); 1530 SectionTable.push_back(S); 1531 break; 1532 } 1533 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N] 1534 std::string S; 1535 if (ConvertToString(Record, 0, S)) 1536 return Error("Invalid MODULE_CODE_GCNAME record"); 1537 GCTable.push_back(S); 1538 break; 1539 } 1540 // GLOBALVAR: [pointer type, isconst, initid, 1541 // linkage, alignment, section, visibility, threadlocal, 1542 // unnamed_addr] 1543 case bitc::MODULE_CODE_GLOBALVAR: { 1544 if (Record.size() < 6) 1545 return Error("Invalid MODULE_CODE_GLOBALVAR record"); 1546 Type *Ty = getTypeByID(Record[0]); 1547 if (!Ty) return Error("Invalid MODULE_CODE_GLOBALVAR record"); 1548 if (!Ty->isPointerTy()) 1549 return Error("Global not a pointer type!"); 1550 unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace(); 1551 Ty = cast<PointerType>(Ty)->getElementType(); 1552 1553 bool isConstant = Record[1]; 1554 GlobalValue::LinkageTypes Linkage = GetDecodedLinkage(Record[3]); 1555 unsigned Alignment = (1 << Record[4]) >> 1; 1556 std::string Section; 1557 if (Record[5]) { 1558 if (Record[5]-1 >= SectionTable.size()) 1559 return Error("Invalid section ID"); 1560 Section = SectionTable[Record[5]-1]; 1561 } 1562 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility; 1563 if (Record.size() > 6) 1564 Visibility = GetDecodedVisibility(Record[6]); 1565 bool isThreadLocal = false; 1566 if (Record.size() > 7) 1567 isThreadLocal = Record[7]; 1568 1569 bool UnnamedAddr = false; 1570 if (Record.size() > 8) 1571 UnnamedAddr = Record[8]; 1572 1573 GlobalVariable *NewGV = 1574 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, 0, "", 0, 1575 isThreadLocal, AddressSpace); 1576 NewGV->setAlignment(Alignment); 1577 if (!Section.empty()) 1578 NewGV->setSection(Section); 1579 NewGV->setVisibility(Visibility); 1580 NewGV->setThreadLocal(isThreadLocal); 1581 NewGV->setUnnamedAddr(UnnamedAddr); 1582 1583 ValueList.push_back(NewGV); 1584 1585 // Remember which value to use for the global initializer. 1586 if (unsigned InitID = Record[2]) 1587 GlobalInits.push_back(std::make_pair(NewGV, InitID-1)); 1588 break; 1589 } 1590 // FUNCTION: [type, callingconv, isproto, linkage, paramattr, 1591 // alignment, section, visibility, gc, unnamed_addr] 1592 case bitc::MODULE_CODE_FUNCTION: { 1593 if (Record.size() < 8) 1594 return Error("Invalid MODULE_CODE_FUNCTION record"); 1595 Type *Ty = getTypeByID(Record[0]); 1596 if (!Ty) return Error("Invalid MODULE_CODE_FUNCTION record"); 1597 if (!Ty->isPointerTy()) 1598 return Error("Function not a pointer type!"); 1599 FunctionType *FTy = 1600 dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType()); 1601 if (!FTy) 1602 return Error("Function not a pointer to function type!"); 1603 1604 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage, 1605 "", TheModule); 1606 1607 Func->setCallingConv(static_cast<CallingConv::ID>(Record[1])); 1608 bool isProto = Record[2]; 1609 Func->setLinkage(GetDecodedLinkage(Record[3])); 1610 Func->setAttributes(getAttributes(Record[4])); 1611 1612 Func->setAlignment((1 << Record[5]) >> 1); 1613 if (Record[6]) { 1614 if (Record[6]-1 >= SectionTable.size()) 1615 return Error("Invalid section ID"); 1616 Func->setSection(SectionTable[Record[6]-1]); 1617 } 1618 Func->setVisibility(GetDecodedVisibility(Record[7])); 1619 if (Record.size() > 8 && Record[8]) { 1620 if (Record[8]-1 > GCTable.size()) 1621 return Error("Invalid GC ID"); 1622 Func->setGC(GCTable[Record[8]-1].c_str()); 1623 } 1624 bool UnnamedAddr = false; 1625 if (Record.size() > 9) 1626 UnnamedAddr = Record[9]; 1627 Func->setUnnamedAddr(UnnamedAddr); 1628 ValueList.push_back(Func); 1629 1630 // If this is a function with a body, remember the prototype we are 1631 // creating now, so that we can match up the body with them later. 1632 if (!isProto) { 1633 FunctionsWithBodies.push_back(Func); 1634 if (LazyStreamer) DeferredFunctionInfo[Func] = 0; 1635 } 1636 break; 1637 } 1638 // ALIAS: [alias type, aliasee val#, linkage] 1639 // ALIAS: [alias type, aliasee val#, linkage, visibility] 1640 case bitc::MODULE_CODE_ALIAS: { 1641 if (Record.size() < 3) 1642 return Error("Invalid MODULE_ALIAS record"); 1643 Type *Ty = getTypeByID(Record[0]); 1644 if (!Ty) return Error("Invalid MODULE_ALIAS record"); 1645 if (!Ty->isPointerTy()) 1646 return Error("Function not a pointer type!"); 1647 1648 GlobalAlias *NewGA = new GlobalAlias(Ty, GetDecodedLinkage(Record[2]), 1649 "", 0, TheModule); 1650 // Old bitcode files didn't have visibility field. 1651 if (Record.size() > 3) 1652 NewGA->setVisibility(GetDecodedVisibility(Record[3])); 1653 ValueList.push_back(NewGA); 1654 AliasInits.push_back(std::make_pair(NewGA, Record[1])); 1655 break; 1656 } 1657 /// MODULE_CODE_PURGEVALS: [numvals] 1658 case bitc::MODULE_CODE_PURGEVALS: 1659 // Trim down the value list to the specified size. 1660 if (Record.size() < 1 || Record[0] > ValueList.size()) 1661 return Error("Invalid MODULE_PURGEVALS record"); 1662 ValueList.shrinkTo(Record[0]); 1663 break; 1664 } 1665 Record.clear(); 1666 } 1667 1668 return Error("Premature end of bitstream"); 1669} 1670 1671bool BitcodeReader::ParseBitcodeInto(Module *M) { 1672 TheModule = 0; 1673 1674 if (InitStream()) return true; 1675 1676 // Sniff for the signature. 1677 if (Stream.Read(8) != 'B' || 1678 Stream.Read(8) != 'C' || 1679 Stream.Read(4) != 0x0 || 1680 Stream.Read(4) != 0xC || 1681 Stream.Read(4) != 0xE || 1682 Stream.Read(4) != 0xD) 1683 return Error("Invalid bitcode signature"); 1684 1685 // We expect a number of well-defined blocks, though we don't necessarily 1686 // need to understand them all. 1687 while (!Stream.AtEndOfStream()) { 1688 unsigned Code = Stream.ReadCode(); 1689 1690 if (Code != bitc::ENTER_SUBBLOCK) { 1691 1692 // The ranlib in xcode 4 will align archive members by appending newlines 1693 // to the end of them. If this file size is a multiple of 4 but not 8, we 1694 // have to read and ignore these final 4 bytes :-( 1695 if (Stream.GetAbbrevIDWidth() == 2 && Code == 2 && 1696 Stream.Read(6) == 2 && Stream.Read(24) == 0xa0a0a && 1697 Stream.AtEndOfStream()) 1698 return false; 1699 1700 return Error("Invalid record at top-level"); 1701 } 1702 1703 unsigned BlockID = Stream.ReadSubBlockID(); 1704 1705 // We only know the MODULE subblock ID. 1706 switch (BlockID) { 1707 case bitc::BLOCKINFO_BLOCK_ID: 1708 if (Stream.ReadBlockInfoBlock()) 1709 return Error("Malformed BlockInfoBlock"); 1710 break; 1711 case bitc::MODULE_BLOCK_ID: 1712 // Reject multiple MODULE_BLOCK's in a single bitstream. 1713 if (TheModule) 1714 return Error("Multiple MODULE_BLOCKs in same stream"); 1715 TheModule = M; 1716 if (ParseModule(false)) 1717 return true; 1718 if (LazyStreamer) return false; 1719 break; 1720 default: 1721 if (Stream.SkipBlock()) 1722 return Error("Malformed block record"); 1723 break; 1724 } 1725 } 1726 1727 return false; 1728} 1729 1730bool BitcodeReader::ParseModuleTriple(std::string &Triple) { 1731 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID)) 1732 return Error("Malformed block record"); 1733 1734 SmallVector<uint64_t, 64> Record; 1735 1736 // Read all the records for this module. 1737 while (!Stream.AtEndOfStream()) { 1738 unsigned Code = Stream.ReadCode(); 1739 if (Code == bitc::END_BLOCK) { 1740 if (Stream.ReadBlockEnd()) 1741 return Error("Error at end of module block"); 1742 1743 return false; 1744 } 1745 1746 if (Code == bitc::ENTER_SUBBLOCK) { 1747 switch (Stream.ReadSubBlockID()) { 1748 default: // Skip unknown content. 1749 if (Stream.SkipBlock()) 1750 return Error("Malformed block record"); 1751 break; 1752 } 1753 continue; 1754 } 1755 1756 if (Code == bitc::DEFINE_ABBREV) { 1757 Stream.ReadAbbrevRecord(); 1758 continue; 1759 } 1760 1761 // Read a record. 1762 switch (Stream.ReadRecord(Code, Record)) { 1763 default: break; // Default behavior, ignore unknown content. 1764 case bitc::MODULE_CODE_VERSION: // VERSION: [version#] 1765 if (Record.size() < 1) 1766 return Error("Malformed MODULE_CODE_VERSION"); 1767 // Only version #0 is supported so far. 1768 if (Record[0] != 0) 1769 return Error("Unknown bitstream version!"); 1770 break; 1771 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N] 1772 std::string S; 1773 if (ConvertToString(Record, 0, S)) 1774 return Error("Invalid MODULE_CODE_TRIPLE record"); 1775 Triple = S; 1776 break; 1777 } 1778 } 1779 Record.clear(); 1780 } 1781 1782 return Error("Premature end of bitstream"); 1783} 1784 1785bool BitcodeReader::ParseTriple(std::string &Triple) { 1786 if (InitStream()) return true; 1787 1788 // Sniff for the signature. 1789 if (Stream.Read(8) != 'B' || 1790 Stream.Read(8) != 'C' || 1791 Stream.Read(4) != 0x0 || 1792 Stream.Read(4) != 0xC || 1793 Stream.Read(4) != 0xE || 1794 Stream.Read(4) != 0xD) 1795 return Error("Invalid bitcode signature"); 1796 1797 // We expect a number of well-defined blocks, though we don't necessarily 1798 // need to understand them all. 1799 while (!Stream.AtEndOfStream()) { 1800 unsigned Code = Stream.ReadCode(); 1801 1802 if (Code != bitc::ENTER_SUBBLOCK) 1803 return Error("Invalid record at top-level"); 1804 1805 unsigned BlockID = Stream.ReadSubBlockID(); 1806 1807 // We only know the MODULE subblock ID. 1808 switch (BlockID) { 1809 case bitc::MODULE_BLOCK_ID: 1810 if (ParseModuleTriple(Triple)) 1811 return true; 1812 break; 1813 default: 1814 if (Stream.SkipBlock()) 1815 return Error("Malformed block record"); 1816 break; 1817 } 1818 } 1819 1820 return false; 1821} 1822 1823/// ParseMetadataAttachment - Parse metadata attachments. 1824bool BitcodeReader::ParseMetadataAttachment() { 1825 if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID)) 1826 return Error("Malformed block record"); 1827 1828 SmallVector<uint64_t, 64> Record; 1829 while(1) { 1830 unsigned Code = Stream.ReadCode(); 1831 if (Code == bitc::END_BLOCK) { 1832 if (Stream.ReadBlockEnd()) 1833 return Error("Error at end of PARAMATTR block"); 1834 break; 1835 } 1836 if (Code == bitc::DEFINE_ABBREV) { 1837 Stream.ReadAbbrevRecord(); 1838 continue; 1839 } 1840 // Read a metadata attachment record. 1841 Record.clear(); 1842 switch (Stream.ReadRecord(Code, Record)) { 1843 default: // Default behavior: ignore. 1844 break; 1845 case bitc::METADATA_ATTACHMENT: { 1846 unsigned RecordLength = Record.size(); 1847 if (Record.empty() || (RecordLength - 1) % 2 == 1) 1848 return Error ("Invalid METADATA_ATTACHMENT reader!"); 1849 Instruction *Inst = InstructionList[Record[0]]; 1850 for (unsigned i = 1; i != RecordLength; i = i+2) { 1851 unsigned Kind = Record[i]; 1852 DenseMap<unsigned, unsigned>::iterator I = 1853 MDKindMap.find(Kind); 1854 if (I == MDKindMap.end()) 1855 return Error("Invalid metadata kind ID"); 1856 Value *Node = MDValueList.getValueFwdRef(Record[i+1]); 1857 Inst->setMetadata(I->second, cast<MDNode>(Node)); 1858 } 1859 break; 1860 } 1861 } 1862 } 1863 return false; 1864} 1865 1866/// ParseFunctionBody - Lazily parse the specified function body block. 1867bool BitcodeReader::ParseFunctionBody(Function *F) { 1868 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID)) 1869 return Error("Malformed block record"); 1870 1871 InstructionList.clear(); 1872 unsigned ModuleValueListSize = ValueList.size(); 1873 unsigned ModuleMDValueListSize = MDValueList.size(); 1874 1875 // Add all the function arguments to the value table. 1876 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I) 1877 ValueList.push_back(I); 1878 1879 unsigned NextValueNo = ValueList.size(); 1880 BasicBlock *CurBB = 0; 1881 unsigned CurBBNo = 0; 1882 1883 DebugLoc LastLoc; 1884 1885 // Read all the records. 1886 SmallVector<uint64_t, 64> Record; 1887 while (1) { 1888 unsigned Code = Stream.ReadCode(); 1889 if (Code == bitc::END_BLOCK) { 1890 if (Stream.ReadBlockEnd()) 1891 return Error("Error at end of function block"); 1892 break; 1893 } 1894 1895 if (Code == bitc::ENTER_SUBBLOCK) { 1896 switch (Stream.ReadSubBlockID()) { 1897 default: // Skip unknown content. 1898 if (Stream.SkipBlock()) 1899 return Error("Malformed block record"); 1900 break; 1901 case bitc::CONSTANTS_BLOCK_ID: 1902 if (ParseConstants()) return true; 1903 NextValueNo = ValueList.size(); 1904 break; 1905 case bitc::VALUE_SYMTAB_BLOCK_ID: 1906 if (ParseValueSymbolTable()) return true; 1907 break; 1908 case bitc::METADATA_ATTACHMENT_ID: 1909 if (ParseMetadataAttachment()) return true; 1910 break; 1911 case bitc::METADATA_BLOCK_ID: 1912 if (ParseMetadata()) return true; 1913 break; 1914 } 1915 continue; 1916 } 1917 1918 if (Code == bitc::DEFINE_ABBREV) { 1919 Stream.ReadAbbrevRecord(); 1920 continue; 1921 } 1922 1923 // Read a record. 1924 Record.clear(); 1925 Instruction *I = 0; 1926 unsigned BitCode = Stream.ReadRecord(Code, Record); 1927 switch (BitCode) { 1928 default: // Default behavior: reject 1929 return Error("Unknown instruction"); 1930 case bitc::FUNC_CODE_DECLAREBLOCKS: // DECLAREBLOCKS: [nblocks] 1931 if (Record.size() < 1 || Record[0] == 0) 1932 return Error("Invalid DECLAREBLOCKS record"); 1933 // Create all the basic blocks for the function. 1934 FunctionBBs.resize(Record[0]); 1935 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i) 1936 FunctionBBs[i] = BasicBlock::Create(Context, "", F); 1937 CurBB = FunctionBBs[0]; 1938 continue; 1939 1940 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN 1941 // This record indicates that the last instruction is at the same 1942 // location as the previous instruction with a location. 1943 I = 0; 1944 1945 // Get the last instruction emitted. 1946 if (CurBB && !CurBB->empty()) 1947 I = &CurBB->back(); 1948 else if (CurBBNo && FunctionBBs[CurBBNo-1] && 1949 !FunctionBBs[CurBBNo-1]->empty()) 1950 I = &FunctionBBs[CurBBNo-1]->back(); 1951 1952 if (I == 0) return Error("Invalid DEBUG_LOC_AGAIN record"); 1953 I->setDebugLoc(LastLoc); 1954 I = 0; 1955 continue; 1956 1957 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia] 1958 I = 0; // Get the last instruction emitted. 1959 if (CurBB && !CurBB->empty()) 1960 I = &CurBB->back(); 1961 else if (CurBBNo && FunctionBBs[CurBBNo-1] && 1962 !FunctionBBs[CurBBNo-1]->empty()) 1963 I = &FunctionBBs[CurBBNo-1]->back(); 1964 if (I == 0 || Record.size() < 4) 1965 return Error("Invalid FUNC_CODE_DEBUG_LOC record"); 1966 1967 unsigned Line = Record[0], Col = Record[1]; 1968 unsigned ScopeID = Record[2], IAID = Record[3]; 1969 1970 MDNode *Scope = 0, *IA = 0; 1971 if (ScopeID) Scope = cast<MDNode>(MDValueList.getValueFwdRef(ScopeID-1)); 1972 if (IAID) IA = cast<MDNode>(MDValueList.getValueFwdRef(IAID-1)); 1973 LastLoc = DebugLoc::get(Line, Col, Scope, IA); 1974 I->setDebugLoc(LastLoc); 1975 I = 0; 1976 continue; 1977 } 1978 1979 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode] 1980 unsigned OpNum = 0; 1981 Value *LHS, *RHS; 1982 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) || 1983 getValue(Record, OpNum, LHS->getType(), RHS) || 1984 OpNum+1 > Record.size()) 1985 return Error("Invalid BINOP record"); 1986 1987 int Opc = GetDecodedBinaryOpcode(Record[OpNum++], LHS->getType()); 1988 if (Opc == -1) return Error("Invalid BINOP record"); 1989 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS); 1990 InstructionList.push_back(I); 1991 if (OpNum < Record.size()) { 1992 if (Opc == Instruction::Add || 1993 Opc == Instruction::Sub || 1994 Opc == Instruction::Mul || 1995 Opc == Instruction::Shl) { 1996 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP)) 1997 cast<BinaryOperator>(I)->setHasNoSignedWrap(true); 1998 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP)) 1999 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true); 2000 } else if (Opc == Instruction::SDiv || 2001 Opc == Instruction::UDiv || 2002 Opc == Instruction::LShr || 2003 Opc == Instruction::AShr) { 2004 if (Record[OpNum] & (1 << bitc::PEO_EXACT)) 2005 cast<BinaryOperator>(I)->setIsExact(true); 2006 } 2007 } 2008 break; 2009 } 2010 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc] 2011 unsigned OpNum = 0; 2012 Value *Op; 2013 if (getValueTypePair(Record, OpNum, NextValueNo, Op) || 2014 OpNum+2 != Record.size()) 2015 return Error("Invalid CAST record"); 2016 2017 Type *ResTy = getTypeByID(Record[OpNum]); 2018 int Opc = GetDecodedCastOpcode(Record[OpNum+1]); 2019 if (Opc == -1 || ResTy == 0) 2020 return Error("Invalid CAST record"); 2021 I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy); 2022 InstructionList.push_back(I); 2023 break; 2024 } 2025 case bitc::FUNC_CODE_INST_INBOUNDS_GEP: 2026 case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands] 2027 unsigned OpNum = 0; 2028 Value *BasePtr; 2029 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr)) 2030 return Error("Invalid GEP record"); 2031 2032 SmallVector<Value*, 16> GEPIdx; 2033 while (OpNum != Record.size()) { 2034 Value *Op; 2035 if (getValueTypePair(Record, OpNum, NextValueNo, Op)) 2036 return Error("Invalid GEP record"); 2037 GEPIdx.push_back(Op); 2038 } 2039 2040 I = GetElementPtrInst::Create(BasePtr, GEPIdx); 2041 InstructionList.push_back(I); 2042 if (BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP) 2043 cast<GetElementPtrInst>(I)->setIsInBounds(true); 2044 break; 2045 } 2046 2047 case bitc::FUNC_CODE_INST_EXTRACTVAL: { 2048 // EXTRACTVAL: [opty, opval, n x indices] 2049 unsigned OpNum = 0; 2050 Value *Agg; 2051 if (getValueTypePair(Record, OpNum, NextValueNo, Agg)) 2052 return Error("Invalid EXTRACTVAL record"); 2053 2054 SmallVector<unsigned, 4> EXTRACTVALIdx; 2055 for (unsigned RecSize = Record.size(); 2056 OpNum != RecSize; ++OpNum) { 2057 uint64_t Index = Record[OpNum]; 2058 if ((unsigned)Index != Index) 2059 return Error("Invalid EXTRACTVAL index"); 2060 EXTRACTVALIdx.push_back((unsigned)Index); 2061 } 2062 2063 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx); 2064 InstructionList.push_back(I); 2065 break; 2066 } 2067 2068 case bitc::FUNC_CODE_INST_INSERTVAL: { 2069 // INSERTVAL: [opty, opval, opty, opval, n x indices] 2070 unsigned OpNum = 0; 2071 Value *Agg; 2072 if (getValueTypePair(Record, OpNum, NextValueNo, Agg)) 2073 return Error("Invalid INSERTVAL record"); 2074 Value *Val; 2075 if (getValueTypePair(Record, OpNum, NextValueNo, Val)) 2076 return Error("Invalid INSERTVAL record"); 2077 2078 SmallVector<unsigned, 4> INSERTVALIdx; 2079 for (unsigned RecSize = Record.size(); 2080 OpNum != RecSize; ++OpNum) { 2081 uint64_t Index = Record[OpNum]; 2082 if ((unsigned)Index != Index) 2083 return Error("Invalid INSERTVAL index"); 2084 INSERTVALIdx.push_back((unsigned)Index); 2085 } 2086 2087 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx); 2088 InstructionList.push_back(I); 2089 break; 2090 } 2091 2092 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval] 2093 // obsolete form of select 2094 // handles select i1 ... in old bitcode 2095 unsigned OpNum = 0; 2096 Value *TrueVal, *FalseVal, *Cond; 2097 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) || 2098 getValue(Record, OpNum, TrueVal->getType(), FalseVal) || 2099 getValue(Record, OpNum, Type::getInt1Ty(Context), Cond)) 2100 return Error("Invalid SELECT record"); 2101 2102 I = SelectInst::Create(Cond, TrueVal, FalseVal); 2103 InstructionList.push_back(I); 2104 break; 2105 } 2106 2107 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred] 2108 // new form of select 2109 // handles select i1 or select [N x i1] 2110 unsigned OpNum = 0; 2111 Value *TrueVal, *FalseVal, *Cond; 2112 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) || 2113 getValue(Record, OpNum, TrueVal->getType(), FalseVal) || 2114 getValueTypePair(Record, OpNum, NextValueNo, Cond)) 2115 return Error("Invalid SELECT record"); 2116 2117 // select condition can be either i1 or [N x i1] 2118 if (VectorType* vector_type = 2119 dyn_cast<VectorType>(Cond->getType())) { 2120 // expect <n x i1> 2121 if (vector_type->getElementType() != Type::getInt1Ty(Context)) 2122 return Error("Invalid SELECT condition type"); 2123 } else { 2124 // expect i1 2125 if (Cond->getType() != Type::getInt1Ty(Context)) 2126 return Error("Invalid SELECT condition type"); 2127 } 2128 2129 I = SelectInst::Create(Cond, TrueVal, FalseVal); 2130 InstructionList.push_back(I); 2131 break; 2132 } 2133 2134 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval] 2135 unsigned OpNum = 0; 2136 Value *Vec, *Idx; 2137 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) || 2138 getValue(Record, OpNum, Type::getInt32Ty(Context), Idx)) 2139 return Error("Invalid EXTRACTELT record"); 2140 I = ExtractElementInst::Create(Vec, Idx); 2141 InstructionList.push_back(I); 2142 break; 2143 } 2144 2145 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval] 2146 unsigned OpNum = 0; 2147 Value *Vec, *Elt, *Idx; 2148 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) || 2149 getValue(Record, OpNum, 2150 cast<VectorType>(Vec->getType())->getElementType(), Elt) || 2151 getValue(Record, OpNum, Type::getInt32Ty(Context), Idx)) 2152 return Error("Invalid INSERTELT record"); 2153 I = InsertElementInst::Create(Vec, Elt, Idx); 2154 InstructionList.push_back(I); 2155 break; 2156 } 2157 2158 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval] 2159 unsigned OpNum = 0; 2160 Value *Vec1, *Vec2, *Mask; 2161 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) || 2162 getValue(Record, OpNum, Vec1->getType(), Vec2)) 2163 return Error("Invalid SHUFFLEVEC record"); 2164 2165 if (getValueTypePair(Record, OpNum, NextValueNo, Mask)) 2166 return Error("Invalid SHUFFLEVEC record"); 2167 I = new ShuffleVectorInst(Vec1, Vec2, Mask); 2168 InstructionList.push_back(I); 2169 break; 2170 } 2171 2172 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred] 2173 // Old form of ICmp/FCmp returning bool 2174 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were 2175 // both legal on vectors but had different behaviour. 2176 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred] 2177 // FCmp/ICmp returning bool or vector of bool 2178 2179 unsigned OpNum = 0; 2180 Value *LHS, *RHS; 2181 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) || 2182 getValue(Record, OpNum, LHS->getType(), RHS) || 2183 OpNum+1 != Record.size()) 2184 return Error("Invalid CMP record"); 2185 2186 if (LHS->getType()->isFPOrFPVectorTy()) 2187 I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS); 2188 else 2189 I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS); 2190 InstructionList.push_back(I); 2191 break; 2192 } 2193 2194 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>] 2195 { 2196 unsigned Size = Record.size(); 2197 if (Size == 0) { 2198 I = ReturnInst::Create(Context); 2199 InstructionList.push_back(I); 2200 break; 2201 } 2202 2203 unsigned OpNum = 0; 2204 Value *Op = NULL; 2205 if (getValueTypePair(Record, OpNum, NextValueNo, Op)) 2206 return Error("Invalid RET record"); 2207 if (OpNum != Record.size()) 2208 return Error("Invalid RET record"); 2209 2210 I = ReturnInst::Create(Context, Op); 2211 InstructionList.push_back(I); 2212 break; 2213 } 2214 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#] 2215 if (Record.size() != 1 && Record.size() != 3) 2216 return Error("Invalid BR record"); 2217 BasicBlock *TrueDest = getBasicBlock(Record[0]); 2218 if (TrueDest == 0) 2219 return Error("Invalid BR record"); 2220 2221 if (Record.size() == 1) { 2222 I = BranchInst::Create(TrueDest); 2223 InstructionList.push_back(I); 2224 } 2225 else { 2226 BasicBlock *FalseDest = getBasicBlock(Record[1]); 2227 Value *Cond = getFnValueByID(Record[2], Type::getInt1Ty(Context)); 2228 if (FalseDest == 0 || Cond == 0) 2229 return Error("Invalid BR record"); 2230 I = BranchInst::Create(TrueDest, FalseDest, Cond); 2231 InstructionList.push_back(I); 2232 } 2233 break; 2234 } 2235 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...] 2236 // Check magic 2237 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) { 2238 // New SwitchInst format with case ranges. 2239 2240 Type *OpTy = getTypeByID(Record[1]); 2241 unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth(); 2242 2243 Value *Cond = getFnValueByID(Record[2], OpTy); 2244 BasicBlock *Default = getBasicBlock(Record[3]); 2245 if (OpTy == 0 || Cond == 0 || Default == 0) 2246 return Error("Invalid SWITCH record"); 2247 2248 unsigned NumCases = Record[4]; 2249 2250 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases); 2251 InstructionList.push_back(SI); 2252 2253 unsigned CurIdx = 5; 2254 for (unsigned i = 0; i != NumCases; ++i) { 2255 CRSBuilder CaseBuilder; 2256 unsigned NumItems = Record[CurIdx++]; 2257 for (unsigned ci = 0; ci != NumItems; ++ci) { 2258 bool isSingleNumber = Record[CurIdx++]; 2259 2260 APInt Low; 2261 unsigned ActiveWords = 1; 2262 if (ValueBitWidth > 64) 2263 ActiveWords = Record[CurIdx++]; 2264 Low = ReadWideAPInt(&Record[CurIdx], ActiveWords, ValueBitWidth); 2265 CurIdx += ActiveWords; 2266 2267 if (!isSingleNumber) { 2268 ActiveWords = 1; 2269 if (ValueBitWidth > 64) 2270 ActiveWords = Record[CurIdx++]; 2271 APInt High = 2272 ReadWideAPInt(&Record[CurIdx], ActiveWords, ValueBitWidth); 2273 CaseBuilder.add(cast<ConstantInt>(ConstantInt::get(OpTy, Low)), 2274 cast<ConstantInt>(ConstantInt::get(OpTy, High))); 2275 CurIdx += ActiveWords; 2276 } else 2277 CaseBuilder.add(cast<ConstantInt>(ConstantInt::get(OpTy, Low))); 2278 } 2279 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]); 2280 ConstantRangesSet Case = CaseBuilder.getCase(); 2281 SI->addCase(Case, DestBB); 2282 } 2283 uint16_t Hash = SI->hash(); 2284 if (Hash != (Record[0] & 0xFFFF)) 2285 return Error("Invalid SWITCH record"); 2286 I = SI; 2287 break; 2288 } 2289 2290 // Old SwitchInst format without case ranges. 2291 2292 if (Record.size() < 3 || (Record.size() & 1) == 0) 2293 return Error("Invalid SWITCH record"); 2294 Type *OpTy = getTypeByID(Record[0]); 2295 Value *Cond = getFnValueByID(Record[1], OpTy); 2296 BasicBlock *Default = getBasicBlock(Record[2]); 2297 if (OpTy == 0 || Cond == 0 || Default == 0) 2298 return Error("Invalid SWITCH record"); 2299 unsigned NumCases = (Record.size()-3)/2; 2300 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases); 2301 InstructionList.push_back(SI); 2302 for (unsigned i = 0, e = NumCases; i != e; ++i) { 2303 ConstantInt *CaseVal = 2304 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy)); 2305 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]); 2306 if (CaseVal == 0 || DestBB == 0) { 2307 delete SI; 2308 return Error("Invalid SWITCH record!"); 2309 } 2310 SI->addCase(CaseVal, DestBB); 2311 } 2312 I = SI; 2313 break; 2314 } 2315 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...] 2316 if (Record.size() < 2) 2317 return Error("Invalid INDIRECTBR record"); 2318 Type *OpTy = getTypeByID(Record[0]); 2319 Value *Address = getFnValueByID(Record[1], OpTy); 2320 if (OpTy == 0 || Address == 0) 2321 return Error("Invalid INDIRECTBR record"); 2322 unsigned NumDests = Record.size()-2; 2323 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests); 2324 InstructionList.push_back(IBI); 2325 for (unsigned i = 0, e = NumDests; i != e; ++i) { 2326 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) { 2327 IBI->addDestination(DestBB); 2328 } else { 2329 delete IBI; 2330 return Error("Invalid INDIRECTBR record!"); 2331 } 2332 } 2333 I = IBI; 2334 break; 2335 } 2336 2337 case bitc::FUNC_CODE_INST_INVOKE: { 2338 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...] 2339 if (Record.size() < 4) return Error("Invalid INVOKE record"); 2340 AttrListPtr PAL = getAttributes(Record[0]); 2341 unsigned CCInfo = Record[1]; 2342 BasicBlock *NormalBB = getBasicBlock(Record[2]); 2343 BasicBlock *UnwindBB = getBasicBlock(Record[3]); 2344 2345 unsigned OpNum = 4; 2346 Value *Callee; 2347 if (getValueTypePair(Record, OpNum, NextValueNo, Callee)) 2348 return Error("Invalid INVOKE record"); 2349 2350 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType()); 2351 FunctionType *FTy = !CalleeTy ? 0 : 2352 dyn_cast<FunctionType>(CalleeTy->getElementType()); 2353 2354 // Check that the right number of fixed parameters are here. 2355 if (FTy == 0 || NormalBB == 0 || UnwindBB == 0 || 2356 Record.size() < OpNum+FTy->getNumParams()) 2357 return Error("Invalid INVOKE record"); 2358 2359 SmallVector<Value*, 16> Ops; 2360 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) { 2361 Ops.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i))); 2362 if (Ops.back() == 0) return Error("Invalid INVOKE record"); 2363 } 2364 2365 if (!FTy->isVarArg()) { 2366 if (Record.size() != OpNum) 2367 return Error("Invalid INVOKE record"); 2368 } else { 2369 // Read type/value pairs for varargs params. 2370 while (OpNum != Record.size()) { 2371 Value *Op; 2372 if (getValueTypePair(Record, OpNum, NextValueNo, Op)) 2373 return Error("Invalid INVOKE record"); 2374 Ops.push_back(Op); 2375 } 2376 } 2377 2378 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops); 2379 InstructionList.push_back(I); 2380 cast<InvokeInst>(I)->setCallingConv( 2381 static_cast<CallingConv::ID>(CCInfo)); 2382 cast<InvokeInst>(I)->setAttributes(PAL); 2383 break; 2384 } 2385 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval] 2386 unsigned Idx = 0; 2387 Value *Val = 0; 2388 if (getValueTypePair(Record, Idx, NextValueNo, Val)) 2389 return Error("Invalid RESUME record"); 2390 I = ResumeInst::Create(Val); 2391 InstructionList.push_back(I); 2392 break; 2393 } 2394 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE 2395 I = new UnreachableInst(Context); 2396 InstructionList.push_back(I); 2397 break; 2398 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...] 2399 if (Record.size() < 1 || ((Record.size()-1)&1)) 2400 return Error("Invalid PHI record"); 2401 Type *Ty = getTypeByID(Record[0]); 2402 if (!Ty) return Error("Invalid PHI record"); 2403 2404 PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2); 2405 InstructionList.push_back(PN); 2406 2407 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) { 2408 Value *V = getFnValueByID(Record[1+i], Ty); 2409 BasicBlock *BB = getBasicBlock(Record[2+i]); 2410 if (!V || !BB) return Error("Invalid PHI record"); 2411 PN->addIncoming(V, BB); 2412 } 2413 I = PN; 2414 break; 2415 } 2416 2417 case bitc::FUNC_CODE_INST_LANDINGPAD: { 2418 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?] 2419 unsigned Idx = 0; 2420 if (Record.size() < 4) 2421 return Error("Invalid LANDINGPAD record"); 2422 Type *Ty = getTypeByID(Record[Idx++]); 2423 if (!Ty) return Error("Invalid LANDINGPAD record"); 2424 Value *PersFn = 0; 2425 if (getValueTypePair(Record, Idx, NextValueNo, PersFn)) 2426 return Error("Invalid LANDINGPAD record"); 2427 2428 bool IsCleanup = !!Record[Idx++]; 2429 unsigned NumClauses = Record[Idx++]; 2430 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, NumClauses); 2431 LP->setCleanup(IsCleanup); 2432 for (unsigned J = 0; J != NumClauses; ++J) { 2433 LandingPadInst::ClauseType CT = 2434 LandingPadInst::ClauseType(Record[Idx++]); (void)CT; 2435 Value *Val; 2436 2437 if (getValueTypePair(Record, Idx, NextValueNo, Val)) { 2438 delete LP; 2439 return Error("Invalid LANDINGPAD record"); 2440 } 2441 2442 assert((CT != LandingPadInst::Catch || 2443 !isa<ArrayType>(Val->getType())) && 2444 "Catch clause has a invalid type!"); 2445 assert((CT != LandingPadInst::Filter || 2446 isa<ArrayType>(Val->getType())) && 2447 "Filter clause has invalid type!"); 2448 LP->addClause(Val); 2449 } 2450 2451 I = LP; 2452 InstructionList.push_back(I); 2453 break; 2454 } 2455 2456 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align] 2457 if (Record.size() != 4) 2458 return Error("Invalid ALLOCA record"); 2459 PointerType *Ty = 2460 dyn_cast_or_null<PointerType>(getTypeByID(Record[0])); 2461 Type *OpTy = getTypeByID(Record[1]); 2462 Value *Size = getFnValueByID(Record[2], OpTy); 2463 unsigned Align = Record[3]; 2464 if (!Ty || !Size) return Error("Invalid ALLOCA record"); 2465 I = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1); 2466 InstructionList.push_back(I); 2467 break; 2468 } 2469 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol] 2470 unsigned OpNum = 0; 2471 Value *Op; 2472 if (getValueTypePair(Record, OpNum, NextValueNo, Op) || 2473 OpNum+2 != Record.size()) 2474 return Error("Invalid LOAD record"); 2475 2476 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1); 2477 InstructionList.push_back(I); 2478 break; 2479 } 2480 case bitc::FUNC_CODE_INST_LOADATOMIC: { 2481 // LOADATOMIC: [opty, op, align, vol, ordering, synchscope] 2482 unsigned OpNum = 0; 2483 Value *Op; 2484 if (getValueTypePair(Record, OpNum, NextValueNo, Op) || 2485 OpNum+4 != Record.size()) 2486 return Error("Invalid LOADATOMIC record"); 2487 2488 2489 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]); 2490 if (Ordering == NotAtomic || Ordering == Release || 2491 Ordering == AcquireRelease) 2492 return Error("Invalid LOADATOMIC record"); 2493 if (Ordering != NotAtomic && Record[OpNum] == 0) 2494 return Error("Invalid LOADATOMIC record"); 2495 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]); 2496 2497 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1, 2498 Ordering, SynchScope); 2499 InstructionList.push_back(I); 2500 break; 2501 } 2502 case bitc::FUNC_CODE_INST_STORE: { // STORE2:[ptrty, ptr, val, align, vol] 2503 unsigned OpNum = 0; 2504 Value *Val, *Ptr; 2505 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) || 2506 getValue(Record, OpNum, 2507 cast<PointerType>(Ptr->getType())->getElementType(), Val) || 2508 OpNum+2 != Record.size()) 2509 return Error("Invalid STORE record"); 2510 2511 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1); 2512 InstructionList.push_back(I); 2513 break; 2514 } 2515 case bitc::FUNC_CODE_INST_STOREATOMIC: { 2516 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope] 2517 unsigned OpNum = 0; 2518 Value *Val, *Ptr; 2519 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) || 2520 getValue(Record, OpNum, 2521 cast<PointerType>(Ptr->getType())->getElementType(), Val) || 2522 OpNum+4 != Record.size()) 2523 return Error("Invalid STOREATOMIC record"); 2524 2525 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]); 2526 if (Ordering == NotAtomic || Ordering == Acquire || 2527 Ordering == AcquireRelease) 2528 return Error("Invalid STOREATOMIC record"); 2529 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]); 2530 if (Ordering != NotAtomic && Record[OpNum] == 0) 2531 return Error("Invalid STOREATOMIC record"); 2532 2533 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1, 2534 Ordering, SynchScope); 2535 InstructionList.push_back(I); 2536 break; 2537 } 2538 case bitc::FUNC_CODE_INST_CMPXCHG: { 2539 // CMPXCHG:[ptrty, ptr, cmp, new, vol, ordering, synchscope] 2540 unsigned OpNum = 0; 2541 Value *Ptr, *Cmp, *New; 2542 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) || 2543 getValue(Record, OpNum, 2544 cast<PointerType>(Ptr->getType())->getElementType(), Cmp) || 2545 getValue(Record, OpNum, 2546 cast<PointerType>(Ptr->getType())->getElementType(), New) || 2547 OpNum+3 != Record.size()) 2548 return Error("Invalid CMPXCHG record"); 2549 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+1]); 2550 if (Ordering == NotAtomic || Ordering == Unordered) 2551 return Error("Invalid CMPXCHG record"); 2552 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+2]); 2553 I = new AtomicCmpXchgInst(Ptr, Cmp, New, Ordering, SynchScope); 2554 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]); 2555 InstructionList.push_back(I); 2556 break; 2557 } 2558 case bitc::FUNC_CODE_INST_ATOMICRMW: { 2559 // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope] 2560 unsigned OpNum = 0; 2561 Value *Ptr, *Val; 2562 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) || 2563 getValue(Record, OpNum, 2564 cast<PointerType>(Ptr->getType())->getElementType(), Val) || 2565 OpNum+4 != Record.size()) 2566 return Error("Invalid ATOMICRMW record"); 2567 AtomicRMWInst::BinOp Operation = GetDecodedRMWOperation(Record[OpNum]); 2568 if (Operation < AtomicRMWInst::FIRST_BINOP || 2569 Operation > AtomicRMWInst::LAST_BINOP) 2570 return Error("Invalid ATOMICRMW record"); 2571 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]); 2572 if (Ordering == NotAtomic || Ordering == Unordered) 2573 return Error("Invalid ATOMICRMW record"); 2574 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]); 2575 I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope); 2576 cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]); 2577 InstructionList.push_back(I); 2578 break; 2579 } 2580 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope] 2581 if (2 != Record.size()) 2582 return Error("Invalid FENCE record"); 2583 AtomicOrdering Ordering = GetDecodedOrdering(Record[0]); 2584 if (Ordering == NotAtomic || Ordering == Unordered || 2585 Ordering == Monotonic) 2586 return Error("Invalid FENCE record"); 2587 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[1]); 2588 I = new FenceInst(Context, Ordering, SynchScope); 2589 InstructionList.push_back(I); 2590 break; 2591 } 2592 case bitc::FUNC_CODE_INST_CALL: { 2593 // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...] 2594 if (Record.size() < 3) 2595 return Error("Invalid CALL record"); 2596 2597 AttrListPtr PAL = getAttributes(Record[0]); 2598 unsigned CCInfo = Record[1]; 2599 2600 unsigned OpNum = 2; 2601 Value *Callee; 2602 if (getValueTypePair(Record, OpNum, NextValueNo, Callee)) 2603 return Error("Invalid CALL record"); 2604 2605 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType()); 2606 FunctionType *FTy = 0; 2607 if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType()); 2608 if (!FTy || Record.size() < FTy->getNumParams()+OpNum) 2609 return Error("Invalid CALL record"); 2610 2611 SmallVector<Value*, 16> Args; 2612 // Read the fixed params. 2613 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) { 2614 if (FTy->getParamType(i)->isLabelTy()) 2615 Args.push_back(getBasicBlock(Record[OpNum])); 2616 else 2617 Args.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i))); 2618 if (Args.back() == 0) return Error("Invalid CALL record"); 2619 } 2620 2621 // Read type/value pairs for varargs params. 2622 if (!FTy->isVarArg()) { 2623 if (OpNum != Record.size()) 2624 return Error("Invalid CALL record"); 2625 } else { 2626 while (OpNum != Record.size()) { 2627 Value *Op; 2628 if (getValueTypePair(Record, OpNum, NextValueNo, Op)) 2629 return Error("Invalid CALL record"); 2630 Args.push_back(Op); 2631 } 2632 } 2633 2634 I = CallInst::Create(Callee, Args); 2635 InstructionList.push_back(I); 2636 cast<CallInst>(I)->setCallingConv( 2637 static_cast<CallingConv::ID>(CCInfo>>1)); 2638 cast<CallInst>(I)->setTailCall(CCInfo & 1); 2639 cast<CallInst>(I)->setAttributes(PAL); 2640 break; 2641 } 2642 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty] 2643 if (Record.size() < 3) 2644 return Error("Invalid VAARG record"); 2645 Type *OpTy = getTypeByID(Record[0]); 2646 Value *Op = getFnValueByID(Record[1], OpTy); 2647 Type *ResTy = getTypeByID(Record[2]); 2648 if (!OpTy || !Op || !ResTy) 2649 return Error("Invalid VAARG record"); 2650 I = new VAArgInst(Op, ResTy); 2651 InstructionList.push_back(I); 2652 break; 2653 } 2654 } 2655 2656 // Add instruction to end of current BB. If there is no current BB, reject 2657 // this file. 2658 if (CurBB == 0) { 2659 delete I; 2660 return Error("Invalid instruction with no BB"); 2661 } 2662 CurBB->getInstList().push_back(I); 2663 2664 // If this was a terminator instruction, move to the next block. 2665 if (isa<TerminatorInst>(I)) { 2666 ++CurBBNo; 2667 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : 0; 2668 } 2669 2670 // Non-void values get registered in the value table for future use. 2671 if (I && !I->getType()->isVoidTy()) 2672 ValueList.AssignValue(I, NextValueNo++); 2673 } 2674 2675 // Check the function list for unresolved values. 2676 if (Argument *A = dyn_cast<Argument>(ValueList.back())) { 2677 if (A->getParent() == 0) { 2678 // We found at least one unresolved value. Nuke them all to avoid leaks. 2679 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){ 2680 if ((A = dyn_cast<Argument>(ValueList[i])) && A->getParent() == 0) { 2681 A->replaceAllUsesWith(UndefValue::get(A->getType())); 2682 delete A; 2683 } 2684 } 2685 return Error("Never resolved value found in function!"); 2686 } 2687 } 2688 2689 // FIXME: Check for unresolved forward-declared metadata references 2690 // and clean up leaks. 2691 2692 // See if anything took the address of blocks in this function. If so, 2693 // resolve them now. 2694 DenseMap<Function*, std::vector<BlockAddrRefTy> >::iterator BAFRI = 2695 BlockAddrFwdRefs.find(F); 2696 if (BAFRI != BlockAddrFwdRefs.end()) { 2697 std::vector<BlockAddrRefTy> &RefList = BAFRI->second; 2698 for (unsigned i = 0, e = RefList.size(); i != e; ++i) { 2699 unsigned BlockIdx = RefList[i].first; 2700 if (BlockIdx >= FunctionBBs.size()) 2701 return Error("Invalid blockaddress block #"); 2702 2703 GlobalVariable *FwdRef = RefList[i].second; 2704 FwdRef->replaceAllUsesWith(BlockAddress::get(F, FunctionBBs[BlockIdx])); 2705 FwdRef->eraseFromParent(); 2706 } 2707 2708 BlockAddrFwdRefs.erase(BAFRI); 2709 } 2710 2711 // Trim the value list down to the size it was before we parsed this function. 2712 ValueList.shrinkTo(ModuleValueListSize); 2713 MDValueList.shrinkTo(ModuleMDValueListSize); 2714 std::vector<BasicBlock*>().swap(FunctionBBs); 2715 return false; 2716} 2717 2718/// FindFunctionInStream - Find the function body in the bitcode stream 2719bool BitcodeReader::FindFunctionInStream(Function *F, 2720 DenseMap<Function*, uint64_t>::iterator DeferredFunctionInfoIterator) { 2721 while (DeferredFunctionInfoIterator->second == 0) { 2722 if (Stream.AtEndOfStream()) 2723 return Error("Could not find Function in stream"); 2724 // ParseModule will parse the next body in the stream and set its 2725 // position in the DeferredFunctionInfo map. 2726 if (ParseModule(true)) return true; 2727 } 2728 return false; 2729} 2730 2731//===----------------------------------------------------------------------===// 2732// GVMaterializer implementation 2733//===----------------------------------------------------------------------===// 2734 2735 2736bool BitcodeReader::isMaterializable(const GlobalValue *GV) const { 2737 if (const Function *F = dyn_cast<Function>(GV)) { 2738 return F->isDeclaration() && 2739 DeferredFunctionInfo.count(const_cast<Function*>(F)); 2740 } 2741 return false; 2742} 2743 2744bool BitcodeReader::Materialize(GlobalValue *GV, std::string *ErrInfo) { 2745 Function *F = dyn_cast<Function>(GV); 2746 // If it's not a function or is already material, ignore the request. 2747 if (!F || !F->isMaterializable()) return false; 2748 2749 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F); 2750 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!"); 2751 // If its position is recorded as 0, its body is somewhere in the stream 2752 // but we haven't seen it yet. 2753 if (DFII->second == 0) 2754 if (LazyStreamer && FindFunctionInStream(F, DFII)) return true; 2755 2756 // Move the bit stream to the saved position of the deferred function body. 2757 Stream.JumpToBit(DFII->second); 2758 2759 if (ParseFunctionBody(F)) { 2760 if (ErrInfo) *ErrInfo = ErrorString; 2761 return true; 2762 } 2763 2764 // Upgrade any old intrinsic calls in the function. 2765 for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(), 2766 E = UpgradedIntrinsics.end(); I != E; ++I) { 2767 if (I->first != I->second) { 2768 for (Value::use_iterator UI = I->first->use_begin(), 2769 UE = I->first->use_end(); UI != UE; ) { 2770 if (CallInst* CI = dyn_cast<CallInst>(*UI++)) 2771 UpgradeIntrinsicCall(CI, I->second); 2772 } 2773 } 2774 } 2775 2776 return false; 2777} 2778 2779bool BitcodeReader::isDematerializable(const GlobalValue *GV) const { 2780 const Function *F = dyn_cast<Function>(GV); 2781 if (!F || F->isDeclaration()) 2782 return false; 2783 return DeferredFunctionInfo.count(const_cast<Function*>(F)); 2784} 2785 2786void BitcodeReader::Dematerialize(GlobalValue *GV) { 2787 Function *F = dyn_cast<Function>(GV); 2788 // If this function isn't dematerializable, this is a noop. 2789 if (!F || !isDematerializable(F)) 2790 return; 2791 2792 assert(DeferredFunctionInfo.count(F) && "No info to read function later?"); 2793 2794 // Just forget the function body, we can remat it later. 2795 F->deleteBody(); 2796} 2797 2798 2799bool BitcodeReader::MaterializeModule(Module *M, std::string *ErrInfo) { 2800 assert(M == TheModule && 2801 "Can only Materialize the Module this BitcodeReader is attached to."); 2802 // Iterate over the module, deserializing any functions that are still on 2803 // disk. 2804 for (Module::iterator F = TheModule->begin(), E = TheModule->end(); 2805 F != E; ++F) 2806 if (F->isMaterializable() && 2807 Materialize(F, ErrInfo)) 2808 return true; 2809 2810 // At this point, if there are any function bodies, the current bit is 2811 // pointing to the END_BLOCK record after them. Now make sure the rest 2812 // of the bits in the module have been read. 2813 if (NextUnreadBit) 2814 ParseModule(true); 2815 2816 // Upgrade any intrinsic calls that slipped through (should not happen!) and 2817 // delete the old functions to clean up. We can't do this unless the entire 2818 // module is materialized because there could always be another function body 2819 // with calls to the old function. 2820 for (std::vector<std::pair<Function*, Function*> >::iterator I = 2821 UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) { 2822 if (I->first != I->second) { 2823 for (Value::use_iterator UI = I->first->use_begin(), 2824 UE = I->first->use_end(); UI != UE; ) { 2825 if (CallInst* CI = dyn_cast<CallInst>(*UI++)) 2826 UpgradeIntrinsicCall(CI, I->second); 2827 } 2828 if (!I->first->use_empty()) 2829 I->first->replaceAllUsesWith(I->second); 2830 I->first->eraseFromParent(); 2831 } 2832 } 2833 std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics); 2834 2835 return false; 2836} 2837 2838bool BitcodeReader::InitStream() { 2839 if (LazyStreamer) return InitLazyStream(); 2840 return InitStreamFromBuffer(); 2841} 2842 2843bool BitcodeReader::InitStreamFromBuffer() { 2844 const unsigned char *BufPtr = (unsigned char *)Buffer->getBufferStart(); 2845 const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize(); 2846 2847 if (Buffer->getBufferSize() & 3) { 2848 if (!isRawBitcode(BufPtr, BufEnd) && !isBitcodeWrapper(BufPtr, BufEnd)) 2849 return Error("Invalid bitcode signature"); 2850 else 2851 return Error("Bitcode stream should be a multiple of 4 bytes in length"); 2852 } 2853 2854 // If we have a wrapper header, parse it and ignore the non-bc file contents. 2855 // The magic number is 0x0B17C0DE stored in little endian. 2856 if (isBitcodeWrapper(BufPtr, BufEnd)) 2857 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true)) 2858 return Error("Invalid bitcode wrapper header"); 2859 2860 StreamFile.reset(new BitstreamReader(BufPtr, BufEnd)); 2861 Stream.init(*StreamFile); 2862 2863 return false; 2864} 2865 2866bool BitcodeReader::InitLazyStream() { 2867 // Check and strip off the bitcode wrapper; BitstreamReader expects never to 2868 // see it. 2869 StreamingMemoryObject *Bytes = new StreamingMemoryObject(LazyStreamer); 2870 StreamFile.reset(new BitstreamReader(Bytes)); 2871 Stream.init(*StreamFile); 2872 2873 unsigned char buf[16]; 2874 if (Bytes->readBytes(0, 16, buf, NULL) == -1) 2875 return Error("Bitcode stream must be at least 16 bytes in length"); 2876 2877 if (!isBitcode(buf, buf + 16)) 2878 return Error("Invalid bitcode signature"); 2879 2880 if (isBitcodeWrapper(buf, buf + 4)) { 2881 const unsigned char *bitcodeStart = buf; 2882 const unsigned char *bitcodeEnd = buf + 16; 2883 SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false); 2884 Bytes->dropLeadingBytes(bitcodeStart - buf); 2885 Bytes->setKnownObjectSize(bitcodeEnd - bitcodeStart); 2886 } 2887 return false; 2888} 2889 2890//===----------------------------------------------------------------------===// 2891// External interface 2892//===----------------------------------------------------------------------===// 2893 2894/// getLazyBitcodeModule - lazy function-at-a-time loading from a file. 2895/// 2896Module *llvm::getLazyBitcodeModule(MemoryBuffer *Buffer, 2897 LLVMContext& Context, 2898 std::string *ErrMsg) { 2899 Module *M = new Module(Buffer->getBufferIdentifier(), Context); 2900 BitcodeReader *R = new BitcodeReader(Buffer, Context); 2901 M->setMaterializer(R); 2902 if (R->ParseBitcodeInto(M)) { 2903 if (ErrMsg) 2904 *ErrMsg = R->getErrorString(); 2905 2906 delete M; // Also deletes R. 2907 return 0; 2908 } 2909 // Have the BitcodeReader dtor delete 'Buffer'. 2910 R->setBufferOwned(true); 2911 2912 R->materializeForwardReferencedFunctions(); 2913 2914 return M; 2915} 2916 2917 2918Module *llvm::getStreamedBitcodeModule(const std::string &name, 2919 DataStreamer *streamer, 2920 LLVMContext &Context, 2921 std::string *ErrMsg) { 2922 Module *M = new Module(name, Context); 2923 BitcodeReader *R = new BitcodeReader(streamer, Context); 2924 M->setMaterializer(R); 2925 if (R->ParseBitcodeInto(M)) { 2926 if (ErrMsg) 2927 *ErrMsg = R->getErrorString(); 2928 delete M; // Also deletes R. 2929 return 0; 2930 } 2931 R->setBufferOwned(false); // no buffer to delete 2932 return M; 2933} 2934 2935/// ParseBitcodeFile - Read the specified bitcode file, returning the module. 2936/// If an error occurs, return null and fill in *ErrMsg if non-null. 2937Module *llvm::ParseBitcodeFile(MemoryBuffer *Buffer, LLVMContext& Context, 2938 std::string *ErrMsg){ 2939 Module *M = getLazyBitcodeModule(Buffer, Context, ErrMsg); 2940 if (!M) return 0; 2941 2942 // Don't let the BitcodeReader dtor delete 'Buffer', regardless of whether 2943 // there was an error. 2944 static_cast<BitcodeReader*>(M->getMaterializer())->setBufferOwned(false); 2945 2946 // Read in the entire module, and destroy the BitcodeReader. 2947 if (M->MaterializeAllPermanently(ErrMsg)) { 2948 delete M; 2949 return 0; 2950 } 2951 2952 // TODO: Restore the use-lists to the in-memory state when the bitcode was 2953 // written. We must defer until the Module has been fully materialized. 2954 2955 return M; 2956} 2957 2958std::string llvm::getBitcodeTargetTriple(MemoryBuffer *Buffer, 2959 LLVMContext& Context, 2960 std::string *ErrMsg) { 2961 BitcodeReader *R = new BitcodeReader(Buffer, Context); 2962 // Don't let the BitcodeReader dtor delete 'Buffer'. 2963 R->setBufferOwned(false); 2964 2965 std::string Triple(""); 2966 if (R->ParseTriple(Triple)) 2967 if (ErrMsg) 2968 *ErrMsg = R->getErrorString(); 2969 2970 delete R; 2971 return Triple; 2972} 2973