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