1 //===- BitcodeReader.cpp - Internal BitcodeReader implementation ----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This header defines the BitcodeReader class.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/Bitcode/ReaderWriter.h"
15 #include "BitcodeReader.h"
16 #include "llvm/Constants.h"
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/InlineAsm.h"
19 #include "llvm/Instructions.h"
20 #include "llvm/LLVMContext.h"
21 #include "llvm/Metadata.h"
22 #include "llvm/Module.h"
23 #include "llvm/Operator.h"
24 #include "llvm/AutoUpgrade.h"
25 #include "llvm/ADT/SmallString.h"
26 #include "llvm/ADT/SmallVector.h"
27 #include "llvm/Support/MathExtras.h"
28 #include "llvm/Support/MemoryBuffer.h"
29 #include "llvm/OperandTraits.h"
32 void BitcodeReader::FreeState() {
35 std::vector<PATypeHolder>().swap(TypeList);
38 std::vector<AttrListPtr>().swap(MAttributes);
39 std::vector<BasicBlock*>().swap(FunctionBBs);
40 std::vector<Function*>().swap(FunctionsWithBodies);
41 DeferredFunctionInfo.clear();
44 //===----------------------------------------------------------------------===//
45 // Helper functions to implement forward reference resolution, etc.
46 //===----------------------------------------------------------------------===//
48 /// ConvertToString - Convert a string from a record into an std::string, return
50 template<typename StrTy>
51 static bool ConvertToString(SmallVector<uint64_t, 64> &Record, unsigned Idx,
53 if (Idx > Record.size())
56 for (unsigned i = Idx, e = Record.size(); i != e; ++i)
57 Result += (char)Record[i];
61 static GlobalValue::LinkageTypes GetDecodedLinkage(unsigned 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;
81 static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned 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;
90 static int GetDecodedCastOpcode(unsigned Val) {
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;
107 static int GetDecodedBinaryOpcode(unsigned Val, const Type *Ty) {
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;
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
139 // allocate space for exactly one operand
140 void *operator new(size_t s) {
141 return User::operator new(s, 1);
143 explicit ConstantPlaceHolder(const Type *Ty, LLVMContext& Context)
144 : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
145 Op<0>() = UndefValue::get(Type::Int32Ty);
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;
156 /// Provide fast operand accessors
157 //DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
161 // FIXME: can we inherit this from ConstantExpr?
163 struct OperandTraits<ConstantPlaceHolder> : FixedNumOperandTraits<1> {
168 void BitcodeReaderValueList::AssignValue(Value *V, unsigned Idx) {
177 WeakVH &OldV = ValuePtrs[Idx];
183 // Handle constants and non-constants (e.g. instrs) differently for
185 if (Constant *PHC = dyn_cast<Constant>(&*OldV)) {
186 ResolveConstants.push_back(std::make_pair(PHC, Idx));
189 // If there was a forward reference to this value, replace it.
190 Value *PrevVal = OldV;
191 OldV->replaceAllUsesWith(V);
197 Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
202 if (Value *V = ValuePtrs[Idx]) {
203 assert(Ty == V->getType() && "Type mismatch in constant table!");
204 return cast<Constant>(V);
207 // Create and return a placeholder, which will later be RAUW'd.
208 Constant *C = new ConstantPlaceHolder(Ty, Context);
213 Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, const Type *Ty) {
217 if (Value *V = ValuePtrs[Idx]) {
218 assert((Ty == 0 || Ty == V->getType()) && "Type mismatch in value table!");
222 // No type specified, must be invalid reference.
223 if (Ty == 0) return 0;
225 // Create and return a placeholder, which will later be RAUW'd.
226 Value *V = new Argument(Ty);
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
238 void BitcodeReaderValueList::ResolveConstantForwardRefs() {
239 // Sort the values by-pointer so that they are efficient to look up with a
241 std::sort(ResolveConstants.begin(), ResolveConstants.end());
243 SmallVector<Constant*, 64> NewOps;
245 while (!ResolveConstants.empty()) {
246 Value *RealVal = operator[](ResolveConstants.back().second);
247 Constant *Placeholder = ResolveConstants.back().first;
248 ResolveConstants.pop_back();
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
253 while (!Placeholder->use_empty()) {
254 Value::use_iterator UI = Placeholder->use_begin();
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);
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();
269 if (!isa<ConstantPlaceHolder>(*I)) {
270 // Not a placeholder reference.
272 } else if (*I == Placeholder) {
273 // Common case is that it just references this one placeholder.
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),
281 assert(It != ResolveConstants.end() && It->first == *I);
282 NewOp = operator[](It->second);
285 NewOps.push_back(cast<Constant>(NewOp));
288 // Make the new constant.
290 if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
291 NewC = ConstantArray::get(UserCA->getType(), &NewOps[0],
293 } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
294 NewC = ConstantStruct::get(&NewOps[0], NewOps.size(),
295 UserCS->getType()->isPacked());
296 } else if (isa<ConstantVector>(UserC)) {
297 NewC = ConstantVector::get(&NewOps[0], NewOps.size());
299 assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr.");
300 NewC = cast<ConstantExpr>(UserC)->getWithOperands(&NewOps[0],
304 UserC->replaceAllUsesWith(NewC);
305 UserC->destroyConstant();
309 // Update all ValueHandles, they should be the only users at this point.
310 Placeholder->replaceAllUsesWith(RealVal);
316 const Type *BitcodeReader::getTypeByID(unsigned ID, bool isTypeTable) {
317 // If the TypeID is in range, return it.
318 if (ID < TypeList.size())
319 return TypeList[ID].get();
320 if (!isTypeTable) return 0;
322 // The type table allows forward references. Push as many Opaque types as
323 // needed to get up to ID.
324 while (TypeList.size() <= ID)
325 TypeList.push_back(OpaqueType::get());
326 return TypeList.back().get();
329 //===----------------------------------------------------------------------===//
330 // Functions for parsing blocks from the bitcode file
331 //===----------------------------------------------------------------------===//
333 bool BitcodeReader::ParseAttributeBlock() {
334 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
335 return Error("Malformed block record");
337 if (!MAttributes.empty())
338 return Error("Multiple PARAMATTR blocks found!");
340 SmallVector<uint64_t, 64> Record;
342 SmallVector<AttributeWithIndex, 8> Attrs;
344 // Read all the records.
346 unsigned Code = Stream.ReadCode();
347 if (Code == bitc::END_BLOCK) {
348 if (Stream.ReadBlockEnd())
349 return Error("Error at end of PARAMATTR block");
353 if (Code == bitc::ENTER_SUBBLOCK) {
354 // No known subblocks, always skip them.
355 Stream.ReadSubBlockID();
356 if (Stream.SkipBlock())
357 return Error("Malformed block record");
361 if (Code == bitc::DEFINE_ABBREV) {
362 Stream.ReadAbbrevRecord();
368 switch (Stream.ReadRecord(Code, Record)) {
369 default: // Default behavior: ignore.
371 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [paramidx0, attr0, ...]
372 if (Record.size() & 1)
373 return Error("Invalid ENTRY record");
375 // FIXME : Remove this autoupgrade code in LLVM 3.0.
376 // If Function attributes are using index 0 then transfer them
377 // to index ~0. Index 0 is used for return value attributes but used to be
378 // used for function attributes.
379 Attributes RetAttribute = Attribute::None;
380 Attributes FnAttribute = Attribute::None;
381 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
382 // FIXME: remove in LLVM 3.0
383 // The alignment is stored as a 16-bit raw value from bits 31--16.
384 // We shift the bits above 31 down by 11 bits.
386 unsigned Alignment = (Record[i+1] & (0xffffull << 16)) >> 16;
387 if (Alignment && !isPowerOf2_32(Alignment))
388 return Error("Alignment is not a power of two.");
390 Attributes ReconstitutedAttr = Record[i+1] & 0xffff;
392 ReconstitutedAttr |= Attribute::constructAlignmentFromInt(Alignment);
393 ReconstitutedAttr |= (Record[i+1] & (0xffffull << 32)) >> 11;
394 Record[i+1] = ReconstitutedAttr;
397 RetAttribute = Record[i+1];
398 else if (Record[i] == ~0U)
399 FnAttribute = Record[i+1];
402 unsigned OldRetAttrs = (Attribute::NoUnwind|Attribute::NoReturn|
403 Attribute::ReadOnly|Attribute::ReadNone);
405 if (FnAttribute == Attribute::None && RetAttribute != Attribute::None &&
406 (RetAttribute & OldRetAttrs) != 0) {
407 if (FnAttribute == Attribute::None) { // add a slot so they get added.
408 Record.push_back(~0U);
412 FnAttribute |= RetAttribute & OldRetAttrs;
413 RetAttribute &= ~OldRetAttrs;
416 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
417 if (Record[i] == 0) {
418 if (RetAttribute != Attribute::None)
419 Attrs.push_back(AttributeWithIndex::get(0, RetAttribute));
420 } else if (Record[i] == ~0U) {
421 if (FnAttribute != Attribute::None)
422 Attrs.push_back(AttributeWithIndex::get(~0U, FnAttribute));
423 } else if (Record[i+1] != Attribute::None)
424 Attrs.push_back(AttributeWithIndex::get(Record[i], Record[i+1]));
427 MAttributes.push_back(AttrListPtr::get(Attrs.begin(), Attrs.end()));
436 bool BitcodeReader::ParseTypeTable() {
437 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID))
438 return Error("Malformed block record");
440 if (!TypeList.empty())
441 return Error("Multiple TYPE_BLOCKs found!");
443 SmallVector<uint64_t, 64> Record;
444 unsigned NumRecords = 0;
446 // Read all the records for this type table.
448 unsigned Code = Stream.ReadCode();
449 if (Code == bitc::END_BLOCK) {
450 if (NumRecords != TypeList.size())
451 return Error("Invalid type forward reference in TYPE_BLOCK");
452 if (Stream.ReadBlockEnd())
453 return Error("Error at end of type table block");
457 if (Code == bitc::ENTER_SUBBLOCK) {
458 // No known subblocks, always skip them.
459 Stream.ReadSubBlockID();
460 if (Stream.SkipBlock())
461 return Error("Malformed block record");
465 if (Code == bitc::DEFINE_ABBREV) {
466 Stream.ReadAbbrevRecord();
472 const Type *ResultTy = 0;
473 switch (Stream.ReadRecord(Code, Record)) {
474 default: // Default behavior: unknown type.
477 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
478 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
479 // type list. This allows us to reserve space.
480 if (Record.size() < 1)
481 return Error("Invalid TYPE_CODE_NUMENTRY record");
482 TypeList.reserve(Record[0]);
484 case bitc::TYPE_CODE_VOID: // VOID
485 ResultTy = Type::VoidTy;
487 case bitc::TYPE_CODE_FLOAT: // FLOAT
488 ResultTy = Type::FloatTy;
490 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
491 ResultTy = Type::DoubleTy;
493 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
494 ResultTy = Type::X86_FP80Ty;
496 case bitc::TYPE_CODE_FP128: // FP128
497 ResultTy = Type::FP128Ty;
499 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
500 ResultTy = Type::PPC_FP128Ty;
502 case bitc::TYPE_CODE_LABEL: // LABEL
503 ResultTy = Type::LabelTy;
505 case bitc::TYPE_CODE_OPAQUE: // OPAQUE
508 case bitc::TYPE_CODE_METADATA: // METADATA
509 ResultTy = Type::MetadataTy;
511 case bitc::TYPE_CODE_INTEGER: // INTEGER: [width]
512 if (Record.size() < 1)
513 return Error("Invalid Integer type record");
515 ResultTy = IntegerType::get(Record[0]);
517 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
518 // [pointee type, address space]
519 if (Record.size() < 1)
520 return Error("Invalid POINTER type record");
521 unsigned AddressSpace = 0;
522 if (Record.size() == 2)
523 AddressSpace = Record[1];
524 ResultTy = PointerType::get(getTypeByID(Record[0], true),
528 case bitc::TYPE_CODE_FUNCTION: {
529 // FIXME: attrid is dead, remove it in LLVM 3.0
530 // FUNCTION: [vararg, attrid, retty, paramty x N]
531 if (Record.size() < 3)
532 return Error("Invalid FUNCTION type record");
533 std::vector<const Type*> ArgTys;
534 for (unsigned i = 3, e = Record.size(); i != e; ++i)
535 ArgTys.push_back(getTypeByID(Record[i], true));
537 ResultTy = FunctionType::get(getTypeByID(Record[2], true), ArgTys,
541 case bitc::TYPE_CODE_STRUCT: { // STRUCT: [ispacked, eltty x N]
542 if (Record.size() < 1)
543 return Error("Invalid STRUCT type record");
544 std::vector<const Type*> EltTys;
545 for (unsigned i = 1, e = Record.size(); i != e; ++i)
546 EltTys.push_back(getTypeByID(Record[i], true));
547 ResultTy = StructType::get(EltTys, Record[0]);
550 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
551 if (Record.size() < 2)
552 return Error("Invalid ARRAY type record");
553 ResultTy = ArrayType::get(getTypeByID(Record[1], true), Record[0]);
555 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
556 if (Record.size() < 2)
557 return Error("Invalid VECTOR type record");
558 ResultTy = VectorType::get(getTypeByID(Record[1], true), Record[0]);
562 if (NumRecords == TypeList.size()) {
563 // If this is a new type slot, just append it.
564 TypeList.push_back(ResultTy ? ResultTy : OpaqueType::get());
566 } else if (ResultTy == 0) {
567 // Otherwise, this was forward referenced, so an opaque type was created,
568 // but the result type is actually just an opaque. Leave the one we
569 // created previously.
572 // Otherwise, this was forward referenced, so an opaque type was created.
573 // Resolve the opaque type to the real type now.
574 assert(NumRecords < TypeList.size() && "Typelist imbalance");
575 const OpaqueType *OldTy = cast<OpaqueType>(TypeList[NumRecords++].get());
577 // Don't directly push the new type on the Tab. Instead we want to replace
578 // the opaque type we previously inserted with the new concrete value. The
579 // refinement from the abstract (opaque) type to the new type causes all
580 // uses of the abstract type to use the concrete type (NewTy). This will
581 // also cause the opaque type to be deleted.
582 const_cast<OpaqueType*>(OldTy)->refineAbstractTypeTo(ResultTy);
584 // This should have replaced the old opaque type with the new type in the
585 // value table... or with a preexisting type that was already in the
586 // system. Let's just make sure it did.
587 assert(TypeList[NumRecords-1].get() != OldTy &&
588 "refineAbstractType didn't work!");
594 bool BitcodeReader::ParseTypeSymbolTable() {
595 if (Stream.EnterSubBlock(bitc::TYPE_SYMTAB_BLOCK_ID))
596 return Error("Malformed block record");
598 SmallVector<uint64_t, 64> Record;
600 // Read all the records for this type table.
601 std::string TypeName;
603 unsigned Code = Stream.ReadCode();
604 if (Code == bitc::END_BLOCK) {
605 if (Stream.ReadBlockEnd())
606 return Error("Error at end of type symbol table block");
610 if (Code == bitc::ENTER_SUBBLOCK) {
611 // No known subblocks, always skip them.
612 Stream.ReadSubBlockID();
613 if (Stream.SkipBlock())
614 return Error("Malformed block record");
618 if (Code == bitc::DEFINE_ABBREV) {
619 Stream.ReadAbbrevRecord();
625 switch (Stream.ReadRecord(Code, Record)) {
626 default: // Default behavior: unknown type.
628 case bitc::TST_CODE_ENTRY: // TST_ENTRY: [typeid, namechar x N]
629 if (ConvertToString(Record, 1, TypeName))
630 return Error("Invalid TST_ENTRY record");
631 unsigned TypeID = Record[0];
632 if (TypeID >= TypeList.size())
633 return Error("Invalid Type ID in TST_ENTRY record");
635 TheModule->addTypeName(TypeName, TypeList[TypeID].get());
642 bool BitcodeReader::ParseValueSymbolTable() {
643 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
644 return Error("Malformed block record");
646 SmallVector<uint64_t, 64> Record;
648 // Read all the records for this value table.
649 SmallString<128> ValueName;
651 unsigned Code = Stream.ReadCode();
652 if (Code == bitc::END_BLOCK) {
653 if (Stream.ReadBlockEnd())
654 return Error("Error at end of value symbol table block");
657 if (Code == bitc::ENTER_SUBBLOCK) {
658 // No known subblocks, always skip them.
659 Stream.ReadSubBlockID();
660 if (Stream.SkipBlock())
661 return Error("Malformed block record");
665 if (Code == bitc::DEFINE_ABBREV) {
666 Stream.ReadAbbrevRecord();
672 switch (Stream.ReadRecord(Code, Record)) {
673 default: // Default behavior: unknown type.
675 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
676 if (ConvertToString(Record, 1, ValueName))
677 return Error("Invalid VST_ENTRY record");
678 unsigned ValueID = Record[0];
679 if (ValueID >= ValueList.size())
680 return Error("Invalid Value ID in VST_ENTRY record");
681 Value *V = ValueList[ValueID];
683 V->setName(StringRef(ValueName.data(), ValueName.size()));
687 case bitc::VST_CODE_BBENTRY: {
688 if (ConvertToString(Record, 1, ValueName))
689 return Error("Invalid VST_BBENTRY record");
690 BasicBlock *BB = getBasicBlock(Record[0]);
692 return Error("Invalid BB ID in VST_BBENTRY record");
694 BB->setName(StringRef(ValueName.data(), ValueName.size()));
702 bool BitcodeReader::ParseMetadata() {
703 unsigned NextValueNo = ValueList.size();
705 if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
706 return Error("Malformed block record");
708 SmallVector<uint64_t, 64> Record;
710 // Read all the records.
712 unsigned Code = Stream.ReadCode();
713 if (Code == bitc::END_BLOCK) {
714 if (Stream.ReadBlockEnd())
715 return Error("Error at end of PARAMATTR block");
719 if (Code == bitc::ENTER_SUBBLOCK) {
720 // No known subblocks, always skip them.
721 Stream.ReadSubBlockID();
722 if (Stream.SkipBlock())
723 return Error("Malformed block record");
727 if (Code == bitc::DEFINE_ABBREV) {
728 Stream.ReadAbbrevRecord();
734 switch (Stream.ReadRecord(Code, Record)) {
735 default: // Default behavior: ignore.
737 case bitc::METADATA_NAME: {
738 // Read named of the named metadata.
739 unsigned NameLength = Record.size();
741 Name.resize(NameLength);
742 for (unsigned i = 0; i != NameLength; ++i)
745 Code = Stream.ReadCode();
747 // METADATA_NAME is always followed by METADATA_NAMED_NODE.
748 if (Stream.ReadRecord(Code, Record) != bitc::METADATA_NAMED_NODE)
749 assert ( 0 && "Inavlid Named Metadata record");
751 // Read named metadata elements.
752 unsigned Size = Record.size();
753 SmallVector<MetadataBase*, 8> Elts;
754 for (unsigned i = 0; i != Size; ++i) {
755 Value *MD = ValueList.getValueFwdRef(Record[i], Type::MetadataTy);
756 if (MetadataBase *B = dyn_cast<MetadataBase>(MD))
759 Value *V = NamedMDNode::Create(Name.c_str(), Elts.data(), Elts.size(),
761 ValueList.AssignValue(V, NextValueNo++);
764 case bitc::METADATA_NODE: {
765 if (Record.empty() || Record.size() % 2 == 1)
766 return Error("Invalid METADATA_NODE record");
768 unsigned Size = Record.size();
769 SmallVector<Value*, 8> Elts;
770 for (unsigned i = 0; i != Size; i += 2) {
771 const Type *Ty = getTypeByID(Record[i], false);
772 if (Ty != Type::VoidTy)
773 Elts.push_back(ValueList.getValueFwdRef(Record[i+1], Ty));
775 Elts.push_back(NULL);
777 Value *V = MDNode::get(Context, &Elts[0], Elts.size());
778 ValueList.AssignValue(V, NextValueNo++);
781 case bitc::METADATA_STRING: {
782 unsigned MDStringLength = Record.size();
783 SmallString<8> String;
784 String.resize(MDStringLength);
785 for (unsigned i = 0; i != MDStringLength; ++i)
786 String[i] = Record[i];
787 Value *V = MDString::get(Context,
788 StringRef(String.data(), String.size()));
789 ValueList.AssignValue(V, NextValueNo++);
796 /// DecodeSignRotatedValue - Decode a signed value stored with the sign bit in
797 /// the LSB for dense VBR encoding.
798 static uint64_t DecodeSignRotatedValue(uint64_t V) {
803 // There is no such thing as -0 with integers. "-0" really means MININT.
807 /// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
808 /// values and aliases that we can.
809 bool BitcodeReader::ResolveGlobalAndAliasInits() {
810 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
811 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
813 GlobalInitWorklist.swap(GlobalInits);
814 AliasInitWorklist.swap(AliasInits);
816 while (!GlobalInitWorklist.empty()) {
817 unsigned ValID = GlobalInitWorklist.back().second;
818 if (ValID >= ValueList.size()) {
819 // Not ready to resolve this yet, it requires something later in the file.
820 GlobalInits.push_back(GlobalInitWorklist.back());
822 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
823 GlobalInitWorklist.back().first->setInitializer(C);
825 return Error("Global variable initializer is not a constant!");
827 GlobalInitWorklist.pop_back();
830 while (!AliasInitWorklist.empty()) {
831 unsigned ValID = AliasInitWorklist.back().second;
832 if (ValID >= ValueList.size()) {
833 AliasInits.push_back(AliasInitWorklist.back());
835 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
836 AliasInitWorklist.back().first->setAliasee(C);
838 return Error("Alias initializer is not a constant!");
840 AliasInitWorklist.pop_back();
845 static void SetOptimizationFlags(Value *V, uint64_t Flags) {
846 if (OverflowingBinaryOperator *OBO =
847 dyn_cast<OverflowingBinaryOperator>(V)) {
848 if (Flags & (1 << bitc::OBO_NO_SIGNED_OVERFLOW))
849 OBO->setHasNoSignedOverflow(true);
850 if (Flags & (1 << bitc::OBO_NO_UNSIGNED_OVERFLOW))
851 OBO->setHasNoUnsignedOverflow(true);
852 } else if (SDivOperator *Div = dyn_cast<SDivOperator>(V)) {
853 if (Flags & (1 << bitc::SDIV_EXACT))
854 Div->setIsExact(true);
858 bool BitcodeReader::ParseConstants() {
859 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
860 return Error("Malformed block record");
862 SmallVector<uint64_t, 64> Record;
864 // Read all the records for this value table.
865 const Type *CurTy = Type::Int32Ty;
866 unsigned NextCstNo = ValueList.size();
868 unsigned Code = Stream.ReadCode();
869 if (Code == bitc::END_BLOCK)
872 if (Code == bitc::ENTER_SUBBLOCK) {
873 // No known subblocks, always skip them.
874 Stream.ReadSubBlockID();
875 if (Stream.SkipBlock())
876 return Error("Malformed block record");
880 if (Code == bitc::DEFINE_ABBREV) {
881 Stream.ReadAbbrevRecord();
888 unsigned BitCode = Stream.ReadRecord(Code, Record);
890 default: // Default behavior: unknown constant
891 case bitc::CST_CODE_UNDEF: // UNDEF
892 V = UndefValue::get(CurTy);
894 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
896 return Error("Malformed CST_SETTYPE record");
897 if (Record[0] >= TypeList.size())
898 return Error("Invalid Type ID in CST_SETTYPE record");
899 CurTy = TypeList[Record[0]];
900 continue; // Skip the ValueList manipulation.
901 case bitc::CST_CODE_NULL: // NULL
902 V = Constant::getNullValue(CurTy);
904 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
905 if (!isa<IntegerType>(CurTy) || Record.empty())
906 return Error("Invalid CST_INTEGER record");
907 V = ConstantInt::get(CurTy, DecodeSignRotatedValue(Record[0]));
909 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
910 if (!isa<IntegerType>(CurTy) || Record.empty())
911 return Error("Invalid WIDE_INTEGER record");
913 unsigned NumWords = Record.size();
914 SmallVector<uint64_t, 8> Words;
915 Words.resize(NumWords);
916 for (unsigned i = 0; i != NumWords; ++i)
917 Words[i] = DecodeSignRotatedValue(Record[i]);
918 V = ConstantInt::get(Context,
919 APInt(cast<IntegerType>(CurTy)->getBitWidth(),
920 NumWords, &Words[0]));
923 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
925 return Error("Invalid FLOAT record");
926 if (CurTy == Type::FloatTy)
927 V = ConstantFP::get(Context, APFloat(APInt(32, (uint32_t)Record[0])));
928 else if (CurTy == Type::DoubleTy)
929 V = ConstantFP::get(Context, APFloat(APInt(64, Record[0])));
930 else if (CurTy == Type::X86_FP80Ty) {
931 // Bits are not stored the same way as a normal i80 APInt, compensate.
932 uint64_t Rearrange[2];
933 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
934 Rearrange[1] = Record[0] >> 48;
935 V = ConstantFP::get(Context, APFloat(APInt(80, 2, Rearrange)));
936 } else if (CurTy == Type::FP128Ty)
937 V = ConstantFP::get(Context, APFloat(APInt(128, 2, &Record[0]), true));
938 else if (CurTy == Type::PPC_FP128Ty)
939 V = ConstantFP::get(Context, APFloat(APInt(128, 2, &Record[0])));
941 V = UndefValue::get(CurTy);
945 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
947 return Error("Invalid CST_AGGREGATE record");
949 unsigned Size = Record.size();
950 std::vector<Constant*> Elts;
952 if (const StructType *STy = dyn_cast<StructType>(CurTy)) {
953 for (unsigned i = 0; i != Size; ++i)
954 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
955 STy->getElementType(i)));
956 V = ConstantStruct::get(STy, Elts);
957 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
958 const Type *EltTy = ATy->getElementType();
959 for (unsigned i = 0; i != Size; ++i)
960 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
961 V = ConstantArray::get(ATy, Elts);
962 } else if (const VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
963 const Type *EltTy = VTy->getElementType();
964 for (unsigned i = 0; i != Size; ++i)
965 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
966 V = ConstantVector::get(Elts);
968 V = UndefValue::get(CurTy);
972 case bitc::CST_CODE_STRING: { // STRING: [values]
974 return Error("Invalid CST_AGGREGATE record");
976 const ArrayType *ATy = cast<ArrayType>(CurTy);
977 const Type *EltTy = ATy->getElementType();
979 unsigned Size = Record.size();
980 std::vector<Constant*> Elts;
981 for (unsigned i = 0; i != Size; ++i)
982 Elts.push_back(ConstantInt::get(EltTy, Record[i]));
983 V = ConstantArray::get(ATy, Elts);
986 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
988 return Error("Invalid CST_AGGREGATE record");
990 const ArrayType *ATy = cast<ArrayType>(CurTy);
991 const Type *EltTy = ATy->getElementType();
993 unsigned Size = Record.size();
994 std::vector<Constant*> Elts;
995 for (unsigned i = 0; i != Size; ++i)
996 Elts.push_back(ConstantInt::get(EltTy, Record[i]));
997 Elts.push_back(Constant::getNullValue(EltTy));
998 V = ConstantArray::get(ATy, Elts);
1001 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
1002 if (Record.size() < 3) return Error("Invalid CE_BINOP record");
1003 int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
1005 V = UndefValue::get(CurTy); // Unknown binop.
1007 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
1008 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
1009 V = ConstantExpr::get(Opc, LHS, RHS);
1011 if (Record.size() >= 4)
1012 SetOptimizationFlags(V, Record[3]);
1015 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
1016 if (Record.size() < 3) return Error("Invalid CE_CAST record");
1017 int Opc = GetDecodedCastOpcode(Record[0]);
1019 V = UndefValue::get(CurTy); // Unknown cast.
1021 const Type *OpTy = getTypeByID(Record[1]);
1022 if (!OpTy) return Error("Invalid CE_CAST record");
1023 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
1024 V = ConstantExpr::getCast(Opc, Op, CurTy);
1028 case bitc::CST_CODE_CE_INBOUNDS_GEP:
1029 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
1030 if (Record.size() & 1) return Error("Invalid CE_GEP record");
1031 SmallVector<Constant*, 16> Elts;
1032 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
1033 const Type *ElTy = getTypeByID(Record[i]);
1034 if (!ElTy) return Error("Invalid CE_GEP record");
1035 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
1037 V = ConstantExpr::getGetElementPtr(Elts[0], &Elts[1],
1039 if (BitCode == bitc::CST_CODE_CE_INBOUNDS_GEP)
1040 cast<GEPOperator>(V)->setIsInBounds(true);
1043 case bitc::CST_CODE_CE_SELECT: // CE_SELECT: [opval#, opval#, opval#]
1044 if (Record.size() < 3) return Error("Invalid CE_SELECT record");
1045 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
1047 ValueList.getConstantFwdRef(Record[1],CurTy),
1048 ValueList.getConstantFwdRef(Record[2],CurTy));
1050 case bitc::CST_CODE_CE_EXTRACTELT: { // CE_EXTRACTELT: [opty, opval, opval]
1051 if (Record.size() < 3) return Error("Invalid CE_EXTRACTELT record");
1052 const VectorType *OpTy =
1053 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1054 if (OpTy == 0) return Error("Invalid CE_EXTRACTELT record");
1055 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1056 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], Type::Int32Ty);
1057 V = ConstantExpr::getExtractElement(Op0, Op1);
1060 case bitc::CST_CODE_CE_INSERTELT: { // CE_INSERTELT: [opval, opval, opval]
1061 const VectorType *OpTy = dyn_cast<VectorType>(CurTy);
1062 if (Record.size() < 3 || OpTy == 0)
1063 return Error("Invalid CE_INSERTELT record");
1064 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1065 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
1066 OpTy->getElementType());
1067 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], Type::Int32Ty);
1068 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
1071 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
1072 const VectorType *OpTy = dyn_cast<VectorType>(CurTy);
1073 if (Record.size() < 3 || OpTy == 0)
1074 return Error("Invalid CE_SHUFFLEVEC record");
1075 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1076 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
1077 const Type *ShufTy = VectorType::get(Type::Int32Ty,
1078 OpTy->getNumElements());
1079 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
1080 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
1083 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
1084 const VectorType *RTy = dyn_cast<VectorType>(CurTy);
1085 const VectorType *OpTy = dyn_cast<VectorType>(getTypeByID(Record[0]));
1086 if (Record.size() < 4 || RTy == 0 || OpTy == 0)
1087 return Error("Invalid CE_SHUFVEC_EX record");
1088 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1089 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1090 const Type *ShufTy = VectorType::get(Type::Int32Ty,
1091 RTy->getNumElements());
1092 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
1093 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
1096 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
1097 if (Record.size() < 4) return Error("Invalid CE_CMP record");
1098 const Type *OpTy = getTypeByID(Record[0]);
1099 if (OpTy == 0) return Error("Invalid CE_CMP record");
1100 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1101 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1103 if (OpTy->isFloatingPoint())
1104 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
1106 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
1109 case bitc::CST_CODE_INLINEASM: {
1110 if (Record.size() < 2) return Error("Invalid INLINEASM record");
1111 std::string AsmStr, ConstrStr;
1112 bool HasSideEffects = Record[0];
1113 unsigned AsmStrSize = Record[1];
1114 if (2+AsmStrSize >= Record.size())
1115 return Error("Invalid INLINEASM record");
1116 unsigned ConstStrSize = Record[2+AsmStrSize];
1117 if (3+AsmStrSize+ConstStrSize > Record.size())
1118 return Error("Invalid INLINEASM record");
1120 for (unsigned i = 0; i != AsmStrSize; ++i)
1121 AsmStr += (char)Record[2+i];
1122 for (unsigned i = 0; i != ConstStrSize; ++i)
1123 ConstrStr += (char)Record[3+AsmStrSize+i];
1124 const PointerType *PTy = cast<PointerType>(CurTy);
1125 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
1126 AsmStr, ConstrStr, HasSideEffects);
1131 ValueList.AssignValue(V, NextCstNo);
1135 if (NextCstNo != ValueList.size())
1136 return Error("Invalid constant reference!");
1138 if (Stream.ReadBlockEnd())
1139 return Error("Error at end of constants block");
1141 // Once all the constants have been read, go through and resolve forward
1143 ValueList.ResolveConstantForwardRefs();
1147 /// RememberAndSkipFunctionBody - When we see the block for a function body,
1148 /// remember where it is and then skip it. This lets us lazily deserialize the
1150 bool BitcodeReader::RememberAndSkipFunctionBody() {
1151 // Get the function we are talking about.
1152 if (FunctionsWithBodies.empty())
1153 return Error("Insufficient function protos");
1155 Function *Fn = FunctionsWithBodies.back();
1156 FunctionsWithBodies.pop_back();
1158 // Save the current stream state.
1159 uint64_t CurBit = Stream.GetCurrentBitNo();
1160 DeferredFunctionInfo[Fn] = std::make_pair(CurBit, Fn->getLinkage());
1162 // Set the functions linkage to GhostLinkage so we know it is lazily
1164 Fn->setLinkage(GlobalValue::GhostLinkage);
1166 // Skip over the function block for now.
1167 if (Stream.SkipBlock())
1168 return Error("Malformed block record");
1172 bool BitcodeReader::ParseModule(const std::string &ModuleID) {
1173 // Reject multiple MODULE_BLOCK's in a single bitstream.
1175 return Error("Multiple MODULE_BLOCKs in same stream");
1177 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
1178 return Error("Malformed block record");
1180 // Otherwise, create the module.
1181 TheModule = new Module(ModuleID, Context);
1183 SmallVector<uint64_t, 64> Record;
1184 std::vector<std::string> SectionTable;
1185 std::vector<std::string> GCTable;
1187 // Read all the records for this module.
1188 while (!Stream.AtEndOfStream()) {
1189 unsigned Code = Stream.ReadCode();
1190 if (Code == bitc::END_BLOCK) {
1191 if (Stream.ReadBlockEnd())
1192 return Error("Error at end of module block");
1194 // Patch the initializers for globals and aliases up.
1195 ResolveGlobalAndAliasInits();
1196 if (!GlobalInits.empty() || !AliasInits.empty())
1197 return Error("Malformed global initializer set");
1198 if (!FunctionsWithBodies.empty())
1199 return Error("Too few function bodies found");
1201 // Look for intrinsic functions which need to be upgraded at some point
1202 for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
1205 if (UpgradeIntrinsicFunction(FI, NewFn))
1206 UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
1209 // Force deallocation of memory for these vectors to favor the client that
1210 // want lazy deserialization.
1211 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
1212 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
1213 std::vector<Function*>().swap(FunctionsWithBodies);
1217 if (Code == bitc::ENTER_SUBBLOCK) {
1218 switch (Stream.ReadSubBlockID()) {
1219 default: // Skip unknown content.
1220 if (Stream.SkipBlock())
1221 return Error("Malformed block record");
1223 case bitc::BLOCKINFO_BLOCK_ID:
1224 if (Stream.ReadBlockInfoBlock())
1225 return Error("Malformed BlockInfoBlock");
1227 case bitc::PARAMATTR_BLOCK_ID:
1228 if (ParseAttributeBlock())
1231 case bitc::TYPE_BLOCK_ID:
1232 if (ParseTypeTable())
1235 case bitc::TYPE_SYMTAB_BLOCK_ID:
1236 if (ParseTypeSymbolTable())
1239 case bitc::VALUE_SYMTAB_BLOCK_ID:
1240 if (ParseValueSymbolTable())
1243 case bitc::CONSTANTS_BLOCK_ID:
1244 if (ParseConstants() || ResolveGlobalAndAliasInits())
1247 case bitc::METADATA_BLOCK_ID:
1248 if (ParseMetadata())
1251 case bitc::FUNCTION_BLOCK_ID:
1252 // If this is the first function body we've seen, reverse the
1253 // FunctionsWithBodies list.
1254 if (!HasReversedFunctionsWithBodies) {
1255 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
1256 HasReversedFunctionsWithBodies = true;
1259 if (RememberAndSkipFunctionBody())
1266 if (Code == bitc::DEFINE_ABBREV) {
1267 Stream.ReadAbbrevRecord();
1272 switch (Stream.ReadRecord(Code, Record)) {
1273 default: break; // Default behavior, ignore unknown content.
1274 case bitc::MODULE_CODE_VERSION: // VERSION: [version#]
1275 if (Record.size() < 1)
1276 return Error("Malformed MODULE_CODE_VERSION");
1277 // Only version #0 is supported so far.
1279 return Error("Unknown bitstream version!");
1281 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
1283 if (ConvertToString(Record, 0, S))
1284 return Error("Invalid MODULE_CODE_TRIPLE record");
1285 TheModule->setTargetTriple(S);
1288 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
1290 if (ConvertToString(Record, 0, S))
1291 return Error("Invalid MODULE_CODE_DATALAYOUT record");
1292 TheModule->setDataLayout(S);
1295 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
1297 if (ConvertToString(Record, 0, S))
1298 return Error("Invalid MODULE_CODE_ASM record");
1299 TheModule->setModuleInlineAsm(S);
1302 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
1304 if (ConvertToString(Record, 0, S))
1305 return Error("Invalid MODULE_CODE_DEPLIB record");
1306 TheModule->addLibrary(S);
1309 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
1311 if (ConvertToString(Record, 0, S))
1312 return Error("Invalid MODULE_CODE_SECTIONNAME record");
1313 SectionTable.push_back(S);
1316 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
1318 if (ConvertToString(Record, 0, S))
1319 return Error("Invalid MODULE_CODE_GCNAME record");
1320 GCTable.push_back(S);
1323 // GLOBALVAR: [pointer type, isconst, initid,
1324 // linkage, alignment, section, visibility, threadlocal]
1325 case bitc::MODULE_CODE_GLOBALVAR: {
1326 if (Record.size() < 6)
1327 return Error("Invalid MODULE_CODE_GLOBALVAR record");
1328 const Type *Ty = getTypeByID(Record[0]);
1329 if (!isa<PointerType>(Ty))
1330 return Error("Global not a pointer type!");
1331 unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
1332 Ty = cast<PointerType>(Ty)->getElementType();
1334 bool isConstant = Record[1];
1335 GlobalValue::LinkageTypes Linkage = GetDecodedLinkage(Record[3]);
1336 unsigned Alignment = (1 << Record[4]) >> 1;
1337 std::string Section;
1339 if (Record[5]-1 >= SectionTable.size())
1340 return Error("Invalid section ID");
1341 Section = SectionTable[Record[5]-1];
1343 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
1344 if (Record.size() > 6)
1345 Visibility = GetDecodedVisibility(Record[6]);
1346 bool isThreadLocal = false;
1347 if (Record.size() > 7)
1348 isThreadLocal = Record[7];
1350 GlobalVariable *NewGV =
1351 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, 0, "", 0,
1352 isThreadLocal, AddressSpace);
1353 NewGV->setAlignment(Alignment);
1354 if (!Section.empty())
1355 NewGV->setSection(Section);
1356 NewGV->setVisibility(Visibility);
1357 NewGV->setThreadLocal(isThreadLocal);
1359 ValueList.push_back(NewGV);
1361 // Remember which value to use for the global initializer.
1362 if (unsigned InitID = Record[2])
1363 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
1366 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
1367 // alignment, section, visibility, gc]
1368 case bitc::MODULE_CODE_FUNCTION: {
1369 if (Record.size() < 8)
1370 return Error("Invalid MODULE_CODE_FUNCTION record");
1371 const Type *Ty = getTypeByID(Record[0]);
1372 if (!isa<PointerType>(Ty))
1373 return Error("Function not a pointer type!");
1374 const FunctionType *FTy =
1375 dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
1377 return Error("Function not a pointer to function type!");
1379 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
1382 Func->setCallingConv(Record[1]);
1383 bool isProto = Record[2];
1384 Func->setLinkage(GetDecodedLinkage(Record[3]));
1385 Func->setAttributes(getAttributes(Record[4]));
1387 Func->setAlignment((1 << Record[5]) >> 1);
1389 if (Record[6]-1 >= SectionTable.size())
1390 return Error("Invalid section ID");
1391 Func->setSection(SectionTable[Record[6]-1]);
1393 Func->setVisibility(GetDecodedVisibility(Record[7]));
1394 if (Record.size() > 8 && Record[8]) {
1395 if (Record[8]-1 > GCTable.size())
1396 return Error("Invalid GC ID");
1397 Func->setGC(GCTable[Record[8]-1].c_str());
1399 ValueList.push_back(Func);
1401 // If this is a function with a body, remember the prototype we are
1402 // creating now, so that we can match up the body with them later.
1404 FunctionsWithBodies.push_back(Func);
1407 // ALIAS: [alias type, aliasee val#, linkage]
1408 // ALIAS: [alias type, aliasee val#, linkage, visibility]
1409 case bitc::MODULE_CODE_ALIAS: {
1410 if (Record.size() < 3)
1411 return Error("Invalid MODULE_ALIAS record");
1412 const Type *Ty = getTypeByID(Record[0]);
1413 if (!isa<PointerType>(Ty))
1414 return Error("Function not a pointer type!");
1416 GlobalAlias *NewGA = new GlobalAlias(Ty, GetDecodedLinkage(Record[2]),
1418 // Old bitcode files didn't have visibility field.
1419 if (Record.size() > 3)
1420 NewGA->setVisibility(GetDecodedVisibility(Record[3]));
1421 ValueList.push_back(NewGA);
1422 AliasInits.push_back(std::make_pair(NewGA, Record[1]));
1425 /// MODULE_CODE_PURGEVALS: [numvals]
1426 case bitc::MODULE_CODE_PURGEVALS:
1427 // Trim down the value list to the specified size.
1428 if (Record.size() < 1 || Record[0] > ValueList.size())
1429 return Error("Invalid MODULE_PURGEVALS record");
1430 ValueList.shrinkTo(Record[0]);
1436 return Error("Premature end of bitstream");
1439 bool BitcodeReader::ParseBitcode() {
1442 if (Buffer->getBufferSize() & 3)
1443 return Error("Bitcode stream should be a multiple of 4 bytes in length");
1445 unsigned char *BufPtr = (unsigned char *)Buffer->getBufferStart();
1446 unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
1448 // If we have a wrapper header, parse it and ignore the non-bc file contents.
1449 // The magic number is 0x0B17C0DE stored in little endian.
1450 if (isBitcodeWrapper(BufPtr, BufEnd))
1451 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd))
1452 return Error("Invalid bitcode wrapper header");
1454 StreamFile.init(BufPtr, BufEnd);
1455 Stream.init(StreamFile);
1457 // Sniff for the signature.
1458 if (Stream.Read(8) != 'B' ||
1459 Stream.Read(8) != 'C' ||
1460 Stream.Read(4) != 0x0 ||
1461 Stream.Read(4) != 0xC ||
1462 Stream.Read(4) != 0xE ||
1463 Stream.Read(4) != 0xD)
1464 return Error("Invalid bitcode signature");
1466 // We expect a number of well-defined blocks, though we don't necessarily
1467 // need to understand them all.
1468 while (!Stream.AtEndOfStream()) {
1469 unsigned Code = Stream.ReadCode();
1471 if (Code != bitc::ENTER_SUBBLOCK)
1472 return Error("Invalid record at top-level");
1474 unsigned BlockID = Stream.ReadSubBlockID();
1476 // We only know the MODULE subblock ID.
1478 case bitc::BLOCKINFO_BLOCK_ID:
1479 if (Stream.ReadBlockInfoBlock())
1480 return Error("Malformed BlockInfoBlock");
1482 case bitc::MODULE_BLOCK_ID:
1483 if (ParseModule(Buffer->getBufferIdentifier()))
1487 if (Stream.SkipBlock())
1488 return Error("Malformed block record");
1497 /// ParseFunctionBody - Lazily parse the specified function body block.
1498 bool BitcodeReader::ParseFunctionBody(Function *F) {
1499 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
1500 return Error("Malformed block record");
1502 unsigned ModuleValueListSize = ValueList.size();
1504 // Add all the function arguments to the value table.
1505 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
1506 ValueList.push_back(I);
1508 unsigned NextValueNo = ValueList.size();
1509 BasicBlock *CurBB = 0;
1510 unsigned CurBBNo = 0;
1512 // Read all the records.
1513 SmallVector<uint64_t, 64> Record;
1515 unsigned Code = Stream.ReadCode();
1516 if (Code == bitc::END_BLOCK) {
1517 if (Stream.ReadBlockEnd())
1518 return Error("Error at end of function block");
1522 if (Code == bitc::ENTER_SUBBLOCK) {
1523 switch (Stream.ReadSubBlockID()) {
1524 default: // Skip unknown content.
1525 if (Stream.SkipBlock())
1526 return Error("Malformed block record");
1528 case bitc::CONSTANTS_BLOCK_ID:
1529 if (ParseConstants()) return true;
1530 NextValueNo = ValueList.size();
1532 case bitc::VALUE_SYMTAB_BLOCK_ID:
1533 if (ParseValueSymbolTable()) return true;
1539 if (Code == bitc::DEFINE_ABBREV) {
1540 Stream.ReadAbbrevRecord();
1547 unsigned BitCode = Stream.ReadRecord(Code, Record);
1549 default: // Default behavior: reject
1550 return Error("Unknown instruction");
1551 case bitc::FUNC_CODE_DECLAREBLOCKS: // DECLAREBLOCKS: [nblocks]
1552 if (Record.size() < 1 || Record[0] == 0)
1553 return Error("Invalid DECLAREBLOCKS record");
1554 // Create all the basic blocks for the function.
1555 FunctionBBs.resize(Record[0]);
1556 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
1557 FunctionBBs[i] = BasicBlock::Create("", F);
1558 CurBB = FunctionBBs[0];
1561 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
1564 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
1565 getValue(Record, OpNum, LHS->getType(), RHS) ||
1566 OpNum+1 > Record.size())
1567 return Error("Invalid BINOP record");
1569 int Opc = GetDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
1570 if (Opc == -1) return Error("Invalid BINOP record");
1571 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
1572 if (OpNum < Record.size())
1573 SetOptimizationFlags(I, Record[3]);
1576 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
1579 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
1580 OpNum+2 != Record.size())
1581 return Error("Invalid CAST record");
1583 const Type *ResTy = getTypeByID(Record[OpNum]);
1584 int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
1585 if (Opc == -1 || ResTy == 0)
1586 return Error("Invalid CAST record");
1587 I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
1590 case bitc::FUNC_CODE_INST_INBOUNDS_GEP:
1591 case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands]
1594 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
1595 return Error("Invalid GEP record");
1597 SmallVector<Value*, 16> GEPIdx;
1598 while (OpNum != Record.size()) {
1600 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
1601 return Error("Invalid GEP record");
1602 GEPIdx.push_back(Op);
1605 I = GetElementPtrInst::Create(BasePtr, GEPIdx.begin(), GEPIdx.end());
1606 if (BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP)
1607 cast<GEPOperator>(I)->setIsInBounds(true);
1611 case bitc::FUNC_CODE_INST_EXTRACTVAL: {
1612 // EXTRACTVAL: [opty, opval, n x indices]
1615 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
1616 return Error("Invalid EXTRACTVAL record");
1618 SmallVector<unsigned, 4> EXTRACTVALIdx;
1619 for (unsigned RecSize = Record.size();
1620 OpNum != RecSize; ++OpNum) {
1621 uint64_t Index = Record[OpNum];
1622 if ((unsigned)Index != Index)
1623 return Error("Invalid EXTRACTVAL index");
1624 EXTRACTVALIdx.push_back((unsigned)Index);
1627 I = ExtractValueInst::Create(Agg,
1628 EXTRACTVALIdx.begin(), EXTRACTVALIdx.end());
1632 case bitc::FUNC_CODE_INST_INSERTVAL: {
1633 // INSERTVAL: [opty, opval, opty, opval, n x indices]
1636 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
1637 return Error("Invalid INSERTVAL record");
1639 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
1640 return Error("Invalid INSERTVAL record");
1642 SmallVector<unsigned, 4> INSERTVALIdx;
1643 for (unsigned RecSize = Record.size();
1644 OpNum != RecSize; ++OpNum) {
1645 uint64_t Index = Record[OpNum];
1646 if ((unsigned)Index != Index)
1647 return Error("Invalid INSERTVAL index");
1648 INSERTVALIdx.push_back((unsigned)Index);
1651 I = InsertValueInst::Create(Agg, Val,
1652 INSERTVALIdx.begin(), INSERTVALIdx.end());
1656 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
1657 // obsolete form of select
1658 // handles select i1 ... in old bitcode
1660 Value *TrueVal, *FalseVal, *Cond;
1661 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
1662 getValue(Record, OpNum, TrueVal->getType(), FalseVal) ||
1663 getValue(Record, OpNum, Type::Int1Ty, Cond))
1664 return Error("Invalid SELECT record");
1666 I = SelectInst::Create(Cond, TrueVal, FalseVal);
1670 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
1671 // new form of select
1672 // handles select i1 or select [N x i1]
1674 Value *TrueVal, *FalseVal, *Cond;
1675 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
1676 getValue(Record, OpNum, TrueVal->getType(), FalseVal) ||
1677 getValueTypePair(Record, OpNum, NextValueNo, Cond))
1678 return Error("Invalid SELECT record");
1680 // select condition can be either i1 or [N x i1]
1681 if (const VectorType* vector_type =
1682 dyn_cast<const VectorType>(Cond->getType())) {
1684 if (vector_type->getElementType() != Type::Int1Ty)
1685 return Error("Invalid SELECT condition type");
1688 if (Cond->getType() != Type::Int1Ty)
1689 return Error("Invalid SELECT condition type");
1692 I = SelectInst::Create(Cond, TrueVal, FalseVal);
1696 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
1699 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
1700 getValue(Record, OpNum, Type::Int32Ty, Idx))
1701 return Error("Invalid EXTRACTELT record");
1702 I = ExtractElementInst::Create(Vec, Idx);
1706 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
1708 Value *Vec, *Elt, *Idx;
1709 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
1710 getValue(Record, OpNum,
1711 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
1712 getValue(Record, OpNum, Type::Int32Ty, Idx))
1713 return Error("Invalid INSERTELT record");
1714 I = InsertElementInst::Create(Vec, Elt, Idx);
1718 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
1720 Value *Vec1, *Vec2, *Mask;
1721 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
1722 getValue(Record, OpNum, Vec1->getType(), Vec2))
1723 return Error("Invalid SHUFFLEVEC record");
1725 if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
1726 return Error("Invalid SHUFFLEVEC record");
1727 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
1731 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
1732 // Old form of ICmp/FCmp returning bool
1733 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
1734 // both legal on vectors but had different behaviour.
1735 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
1736 // FCmp/ICmp returning bool or vector of bool
1740 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
1741 getValue(Record, OpNum, LHS->getType(), RHS) ||
1742 OpNum+1 != Record.size())
1743 return Error("Invalid CMP record");
1745 if (LHS->getType()->isFPOrFPVector())
1746 I = new FCmpInst(Context, (FCmpInst::Predicate)Record[OpNum], LHS, RHS);
1748 I = new ICmpInst(Context, (ICmpInst::Predicate)Record[OpNum], LHS, RHS);
1752 case bitc::FUNC_CODE_INST_GETRESULT: { // GETRESULT: [ty, val, n]
1753 if (Record.size() != 2)
1754 return Error("Invalid GETRESULT record");
1757 getValueTypePair(Record, OpNum, NextValueNo, Op);
1758 unsigned Index = Record[1];
1759 I = ExtractValueInst::Create(Op, Index);
1763 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
1765 unsigned Size = Record.size();
1767 I = ReturnInst::Create();
1772 SmallVector<Value *,4> Vs;
1775 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
1776 return Error("Invalid RET record");
1778 } while(OpNum != Record.size());
1780 const Type *ReturnType = F->getReturnType();
1781 if (Vs.size() > 1 ||
1782 (isa<StructType>(ReturnType) &&
1783 (Vs.empty() || Vs[0]->getType() != ReturnType))) {
1784 Value *RV = UndefValue::get(ReturnType);
1785 for (unsigned i = 0, e = Vs.size(); i != e; ++i) {
1786 I = InsertValueInst::Create(RV, Vs[i], i, "mrv");
1787 CurBB->getInstList().push_back(I);
1788 ValueList.AssignValue(I, NextValueNo++);
1791 I = ReturnInst::Create(RV);
1795 I = ReturnInst::Create(Vs[0]);
1798 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
1799 if (Record.size() != 1 && Record.size() != 3)
1800 return Error("Invalid BR record");
1801 BasicBlock *TrueDest = getBasicBlock(Record[0]);
1803 return Error("Invalid BR record");
1805 if (Record.size() == 1)
1806 I = BranchInst::Create(TrueDest);
1808 BasicBlock *FalseDest = getBasicBlock(Record[1]);
1809 Value *Cond = getFnValueByID(Record[2], Type::Int1Ty);
1810 if (FalseDest == 0 || Cond == 0)
1811 return Error("Invalid BR record");
1812 I = BranchInst::Create(TrueDest, FalseDest, Cond);
1816 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, opval, n, n x ops]
1817 if (Record.size() < 3 || (Record.size() & 1) == 0)
1818 return Error("Invalid SWITCH record");
1819 const Type *OpTy = getTypeByID(Record[0]);
1820 Value *Cond = getFnValueByID(Record[1], OpTy);
1821 BasicBlock *Default = getBasicBlock(Record[2]);
1822 if (OpTy == 0 || Cond == 0 || Default == 0)
1823 return Error("Invalid SWITCH record");
1824 unsigned NumCases = (Record.size()-3)/2;
1825 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
1826 for (unsigned i = 0, e = NumCases; i != e; ++i) {
1827 ConstantInt *CaseVal =
1828 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
1829 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
1830 if (CaseVal == 0 || DestBB == 0) {
1832 return Error("Invalid SWITCH record!");
1834 SI->addCase(CaseVal, DestBB);
1840 case bitc::FUNC_CODE_INST_INVOKE: {
1841 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
1842 if (Record.size() < 4) return Error("Invalid INVOKE record");
1843 AttrListPtr PAL = getAttributes(Record[0]);
1844 unsigned CCInfo = Record[1];
1845 BasicBlock *NormalBB = getBasicBlock(Record[2]);
1846 BasicBlock *UnwindBB = getBasicBlock(Record[3]);
1850 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
1851 return Error("Invalid INVOKE record");
1853 const PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
1854 const FunctionType *FTy = !CalleeTy ? 0 :
1855 dyn_cast<FunctionType>(CalleeTy->getElementType());
1857 // Check that the right number of fixed parameters are here.
1858 if (FTy == 0 || NormalBB == 0 || UnwindBB == 0 ||
1859 Record.size() < OpNum+FTy->getNumParams())
1860 return Error("Invalid INVOKE record");
1862 SmallVector<Value*, 16> Ops;
1863 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
1864 Ops.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
1865 if (Ops.back() == 0) return Error("Invalid INVOKE record");
1868 if (!FTy->isVarArg()) {
1869 if (Record.size() != OpNum)
1870 return Error("Invalid INVOKE record");
1872 // Read type/value pairs for varargs params.
1873 while (OpNum != Record.size()) {
1875 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
1876 return Error("Invalid INVOKE record");
1881 I = InvokeInst::Create(Callee, NormalBB, UnwindBB,
1882 Ops.begin(), Ops.end());
1883 cast<InvokeInst>(I)->setCallingConv(CCInfo);
1884 cast<InvokeInst>(I)->setAttributes(PAL);
1887 case bitc::FUNC_CODE_INST_UNWIND: // UNWIND
1888 I = new UnwindInst();
1890 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
1891 I = new UnreachableInst();
1893 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
1894 if (Record.size() < 1 || ((Record.size()-1)&1))
1895 return Error("Invalid PHI record");
1896 const Type *Ty = getTypeByID(Record[0]);
1897 if (!Ty) return Error("Invalid PHI record");
1899 PHINode *PN = PHINode::Create(Ty);
1900 PN->reserveOperandSpace((Record.size()-1)/2);
1902 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
1903 Value *V = getFnValueByID(Record[1+i], Ty);
1904 BasicBlock *BB = getBasicBlock(Record[2+i]);
1905 if (!V || !BB) return Error("Invalid PHI record");
1906 PN->addIncoming(V, BB);
1912 case bitc::FUNC_CODE_INST_MALLOC: { // MALLOC: [instty, op, align]
1913 if (Record.size() < 3)
1914 return Error("Invalid MALLOC record");
1915 const PointerType *Ty =
1916 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
1917 Value *Size = getFnValueByID(Record[1], Type::Int32Ty);
1918 unsigned Align = Record[2];
1919 if (!Ty || !Size) return Error("Invalid MALLOC record");
1920 I = new MallocInst(Ty->getElementType(), Size, (1 << Align) >> 1);
1923 case bitc::FUNC_CODE_INST_FREE: { // FREE: [op, opty]
1926 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
1927 OpNum != Record.size())
1928 return Error("Invalid FREE record");
1929 I = new FreeInst(Op);
1932 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, op, align]
1933 if (Record.size() < 3)
1934 return Error("Invalid ALLOCA record");
1935 const PointerType *Ty =
1936 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
1937 Value *Size = getFnValueByID(Record[1], Type::Int32Ty);
1938 unsigned Align = Record[2];
1939 if (!Ty || !Size) return Error("Invalid ALLOCA record");
1940 I = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
1943 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
1946 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
1947 OpNum+2 != Record.size())
1948 return Error("Invalid LOAD record");
1950 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1);
1953 case bitc::FUNC_CODE_INST_STORE2: { // STORE2:[ptrty, ptr, val, align, vol]
1956 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
1957 getValue(Record, OpNum,
1958 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
1959 OpNum+2 != Record.size())
1960 return Error("Invalid STORE record");
1962 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
1965 case bitc::FUNC_CODE_INST_STORE: { // STORE:[val, valty, ptr, align, vol]
1966 // FIXME: Legacy form of store instruction. Should be removed in LLVM 3.0.
1969 if (getValueTypePair(Record, OpNum, NextValueNo, Val) ||
1970 getValue(Record, OpNum,
1971 PointerType::getUnqual(Val->getType()), Ptr)||
1972 OpNum+2 != Record.size())
1973 return Error("Invalid STORE record");
1975 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
1978 case bitc::FUNC_CODE_INST_CALL: {
1979 // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
1980 if (Record.size() < 3)
1981 return Error("Invalid CALL record");
1983 AttrListPtr PAL = getAttributes(Record[0]);
1984 unsigned CCInfo = Record[1];
1988 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
1989 return Error("Invalid CALL record");
1991 const PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
1992 const FunctionType *FTy = 0;
1993 if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
1994 if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
1995 return Error("Invalid CALL record");
1997 SmallVector<Value*, 16> Args;
1998 // Read the fixed params.
1999 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
2000 if (FTy->getParamType(i)->getTypeID()==Type::LabelTyID)
2001 Args.push_back(getBasicBlock(Record[OpNum]));
2003 Args.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
2004 if (Args.back() == 0) return Error("Invalid CALL record");
2007 // Read type/value pairs for varargs params.
2008 if (!FTy->isVarArg()) {
2009 if (OpNum != Record.size())
2010 return Error("Invalid CALL record");
2012 while (OpNum != Record.size()) {
2014 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2015 return Error("Invalid CALL record");
2020 I = CallInst::Create(Callee, Args.begin(), Args.end());
2021 cast<CallInst>(I)->setCallingConv(CCInfo>>1);
2022 cast<CallInst>(I)->setTailCall(CCInfo & 1);
2023 cast<CallInst>(I)->setAttributes(PAL);
2026 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
2027 if (Record.size() < 3)
2028 return Error("Invalid VAARG record");
2029 const Type *OpTy = getTypeByID(Record[0]);
2030 Value *Op = getFnValueByID(Record[1], OpTy);
2031 const Type *ResTy = getTypeByID(Record[2]);
2032 if (!OpTy || !Op || !ResTy)
2033 return Error("Invalid VAARG record");
2034 I = new VAArgInst(Op, ResTy);
2039 // Add instruction to end of current BB. If there is no current BB, reject
2043 return Error("Invalid instruction with no BB");
2045 CurBB->getInstList().push_back(I);
2047 // If this was a terminator instruction, move to the next block.
2048 if (isa<TerminatorInst>(I)) {
2050 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : 0;
2053 // Non-void values get registered in the value table for future use.
2054 if (I && I->getType() != Type::VoidTy)
2055 ValueList.AssignValue(I, NextValueNo++);
2058 // Check the function list for unresolved values.
2059 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
2060 if (A->getParent() == 0) {
2061 // We found at least one unresolved value. Nuke them all to avoid leaks.
2062 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
2063 if ((A = dyn_cast<Argument>(ValueList.back())) && A->getParent() == 0) {
2064 A->replaceAllUsesWith(UndefValue::get(A->getType()));
2068 return Error("Never resolved value found in function!");
2072 // Trim the value list down to the size it was before we parsed this function.
2073 ValueList.shrinkTo(ModuleValueListSize);
2074 std::vector<BasicBlock*>().swap(FunctionBBs);
2079 //===----------------------------------------------------------------------===//
2080 // ModuleProvider implementation
2081 //===----------------------------------------------------------------------===//
2084 bool BitcodeReader::materializeFunction(Function *F, std::string *ErrInfo) {
2085 // If it already is material, ignore the request.
2086 if (!F->hasNotBeenReadFromBitcode()) return false;
2088 DenseMap<Function*, std::pair<uint64_t, unsigned> >::iterator DFII =
2089 DeferredFunctionInfo.find(F);
2090 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
2092 // Move the bit stream to the saved position of the deferred function body and
2093 // restore the real linkage type for the function.
2094 Stream.JumpToBit(DFII->second.first);
2095 F->setLinkage((GlobalValue::LinkageTypes)DFII->second.second);
2097 if (ParseFunctionBody(F)) {
2098 if (ErrInfo) *ErrInfo = ErrorString;
2102 // Upgrade any old intrinsic calls in the function.
2103 for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
2104 E = UpgradedIntrinsics.end(); I != E; ++I) {
2105 if (I->first != I->second) {
2106 for (Value::use_iterator UI = I->first->use_begin(),
2107 UE = I->first->use_end(); UI != UE; ) {
2108 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
2109 UpgradeIntrinsicCall(CI, I->second);
2117 void BitcodeReader::dematerializeFunction(Function *F) {
2118 // If this function isn't materialized, or if it is a proto, this is a noop.
2119 if (F->hasNotBeenReadFromBitcode() || F->isDeclaration())
2122 assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
2124 // Just forget the function body, we can remat it later.
2126 F->setLinkage(GlobalValue::GhostLinkage);
2130 Module *BitcodeReader::materializeModule(std::string *ErrInfo) {
2131 // Iterate over the module, deserializing any functions that are still on
2133 for (Module::iterator F = TheModule->begin(), E = TheModule->end();
2135 if (F->hasNotBeenReadFromBitcode() &&
2136 materializeFunction(F, ErrInfo))
2139 // Upgrade any intrinsic calls that slipped through (should not happen!) and
2140 // delete the old functions to clean up. We can't do this unless the entire
2141 // module is materialized because there could always be another function body
2142 // with calls to the old function.
2143 for (std::vector<std::pair<Function*, Function*> >::iterator I =
2144 UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
2145 if (I->first != I->second) {
2146 for (Value::use_iterator UI = I->first->use_begin(),
2147 UE = I->first->use_end(); UI != UE; ) {
2148 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
2149 UpgradeIntrinsicCall(CI, I->second);
2151 if (!I->first->use_empty())
2152 I->first->replaceAllUsesWith(I->second);
2153 I->first->eraseFromParent();
2156 std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
2162 /// This method is provided by the parent ModuleProvde class and overriden
2163 /// here. It simply releases the module from its provided and frees up our
2165 /// @brief Release our hold on the generated module
2166 Module *BitcodeReader::releaseModule(std::string *ErrInfo) {
2167 // Since we're losing control of this Module, we must hand it back complete
2168 Module *M = ModuleProvider::releaseModule(ErrInfo);
2174 //===----------------------------------------------------------------------===//
2175 // External interface
2176 //===----------------------------------------------------------------------===//
2178 /// getBitcodeModuleProvider - lazy function-at-a-time loading from a file.
2180 ModuleProvider *llvm::getBitcodeModuleProvider(MemoryBuffer *Buffer,
2181 LLVMContext& Context,
2182 std::string *ErrMsg) {
2183 BitcodeReader *R = new BitcodeReader(Buffer, Context);
2184 if (R->ParseBitcode()) {
2186 *ErrMsg = R->getErrorString();
2188 // Don't let the BitcodeReader dtor delete 'Buffer'.
2189 R->releaseMemoryBuffer();
2196 /// ParseBitcodeFile - Read the specified bitcode file, returning the module.
2197 /// If an error occurs, return null and fill in *ErrMsg if non-null.
2198 Module *llvm::ParseBitcodeFile(MemoryBuffer *Buffer, LLVMContext& Context,
2199 std::string *ErrMsg){
2201 R = static_cast<BitcodeReader*>(getBitcodeModuleProvider(Buffer, Context,
2205 // Read in the entire module.
2206 Module *M = R->materializeModule(ErrMsg);
2208 // Don't let the BitcodeReader dtor delete 'Buffer', regardless of whether
2209 // there was an error.
2210 R->releaseMemoryBuffer();
2212 // If there was no error, tell ModuleProvider not to delete it when its dtor
2215 M = R->releaseModule(ErrMsg);