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