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