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