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