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