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