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