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