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