1 //===- BitcodeReader.cpp - Internal BitcodeReader implementation ----------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This header defines the BitcodeReader class. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "llvm/Bitcode/ReaderWriter.h" 15 #include "BitcodeReader.h" 16 #include "llvm/Constants.h" 17 #include "llvm/DerivedTypes.h" 18 #include "llvm/InlineAsm.h" 19 #include "llvm/Instructions.h" 20 #include "llvm/LLVMContext.h" 21 #include "llvm/MDNode.h" 22 #include "llvm/Module.h" 23 #include "llvm/AutoUpgrade.h" 24 #include "llvm/ADT/SmallString.h" 25 #include "llvm/ADT/SmallVector.h" 26 #include "llvm/Support/MathExtras.h" 27 #include "llvm/Support/MemoryBuffer.h" 28 #include "llvm/OperandTraits.h" 29 using namespace llvm; 30 31 void BitcodeReader::FreeState() { 32 delete Buffer; 33 Buffer = 0; 34 std::vector<PATypeHolder>().swap(TypeList); 35 ValueList.clear(); 36 37 std::vector<AttrListPtr>().swap(MAttributes); 38 std::vector<BasicBlock*>().swap(FunctionBBs); 39 std::vector<Function*>().swap(FunctionsWithBodies); 40 DeferredFunctionInfo.clear(); 41 } 42 43 //===----------------------------------------------------------------------===// 44 // Helper functions to implement forward reference resolution, etc. 45 //===----------------------------------------------------------------------===// 46 47 /// ConvertToString - Convert a string from a record into an std::string, return 48 /// true on failure. 49 template<typename StrTy> 50 static bool ConvertToString(SmallVector<uint64_t, 64> &Record, unsigned Idx, 51 StrTy &Result) { 52 if (Idx > Record.size()) 53 return true; 54 55 for (unsigned i = Idx, e = Record.size(); i != e; ++i) 56 Result += (char)Record[i]; 57 return false; 58 } 59 60 static GlobalValue::LinkageTypes GetDecodedLinkage(unsigned Val) { 61 switch (Val) { 62 default: // Map unknown/new linkages to external 63 case 0: return GlobalValue::ExternalLinkage; 64 case 1: return GlobalValue::WeakAnyLinkage; 65 case 2: return GlobalValue::AppendingLinkage; 66 case 3: return GlobalValue::InternalLinkage; 67 case 4: return GlobalValue::LinkOnceAnyLinkage; 68 case 5: return GlobalValue::DLLImportLinkage; 69 case 6: return GlobalValue::DLLExportLinkage; 70 case 7: return GlobalValue::ExternalWeakLinkage; 71 case 8: return GlobalValue::CommonLinkage; 72 case 9: return GlobalValue::PrivateLinkage; 73 case 10: return GlobalValue::WeakODRLinkage; 74 case 11: return GlobalValue::LinkOnceODRLinkage; 75 case 12: return GlobalValue::AvailableExternallyLinkage; 76 case 13: return GlobalValue::LinkerPrivateLinkage; 77 } 78 } 79 80 static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned Val) { 81 switch (Val) { 82 default: // Map unknown visibilities to default. 83 case 0: return GlobalValue::DefaultVisibility; 84 case 1: return GlobalValue::HiddenVisibility; 85 case 2: return GlobalValue::ProtectedVisibility; 86 } 87 } 88 89 static int GetDecodedCastOpcode(unsigned Val) { 90 switch (Val) { 91 default: return -1; 92 case bitc::CAST_TRUNC : return Instruction::Trunc; 93 case bitc::CAST_ZEXT : return Instruction::ZExt; 94 case bitc::CAST_SEXT : return Instruction::SExt; 95 case bitc::CAST_FPTOUI : return Instruction::FPToUI; 96 case bitc::CAST_FPTOSI : return Instruction::FPToSI; 97 case bitc::CAST_UITOFP : return Instruction::UIToFP; 98 case bitc::CAST_SITOFP : return Instruction::SIToFP; 99 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc; 100 case bitc::CAST_FPEXT : return Instruction::FPExt; 101 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt; 102 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr; 103 case bitc::CAST_BITCAST : return Instruction::BitCast; 104 } 105 } 106 static int GetDecodedBinaryOpcode(unsigned Val, const Type *Ty) { 107 switch (Val) { 108 default: return -1; 109 case bitc::BINOP_ADD: 110 return Ty->isFPOrFPVector() ? Instruction::FAdd : Instruction::Add; 111 case bitc::BINOP_SUB: 112 return Ty->isFPOrFPVector() ? Instruction::FSub : Instruction::Sub; 113 case bitc::BINOP_MUL: 114 return Ty->isFPOrFPVector() ? Instruction::FMul : Instruction::Mul; 115 case bitc::BINOP_UDIV: return Instruction::UDiv; 116 case bitc::BINOP_SDIV: 117 return Ty->isFPOrFPVector() ? Instruction::FDiv : Instruction::SDiv; 118 case bitc::BINOP_UREM: return Instruction::URem; 119 case bitc::BINOP_SREM: 120 return Ty->isFPOrFPVector() ? Instruction::FRem : Instruction::SRem; 121 case bitc::BINOP_SHL: return Instruction::Shl; 122 case bitc::BINOP_LSHR: return Instruction::LShr; 123 case bitc::BINOP_ASHR: return Instruction::AShr; 124 case bitc::BINOP_AND: return Instruction::And; 125 case bitc::BINOP_OR: return Instruction::Or; 126 case bitc::BINOP_XOR: return Instruction::Xor; 127 } 128 } 129 130 namespace llvm { 131 namespace { 132 /// @brief A class for maintaining the slot number definition 133 /// as a placeholder for the actual definition for forward constants defs. 134 class ConstantPlaceHolder : public ConstantExpr { 135 ConstantPlaceHolder(); // DO NOT IMPLEMENT 136 void operator=(const ConstantPlaceHolder &); // DO NOT IMPLEMENT 137 public: 138 // allocate space for exactly one operand 139 void *operator new(size_t s) { 140 return User::operator new(s, 1); 141 } 142 explicit ConstantPlaceHolder(const Type *Ty, LLVMContext& Context) 143 : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) { 144 Op<0>() = Context.getUndef(Type::Int32Ty); 145 } 146 147 /// @brief Methods to support type inquiry through isa, cast, and dyn_cast. 148 static inline bool classof(const ConstantPlaceHolder *) { return true; } 149 static bool classof(const Value *V) { 150 return isa<ConstantExpr>(V) && 151 cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1; 152 } 153 154 155 /// Provide fast operand accessors 156 //DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value); 157 }; 158 } 159 160 // FIXME: can we inherit this from ConstantExpr? 161 template <> 162 struct OperandTraits<ConstantPlaceHolder> : FixedNumOperandTraits<1> { 163 }; 164 } 165 166 167 void BitcodeReaderValueList::AssignValue(Value *V, unsigned Idx) { 168 if (Idx == size()) { 169 push_back(V); 170 return; 171 } 172 173 if (Idx >= size()) 174 resize(Idx+1); 175 176 WeakVH &OldV = ValuePtrs[Idx]; 177 if (OldV == 0) { 178 OldV = V; 179 return; 180 } 181 182 // Handle constants and non-constants (e.g. instrs) differently for 183 // efficiency. 184 if (Constant *PHC = dyn_cast<Constant>(&*OldV)) { 185 ResolveConstants.push_back(std::make_pair(PHC, Idx)); 186 OldV = V; 187 } else { 188 // If there was a forward reference to this value, replace it. 189 Value *PrevVal = OldV; 190 OldV->replaceAllUsesWith(V); 191 delete PrevVal; 192 } 193 } 194 195 196 Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx, 197 const Type *Ty) { 198 if (Idx >= size()) 199 resize(Idx + 1); 200 201 if (Value *V = ValuePtrs[Idx]) { 202 assert(Ty == V->getType() && "Type mismatch in constant table!"); 203 return cast<Constant>(V); 204 } 205 206 // Create and return a placeholder, which will later be RAUW'd. 207 Constant *C = new ConstantPlaceHolder(Ty, Context); 208 ValuePtrs[Idx] = C; 209 return C; 210 } 211 212 Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, const Type *Ty) { 213 if (Idx >= size()) 214 resize(Idx + 1); 215 216 if (Value *V = ValuePtrs[Idx]) { 217 assert((Ty == 0 || Ty == V->getType()) && "Type mismatch in value table!"); 218 return V; 219 } 220 221 // No type specified, must be invalid reference. 222 if (Ty == 0) return 0; 223 224 // Create and return a placeholder, which will later be RAUW'd. 225 Value *V = new Argument(Ty); 226 ValuePtrs[Idx] = V; 227 return V; 228 } 229 230 /// ResolveConstantForwardRefs - Once all constants are read, this method bulk 231 /// resolves any forward references. The idea behind this is that we sometimes 232 /// get constants (such as large arrays) which reference *many* forward ref 233 /// constants. Replacing each of these causes a lot of thrashing when 234 /// building/reuniquing the constant. Instead of doing this, we look at all the 235 /// uses and rewrite all the place holders at once for any constant that uses 236 /// a placeholder. 237 void BitcodeReaderValueList::ResolveConstantForwardRefs() { 238 // Sort the values by-pointer so that they are efficient to look up with a 239 // binary search. 240 std::sort(ResolveConstants.begin(), ResolveConstants.end()); 241 242 SmallVector<Constant*, 64> NewOps; 243 244 while (!ResolveConstants.empty()) { 245 Value *RealVal = operator[](ResolveConstants.back().second); 246 Constant *Placeholder = ResolveConstants.back().first; 247 ResolveConstants.pop_back(); 248 249 // Loop over all users of the placeholder, updating them to reference the 250 // new value. If they reference more than one placeholder, update them all 251 // at once. 252 while (!Placeholder->use_empty()) { 253 Value::use_iterator UI = Placeholder->use_begin(); 254 255 // If the using object isn't uniqued, just update the operands. This 256 // handles instructions and initializers for global variables. 257 if (!isa<Constant>(*UI) || isa<GlobalValue>(*UI)) { 258 UI.getUse().set(RealVal); 259 continue; 260 } 261 262 // Otherwise, we have a constant that uses the placeholder. Replace that 263 // constant with a new constant that has *all* placeholder uses updated. 264 Constant *UserC = cast<Constant>(*UI); 265 for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end(); 266 I != E; ++I) { 267 Value *NewOp; 268 if (!isa<ConstantPlaceHolder>(*I)) { 269 // Not a placeholder reference. 270 NewOp = *I; 271 } else if (*I == Placeholder) { 272 // Common case is that it just references this one placeholder. 273 NewOp = RealVal; 274 } else { 275 // Otherwise, look up the placeholder in ResolveConstants. 276 ResolveConstantsTy::iterator It = 277 std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(), 278 std::pair<Constant*, unsigned>(cast<Constant>(*I), 279 0)); 280 assert(It != ResolveConstants.end() && It->first == *I); 281 NewOp = operator[](It->second); 282 } 283 284 NewOps.push_back(cast<Constant>(NewOp)); 285 } 286 287 // Make the new constant. 288 Constant *NewC; 289 if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) { 290 NewC = Context.getConstantArray(UserCA->getType(), &NewOps[0], 291 NewOps.size()); 292 } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) { 293 NewC = Context.getConstantStruct(&NewOps[0], NewOps.size(), 294 UserCS->getType()->isPacked()); 295 } else if (isa<ConstantVector>(UserC)) { 296 NewC = Context.getConstantVector(&NewOps[0], NewOps.size()); 297 } else { 298 assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr."); 299 NewC = cast<ConstantExpr>(UserC)->getWithOperands(&NewOps[0], 300 NewOps.size()); 301 } 302 303 UserC->replaceAllUsesWith(NewC); 304 UserC->destroyConstant(); 305 NewOps.clear(); 306 } 307 308 // Update all ValueHandles, they should be the only users at this point. 309 Placeholder->replaceAllUsesWith(RealVal); 310 delete Placeholder; 311 } 312 } 313 314 315 const Type *BitcodeReader::getTypeByID(unsigned ID, bool isTypeTable) { 316 // If the TypeID is in range, return it. 317 if (ID < TypeList.size()) 318 return TypeList[ID].get(); 319 if (!isTypeTable) return 0; 320 321 // The type table allows forward references. Push as many Opaque types as 322 // needed to get up to ID. 323 while (TypeList.size() <= ID) 324 TypeList.push_back(Context.getOpaqueType()); 325 return TypeList.back().get(); 326 } 327 328 //===----------------------------------------------------------------------===// 329 // Functions for parsing blocks from the bitcode file 330 //===----------------------------------------------------------------------===// 331 332 bool BitcodeReader::ParseAttributeBlock() { 333 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID)) 334 return Error("Malformed block record"); 335 336 if (!MAttributes.empty()) 337 return Error("Multiple PARAMATTR blocks found!"); 338 339 SmallVector<uint64_t, 64> Record; 340 341 SmallVector<AttributeWithIndex, 8> Attrs; 342 343 // Read all the records. 344 while (1) { 345 unsigned Code = Stream.ReadCode(); 346 if (Code == bitc::END_BLOCK) { 347 if (Stream.ReadBlockEnd()) 348 return Error("Error at end of PARAMATTR block"); 349 return false; 350 } 351 352 if (Code == bitc::ENTER_SUBBLOCK) { 353 // No known subblocks, always skip them. 354 Stream.ReadSubBlockID(); 355 if (Stream.SkipBlock()) 356 return Error("Malformed block record"); 357 continue; 358 } 359 360 if (Code == bitc::DEFINE_ABBREV) { 361 Stream.ReadAbbrevRecord(); 362 continue; 363 } 364 365 // Read a record. 366 Record.clear(); 367 switch (Stream.ReadRecord(Code, Record)) { 368 default: // Default behavior: ignore. 369 break; 370 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [paramidx0, attr0, ...] 371 if (Record.size() & 1) 372 return Error("Invalid ENTRY record"); 373 374 // FIXME : Remove this autoupgrade code in LLVM 3.0. 375 // If Function attributes are using index 0 then transfer them 376 // to index ~0. Index 0 is used for return value attributes but used to be 377 // used for function attributes. 378 Attributes RetAttribute = Attribute::None; 379 Attributes FnAttribute = Attribute::None; 380 for (unsigned i = 0, e = Record.size(); i != e; i += 2) { 381 // FIXME: remove in LLVM 3.0 382 // The alignment is stored as a 16-bit raw value from bits 31--16. 383 // We shift the bits above 31 down by 11 bits. 384 385 unsigned Alignment = (Record[i+1] & (0xffffull << 16)) >> 16; 386 if (Alignment && !isPowerOf2_32(Alignment)) 387 return Error("Alignment is not a power of two."); 388 389 Attributes ReconstitutedAttr = Record[i+1] & 0xffff; 390 if (Alignment) 391 ReconstitutedAttr |= Attribute::constructAlignmentFromInt(Alignment); 392 ReconstitutedAttr |= (Record[i+1] & (0xffffull << 32)) >> 11; 393 Record[i+1] = ReconstitutedAttr; 394 395 if (Record[i] == 0) 396 RetAttribute = Record[i+1]; 397 else if (Record[i] == ~0U) 398 FnAttribute = Record[i+1]; 399 } 400 401 unsigned OldRetAttrs = (Attribute::NoUnwind|Attribute::NoReturn| 402 Attribute::ReadOnly|Attribute::ReadNone); 403 404 if (FnAttribute == Attribute::None && RetAttribute != Attribute::None && 405 (RetAttribute & OldRetAttrs) != 0) { 406 if (FnAttribute == Attribute::None) { // add a slot so they get added. 407 Record.push_back(~0U); 408 Record.push_back(0); 409 } 410 411 FnAttribute |= RetAttribute & OldRetAttrs; 412 RetAttribute &= ~OldRetAttrs; 413 } 414 415 for (unsigned i = 0, e = Record.size(); i != e; i += 2) { 416 if (Record[i] == 0) { 417 if (RetAttribute != Attribute::None) 418 Attrs.push_back(AttributeWithIndex::get(0, RetAttribute)); 419 } else if (Record[i] == ~0U) { 420 if (FnAttribute != Attribute::None) 421 Attrs.push_back(AttributeWithIndex::get(~0U, FnAttribute)); 422 } else if (Record[i+1] != Attribute::None) 423 Attrs.push_back(AttributeWithIndex::get(Record[i], Record[i+1])); 424 } 425 426 MAttributes.push_back(AttrListPtr::get(Attrs.begin(), Attrs.end())); 427 Attrs.clear(); 428 break; 429 } 430 } 431 } 432 } 433 434 435 bool BitcodeReader::ParseTypeTable() { 436 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID)) 437 return Error("Malformed block record"); 438 439 if (!TypeList.empty()) 440 return Error("Multiple TYPE_BLOCKs found!"); 441 442 SmallVector<uint64_t, 64> Record; 443 unsigned NumRecords = 0; 444 445 // Read all the records for this type table. 446 while (1) { 447 unsigned Code = Stream.ReadCode(); 448 if (Code == bitc::END_BLOCK) { 449 if (NumRecords != TypeList.size()) 450 return Error("Invalid type forward reference in TYPE_BLOCK"); 451 if (Stream.ReadBlockEnd()) 452 return Error("Error at end of type table block"); 453 return false; 454 } 455 456 if (Code == bitc::ENTER_SUBBLOCK) { 457 // No known subblocks, always skip them. 458 Stream.ReadSubBlockID(); 459 if (Stream.SkipBlock()) 460 return Error("Malformed block record"); 461 continue; 462 } 463 464 if (Code == bitc::DEFINE_ABBREV) { 465 Stream.ReadAbbrevRecord(); 466 continue; 467 } 468 469 // Read a record. 470 Record.clear(); 471 const Type *ResultTy = 0; 472 switch (Stream.ReadRecord(Code, Record)) { 473 default: // Default behavior: unknown type. 474 ResultTy = 0; 475 break; 476 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries] 477 // TYPE_CODE_NUMENTRY contains a count of the number of types in the 478 // type list. This allows us to reserve space. 479 if (Record.size() < 1) 480 return Error("Invalid TYPE_CODE_NUMENTRY record"); 481 TypeList.reserve(Record[0]); 482 continue; 483 case bitc::TYPE_CODE_VOID: // VOID 484 ResultTy = Type::VoidTy; 485 break; 486 case bitc::TYPE_CODE_FLOAT: // FLOAT 487 ResultTy = Type::FloatTy; 488 break; 489 case bitc::TYPE_CODE_DOUBLE: // DOUBLE 490 ResultTy = Type::DoubleTy; 491 break; 492 case bitc::TYPE_CODE_X86_FP80: // X86_FP80 493 ResultTy = Type::X86_FP80Ty; 494 break; 495 case bitc::TYPE_CODE_FP128: // FP128 496 ResultTy = Type::FP128Ty; 497 break; 498 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128 499 ResultTy = Type::PPC_FP128Ty; 500 break; 501 case bitc::TYPE_CODE_LABEL: // LABEL 502 ResultTy = Type::LabelTy; 503 break; 504 case bitc::TYPE_CODE_OPAQUE: // OPAQUE 505 ResultTy = 0; 506 break; 507 case bitc::TYPE_CODE_METADATA: // METADATA 508 ResultTy = Type::MetadataTy; 509 break; 510 case bitc::TYPE_CODE_INTEGER: // INTEGER: [width] 511 if (Record.size() < 1) 512 return Error("Invalid Integer type record"); 513 514 ResultTy = Context.getIntegerType(Record[0]); 515 break; 516 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or 517 // [pointee type, address space] 518 if (Record.size() < 1) 519 return Error("Invalid POINTER type record"); 520 unsigned AddressSpace = 0; 521 if (Record.size() == 2) 522 AddressSpace = Record[1]; 523 ResultTy = Context.getPointerType(getTypeByID(Record[0], true), 524 AddressSpace); 525 break; 526 } 527 case bitc::TYPE_CODE_FUNCTION: { 528 // FIXME: attrid is dead, remove it in LLVM 3.0 529 // FUNCTION: [vararg, attrid, retty, paramty x N] 530 if (Record.size() < 3) 531 return Error("Invalid FUNCTION type record"); 532 std::vector<const Type*> ArgTys; 533 for (unsigned i = 3, e = Record.size(); i != e; ++i) 534 ArgTys.push_back(getTypeByID(Record[i], true)); 535 536 ResultTy = Context.getFunctionType(getTypeByID(Record[2], true), ArgTys, 537 Record[0]); 538 break; 539 } 540 case bitc::TYPE_CODE_STRUCT: { // STRUCT: [ispacked, eltty x N] 541 if (Record.size() < 1) 542 return Error("Invalid STRUCT type record"); 543 std::vector<const Type*> EltTys; 544 for (unsigned i = 1, e = Record.size(); i != e; ++i) 545 EltTys.push_back(getTypeByID(Record[i], true)); 546 ResultTy = Context.getStructType(EltTys, Record[0]); 547 break; 548 } 549 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty] 550 if (Record.size() < 2) 551 return Error("Invalid ARRAY type record"); 552 ResultTy = Context.getArrayType(getTypeByID(Record[1], true), Record[0]); 553 break; 554 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty] 555 if (Record.size() < 2) 556 return Error("Invalid VECTOR type record"); 557 ResultTy = Context.getVectorType(getTypeByID(Record[1], true), Record[0]); 558 break; 559 } 560 561 if (NumRecords == TypeList.size()) { 562 // If this is a new type slot, just append it. 563 TypeList.push_back(ResultTy ? ResultTy : Context.getOpaqueType()); 564 ++NumRecords; 565 } else if (ResultTy == 0) { 566 // Otherwise, this was forward referenced, so an opaque type was created, 567 // but the result type is actually just an opaque. Leave the one we 568 // created previously. 569 ++NumRecords; 570 } else { 571 // Otherwise, this was forward referenced, so an opaque type was created. 572 // Resolve the opaque type to the real type now. 573 assert(NumRecords < TypeList.size() && "Typelist imbalance"); 574 const OpaqueType *OldTy = cast<OpaqueType>(TypeList[NumRecords++].get()); 575 576 // Don't directly push the new type on the Tab. Instead we want to replace 577 // the opaque type we previously inserted with the new concrete value. The 578 // refinement from the abstract (opaque) type to the new type causes all 579 // uses of the abstract type to use the concrete type (NewTy). This will 580 // also cause the opaque type to be deleted. 581 const_cast<OpaqueType*>(OldTy)->refineAbstractTypeTo(ResultTy); 582 583 // This should have replaced the old opaque type with the new type in the 584 // value table... or with a preexisting type that was already in the 585 // system. Let's just make sure it did. 586 assert(TypeList[NumRecords-1].get() != OldTy && 587 "refineAbstractType didn't work!"); 588 } 589 } 590 } 591 592 593 bool BitcodeReader::ParseTypeSymbolTable() { 594 if (Stream.EnterSubBlock(bitc::TYPE_SYMTAB_BLOCK_ID)) 595 return Error("Malformed block record"); 596 597 SmallVector<uint64_t, 64> Record; 598 599 // Read all the records for this type table. 600 std::string TypeName; 601 while (1) { 602 unsigned Code = Stream.ReadCode(); 603 if (Code == bitc::END_BLOCK) { 604 if (Stream.ReadBlockEnd()) 605 return Error("Error at end of type symbol table block"); 606 return false; 607 } 608 609 if (Code == bitc::ENTER_SUBBLOCK) { 610 // No known subblocks, always skip them. 611 Stream.ReadSubBlockID(); 612 if (Stream.SkipBlock()) 613 return Error("Malformed block record"); 614 continue; 615 } 616 617 if (Code == bitc::DEFINE_ABBREV) { 618 Stream.ReadAbbrevRecord(); 619 continue; 620 } 621 622 // Read a record. 623 Record.clear(); 624 switch (Stream.ReadRecord(Code, Record)) { 625 default: // Default behavior: unknown type. 626 break; 627 case bitc::TST_CODE_ENTRY: // TST_ENTRY: [typeid, namechar x N] 628 if (ConvertToString(Record, 1, TypeName)) 629 return Error("Invalid TST_ENTRY record"); 630 unsigned TypeID = Record[0]; 631 if (TypeID >= TypeList.size()) 632 return Error("Invalid Type ID in TST_ENTRY record"); 633 634 TheModule->addTypeName(TypeName, TypeList[TypeID].get()); 635 TypeName.clear(); 636 break; 637 } 638 } 639 } 640 641 bool BitcodeReader::ParseValueSymbolTable() { 642 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID)) 643 return Error("Malformed block record"); 644 645 SmallVector<uint64_t, 64> Record; 646 647 // Read all the records for this value table. 648 SmallString<128> ValueName; 649 while (1) { 650 unsigned Code = Stream.ReadCode(); 651 if (Code == bitc::END_BLOCK) { 652 if (Stream.ReadBlockEnd()) 653 return Error("Error at end of value symbol table block"); 654 return false; 655 } 656 if (Code == bitc::ENTER_SUBBLOCK) { 657 // No known subblocks, always skip them. 658 Stream.ReadSubBlockID(); 659 if (Stream.SkipBlock()) 660 return Error("Malformed block record"); 661 continue; 662 } 663 664 if (Code == bitc::DEFINE_ABBREV) { 665 Stream.ReadAbbrevRecord(); 666 continue; 667 } 668 669 // Read a record. 670 Record.clear(); 671 switch (Stream.ReadRecord(Code, Record)) { 672 default: // Default behavior: unknown type. 673 break; 674 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N] 675 if (ConvertToString(Record, 1, ValueName)) 676 return Error("Invalid VST_ENTRY record"); 677 unsigned ValueID = Record[0]; 678 if (ValueID >= ValueList.size()) 679 return Error("Invalid Value ID in VST_ENTRY record"); 680 Value *V = ValueList[ValueID]; 681 682 V->setName(&ValueName[0], ValueName.size()); 683 ValueName.clear(); 684 break; 685 } 686 case bitc::VST_CODE_BBENTRY: { 687 if (ConvertToString(Record, 1, ValueName)) 688 return Error("Invalid VST_BBENTRY record"); 689 BasicBlock *BB = getBasicBlock(Record[0]); 690 if (BB == 0) 691 return Error("Invalid BB ID in VST_BBENTRY record"); 692 693 BB->setName(&ValueName[0], ValueName.size()); 694 ValueName.clear(); 695 break; 696 } 697 } 698 } 699 } 700 701 /// DecodeSignRotatedValue - Decode a signed value stored with the sign bit in 702 /// the LSB for dense VBR encoding. 703 static uint64_t DecodeSignRotatedValue(uint64_t V) { 704 if ((V & 1) == 0) 705 return V >> 1; 706 if (V != 1) 707 return -(V >> 1); 708 // There is no such thing as -0 with integers. "-0" really means MININT. 709 return 1ULL << 63; 710 } 711 712 /// ResolveGlobalAndAliasInits - Resolve all of the initializers for global 713 /// values and aliases that we can. 714 bool BitcodeReader::ResolveGlobalAndAliasInits() { 715 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist; 716 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist; 717 718 GlobalInitWorklist.swap(GlobalInits); 719 AliasInitWorklist.swap(AliasInits); 720 721 while (!GlobalInitWorklist.empty()) { 722 unsigned ValID = GlobalInitWorklist.back().second; 723 if (ValID >= ValueList.size()) { 724 // Not ready to resolve this yet, it requires something later in the file. 725 GlobalInits.push_back(GlobalInitWorklist.back()); 726 } else { 727 if (Constant *C = dyn_cast<Constant>(ValueList[ValID])) 728 GlobalInitWorklist.back().first->setInitializer(C); 729 else 730 return Error("Global variable initializer is not a constant!"); 731 } 732 GlobalInitWorklist.pop_back(); 733 } 734 735 while (!AliasInitWorklist.empty()) { 736 unsigned ValID = AliasInitWorklist.back().second; 737 if (ValID >= ValueList.size()) { 738 AliasInits.push_back(AliasInitWorklist.back()); 739 } else { 740 if (Constant *C = dyn_cast<Constant>(ValueList[ValID])) 741 AliasInitWorklist.back().first->setAliasee(C); 742 else 743 return Error("Alias initializer is not a constant!"); 744 } 745 AliasInitWorklist.pop_back(); 746 } 747 return false; 748 } 749 750 751 bool BitcodeReader::ParseConstants() { 752 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID)) 753 return Error("Malformed block record"); 754 755 SmallVector<uint64_t, 64> Record; 756 757 // Read all the records for this value table. 758 const Type *CurTy = Type::Int32Ty; 759 unsigned NextCstNo = ValueList.size(); 760 while (1) { 761 unsigned Code = Stream.ReadCode(); 762 if (Code == bitc::END_BLOCK) 763 break; 764 765 if (Code == bitc::ENTER_SUBBLOCK) { 766 // No known subblocks, always skip them. 767 Stream.ReadSubBlockID(); 768 if (Stream.SkipBlock()) 769 return Error("Malformed block record"); 770 continue; 771 } 772 773 if (Code == bitc::DEFINE_ABBREV) { 774 Stream.ReadAbbrevRecord(); 775 continue; 776 } 777 778 // Read a record. 779 Record.clear(); 780 Value *V = 0; 781 switch (Stream.ReadRecord(Code, Record)) { 782 default: // Default behavior: unknown constant 783 case bitc::CST_CODE_UNDEF: // UNDEF 784 V = Context.getUndef(CurTy); 785 break; 786 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid] 787 if (Record.empty()) 788 return Error("Malformed CST_SETTYPE record"); 789 if (Record[0] >= TypeList.size()) 790 return Error("Invalid Type ID in CST_SETTYPE record"); 791 CurTy = TypeList[Record[0]]; 792 continue; // Skip the ValueList manipulation. 793 case bitc::CST_CODE_NULL: // NULL 794 V = Context.getNullValue(CurTy); 795 break; 796 case bitc::CST_CODE_INTEGER: // INTEGER: [intval] 797 if (!isa<IntegerType>(CurTy) || Record.empty()) 798 return Error("Invalid CST_INTEGER record"); 799 V = Context.getConstantInt(CurTy, DecodeSignRotatedValue(Record[0])); 800 break; 801 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval] 802 if (!isa<IntegerType>(CurTy) || Record.empty()) 803 return Error("Invalid WIDE_INTEGER record"); 804 805 unsigned NumWords = Record.size(); 806 SmallVector<uint64_t, 8> Words; 807 Words.resize(NumWords); 808 for (unsigned i = 0; i != NumWords; ++i) 809 Words[i] = DecodeSignRotatedValue(Record[i]); 810 V = Context.getConstantInt(APInt(cast<IntegerType>(CurTy)->getBitWidth(), 811 NumWords, &Words[0])); 812 break; 813 } 814 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval] 815 if (Record.empty()) 816 return Error("Invalid FLOAT record"); 817 if (CurTy == Type::FloatTy) 818 V = Context.getConstantFP(APFloat(APInt(32, (uint32_t)Record[0]))); 819 else if (CurTy == Type::DoubleTy) 820 V = Context.getConstantFP(APFloat(APInt(64, Record[0]))); 821 else if (CurTy == Type::X86_FP80Ty) { 822 // Bits are not stored the same way as a normal i80 APInt, compensate. 823 uint64_t Rearrange[2]; 824 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16); 825 Rearrange[1] = Record[0] >> 48; 826 V = Context.getConstantFP(APFloat(APInt(80, 2, Rearrange))); 827 } else if (CurTy == Type::FP128Ty) 828 V = Context.getConstantFP(APFloat(APInt(128, 2, &Record[0]), true)); 829 else if (CurTy == Type::PPC_FP128Ty) 830 V = Context.getConstantFP(APFloat(APInt(128, 2, &Record[0]))); 831 else 832 V = Context.getUndef(CurTy); 833 break; 834 } 835 836 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number] 837 if (Record.empty()) 838 return Error("Invalid CST_AGGREGATE record"); 839 840 unsigned Size = Record.size(); 841 std::vector<Constant*> Elts; 842 843 if (const StructType *STy = dyn_cast<StructType>(CurTy)) { 844 for (unsigned i = 0; i != Size; ++i) 845 Elts.push_back(ValueList.getConstantFwdRef(Record[i], 846 STy->getElementType(i))); 847 V = Context.getConstantStruct(STy, Elts); 848 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) { 849 const Type *EltTy = ATy->getElementType(); 850 for (unsigned i = 0; i != Size; ++i) 851 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy)); 852 V = Context.getConstantArray(ATy, Elts); 853 } else if (const VectorType *VTy = dyn_cast<VectorType>(CurTy)) { 854 const Type *EltTy = VTy->getElementType(); 855 for (unsigned i = 0; i != Size; ++i) 856 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy)); 857 V = Context.getConstantVector(Elts); 858 } else { 859 V = Context.getUndef(CurTy); 860 } 861 break; 862 } 863 case bitc::CST_CODE_STRING: { // STRING: [values] 864 if (Record.empty()) 865 return Error("Invalid CST_AGGREGATE record"); 866 867 const ArrayType *ATy = cast<ArrayType>(CurTy); 868 const Type *EltTy = ATy->getElementType(); 869 870 unsigned Size = Record.size(); 871 std::vector<Constant*> Elts; 872 for (unsigned i = 0; i != Size; ++i) 873 Elts.push_back(Context.getConstantInt(EltTy, Record[i])); 874 V = Context.getConstantArray(ATy, Elts); 875 break; 876 } 877 case bitc::CST_CODE_CSTRING: { // CSTRING: [values] 878 if (Record.empty()) 879 return Error("Invalid CST_AGGREGATE record"); 880 881 const ArrayType *ATy = cast<ArrayType>(CurTy); 882 const Type *EltTy = ATy->getElementType(); 883 884 unsigned Size = Record.size(); 885 std::vector<Constant*> Elts; 886 for (unsigned i = 0; i != Size; ++i) 887 Elts.push_back(Context.getConstantInt(EltTy, Record[i])); 888 Elts.push_back(Context.getNullValue(EltTy)); 889 V = Context.getConstantArray(ATy, Elts); 890 break; 891 } 892 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval] 893 if (Record.size() < 3) return Error("Invalid CE_BINOP record"); 894 int Opc = GetDecodedBinaryOpcode(Record[0], CurTy); 895 if (Opc < 0) { 896 V = Context.getUndef(CurTy); // Unknown binop. 897 } else { 898 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy); 899 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy); 900 V = Context.getConstantExpr(Opc, LHS, RHS); 901 } 902 break; 903 } 904 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval] 905 if (Record.size() < 3) return Error("Invalid CE_CAST record"); 906 int Opc = GetDecodedCastOpcode(Record[0]); 907 if (Opc < 0) { 908 V = Context.getUndef(CurTy); // Unknown cast. 909 } else { 910 const Type *OpTy = getTypeByID(Record[1]); 911 if (!OpTy) return Error("Invalid CE_CAST record"); 912 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy); 913 V = Context.getConstantExprCast(Opc, Op, CurTy); 914 } 915 break; 916 } 917 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands] 918 if (Record.size() & 1) return Error("Invalid CE_GEP record"); 919 SmallVector<Constant*, 16> Elts; 920 for (unsigned i = 0, e = Record.size(); i != e; i += 2) { 921 const Type *ElTy = getTypeByID(Record[i]); 922 if (!ElTy) return Error("Invalid CE_GEP record"); 923 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy)); 924 } 925 V = Context.getConstantExprGetElementPtr(Elts[0], &Elts[1], 926 Elts.size()-1); 927 break; 928 } 929 case bitc::CST_CODE_CE_SELECT: // CE_SELECT: [opval#, opval#, opval#] 930 if (Record.size() < 3) return Error("Invalid CE_SELECT record"); 931 V = Context.getConstantExprSelect(ValueList.getConstantFwdRef(Record[0], 932 Type::Int1Ty), 933 ValueList.getConstantFwdRef(Record[1],CurTy), 934 ValueList.getConstantFwdRef(Record[2],CurTy)); 935 break; 936 case bitc::CST_CODE_CE_EXTRACTELT: { // CE_EXTRACTELT: [opty, opval, opval] 937 if (Record.size() < 3) return Error("Invalid CE_EXTRACTELT record"); 938 const VectorType *OpTy = 939 dyn_cast_or_null<VectorType>(getTypeByID(Record[0])); 940 if (OpTy == 0) return Error("Invalid CE_EXTRACTELT record"); 941 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy); 942 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], Type::Int32Ty); 943 V = Context.getConstantExprExtractElement(Op0, Op1); 944 break; 945 } 946 case bitc::CST_CODE_CE_INSERTELT: { // CE_INSERTELT: [opval, opval, opval] 947 const VectorType *OpTy = dyn_cast<VectorType>(CurTy); 948 if (Record.size() < 3 || OpTy == 0) 949 return Error("Invalid CE_INSERTELT record"); 950 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy); 951 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], 952 OpTy->getElementType()); 953 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], Type::Int32Ty); 954 V = Context.getConstantExprInsertElement(Op0, Op1, Op2); 955 break; 956 } 957 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval] 958 const VectorType *OpTy = dyn_cast<VectorType>(CurTy); 959 if (Record.size() < 3 || OpTy == 0) 960 return Error("Invalid CE_SHUFFLEVEC record"); 961 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy); 962 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy); 963 const Type *ShufTy = Context.getVectorType(Type::Int32Ty, 964 OpTy->getNumElements()); 965 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy); 966 V = Context.getConstantExprShuffleVector(Op0, Op1, Op2); 967 break; 968 } 969 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval] 970 const VectorType *RTy = dyn_cast<VectorType>(CurTy); 971 const VectorType *OpTy = dyn_cast<VectorType>(getTypeByID(Record[0])); 972 if (Record.size() < 4 || RTy == 0 || OpTy == 0) 973 return Error("Invalid CE_SHUFVEC_EX record"); 974 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy); 975 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy); 976 const Type *ShufTy = Context.getVectorType(Type::Int32Ty, 977 RTy->getNumElements()); 978 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy); 979 V = Context.getConstantExprShuffleVector(Op0, Op1, Op2); 980 break; 981 } 982 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred] 983 if (Record.size() < 4) return Error("Invalid CE_CMP record"); 984 const Type *OpTy = getTypeByID(Record[0]); 985 if (OpTy == 0) return Error("Invalid CE_CMP record"); 986 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy); 987 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy); 988 989 if (OpTy->isFloatingPoint()) 990 V = Context.getConstantExprFCmp(Record[3], Op0, Op1); 991 else 992 V = Context.getConstantExprICmp(Record[3], Op0, Op1); 993 break; 994 } 995 case bitc::CST_CODE_INLINEASM: { 996 if (Record.size() < 2) return Error("Invalid INLINEASM record"); 997 std::string AsmStr, ConstrStr; 998 bool HasSideEffects = Record[0]; 999 unsigned AsmStrSize = Record[1]; 1000 if (2+AsmStrSize >= Record.size()) 1001 return Error("Invalid INLINEASM record"); 1002 unsigned ConstStrSize = Record[2+AsmStrSize]; 1003 if (3+AsmStrSize+ConstStrSize > Record.size()) 1004 return Error("Invalid INLINEASM record"); 1005 1006 for (unsigned i = 0; i != AsmStrSize; ++i) 1007 AsmStr += (char)Record[2+i]; 1008 for (unsigned i = 0; i != ConstStrSize; ++i) 1009 ConstrStr += (char)Record[3+AsmStrSize+i]; 1010 const PointerType *PTy = cast<PointerType>(CurTy); 1011 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()), 1012 AsmStr, ConstrStr, HasSideEffects); 1013 break; 1014 } 1015 case bitc::CST_CODE_MDSTRING: { 1016 unsigned MDStringLength = Record.size(); 1017 SmallString<8> String; 1018 String.resize(MDStringLength); 1019 for (unsigned i = 0; i != MDStringLength; ++i) 1020 String[i] = Record[i]; 1021 V = Context.getMDString(String.c_str(), String.c_str() + MDStringLength); 1022 break; 1023 } 1024 case bitc::CST_CODE_MDNODE: { 1025 if (Record.empty() || Record.size() % 2 == 1) 1026 return Error("Invalid CST_MDNODE record"); 1027 1028 unsigned Size = Record.size(); 1029 SmallVector<Value*, 8> Elts; 1030 for (unsigned i = 0; i != Size; i += 2) { 1031 const Type *Ty = getTypeByID(Record[i], false); 1032 if (Ty != Type::VoidTy) 1033 Elts.push_back(ValueList.getValueFwdRef(Record[i+1], Ty)); 1034 else 1035 Elts.push_back(NULL); 1036 } 1037 V = Context.getMDNode(&Elts[0], Elts.size()); 1038 break; 1039 } 1040 } 1041 1042 ValueList.AssignValue(V, NextCstNo); 1043 ++NextCstNo; 1044 } 1045 1046 if (NextCstNo != ValueList.size()) 1047 return Error("Invalid constant reference!"); 1048 1049 if (Stream.ReadBlockEnd()) 1050 return Error("Error at end of constants block"); 1051 1052 // Once all the constants have been read, go through and resolve forward 1053 // references. 1054 ValueList.ResolveConstantForwardRefs(); 1055 return false; 1056 } 1057 1058 /// RememberAndSkipFunctionBody - When we see the block for a function body, 1059 /// remember where it is and then skip it. This lets us lazily deserialize the 1060 /// functions. 1061 bool BitcodeReader::RememberAndSkipFunctionBody() { 1062 // Get the function we are talking about. 1063 if (FunctionsWithBodies.empty()) 1064 return Error("Insufficient function protos"); 1065 1066 Function *Fn = FunctionsWithBodies.back(); 1067 FunctionsWithBodies.pop_back(); 1068 1069 // Save the current stream state. 1070 uint64_t CurBit = Stream.GetCurrentBitNo(); 1071 DeferredFunctionInfo[Fn] = std::make_pair(CurBit, Fn->getLinkage()); 1072 1073 // Set the functions linkage to GhostLinkage so we know it is lazily 1074 // deserialized. 1075 Fn->setLinkage(GlobalValue::GhostLinkage); 1076 1077 // Skip over the function block for now. 1078 if (Stream.SkipBlock()) 1079 return Error("Malformed block record"); 1080 return false; 1081 } 1082 1083 bool BitcodeReader::ParseModule(const std::string &ModuleID) { 1084 // Reject multiple MODULE_BLOCK's in a single bitstream. 1085 if (TheModule) 1086 return Error("Multiple MODULE_BLOCKs in same stream"); 1087 1088 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID)) 1089 return Error("Malformed block record"); 1090 1091 // Otherwise, create the module. 1092 TheModule = new Module(ModuleID, Context); 1093 1094 SmallVector<uint64_t, 64> Record; 1095 std::vector<std::string> SectionTable; 1096 std::vector<std::string> GCTable; 1097 1098 // Read all the records for this module. 1099 while (!Stream.AtEndOfStream()) { 1100 unsigned Code = Stream.ReadCode(); 1101 if (Code == bitc::END_BLOCK) { 1102 if (Stream.ReadBlockEnd()) 1103 return Error("Error at end of module block"); 1104 1105 // Patch the initializers for globals and aliases up. 1106 ResolveGlobalAndAliasInits(); 1107 if (!GlobalInits.empty() || !AliasInits.empty()) 1108 return Error("Malformed global initializer set"); 1109 if (!FunctionsWithBodies.empty()) 1110 return Error("Too few function bodies found"); 1111 1112 // Look for intrinsic functions which need to be upgraded at some point 1113 for (Module::iterator FI = TheModule->begin(), FE = TheModule->end(); 1114 FI != FE; ++FI) { 1115 Function* NewFn; 1116 if (UpgradeIntrinsicFunction(FI, NewFn)) 1117 UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn)); 1118 } 1119 1120 // Force deallocation of memory for these vectors to favor the client that 1121 // want lazy deserialization. 1122 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits); 1123 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits); 1124 std::vector<Function*>().swap(FunctionsWithBodies); 1125 return false; 1126 } 1127 1128 if (Code == bitc::ENTER_SUBBLOCK) { 1129 switch (Stream.ReadSubBlockID()) { 1130 default: // Skip unknown content. 1131 if (Stream.SkipBlock()) 1132 return Error("Malformed block record"); 1133 break; 1134 case bitc::BLOCKINFO_BLOCK_ID: 1135 if (Stream.ReadBlockInfoBlock()) 1136 return Error("Malformed BlockInfoBlock"); 1137 break; 1138 case bitc::PARAMATTR_BLOCK_ID: 1139 if (ParseAttributeBlock()) 1140 return true; 1141 break; 1142 case bitc::TYPE_BLOCK_ID: 1143 if (ParseTypeTable()) 1144 return true; 1145 break; 1146 case bitc::TYPE_SYMTAB_BLOCK_ID: 1147 if (ParseTypeSymbolTable()) 1148 return true; 1149 break; 1150 case bitc::VALUE_SYMTAB_BLOCK_ID: 1151 if (ParseValueSymbolTable()) 1152 return true; 1153 break; 1154 case bitc::CONSTANTS_BLOCK_ID: 1155 if (ParseConstants() || ResolveGlobalAndAliasInits()) 1156 return true; 1157 break; 1158 case bitc::FUNCTION_BLOCK_ID: 1159 // If this is the first function body we've seen, reverse the 1160 // FunctionsWithBodies list. 1161 if (!HasReversedFunctionsWithBodies) { 1162 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end()); 1163 HasReversedFunctionsWithBodies = true; 1164 } 1165 1166 if (RememberAndSkipFunctionBody()) 1167 return true; 1168 break; 1169 } 1170 continue; 1171 } 1172 1173 if (Code == bitc::DEFINE_ABBREV) { 1174 Stream.ReadAbbrevRecord(); 1175 continue; 1176 } 1177 1178 // Read a record. 1179 switch (Stream.ReadRecord(Code, Record)) { 1180 default: break; // Default behavior, ignore unknown content. 1181 case bitc::MODULE_CODE_VERSION: // VERSION: [version#] 1182 if (Record.size() < 1) 1183 return Error("Malformed MODULE_CODE_VERSION"); 1184 // Only version #0 is supported so far. 1185 if (Record[0] != 0) 1186 return Error("Unknown bitstream version!"); 1187 break; 1188 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N] 1189 std::string S; 1190 if (ConvertToString(Record, 0, S)) 1191 return Error("Invalid MODULE_CODE_TRIPLE record"); 1192 TheModule->setTargetTriple(S); 1193 break; 1194 } 1195 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N] 1196 std::string S; 1197 if (ConvertToString(Record, 0, S)) 1198 return Error("Invalid MODULE_CODE_DATALAYOUT record"); 1199 TheModule->setDataLayout(S); 1200 break; 1201 } 1202 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N] 1203 std::string S; 1204 if (ConvertToString(Record, 0, S)) 1205 return Error("Invalid MODULE_CODE_ASM record"); 1206 TheModule->setModuleInlineAsm(S); 1207 break; 1208 } 1209 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N] 1210 std::string S; 1211 if (ConvertToString(Record, 0, S)) 1212 return Error("Invalid MODULE_CODE_DEPLIB record"); 1213 TheModule->addLibrary(S); 1214 break; 1215 } 1216 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N] 1217 std::string S; 1218 if (ConvertToString(Record, 0, S)) 1219 return Error("Invalid MODULE_CODE_SECTIONNAME record"); 1220 SectionTable.push_back(S); 1221 break; 1222 } 1223 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N] 1224 std::string S; 1225 if (ConvertToString(Record, 0, S)) 1226 return Error("Invalid MODULE_CODE_GCNAME record"); 1227 GCTable.push_back(S); 1228 break; 1229 } 1230 // GLOBALVAR: [pointer type, isconst, initid, 1231 // linkage, alignment, section, visibility, threadlocal] 1232 case bitc::MODULE_CODE_GLOBALVAR: { 1233 if (Record.size() < 6) 1234 return Error("Invalid MODULE_CODE_GLOBALVAR record"); 1235 const Type *Ty = getTypeByID(Record[0]); 1236 if (!isa<PointerType>(Ty)) 1237 return Error("Global not a pointer type!"); 1238 unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace(); 1239 Ty = cast<PointerType>(Ty)->getElementType(); 1240 1241 bool isConstant = Record[1]; 1242 GlobalValue::LinkageTypes Linkage = GetDecodedLinkage(Record[3]); 1243 unsigned Alignment = (1 << Record[4]) >> 1; 1244 std::string Section; 1245 if (Record[5]) { 1246 if (Record[5]-1 >= SectionTable.size()) 1247 return Error("Invalid section ID"); 1248 Section = SectionTable[Record[5]-1]; 1249 } 1250 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility; 1251 if (Record.size() > 6) 1252 Visibility = GetDecodedVisibility(Record[6]); 1253 bool isThreadLocal = false; 1254 if (Record.size() > 7) 1255 isThreadLocal = Record[7]; 1256 1257 GlobalVariable *NewGV = 1258 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, 0, "", 0, 1259 isThreadLocal, AddressSpace); 1260 NewGV->setAlignment(Alignment); 1261 if (!Section.empty()) 1262 NewGV->setSection(Section); 1263 NewGV->setVisibility(Visibility); 1264 NewGV->setThreadLocal(isThreadLocal); 1265 1266 ValueList.push_back(NewGV); 1267 1268 // Remember which value to use for the global initializer. 1269 if (unsigned InitID = Record[2]) 1270 GlobalInits.push_back(std::make_pair(NewGV, InitID-1)); 1271 break; 1272 } 1273 // FUNCTION: [type, callingconv, isproto, linkage, paramattr, 1274 // alignment, section, visibility, gc] 1275 case bitc::MODULE_CODE_FUNCTION: { 1276 if (Record.size() < 8) 1277 return Error("Invalid MODULE_CODE_FUNCTION record"); 1278 const Type *Ty = getTypeByID(Record[0]); 1279 if (!isa<PointerType>(Ty)) 1280 return Error("Function not a pointer type!"); 1281 const FunctionType *FTy = 1282 dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType()); 1283 if (!FTy) 1284 return Error("Function not a pointer to function type!"); 1285 1286 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage, 1287 "", TheModule); 1288 1289 Func->setCallingConv(Record[1]); 1290 bool isProto = Record[2]; 1291 Func->setLinkage(GetDecodedLinkage(Record[3])); 1292 Func->setAttributes(getAttributes(Record[4])); 1293 1294 Func->setAlignment((1 << Record[5]) >> 1); 1295 if (Record[6]) { 1296 if (Record[6]-1 >= SectionTable.size()) 1297 return Error("Invalid section ID"); 1298 Func->setSection(SectionTable[Record[6]-1]); 1299 } 1300 Func->setVisibility(GetDecodedVisibility(Record[7])); 1301 if (Record.size() > 8 && Record[8]) { 1302 if (Record[8]-1 > GCTable.size()) 1303 return Error("Invalid GC ID"); 1304 Func->setGC(GCTable[Record[8]-1].c_str()); 1305 } 1306 ValueList.push_back(Func); 1307 1308 // If this is a function with a body, remember the prototype we are 1309 // creating now, so that we can match up the body with them later. 1310 if (!isProto) 1311 FunctionsWithBodies.push_back(Func); 1312 break; 1313 } 1314 // ALIAS: [alias type, aliasee val#, linkage] 1315 // ALIAS: [alias type, aliasee val#, linkage, visibility] 1316 case bitc::MODULE_CODE_ALIAS: { 1317 if (Record.size() < 3) 1318 return Error("Invalid MODULE_ALIAS record"); 1319 const Type *Ty = getTypeByID(Record[0]); 1320 if (!isa<PointerType>(Ty)) 1321 return Error("Function not a pointer type!"); 1322 1323 GlobalAlias *NewGA = new GlobalAlias(Ty, GetDecodedLinkage(Record[2]), 1324 "", 0, TheModule); 1325 // Old bitcode files didn't have visibility field. 1326 if (Record.size() > 3) 1327 NewGA->setVisibility(GetDecodedVisibility(Record[3])); 1328 ValueList.push_back(NewGA); 1329 AliasInits.push_back(std::make_pair(NewGA, Record[1])); 1330 break; 1331 } 1332 /// MODULE_CODE_PURGEVALS: [numvals] 1333 case bitc::MODULE_CODE_PURGEVALS: 1334 // Trim down the value list to the specified size. 1335 if (Record.size() < 1 || Record[0] > ValueList.size()) 1336 return Error("Invalid MODULE_PURGEVALS record"); 1337 ValueList.shrinkTo(Record[0]); 1338 break; 1339 } 1340 Record.clear(); 1341 } 1342 1343 return Error("Premature end of bitstream"); 1344 } 1345 1346 bool BitcodeReader::ParseBitcode() { 1347 TheModule = 0; 1348 1349 if (Buffer->getBufferSize() & 3) 1350 return Error("Bitcode stream should be a multiple of 4 bytes in length"); 1351 1352 unsigned char *BufPtr = (unsigned char *)Buffer->getBufferStart(); 1353 unsigned char *BufEnd = BufPtr+Buffer->getBufferSize(); 1354 1355 // If we have a wrapper header, parse it and ignore the non-bc file contents. 1356 // The magic number is 0x0B17C0DE stored in little endian. 1357 if (isBitcodeWrapper(BufPtr, BufEnd)) 1358 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd)) 1359 return Error("Invalid bitcode wrapper header"); 1360 1361 StreamFile.init(BufPtr, BufEnd); 1362 Stream.init(StreamFile); 1363 1364 // Sniff for the signature. 1365 if (Stream.Read(8) != 'B' || 1366 Stream.Read(8) != 'C' || 1367 Stream.Read(4) != 0x0 || 1368 Stream.Read(4) != 0xC || 1369 Stream.Read(4) != 0xE || 1370 Stream.Read(4) != 0xD) 1371 return Error("Invalid bitcode signature"); 1372 1373 // We expect a number of well-defined blocks, though we don't necessarily 1374 // need to understand them all. 1375 while (!Stream.AtEndOfStream()) { 1376 unsigned Code = Stream.ReadCode(); 1377 1378 if (Code != bitc::ENTER_SUBBLOCK) 1379 return Error("Invalid record at top-level"); 1380 1381 unsigned BlockID = Stream.ReadSubBlockID(); 1382 1383 // We only know the MODULE subblock ID. 1384 switch (BlockID) { 1385 case bitc::BLOCKINFO_BLOCK_ID: 1386 if (Stream.ReadBlockInfoBlock()) 1387 return Error("Malformed BlockInfoBlock"); 1388 break; 1389 case bitc::MODULE_BLOCK_ID: 1390 if (ParseModule(Buffer->getBufferIdentifier())) 1391 return true; 1392 break; 1393 default: 1394 if (Stream.SkipBlock()) 1395 return Error("Malformed block record"); 1396 break; 1397 } 1398 } 1399 1400 return false; 1401 } 1402 1403 1404 /// ParseFunctionBody - Lazily parse the specified function body block. 1405 bool BitcodeReader::ParseFunctionBody(Function *F) { 1406 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID)) 1407 return Error("Malformed block record"); 1408 1409 unsigned ModuleValueListSize = ValueList.size(); 1410 1411 // Add all the function arguments to the value table. 1412 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I) 1413 ValueList.push_back(I); 1414 1415 unsigned NextValueNo = ValueList.size(); 1416 BasicBlock *CurBB = 0; 1417 unsigned CurBBNo = 0; 1418 1419 // Read all the records. 1420 SmallVector<uint64_t, 64> Record; 1421 while (1) { 1422 unsigned Code = Stream.ReadCode(); 1423 if (Code == bitc::END_BLOCK) { 1424 if (Stream.ReadBlockEnd()) 1425 return Error("Error at end of function block"); 1426 break; 1427 } 1428 1429 if (Code == bitc::ENTER_SUBBLOCK) { 1430 switch (Stream.ReadSubBlockID()) { 1431 default: // Skip unknown content. 1432 if (Stream.SkipBlock()) 1433 return Error("Malformed block record"); 1434 break; 1435 case bitc::CONSTANTS_BLOCK_ID: 1436 if (ParseConstants()) return true; 1437 NextValueNo = ValueList.size(); 1438 break; 1439 case bitc::VALUE_SYMTAB_BLOCK_ID: 1440 if (ParseValueSymbolTable()) return true; 1441 break; 1442 } 1443 continue; 1444 } 1445 1446 if (Code == bitc::DEFINE_ABBREV) { 1447 Stream.ReadAbbrevRecord(); 1448 continue; 1449 } 1450 1451 // Read a record. 1452 Record.clear(); 1453 Instruction *I = 0; 1454 switch (Stream.ReadRecord(Code, Record)) { 1455 default: // Default behavior: reject 1456 return Error("Unknown instruction"); 1457 case bitc::FUNC_CODE_DECLAREBLOCKS: // DECLAREBLOCKS: [nblocks] 1458 if (Record.size() < 1 || Record[0] == 0) 1459 return Error("Invalid DECLAREBLOCKS record"); 1460 // Create all the basic blocks for the function. 1461 FunctionBBs.resize(Record[0]); 1462 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i) 1463 FunctionBBs[i] = BasicBlock::Create("", F); 1464 CurBB = FunctionBBs[0]; 1465 continue; 1466 1467 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode] 1468 unsigned OpNum = 0; 1469 Value *LHS, *RHS; 1470 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) || 1471 getValue(Record, OpNum, LHS->getType(), RHS) || 1472 OpNum+1 != Record.size()) 1473 return Error("Invalid BINOP record"); 1474 1475 int Opc = GetDecodedBinaryOpcode(Record[OpNum], LHS->getType()); 1476 if (Opc == -1) return Error("Invalid BINOP record"); 1477 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS); 1478 break; 1479 } 1480 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc] 1481 unsigned OpNum = 0; 1482 Value *Op; 1483 if (getValueTypePair(Record, OpNum, NextValueNo, Op) || 1484 OpNum+2 != Record.size()) 1485 return Error("Invalid CAST record"); 1486 1487 const Type *ResTy = getTypeByID(Record[OpNum]); 1488 int Opc = GetDecodedCastOpcode(Record[OpNum+1]); 1489 if (Opc == -1 || ResTy == 0) 1490 return Error("Invalid CAST record"); 1491 I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy); 1492 break; 1493 } 1494 case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands] 1495 unsigned OpNum = 0; 1496 Value *BasePtr; 1497 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr)) 1498 return Error("Invalid GEP record"); 1499 1500 SmallVector<Value*, 16> GEPIdx; 1501 while (OpNum != Record.size()) { 1502 Value *Op; 1503 if (getValueTypePair(Record, OpNum, NextValueNo, Op)) 1504 return Error("Invalid GEP record"); 1505 GEPIdx.push_back(Op); 1506 } 1507 1508 I = GetElementPtrInst::Create(BasePtr, GEPIdx.begin(), GEPIdx.end()); 1509 break; 1510 } 1511 1512 case bitc::FUNC_CODE_INST_EXTRACTVAL: { 1513 // EXTRACTVAL: [opty, opval, n x indices] 1514 unsigned OpNum = 0; 1515 Value *Agg; 1516 if (getValueTypePair(Record, OpNum, NextValueNo, Agg)) 1517 return Error("Invalid EXTRACTVAL record"); 1518 1519 SmallVector<unsigned, 4> EXTRACTVALIdx; 1520 for (unsigned RecSize = Record.size(); 1521 OpNum != RecSize; ++OpNum) { 1522 uint64_t Index = Record[OpNum]; 1523 if ((unsigned)Index != Index) 1524 return Error("Invalid EXTRACTVAL index"); 1525 EXTRACTVALIdx.push_back((unsigned)Index); 1526 } 1527 1528 I = ExtractValueInst::Create(Agg, 1529 EXTRACTVALIdx.begin(), EXTRACTVALIdx.end()); 1530 break; 1531 } 1532 1533 case bitc::FUNC_CODE_INST_INSERTVAL: { 1534 // INSERTVAL: [opty, opval, opty, opval, n x indices] 1535 unsigned OpNum = 0; 1536 Value *Agg; 1537 if (getValueTypePair(Record, OpNum, NextValueNo, Agg)) 1538 return Error("Invalid INSERTVAL record"); 1539 Value *Val; 1540 if (getValueTypePair(Record, OpNum, NextValueNo, Val)) 1541 return Error("Invalid INSERTVAL record"); 1542 1543 SmallVector<unsigned, 4> INSERTVALIdx; 1544 for (unsigned RecSize = Record.size(); 1545 OpNum != RecSize; ++OpNum) { 1546 uint64_t Index = Record[OpNum]; 1547 if ((unsigned)Index != Index) 1548 return Error("Invalid INSERTVAL index"); 1549 INSERTVALIdx.push_back((unsigned)Index); 1550 } 1551 1552 I = InsertValueInst::Create(Agg, Val, 1553 INSERTVALIdx.begin(), INSERTVALIdx.end()); 1554 break; 1555 } 1556 1557 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval] 1558 // obsolete form of select 1559 // handles select i1 ... in old bitcode 1560 unsigned OpNum = 0; 1561 Value *TrueVal, *FalseVal, *Cond; 1562 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) || 1563 getValue(Record, OpNum, TrueVal->getType(), FalseVal) || 1564 getValue(Record, OpNum, Type::Int1Ty, Cond)) 1565 return Error("Invalid SELECT record"); 1566 1567 I = SelectInst::Create(Cond, TrueVal, FalseVal); 1568 break; 1569 } 1570 1571 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred] 1572 // new form of select 1573 // handles select i1 or select [N x i1] 1574 unsigned OpNum = 0; 1575 Value *TrueVal, *FalseVal, *Cond; 1576 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) || 1577 getValue(Record, OpNum, TrueVal->getType(), FalseVal) || 1578 getValueTypePair(Record, OpNum, NextValueNo, Cond)) 1579 return Error("Invalid SELECT record"); 1580 1581 // select condition can be either i1 or [N x i1] 1582 if (const VectorType* vector_type = 1583 dyn_cast<const VectorType>(Cond->getType())) { 1584 // expect <n x i1> 1585 if (vector_type->getElementType() != Type::Int1Ty) 1586 return Error("Invalid SELECT condition type"); 1587 } else { 1588 // expect i1 1589 if (Cond->getType() != Type::Int1Ty) 1590 return Error("Invalid SELECT condition type"); 1591 } 1592 1593 I = SelectInst::Create(Cond, TrueVal, FalseVal); 1594 break; 1595 } 1596 1597 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval] 1598 unsigned OpNum = 0; 1599 Value *Vec, *Idx; 1600 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) || 1601 getValue(Record, OpNum, Type::Int32Ty, Idx)) 1602 return Error("Invalid EXTRACTELT record"); 1603 I = new ExtractElementInst(Vec, Idx); 1604 break; 1605 } 1606 1607 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval] 1608 unsigned OpNum = 0; 1609 Value *Vec, *Elt, *Idx; 1610 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) || 1611 getValue(Record, OpNum, 1612 cast<VectorType>(Vec->getType())->getElementType(), Elt) || 1613 getValue(Record, OpNum, Type::Int32Ty, Idx)) 1614 return Error("Invalid INSERTELT record"); 1615 I = InsertElementInst::Create(Vec, Elt, Idx); 1616 break; 1617 } 1618 1619 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval] 1620 unsigned OpNum = 0; 1621 Value *Vec1, *Vec2, *Mask; 1622 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) || 1623 getValue(Record, OpNum, Vec1->getType(), Vec2)) 1624 return Error("Invalid SHUFFLEVEC record"); 1625 1626 if (getValueTypePair(Record, OpNum, NextValueNo, Mask)) 1627 return Error("Invalid SHUFFLEVEC record"); 1628 I = new ShuffleVectorInst(Vec1, Vec2, Mask); 1629 break; 1630 } 1631 1632 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred] 1633 // Old form of ICmp/FCmp returning bool 1634 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were 1635 // both legal on vectors but had different behaviour. 1636 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred] 1637 // FCmp/ICmp returning bool or vector of bool 1638 1639 unsigned OpNum = 0; 1640 Value *LHS, *RHS; 1641 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) || 1642 getValue(Record, OpNum, LHS->getType(), RHS) || 1643 OpNum+1 != Record.size()) 1644 return Error("Invalid CMP record"); 1645 1646 if (LHS->getType()->isFPOrFPVector()) 1647 I = new FCmpInst(Context, (FCmpInst::Predicate)Record[OpNum], LHS, RHS); 1648 else 1649 I = new ICmpInst(Context, (ICmpInst::Predicate)Record[OpNum], LHS, RHS); 1650 break; 1651 } 1652 1653 case bitc::FUNC_CODE_INST_GETRESULT: { // GETRESULT: [ty, val, n] 1654 if (Record.size() != 2) 1655 return Error("Invalid GETRESULT record"); 1656 unsigned OpNum = 0; 1657 Value *Op; 1658 getValueTypePair(Record, OpNum, NextValueNo, Op); 1659 unsigned Index = Record[1]; 1660 I = ExtractValueInst::Create(Op, Index); 1661 break; 1662 } 1663 1664 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>] 1665 { 1666 unsigned Size = Record.size(); 1667 if (Size == 0) { 1668 I = ReturnInst::Create(); 1669 break; 1670 } 1671 1672 unsigned OpNum = 0; 1673 SmallVector<Value *,4> Vs; 1674 do { 1675 Value *Op = NULL; 1676 if (getValueTypePair(Record, OpNum, NextValueNo, Op)) 1677 return Error("Invalid RET record"); 1678 Vs.push_back(Op); 1679 } while(OpNum != Record.size()); 1680 1681 const Type *ReturnType = F->getReturnType(); 1682 if (Vs.size() > 1 || 1683 (isa<StructType>(ReturnType) && 1684 (Vs.empty() || Vs[0]->getType() != ReturnType))) { 1685 Value *RV = Context.getUndef(ReturnType); 1686 for (unsigned i = 0, e = Vs.size(); i != e; ++i) { 1687 I = InsertValueInst::Create(RV, Vs[i], i, "mrv"); 1688 CurBB->getInstList().push_back(I); 1689 ValueList.AssignValue(I, NextValueNo++); 1690 RV = I; 1691 } 1692 I = ReturnInst::Create(RV); 1693 break; 1694 } 1695 1696 I = ReturnInst::Create(Vs[0]); 1697 break; 1698 } 1699 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#] 1700 if (Record.size() != 1 && Record.size() != 3) 1701 return Error("Invalid BR record"); 1702 BasicBlock *TrueDest = getBasicBlock(Record[0]); 1703 if (TrueDest == 0) 1704 return Error("Invalid BR record"); 1705 1706 if (Record.size() == 1) 1707 I = BranchInst::Create(TrueDest); 1708 else { 1709 BasicBlock *FalseDest = getBasicBlock(Record[1]); 1710 Value *Cond = getFnValueByID(Record[2], Type::Int1Ty); 1711 if (FalseDest == 0 || Cond == 0) 1712 return Error("Invalid BR record"); 1713 I = BranchInst::Create(TrueDest, FalseDest, Cond); 1714 } 1715 break; 1716 } 1717 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, opval, n, n x ops] 1718 if (Record.size() < 3 || (Record.size() & 1) == 0) 1719 return Error("Invalid SWITCH record"); 1720 const Type *OpTy = getTypeByID(Record[0]); 1721 Value *Cond = getFnValueByID(Record[1], OpTy); 1722 BasicBlock *Default = getBasicBlock(Record[2]); 1723 if (OpTy == 0 || Cond == 0 || Default == 0) 1724 return Error("Invalid SWITCH record"); 1725 unsigned NumCases = (Record.size()-3)/2; 1726 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases); 1727 for (unsigned i = 0, e = NumCases; i != e; ++i) { 1728 ConstantInt *CaseVal = 1729 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy)); 1730 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]); 1731 if (CaseVal == 0 || DestBB == 0) { 1732 delete SI; 1733 return Error("Invalid SWITCH record!"); 1734 } 1735 SI->addCase(CaseVal, DestBB); 1736 } 1737 I = SI; 1738 break; 1739 } 1740 1741 case bitc::FUNC_CODE_INST_INVOKE: { 1742 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...] 1743 if (Record.size() < 4) return Error("Invalid INVOKE record"); 1744 AttrListPtr PAL = getAttributes(Record[0]); 1745 unsigned CCInfo = Record[1]; 1746 BasicBlock *NormalBB = getBasicBlock(Record[2]); 1747 BasicBlock *UnwindBB = getBasicBlock(Record[3]); 1748 1749 unsigned OpNum = 4; 1750 Value *Callee; 1751 if (getValueTypePair(Record, OpNum, NextValueNo, Callee)) 1752 return Error("Invalid INVOKE record"); 1753 1754 const PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType()); 1755 const FunctionType *FTy = !CalleeTy ? 0 : 1756 dyn_cast<FunctionType>(CalleeTy->getElementType()); 1757 1758 // Check that the right number of fixed parameters are here. 1759 if (FTy == 0 || NormalBB == 0 || UnwindBB == 0 || 1760 Record.size() < OpNum+FTy->getNumParams()) 1761 return Error("Invalid INVOKE record"); 1762 1763 SmallVector<Value*, 16> Ops; 1764 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) { 1765 Ops.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i))); 1766 if (Ops.back() == 0) return Error("Invalid INVOKE record"); 1767 } 1768 1769 if (!FTy->isVarArg()) { 1770 if (Record.size() != OpNum) 1771 return Error("Invalid INVOKE record"); 1772 } else { 1773 // Read type/value pairs for varargs params. 1774 while (OpNum != Record.size()) { 1775 Value *Op; 1776 if (getValueTypePair(Record, OpNum, NextValueNo, Op)) 1777 return Error("Invalid INVOKE record"); 1778 Ops.push_back(Op); 1779 } 1780 } 1781 1782 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, 1783 Ops.begin(), Ops.end()); 1784 cast<InvokeInst>(I)->setCallingConv(CCInfo); 1785 cast<InvokeInst>(I)->setAttributes(PAL); 1786 break; 1787 } 1788 case bitc::FUNC_CODE_INST_UNWIND: // UNWIND 1789 I = new UnwindInst(); 1790 break; 1791 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE 1792 I = new UnreachableInst(); 1793 break; 1794 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...] 1795 if (Record.size() < 1 || ((Record.size()-1)&1)) 1796 return Error("Invalid PHI record"); 1797 const Type *Ty = getTypeByID(Record[0]); 1798 if (!Ty) return Error("Invalid PHI record"); 1799 1800 PHINode *PN = PHINode::Create(Ty); 1801 PN->reserveOperandSpace((Record.size()-1)/2); 1802 1803 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) { 1804 Value *V = getFnValueByID(Record[1+i], Ty); 1805 BasicBlock *BB = getBasicBlock(Record[2+i]); 1806 if (!V || !BB) return Error("Invalid PHI record"); 1807 PN->addIncoming(V, BB); 1808 } 1809 I = PN; 1810 break; 1811 } 1812 1813 case bitc::FUNC_CODE_INST_MALLOC: { // MALLOC: [instty, op, align] 1814 if (Record.size() < 3) 1815 return Error("Invalid MALLOC record"); 1816 const PointerType *Ty = 1817 dyn_cast_or_null<PointerType>(getTypeByID(Record[0])); 1818 Value *Size = getFnValueByID(Record[1], Type::Int32Ty); 1819 unsigned Align = Record[2]; 1820 if (!Ty || !Size) return Error("Invalid MALLOC record"); 1821 I = new MallocInst(Ty->getElementType(), Size, (1 << Align) >> 1); 1822 break; 1823 } 1824 case bitc::FUNC_CODE_INST_FREE: { // FREE: [op, opty] 1825 unsigned OpNum = 0; 1826 Value *Op; 1827 if (getValueTypePair(Record, OpNum, NextValueNo, Op) || 1828 OpNum != Record.size()) 1829 return Error("Invalid FREE record"); 1830 I = new FreeInst(Op); 1831 break; 1832 } 1833 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, op, align] 1834 if (Record.size() < 3) 1835 return Error("Invalid ALLOCA record"); 1836 const PointerType *Ty = 1837 dyn_cast_or_null<PointerType>(getTypeByID(Record[0])); 1838 Value *Size = getFnValueByID(Record[1], Type::Int32Ty); 1839 unsigned Align = Record[2]; 1840 if (!Ty || !Size) return Error("Invalid ALLOCA record"); 1841 I = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1); 1842 break; 1843 } 1844 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol] 1845 unsigned OpNum = 0; 1846 Value *Op; 1847 if (getValueTypePair(Record, OpNum, NextValueNo, Op) || 1848 OpNum+2 != Record.size()) 1849 return Error("Invalid LOAD record"); 1850 1851 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1); 1852 break; 1853 } 1854 case bitc::FUNC_CODE_INST_STORE2: { // STORE2:[ptrty, ptr, val, align, vol] 1855 unsigned OpNum = 0; 1856 Value *Val, *Ptr; 1857 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) || 1858 getValue(Record, OpNum, 1859 cast<PointerType>(Ptr->getType())->getElementType(), Val) || 1860 OpNum+2 != Record.size()) 1861 return Error("Invalid STORE record"); 1862 1863 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1); 1864 break; 1865 } 1866 case bitc::FUNC_CODE_INST_STORE: { // STORE:[val, valty, ptr, align, vol] 1867 // FIXME: Legacy form of store instruction. Should be removed in LLVM 3.0. 1868 unsigned OpNum = 0; 1869 Value *Val, *Ptr; 1870 if (getValueTypePair(Record, OpNum, NextValueNo, Val) || 1871 getValue(Record, OpNum, 1872 Context.getPointerTypeUnqual(Val->getType()), Ptr)|| 1873 OpNum+2 != Record.size()) 1874 return Error("Invalid STORE record"); 1875 1876 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1); 1877 break; 1878 } 1879 case bitc::FUNC_CODE_INST_CALL: { 1880 // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...] 1881 if (Record.size() < 3) 1882 return Error("Invalid CALL record"); 1883 1884 AttrListPtr PAL = getAttributes(Record[0]); 1885 unsigned CCInfo = Record[1]; 1886 1887 unsigned OpNum = 2; 1888 Value *Callee; 1889 if (getValueTypePair(Record, OpNum, NextValueNo, Callee)) 1890 return Error("Invalid CALL record"); 1891 1892 const PointerType *OpTy = dyn_cast<PointerType>(Callee->getType()); 1893 const FunctionType *FTy = 0; 1894 if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType()); 1895 if (!FTy || Record.size() < FTy->getNumParams()+OpNum) 1896 return Error("Invalid CALL record"); 1897 1898 SmallVector<Value*, 16> Args; 1899 // Read the fixed params. 1900 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) { 1901 if (FTy->getParamType(i)->getTypeID()==Type::LabelTyID) 1902 Args.push_back(getBasicBlock(Record[OpNum])); 1903 else 1904 Args.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i))); 1905 if (Args.back() == 0) return Error("Invalid CALL record"); 1906 } 1907 1908 // Read type/value pairs for varargs params. 1909 if (!FTy->isVarArg()) { 1910 if (OpNum != Record.size()) 1911 return Error("Invalid CALL record"); 1912 } else { 1913 while (OpNum != Record.size()) { 1914 Value *Op; 1915 if (getValueTypePair(Record, OpNum, NextValueNo, Op)) 1916 return Error("Invalid CALL record"); 1917 Args.push_back(Op); 1918 } 1919 } 1920 1921 I = CallInst::Create(Callee, Args.begin(), Args.end()); 1922 cast<CallInst>(I)->setCallingConv(CCInfo>>1); 1923 cast<CallInst>(I)->setTailCall(CCInfo & 1); 1924 cast<CallInst>(I)->setAttributes(PAL); 1925 break; 1926 } 1927 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty] 1928 if (Record.size() < 3) 1929 return Error("Invalid VAARG record"); 1930 const Type *OpTy = getTypeByID(Record[0]); 1931 Value *Op = getFnValueByID(Record[1], OpTy); 1932 const Type *ResTy = getTypeByID(Record[2]); 1933 if (!OpTy || !Op || !ResTy) 1934 return Error("Invalid VAARG record"); 1935 I = new VAArgInst(Op, ResTy); 1936 break; 1937 } 1938 } 1939 1940 // Add instruction to end of current BB. If there is no current BB, reject 1941 // this file. 1942 if (CurBB == 0) { 1943 delete I; 1944 return Error("Invalid instruction with no BB"); 1945 } 1946 CurBB->getInstList().push_back(I); 1947 1948 // If this was a terminator instruction, move to the next block. 1949 if (isa<TerminatorInst>(I)) { 1950 ++CurBBNo; 1951 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : 0; 1952 } 1953 1954 // Non-void values get registered in the value table for future use. 1955 if (I && I->getType() != Type::VoidTy) 1956 ValueList.AssignValue(I, NextValueNo++); 1957 } 1958 1959 // Check the function list for unresolved values. 1960 if (Argument *A = dyn_cast<Argument>(ValueList.back())) { 1961 if (A->getParent() == 0) { 1962 // We found at least one unresolved value. Nuke them all to avoid leaks. 1963 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){ 1964 if ((A = dyn_cast<Argument>(ValueList.back())) && A->getParent() == 0) { 1965 A->replaceAllUsesWith(Context.getUndef(A->getType())); 1966 delete A; 1967 } 1968 } 1969 return Error("Never resolved value found in function!"); 1970 } 1971 } 1972 1973 // Trim the value list down to the size it was before we parsed this function. 1974 ValueList.shrinkTo(ModuleValueListSize); 1975 std::vector<BasicBlock*>().swap(FunctionBBs); 1976 1977 return false; 1978 } 1979 1980 //===----------------------------------------------------------------------===// 1981 // ModuleProvider implementation 1982 //===----------------------------------------------------------------------===// 1983 1984 1985 bool BitcodeReader::materializeFunction(Function *F, std::string *ErrInfo) { 1986 // If it already is material, ignore the request. 1987 if (!F->hasNotBeenReadFromBitcode()) return false; 1988 1989 DenseMap<Function*, std::pair<uint64_t, unsigned> >::iterator DFII = 1990 DeferredFunctionInfo.find(F); 1991 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!"); 1992 1993 // Move the bit stream to the saved position of the deferred function body and 1994 // restore the real linkage type for the function. 1995 Stream.JumpToBit(DFII->second.first); 1996 F->setLinkage((GlobalValue::LinkageTypes)DFII->second.second); 1997 1998 if (ParseFunctionBody(F)) { 1999 if (ErrInfo) *ErrInfo = ErrorString; 2000 return true; 2001 } 2002 2003 // Upgrade any old intrinsic calls in the function. 2004 for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(), 2005 E = UpgradedIntrinsics.end(); I != E; ++I) { 2006 if (I->first != I->second) { 2007 for (Value::use_iterator UI = I->first->use_begin(), 2008 UE = I->first->use_end(); UI != UE; ) { 2009 if (CallInst* CI = dyn_cast<CallInst>(*UI++)) 2010 UpgradeIntrinsicCall(CI, I->second); 2011 } 2012 } 2013 } 2014 2015 return false; 2016 } 2017 2018 void BitcodeReader::dematerializeFunction(Function *F) { 2019 // If this function isn't materialized, or if it is a proto, this is a noop. 2020 if (F->hasNotBeenReadFromBitcode() || F->isDeclaration()) 2021 return; 2022 2023 assert(DeferredFunctionInfo.count(F) && "No info to read function later?"); 2024 2025 // Just forget the function body, we can remat it later. 2026 F->deleteBody(); 2027 F->setLinkage(GlobalValue::GhostLinkage); 2028 } 2029 2030 2031 Module *BitcodeReader::materializeModule(std::string *ErrInfo) { 2032 // Iterate over the module, deserializing any functions that are still on 2033 // disk. 2034 for (Module::iterator F = TheModule->begin(), E = TheModule->end(); 2035 F != E; ++F) 2036 if (F->hasNotBeenReadFromBitcode() && 2037 materializeFunction(F, ErrInfo)) 2038 return 0; 2039 2040 // Upgrade any intrinsic calls that slipped through (should not happen!) and 2041 // delete the old functions to clean up. We can't do this unless the entire 2042 // module is materialized because there could always be another function body 2043 // with calls to the old function. 2044 for (std::vector<std::pair<Function*, Function*> >::iterator I = 2045 UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) { 2046 if (I->first != I->second) { 2047 for (Value::use_iterator UI = I->first->use_begin(), 2048 UE = I->first->use_end(); UI != UE; ) { 2049 if (CallInst* CI = dyn_cast<CallInst>(*UI++)) 2050 UpgradeIntrinsicCall(CI, I->second); 2051 } 2052 if (!I->first->use_empty()) 2053 I->first->replaceAllUsesWith(I->second); 2054 I->first->eraseFromParent(); 2055 } 2056 } 2057 std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics); 2058 2059 return TheModule; 2060 } 2061 2062 2063 /// This method is provided by the parent ModuleProvde class and overriden 2064 /// here. It simply releases the module from its provided and frees up our 2065 /// state. 2066 /// @brief Release our hold on the generated module 2067 Module *BitcodeReader::releaseModule(std::string *ErrInfo) { 2068 // Since we're losing control of this Module, we must hand it back complete 2069 Module *M = ModuleProvider::releaseModule(ErrInfo); 2070 FreeState(); 2071 return M; 2072 } 2073 2074 2075 //===----------------------------------------------------------------------===// 2076 // External interface 2077 //===----------------------------------------------------------------------===// 2078 2079 /// getBitcodeModuleProvider - lazy function-at-a-time loading from a file. 2080 /// 2081 ModuleProvider *llvm::getBitcodeModuleProvider(MemoryBuffer *Buffer, 2082 LLVMContext& Context, 2083 std::string *ErrMsg) { 2084 BitcodeReader *R = new BitcodeReader(Buffer, Context); 2085 if (R->ParseBitcode()) { 2086 if (ErrMsg) 2087 *ErrMsg = R->getErrorString(); 2088 2089 // Don't let the BitcodeReader dtor delete 'Buffer'. 2090 R->releaseMemoryBuffer(); 2091 delete R; 2092 return 0; 2093 } 2094 return R; 2095 } 2096 2097 /// ParseBitcodeFile - Read the specified bitcode file, returning the module. 2098 /// If an error occurs, return null and fill in *ErrMsg if non-null. 2099 Module *llvm::ParseBitcodeFile(MemoryBuffer *Buffer, LLVMContext& Context, 2100 std::string *ErrMsg){ 2101 BitcodeReader *R; 2102 R = static_cast<BitcodeReader*>(getBitcodeModuleProvider(Buffer, Context, 2103 ErrMsg)); 2104 if (!R) return 0; 2105 2106 // Read in the entire module. 2107 Module *M = R->materializeModule(ErrMsg); 2108 2109 // Don't let the BitcodeReader dtor delete 'Buffer', regardless of whether 2110 // there was an error. 2111 R->releaseMemoryBuffer(); 2112 2113 // If there was no error, tell ModuleProvider not to delete it when its dtor 2114 // is run. 2115 if (M) 2116 M = R->releaseModule(ErrMsg); 2117 2118 delete R; 2119 return M; 2120 } 2121