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 #include "llvm/Bitcode/ReaderWriter.h"
11 #include "BitcodeReader.h"
12 #include "llvm/ADT/SmallString.h"
13 #include "llvm/ADT/SmallVector.h"
14 #include "llvm/AutoUpgrade.h"
15 #include "llvm/Bitcode/LLVMBitCodes.h"
16 #include "llvm/IR/Constants.h"
17 #include "llvm/IR/DerivedTypes.h"
18 #include "llvm/IR/InlineAsm.h"
19 #include "llvm/IR/IntrinsicInst.h"
20 #include "llvm/IR/LLVMContext.h"
21 #include "llvm/IR/Module.h"
22 #include "llvm/IR/OperandTraits.h"
23 #include "llvm/IR/Operator.h"
24 #include "llvm/Support/DataStream.h"
25 #include "llvm/Support/MathExtras.h"
26 #include "llvm/Support/MemoryBuffer.h"
27 #include "llvm/Support/raw_ostream.h"
31 SWITCH_INST_MAGIC = 0x4B5 // May 2012 => 1205 => Hex
34 void BitcodeReader::materializeForwardReferencedFunctions() {
35 while (!BlockAddrFwdRefs.empty()) {
36 Function *F = BlockAddrFwdRefs.begin()->first;
41 void BitcodeReader::FreeState() {
45 std::vector<Type*>().swap(TypeList);
49 std::vector<AttributeSet>().swap(MAttributes);
50 std::vector<BasicBlock*>().swap(FunctionBBs);
51 std::vector<Function*>().swap(FunctionsWithBodies);
52 DeferredFunctionInfo.clear();
55 assert(BlockAddrFwdRefs.empty() && "Unresolved blockaddress fwd references");
58 //===----------------------------------------------------------------------===//
59 // Helper functions to implement forward reference resolution, etc.
60 //===----------------------------------------------------------------------===//
62 /// ConvertToString - Convert a string from a record into an std::string, return
64 template<typename StrTy>
65 static bool ConvertToString(ArrayRef<uint64_t> Record, unsigned Idx,
67 if (Idx > Record.size())
70 for (unsigned i = Idx, e = Record.size(); i != e; ++i)
71 Result += (char)Record[i];
75 static GlobalValue::LinkageTypes GetDecodedLinkage(unsigned Val) {
77 default: // Map unknown/new linkages to external
78 case 0: return GlobalValue::ExternalLinkage;
79 case 1: return GlobalValue::WeakAnyLinkage;
80 case 2: return GlobalValue::AppendingLinkage;
81 case 3: return GlobalValue::InternalLinkage;
82 case 4: return GlobalValue::LinkOnceAnyLinkage;
83 case 5: return GlobalValue::DLLImportLinkage;
84 case 6: return GlobalValue::DLLExportLinkage;
85 case 7: return GlobalValue::ExternalWeakLinkage;
86 case 8: return GlobalValue::CommonLinkage;
87 case 9: return GlobalValue::PrivateLinkage;
88 case 10: return GlobalValue::WeakODRLinkage;
89 case 11: return GlobalValue::LinkOnceODRLinkage;
90 case 12: return GlobalValue::AvailableExternallyLinkage;
91 case 13: return GlobalValue::LinkerPrivateLinkage;
92 case 14: return GlobalValue::LinkerPrivateWeakLinkage;
93 case 15: return GlobalValue::LinkOnceODRAutoHideLinkage;
97 static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned Val) {
99 default: // Map unknown visibilities to default.
100 case 0: return GlobalValue::DefaultVisibility;
101 case 1: return GlobalValue::HiddenVisibility;
102 case 2: return GlobalValue::ProtectedVisibility;
106 static GlobalVariable::ThreadLocalMode GetDecodedThreadLocalMode(unsigned Val) {
108 case 0: return GlobalVariable::NotThreadLocal;
109 default: // Map unknown non-zero value to general dynamic.
110 case 1: return GlobalVariable::GeneralDynamicTLSModel;
111 case 2: return GlobalVariable::LocalDynamicTLSModel;
112 case 3: return GlobalVariable::InitialExecTLSModel;
113 case 4: return GlobalVariable::LocalExecTLSModel;
117 static int GetDecodedCastOpcode(unsigned Val) {
120 case bitc::CAST_TRUNC : return Instruction::Trunc;
121 case bitc::CAST_ZEXT : return Instruction::ZExt;
122 case bitc::CAST_SEXT : return Instruction::SExt;
123 case bitc::CAST_FPTOUI : return Instruction::FPToUI;
124 case bitc::CAST_FPTOSI : return Instruction::FPToSI;
125 case bitc::CAST_UITOFP : return Instruction::UIToFP;
126 case bitc::CAST_SITOFP : return Instruction::SIToFP;
127 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
128 case bitc::CAST_FPEXT : return Instruction::FPExt;
129 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
130 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
131 case bitc::CAST_BITCAST : return Instruction::BitCast;
134 static int GetDecodedBinaryOpcode(unsigned Val, Type *Ty) {
137 case bitc::BINOP_ADD:
138 return Ty->isFPOrFPVectorTy() ? Instruction::FAdd : Instruction::Add;
139 case bitc::BINOP_SUB:
140 return Ty->isFPOrFPVectorTy() ? Instruction::FSub : Instruction::Sub;
141 case bitc::BINOP_MUL:
142 return Ty->isFPOrFPVectorTy() ? Instruction::FMul : Instruction::Mul;
143 case bitc::BINOP_UDIV: return Instruction::UDiv;
144 case bitc::BINOP_SDIV:
145 return Ty->isFPOrFPVectorTy() ? Instruction::FDiv : Instruction::SDiv;
146 case bitc::BINOP_UREM: return Instruction::URem;
147 case bitc::BINOP_SREM:
148 return Ty->isFPOrFPVectorTy() ? Instruction::FRem : Instruction::SRem;
149 case bitc::BINOP_SHL: return Instruction::Shl;
150 case bitc::BINOP_LSHR: return Instruction::LShr;
151 case bitc::BINOP_ASHR: return Instruction::AShr;
152 case bitc::BINOP_AND: return Instruction::And;
153 case bitc::BINOP_OR: return Instruction::Or;
154 case bitc::BINOP_XOR: return Instruction::Xor;
158 static AtomicRMWInst::BinOp GetDecodedRMWOperation(unsigned Val) {
160 default: return AtomicRMWInst::BAD_BINOP;
161 case bitc::RMW_XCHG: return AtomicRMWInst::Xchg;
162 case bitc::RMW_ADD: return AtomicRMWInst::Add;
163 case bitc::RMW_SUB: return AtomicRMWInst::Sub;
164 case bitc::RMW_AND: return AtomicRMWInst::And;
165 case bitc::RMW_NAND: return AtomicRMWInst::Nand;
166 case bitc::RMW_OR: return AtomicRMWInst::Or;
167 case bitc::RMW_XOR: return AtomicRMWInst::Xor;
168 case bitc::RMW_MAX: return AtomicRMWInst::Max;
169 case bitc::RMW_MIN: return AtomicRMWInst::Min;
170 case bitc::RMW_UMAX: return AtomicRMWInst::UMax;
171 case bitc::RMW_UMIN: return AtomicRMWInst::UMin;
175 static AtomicOrdering GetDecodedOrdering(unsigned Val) {
177 case bitc::ORDERING_NOTATOMIC: return NotAtomic;
178 case bitc::ORDERING_UNORDERED: return Unordered;
179 case bitc::ORDERING_MONOTONIC: return Monotonic;
180 case bitc::ORDERING_ACQUIRE: return Acquire;
181 case bitc::ORDERING_RELEASE: return Release;
182 case bitc::ORDERING_ACQREL: return AcquireRelease;
183 default: // Map unknown orderings to sequentially-consistent.
184 case bitc::ORDERING_SEQCST: return SequentiallyConsistent;
188 static SynchronizationScope GetDecodedSynchScope(unsigned Val) {
190 case bitc::SYNCHSCOPE_SINGLETHREAD: return SingleThread;
191 default: // Map unknown scopes to cross-thread.
192 case bitc::SYNCHSCOPE_CROSSTHREAD: return CrossThread;
198 /// @brief A class for maintaining the slot number definition
199 /// as a placeholder for the actual definition for forward constants defs.
200 class ConstantPlaceHolder : public ConstantExpr {
201 void operator=(const ConstantPlaceHolder &) LLVM_DELETED_FUNCTION;
203 // allocate space for exactly one operand
204 void *operator new(size_t s) {
205 return User::operator new(s, 1);
207 explicit ConstantPlaceHolder(Type *Ty, LLVMContext& Context)
208 : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
209 Op<0>() = UndefValue::get(Type::getInt32Ty(Context));
212 /// @brief Methods to support type inquiry through isa, cast, and dyn_cast.
213 static bool classof(const Value *V) {
214 return isa<ConstantExpr>(V) &&
215 cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
219 /// Provide fast operand accessors
220 //DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
224 // FIXME: can we inherit this from ConstantExpr?
226 struct OperandTraits<ConstantPlaceHolder> :
227 public FixedNumOperandTraits<ConstantPlaceHolder, 1> {
232 void BitcodeReaderValueList::AssignValue(Value *V, unsigned Idx) {
241 WeakVH &OldV = ValuePtrs[Idx];
247 // Handle constants and non-constants (e.g. instrs) differently for
249 if (Constant *PHC = dyn_cast<Constant>(&*OldV)) {
250 ResolveConstants.push_back(std::make_pair(PHC, Idx));
253 // If there was a forward reference to this value, replace it.
254 Value *PrevVal = OldV;
255 OldV->replaceAllUsesWith(V);
261 Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
266 if (Value *V = ValuePtrs[Idx]) {
267 assert(Ty == V->getType() && "Type mismatch in constant table!");
268 return cast<Constant>(V);
271 // Create and return a placeholder, which will later be RAUW'd.
272 Constant *C = new ConstantPlaceHolder(Ty, Context);
277 Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, Type *Ty) {
281 if (Value *V = ValuePtrs[Idx]) {
282 assert((Ty == 0 || Ty == V->getType()) && "Type mismatch in value table!");
286 // No type specified, must be invalid reference.
287 if (Ty == 0) return 0;
289 // Create and return a placeholder, which will later be RAUW'd.
290 Value *V = new Argument(Ty);
295 /// ResolveConstantForwardRefs - Once all constants are read, this method bulk
296 /// resolves any forward references. The idea behind this is that we sometimes
297 /// get constants (such as large arrays) which reference *many* forward ref
298 /// constants. Replacing each of these causes a lot of thrashing when
299 /// building/reuniquing the constant. Instead of doing this, we look at all the
300 /// uses and rewrite all the place holders at once for any constant that uses
302 void BitcodeReaderValueList::ResolveConstantForwardRefs() {
303 // Sort the values by-pointer so that they are efficient to look up with a
305 std::sort(ResolveConstants.begin(), ResolveConstants.end());
307 SmallVector<Constant*, 64> NewOps;
309 while (!ResolveConstants.empty()) {
310 Value *RealVal = operator[](ResolveConstants.back().second);
311 Constant *Placeholder = ResolveConstants.back().first;
312 ResolveConstants.pop_back();
314 // Loop over all users of the placeholder, updating them to reference the
315 // new value. If they reference more than one placeholder, update them all
317 while (!Placeholder->use_empty()) {
318 Value::use_iterator UI = Placeholder->use_begin();
321 // If the using object isn't uniqued, just update the operands. This
322 // handles instructions and initializers for global variables.
323 if (!isa<Constant>(U) || isa<GlobalValue>(U)) {
324 UI.getUse().set(RealVal);
328 // Otherwise, we have a constant that uses the placeholder. Replace that
329 // constant with a new constant that has *all* placeholder uses updated.
330 Constant *UserC = cast<Constant>(U);
331 for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end();
334 if (!isa<ConstantPlaceHolder>(*I)) {
335 // Not a placeholder reference.
337 } else if (*I == Placeholder) {
338 // Common case is that it just references this one placeholder.
341 // Otherwise, look up the placeholder in ResolveConstants.
342 ResolveConstantsTy::iterator It =
343 std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(),
344 std::pair<Constant*, unsigned>(cast<Constant>(*I),
346 assert(It != ResolveConstants.end() && It->first == *I);
347 NewOp = operator[](It->second);
350 NewOps.push_back(cast<Constant>(NewOp));
353 // Make the new constant.
355 if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
356 NewC = ConstantArray::get(UserCA->getType(), NewOps);
357 } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
358 NewC = ConstantStruct::get(UserCS->getType(), NewOps);
359 } else if (isa<ConstantVector>(UserC)) {
360 NewC = ConstantVector::get(NewOps);
362 assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr.");
363 NewC = cast<ConstantExpr>(UserC)->getWithOperands(NewOps);
366 UserC->replaceAllUsesWith(NewC);
367 UserC->destroyConstant();
371 // Update all ValueHandles, they should be the only users at this point.
372 Placeholder->replaceAllUsesWith(RealVal);
377 void BitcodeReaderMDValueList::AssignValue(Value *V, unsigned Idx) {
386 WeakVH &OldV = MDValuePtrs[Idx];
392 // If there was a forward reference to this value, replace it.
393 MDNode *PrevVal = cast<MDNode>(OldV);
394 OldV->replaceAllUsesWith(V);
395 MDNode::deleteTemporary(PrevVal);
396 // Deleting PrevVal sets Idx value in MDValuePtrs to null. Set new
398 MDValuePtrs[Idx] = V;
401 Value *BitcodeReaderMDValueList::getValueFwdRef(unsigned Idx) {
405 if (Value *V = MDValuePtrs[Idx]) {
406 assert(V->getType()->isMetadataTy() && "Type mismatch in value table!");
410 // Create and return a placeholder, which will later be RAUW'd.
411 Value *V = MDNode::getTemporary(Context, None);
412 MDValuePtrs[Idx] = V;
416 Type *BitcodeReader::getTypeByID(unsigned ID) {
417 // The type table size is always specified correctly.
418 if (ID >= TypeList.size())
421 if (Type *Ty = TypeList[ID])
424 // If we have a forward reference, the only possible case is when it is to a
425 // named struct. Just create a placeholder for now.
426 return TypeList[ID] = StructType::create(Context);
430 //===----------------------------------------------------------------------===//
431 // Functions for parsing blocks from the bitcode file
432 //===----------------------------------------------------------------------===//
435 /// \brief This fills an AttrBuilder object with the LLVM attributes that have
436 /// been decoded from the given integer. This function must stay in sync with
437 /// 'encodeLLVMAttributesForBitcode'.
438 static void decodeLLVMAttributesForBitcode(AttrBuilder &B,
439 uint64_t EncodedAttrs) {
440 // FIXME: Remove in 4.0.
442 // The alignment is stored as a 16-bit raw value from bits 31--16. We shift
443 // the bits above 31 down by 11 bits.
444 unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
445 assert((!Alignment || isPowerOf2_32(Alignment)) &&
446 "Alignment must be a power of two.");
449 B.addAlignmentAttr(Alignment);
450 B.addRawValue(((EncodedAttrs & (0xfffffULL << 32)) >> 11) |
451 (EncodedAttrs & 0xffff));
454 bool BitcodeReader::ParseAttributeBlock() {
455 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
456 return Error("Malformed block record");
458 if (!MAttributes.empty())
459 return Error("Multiple PARAMATTR blocks found!");
461 SmallVector<uint64_t, 64> Record;
463 SmallVector<AttributeSet, 8> Attrs;
465 // Read all the records.
467 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
469 switch (Entry.Kind) {
470 case BitstreamEntry::SubBlock: // Handled for us already.
471 case BitstreamEntry::Error:
472 return Error("Error at end of PARAMATTR block");
473 case BitstreamEntry::EndBlock:
475 case BitstreamEntry::Record:
476 // The interesting case.
482 switch (Stream.readRecord(Entry.ID, Record)) {
483 default: // Default behavior: ignore.
485 case bitc::PARAMATTR_CODE_ENTRY_OLD: { // ENTRY: [paramidx0, attr0, ...]
486 // FIXME: Remove in 4.0.
487 if (Record.size() & 1)
488 return Error("Invalid ENTRY record");
490 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
492 decodeLLVMAttributesForBitcode(B, Record[i+1]);
493 Attrs.push_back(AttributeSet::get(Context, Record[i], B));
496 MAttributes.push_back(AttributeSet::get(Context, Attrs));
500 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [attrgrp0, attrgrp1, ...]
501 for (unsigned i = 0, e = Record.size(); i != e; ++i)
502 Attrs.push_back(MAttributeGroups[Record[i]]);
504 MAttributes.push_back(AttributeSet::get(Context, Attrs));
512 bool BitcodeReader::ParseAttrKind(uint64_t Code, Attribute::AttrKind *Kind) {
514 case bitc::ATTR_KIND_ALIGNMENT:
515 *Kind = Attribute::Alignment;
517 case bitc::ATTR_KIND_ALWAYS_INLINE:
518 *Kind = Attribute::AlwaysInline;
520 case bitc::ATTR_KIND_BUILTIN:
521 *Kind = Attribute::Builtin;
523 case bitc::ATTR_KIND_BY_VAL:
524 *Kind = Attribute::ByVal;
526 case bitc::ATTR_KIND_COLD:
527 *Kind = Attribute::Cold;
529 case bitc::ATTR_KIND_INLINE_HINT:
530 *Kind = Attribute::InlineHint;
532 case bitc::ATTR_KIND_IN_REG:
533 *Kind = Attribute::InReg;
535 case bitc::ATTR_KIND_MIN_SIZE:
536 *Kind = Attribute::MinSize;
538 case bitc::ATTR_KIND_NAKED:
539 *Kind = Attribute::Naked;
541 case bitc::ATTR_KIND_NEST:
542 *Kind = Attribute::Nest;
544 case bitc::ATTR_KIND_NO_ALIAS:
545 *Kind = Attribute::NoAlias;
547 case bitc::ATTR_KIND_NO_BUILTIN:
548 *Kind = Attribute::NoBuiltin;
550 case bitc::ATTR_KIND_NO_CAPTURE:
551 *Kind = Attribute::NoCapture;
553 case bitc::ATTR_KIND_NO_DUPLICATE:
554 *Kind = Attribute::NoDuplicate;
556 case bitc::ATTR_KIND_NO_IMPLICIT_FLOAT:
557 *Kind = Attribute::NoImplicitFloat;
559 case bitc::ATTR_KIND_NO_INLINE:
560 *Kind = Attribute::NoInline;
562 case bitc::ATTR_KIND_NON_LAZY_BIND:
563 *Kind = Attribute::NonLazyBind;
565 case bitc::ATTR_KIND_NO_RED_ZONE:
566 *Kind = Attribute::NoRedZone;
568 case bitc::ATTR_KIND_NO_RETURN:
569 *Kind = Attribute::NoReturn;
571 case bitc::ATTR_KIND_NO_UNWIND:
572 *Kind = Attribute::NoUnwind;
574 case bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE:
575 *Kind = Attribute::OptimizeForSize;
577 case bitc::ATTR_KIND_OPTIMIZE_NONE:
578 *Kind = Attribute::OptimizeNone;
580 case bitc::ATTR_KIND_READ_NONE:
581 *Kind = Attribute::ReadNone;
583 case bitc::ATTR_KIND_READ_ONLY:
584 *Kind = Attribute::ReadOnly;
586 case bitc::ATTR_KIND_RETURNED:
587 *Kind = Attribute::Returned;
589 case bitc::ATTR_KIND_RETURNS_TWICE:
590 *Kind = Attribute::ReturnsTwice;
592 case bitc::ATTR_KIND_S_EXT:
593 *Kind = Attribute::SExt;
595 case bitc::ATTR_KIND_STACK_ALIGNMENT:
596 *Kind = Attribute::StackAlignment;
598 case bitc::ATTR_KIND_STACK_PROTECT:
599 *Kind = Attribute::StackProtect;
601 case bitc::ATTR_KIND_STACK_PROTECT_REQ:
602 *Kind = Attribute::StackProtectReq;
604 case bitc::ATTR_KIND_STACK_PROTECT_STRONG:
605 *Kind = Attribute::StackProtectStrong;
607 case bitc::ATTR_KIND_STRUCT_RET:
608 *Kind = Attribute::StructRet;
610 case bitc::ATTR_KIND_SANITIZE_ADDRESS:
611 *Kind = Attribute::SanitizeAddress;
613 case bitc::ATTR_KIND_SANITIZE_THREAD:
614 *Kind = Attribute::SanitizeThread;
616 case bitc::ATTR_KIND_SANITIZE_MEMORY:
617 *Kind = Attribute::SanitizeMemory;
619 case bitc::ATTR_KIND_UW_TABLE:
620 *Kind = Attribute::UWTable;
622 case bitc::ATTR_KIND_Z_EXT:
623 *Kind = Attribute::ZExt;
627 raw_string_ostream fmt(Buf);
628 fmt << "Unknown attribute kind (" << Code << ")";
630 return Error(Buf.c_str());
634 bool BitcodeReader::ParseAttributeGroupBlock() {
635 if (Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID))
636 return Error("Malformed block record");
638 if (!MAttributeGroups.empty())
639 return Error("Multiple PARAMATTR_GROUP blocks found!");
641 SmallVector<uint64_t, 64> Record;
643 // Read all the records.
645 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
647 switch (Entry.Kind) {
648 case BitstreamEntry::SubBlock: // Handled for us already.
649 case BitstreamEntry::Error:
650 return Error("Error at end of PARAMATTR_GROUP block");
651 case BitstreamEntry::EndBlock:
653 case BitstreamEntry::Record:
654 // The interesting case.
660 switch (Stream.readRecord(Entry.ID, Record)) {
661 default: // Default behavior: ignore.
663 case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...]
664 if (Record.size() < 3)
665 return Error("Invalid ENTRY record");
667 uint64_t GrpID = Record[0];
668 uint64_t Idx = Record[1]; // Index of the object this attribute refers to.
671 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
672 if (Record[i] == 0) { // Enum attribute
673 Attribute::AttrKind Kind;
674 if (ParseAttrKind(Record[++i], &Kind))
677 B.addAttribute(Kind);
678 } else if (Record[i] == 1) { // Align attribute
679 Attribute::AttrKind Kind;
680 if (ParseAttrKind(Record[++i], &Kind))
682 if (Kind == Attribute::Alignment)
683 B.addAlignmentAttr(Record[++i]);
685 B.addStackAlignmentAttr(Record[++i]);
686 } else { // String attribute
687 assert((Record[i] == 3 || Record[i] == 4) &&
688 "Invalid attribute group entry");
689 bool HasValue = (Record[i++] == 4);
690 SmallString<64> KindStr;
691 SmallString<64> ValStr;
693 while (Record[i] != 0 && i != e)
694 KindStr += Record[i++];
695 assert(Record[i] == 0 && "Kind string not null terminated");
698 // Has a value associated with it.
699 ++i; // Skip the '0' that terminates the "kind" string.
700 while (Record[i] != 0 && i != e)
701 ValStr += Record[i++];
702 assert(Record[i] == 0 && "Value string not null terminated");
705 B.addAttribute(KindStr.str(), ValStr.str());
709 MAttributeGroups[GrpID] = AttributeSet::get(Context, Idx, B);
716 bool BitcodeReader::ParseTypeTable() {
717 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
718 return Error("Malformed block record");
720 return ParseTypeTableBody();
723 bool BitcodeReader::ParseTypeTableBody() {
724 if (!TypeList.empty())
725 return Error("Multiple TYPE_BLOCKs found!");
727 SmallVector<uint64_t, 64> Record;
728 unsigned NumRecords = 0;
730 SmallString<64> TypeName;
732 // Read all the records for this type table.
734 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
736 switch (Entry.Kind) {
737 case BitstreamEntry::SubBlock: // Handled for us already.
738 case BitstreamEntry::Error:
739 Error("Error in the type table block");
741 case BitstreamEntry::EndBlock:
742 if (NumRecords != TypeList.size())
743 return Error("Invalid type forward reference in TYPE_BLOCK");
745 case BitstreamEntry::Record:
746 // The interesting case.
753 switch (Stream.readRecord(Entry.ID, Record)) {
754 default: return Error("unknown type in type table");
755 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
756 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
757 // type list. This allows us to reserve space.
758 if (Record.size() < 1)
759 return Error("Invalid TYPE_CODE_NUMENTRY record");
760 TypeList.resize(Record[0]);
762 case bitc::TYPE_CODE_VOID: // VOID
763 ResultTy = Type::getVoidTy(Context);
765 case bitc::TYPE_CODE_HALF: // HALF
766 ResultTy = Type::getHalfTy(Context);
768 case bitc::TYPE_CODE_FLOAT: // FLOAT
769 ResultTy = Type::getFloatTy(Context);
771 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
772 ResultTy = Type::getDoubleTy(Context);
774 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
775 ResultTy = Type::getX86_FP80Ty(Context);
777 case bitc::TYPE_CODE_FP128: // FP128
778 ResultTy = Type::getFP128Ty(Context);
780 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
781 ResultTy = Type::getPPC_FP128Ty(Context);
783 case bitc::TYPE_CODE_LABEL: // LABEL
784 ResultTy = Type::getLabelTy(Context);
786 case bitc::TYPE_CODE_METADATA: // METADATA
787 ResultTy = Type::getMetadataTy(Context);
789 case bitc::TYPE_CODE_X86_MMX: // X86_MMX
790 ResultTy = Type::getX86_MMXTy(Context);
792 case bitc::TYPE_CODE_INTEGER: // INTEGER: [width]
793 if (Record.size() < 1)
794 return Error("Invalid Integer type record");
796 ResultTy = IntegerType::get(Context, Record[0]);
798 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
799 // [pointee type, address space]
800 if (Record.size() < 1)
801 return Error("Invalid POINTER type record");
802 unsigned AddressSpace = 0;
803 if (Record.size() == 2)
804 AddressSpace = Record[1];
805 ResultTy = getTypeByID(Record[0]);
806 if (ResultTy == 0) return Error("invalid element type in pointer type");
807 ResultTy = PointerType::get(ResultTy, AddressSpace);
810 case bitc::TYPE_CODE_FUNCTION_OLD: {
811 // FIXME: attrid is dead, remove it in LLVM 4.0
812 // FUNCTION: [vararg, attrid, retty, paramty x N]
813 if (Record.size() < 3)
814 return Error("Invalid FUNCTION type record");
815 SmallVector<Type*, 8> ArgTys;
816 for (unsigned i = 3, e = Record.size(); i != e; ++i) {
817 if (Type *T = getTypeByID(Record[i]))
823 ResultTy = getTypeByID(Record[2]);
824 if (ResultTy == 0 || ArgTys.size() < Record.size()-3)
825 return Error("invalid type in function type");
827 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
830 case bitc::TYPE_CODE_FUNCTION: {
831 // FUNCTION: [vararg, retty, paramty x N]
832 if (Record.size() < 2)
833 return Error("Invalid FUNCTION type record");
834 SmallVector<Type*, 8> ArgTys;
835 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
836 if (Type *T = getTypeByID(Record[i]))
842 ResultTy = getTypeByID(Record[1]);
843 if (ResultTy == 0 || ArgTys.size() < Record.size()-2)
844 return Error("invalid type in function type");
846 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
849 case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N]
850 if (Record.size() < 1)
851 return Error("Invalid STRUCT type record");
852 SmallVector<Type*, 8> EltTys;
853 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
854 if (Type *T = getTypeByID(Record[i]))
859 if (EltTys.size() != Record.size()-1)
860 return Error("invalid type in struct type");
861 ResultTy = StructType::get(Context, EltTys, Record[0]);
864 case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N]
865 if (ConvertToString(Record, 0, TypeName))
866 return Error("Invalid STRUCT_NAME record");
869 case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
870 if (Record.size() < 1)
871 return Error("Invalid STRUCT type record");
873 if (NumRecords >= TypeList.size())
874 return Error("invalid TYPE table");
876 // Check to see if this was forward referenced, if so fill in the temp.
877 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
879 Res->setName(TypeName);
880 TypeList[NumRecords] = 0;
881 } else // Otherwise, create a new struct.
882 Res = StructType::create(Context, TypeName);
885 SmallVector<Type*, 8> EltTys;
886 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
887 if (Type *T = getTypeByID(Record[i]))
892 if (EltTys.size() != Record.size()-1)
893 return Error("invalid STRUCT type record");
894 Res->setBody(EltTys, Record[0]);
898 case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: []
899 if (Record.size() != 1)
900 return Error("Invalid OPAQUE type record");
902 if (NumRecords >= TypeList.size())
903 return Error("invalid TYPE table");
905 // Check to see if this was forward referenced, if so fill in the temp.
906 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
908 Res->setName(TypeName);
909 TypeList[NumRecords] = 0;
910 } else // Otherwise, create a new struct with no body.
911 Res = StructType::create(Context, TypeName);
916 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
917 if (Record.size() < 2)
918 return Error("Invalid ARRAY type record");
919 if ((ResultTy = getTypeByID(Record[1])))
920 ResultTy = ArrayType::get(ResultTy, Record[0]);
922 return Error("Invalid ARRAY type element");
924 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
925 if (Record.size() < 2)
926 return Error("Invalid VECTOR type record");
927 if ((ResultTy = getTypeByID(Record[1])))
928 ResultTy = VectorType::get(ResultTy, Record[0]);
930 return Error("Invalid ARRAY type element");
934 if (NumRecords >= TypeList.size())
935 return Error("invalid TYPE table");
936 assert(ResultTy && "Didn't read a type?");
937 assert(TypeList[NumRecords] == 0 && "Already read type?");
938 TypeList[NumRecords++] = ResultTy;
942 bool BitcodeReader::ParseValueSymbolTable() {
943 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
944 return Error("Malformed block record");
946 SmallVector<uint64_t, 64> Record;
948 // Read all the records for this value table.
949 SmallString<128> ValueName;
951 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
953 switch (Entry.Kind) {
954 case BitstreamEntry::SubBlock: // Handled for us already.
955 case BitstreamEntry::Error:
956 return Error("malformed value symbol table block");
957 case BitstreamEntry::EndBlock:
959 case BitstreamEntry::Record:
960 // The interesting case.
966 switch (Stream.readRecord(Entry.ID, Record)) {
967 default: // Default behavior: unknown type.
969 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
970 if (ConvertToString(Record, 1, ValueName))
971 return Error("Invalid VST_ENTRY record");
972 unsigned ValueID = Record[0];
973 if (ValueID >= ValueList.size())
974 return Error("Invalid Value ID in VST_ENTRY record");
975 Value *V = ValueList[ValueID];
977 V->setName(StringRef(ValueName.data(), ValueName.size()));
981 case bitc::VST_CODE_BBENTRY: {
982 if (ConvertToString(Record, 1, ValueName))
983 return Error("Invalid VST_BBENTRY record");
984 BasicBlock *BB = getBasicBlock(Record[0]);
986 return Error("Invalid BB ID in VST_BBENTRY record");
988 BB->setName(StringRef(ValueName.data(), ValueName.size()));
996 bool BitcodeReader::ParseMetadata() {
997 unsigned NextMDValueNo = MDValueList.size();
999 if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
1000 return Error("Malformed block record");
1002 SmallVector<uint64_t, 64> Record;
1004 // Read all the records.
1006 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1008 switch (Entry.Kind) {
1009 case BitstreamEntry::SubBlock: // Handled for us already.
1010 case BitstreamEntry::Error:
1011 Error("malformed metadata block");
1013 case BitstreamEntry::EndBlock:
1015 case BitstreamEntry::Record:
1016 // The interesting case.
1020 bool IsFunctionLocal = false;
1023 unsigned Code = Stream.readRecord(Entry.ID, Record);
1025 default: // Default behavior: ignore.
1027 case bitc::METADATA_NAME: {
1028 // Read name of the named metadata.
1029 SmallString<8> Name(Record.begin(), Record.end());
1031 Code = Stream.ReadCode();
1033 // METADATA_NAME is always followed by METADATA_NAMED_NODE.
1034 unsigned NextBitCode = Stream.readRecord(Code, Record);
1035 assert(NextBitCode == bitc::METADATA_NAMED_NODE); (void)NextBitCode;
1037 // Read named metadata elements.
1038 unsigned Size = Record.size();
1039 NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name);
1040 for (unsigned i = 0; i != Size; ++i) {
1041 MDNode *MD = dyn_cast<MDNode>(MDValueList.getValueFwdRef(Record[i]));
1043 return Error("Malformed metadata record");
1044 NMD->addOperand(MD);
1048 case bitc::METADATA_FN_NODE:
1049 IsFunctionLocal = true;
1051 case bitc::METADATA_NODE: {
1052 if (Record.size() % 2 == 1)
1053 return Error("Invalid METADATA_NODE record");
1055 unsigned Size = Record.size();
1056 SmallVector<Value*, 8> Elts;
1057 for (unsigned i = 0; i != Size; i += 2) {
1058 Type *Ty = getTypeByID(Record[i]);
1059 if (!Ty) return Error("Invalid METADATA_NODE record");
1060 if (Ty->isMetadataTy())
1061 Elts.push_back(MDValueList.getValueFwdRef(Record[i+1]));
1062 else if (!Ty->isVoidTy())
1063 Elts.push_back(ValueList.getValueFwdRef(Record[i+1], Ty));
1065 Elts.push_back(NULL);
1067 Value *V = MDNode::getWhenValsUnresolved(Context, Elts, IsFunctionLocal);
1068 IsFunctionLocal = false;
1069 MDValueList.AssignValue(V, NextMDValueNo++);
1072 case bitc::METADATA_STRING: {
1073 SmallString<8> String(Record.begin(), Record.end());
1074 Value *V = MDString::get(Context, String);
1075 MDValueList.AssignValue(V, NextMDValueNo++);
1078 case bitc::METADATA_KIND: {
1079 if (Record.size() < 2)
1080 return Error("Invalid METADATA_KIND record");
1082 unsigned Kind = Record[0];
1083 SmallString<8> Name(Record.begin()+1, Record.end());
1085 unsigned NewKind = TheModule->getMDKindID(Name.str());
1086 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
1087 return Error("Conflicting METADATA_KIND records");
1094 /// decodeSignRotatedValue - Decode a signed value stored with the sign bit in
1095 /// the LSB for dense VBR encoding.
1096 uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
1101 // There is no such thing as -0 with integers. "-0" really means MININT.
1105 /// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
1106 /// values and aliases that we can.
1107 bool BitcodeReader::ResolveGlobalAndAliasInits() {
1108 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
1109 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
1110 std::vector<std::pair<Function*, unsigned> > FunctionPrefixWorklist;
1112 GlobalInitWorklist.swap(GlobalInits);
1113 AliasInitWorklist.swap(AliasInits);
1114 FunctionPrefixWorklist.swap(FunctionPrefixes);
1116 while (!GlobalInitWorklist.empty()) {
1117 unsigned ValID = GlobalInitWorklist.back().second;
1118 if (ValID >= ValueList.size()) {
1119 // Not ready to resolve this yet, it requires something later in the file.
1120 GlobalInits.push_back(GlobalInitWorklist.back());
1122 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
1123 GlobalInitWorklist.back().first->setInitializer(C);
1125 return Error("Global variable initializer is not a constant!");
1127 GlobalInitWorklist.pop_back();
1130 while (!AliasInitWorklist.empty()) {
1131 unsigned ValID = AliasInitWorklist.back().second;
1132 if (ValID >= ValueList.size()) {
1133 AliasInits.push_back(AliasInitWorklist.back());
1135 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
1136 AliasInitWorklist.back().first->setAliasee(C);
1138 return Error("Alias initializer is not a constant!");
1140 AliasInitWorklist.pop_back();
1143 while (!FunctionPrefixWorklist.empty()) {
1144 unsigned ValID = FunctionPrefixWorklist.back().second;
1145 if (ValID >= ValueList.size()) {
1146 FunctionPrefixes.push_back(FunctionPrefixWorklist.back());
1148 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
1149 FunctionPrefixWorklist.back().first->setPrefixData(C);
1151 return Error("Function prefix is not a constant!");
1153 FunctionPrefixWorklist.pop_back();
1159 static APInt ReadWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
1160 SmallVector<uint64_t, 8> Words(Vals.size());
1161 std::transform(Vals.begin(), Vals.end(), Words.begin(),
1162 BitcodeReader::decodeSignRotatedValue);
1164 return APInt(TypeBits, Words);
1167 bool BitcodeReader::ParseConstants() {
1168 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
1169 return Error("Malformed block record");
1171 SmallVector<uint64_t, 64> Record;
1173 // Read all the records for this value table.
1174 Type *CurTy = Type::getInt32Ty(Context);
1175 unsigned NextCstNo = ValueList.size();
1177 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1179 switch (Entry.Kind) {
1180 case BitstreamEntry::SubBlock: // Handled for us already.
1181 case BitstreamEntry::Error:
1182 return Error("malformed block record in AST file");
1183 case BitstreamEntry::EndBlock:
1184 if (NextCstNo != ValueList.size())
1185 return Error("Invalid constant reference!");
1187 // Once all the constants have been read, go through and resolve forward
1189 ValueList.ResolveConstantForwardRefs();
1191 case BitstreamEntry::Record:
1192 // The interesting case.
1199 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
1201 default: // Default behavior: unknown constant
1202 case bitc::CST_CODE_UNDEF: // UNDEF
1203 V = UndefValue::get(CurTy);
1205 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
1207 return Error("Malformed CST_SETTYPE record");
1208 if (Record[0] >= TypeList.size())
1209 return Error("Invalid Type ID in CST_SETTYPE record");
1210 CurTy = TypeList[Record[0]];
1211 continue; // Skip the ValueList manipulation.
1212 case bitc::CST_CODE_NULL: // NULL
1213 V = Constant::getNullValue(CurTy);
1215 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
1216 if (!CurTy->isIntegerTy() || Record.empty())
1217 return Error("Invalid CST_INTEGER record");
1218 V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
1220 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
1221 if (!CurTy->isIntegerTy() || Record.empty())
1222 return Error("Invalid WIDE_INTEGER record");
1224 APInt VInt = ReadWideAPInt(Record,
1225 cast<IntegerType>(CurTy)->getBitWidth());
1226 V = ConstantInt::get(Context, VInt);
1230 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
1232 return Error("Invalid FLOAT record");
1233 if (CurTy->isHalfTy())
1234 V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf,
1235 APInt(16, (uint16_t)Record[0])));
1236 else if (CurTy->isFloatTy())
1237 V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle,
1238 APInt(32, (uint32_t)Record[0])));
1239 else if (CurTy->isDoubleTy())
1240 V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble,
1241 APInt(64, Record[0])));
1242 else if (CurTy->isX86_FP80Ty()) {
1243 // Bits are not stored the same way as a normal i80 APInt, compensate.
1244 uint64_t Rearrange[2];
1245 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
1246 Rearrange[1] = Record[0] >> 48;
1247 V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended,
1248 APInt(80, Rearrange)));
1249 } else if (CurTy->isFP128Ty())
1250 V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad,
1251 APInt(128, Record)));
1252 else if (CurTy->isPPC_FP128Ty())
1253 V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble,
1254 APInt(128, Record)));
1256 V = UndefValue::get(CurTy);
1260 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
1262 return Error("Invalid CST_AGGREGATE record");
1264 unsigned Size = Record.size();
1265 SmallVector<Constant*, 16> Elts;
1267 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
1268 for (unsigned i = 0; i != Size; ++i)
1269 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
1270 STy->getElementType(i)));
1271 V = ConstantStruct::get(STy, Elts);
1272 } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
1273 Type *EltTy = ATy->getElementType();
1274 for (unsigned i = 0; i != Size; ++i)
1275 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
1276 V = ConstantArray::get(ATy, Elts);
1277 } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
1278 Type *EltTy = VTy->getElementType();
1279 for (unsigned i = 0; i != Size; ++i)
1280 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
1281 V = ConstantVector::get(Elts);
1283 V = UndefValue::get(CurTy);
1287 case bitc::CST_CODE_STRING: // STRING: [values]
1288 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
1290 return Error("Invalid CST_STRING record");
1292 SmallString<16> Elts(Record.begin(), Record.end());
1293 V = ConstantDataArray::getString(Context, Elts,
1294 BitCode == bitc::CST_CODE_CSTRING);
1297 case bitc::CST_CODE_DATA: {// DATA: [n x value]
1299 return Error("Invalid CST_DATA record");
1301 Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
1302 unsigned Size = Record.size();
1304 if (EltTy->isIntegerTy(8)) {
1305 SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
1306 if (isa<VectorType>(CurTy))
1307 V = ConstantDataVector::get(Context, Elts);
1309 V = ConstantDataArray::get(Context, Elts);
1310 } else if (EltTy->isIntegerTy(16)) {
1311 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
1312 if (isa<VectorType>(CurTy))
1313 V = ConstantDataVector::get(Context, Elts);
1315 V = ConstantDataArray::get(Context, Elts);
1316 } else if (EltTy->isIntegerTy(32)) {
1317 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
1318 if (isa<VectorType>(CurTy))
1319 V = ConstantDataVector::get(Context, Elts);
1321 V = ConstantDataArray::get(Context, Elts);
1322 } else if (EltTy->isIntegerTy(64)) {
1323 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
1324 if (isa<VectorType>(CurTy))
1325 V = ConstantDataVector::get(Context, Elts);
1327 V = ConstantDataArray::get(Context, Elts);
1328 } else if (EltTy->isFloatTy()) {
1329 SmallVector<float, 16> Elts(Size);
1330 std::transform(Record.begin(), Record.end(), Elts.begin(), BitsToFloat);
1331 if (isa<VectorType>(CurTy))
1332 V = ConstantDataVector::get(Context, Elts);
1334 V = ConstantDataArray::get(Context, Elts);
1335 } else if (EltTy->isDoubleTy()) {
1336 SmallVector<double, 16> Elts(Size);
1337 std::transform(Record.begin(), Record.end(), Elts.begin(),
1339 if (isa<VectorType>(CurTy))
1340 V = ConstantDataVector::get(Context, Elts);
1342 V = ConstantDataArray::get(Context, Elts);
1344 return Error("Unknown element type in CE_DATA");
1349 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
1350 if (Record.size() < 3) return Error("Invalid CE_BINOP record");
1351 int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
1353 V = UndefValue::get(CurTy); // Unknown binop.
1355 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
1356 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
1358 if (Record.size() >= 4) {
1359 if (Opc == Instruction::Add ||
1360 Opc == Instruction::Sub ||
1361 Opc == Instruction::Mul ||
1362 Opc == Instruction::Shl) {
1363 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
1364 Flags |= OverflowingBinaryOperator::NoSignedWrap;
1365 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
1366 Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
1367 } else if (Opc == Instruction::SDiv ||
1368 Opc == Instruction::UDiv ||
1369 Opc == Instruction::LShr ||
1370 Opc == Instruction::AShr) {
1371 if (Record[3] & (1 << bitc::PEO_EXACT))
1372 Flags |= SDivOperator::IsExact;
1375 V = ConstantExpr::get(Opc, LHS, RHS, Flags);
1379 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
1380 if (Record.size() < 3) return Error("Invalid CE_CAST record");
1381 int Opc = GetDecodedCastOpcode(Record[0]);
1383 V = UndefValue::get(CurTy); // Unknown cast.
1385 Type *OpTy = getTypeByID(Record[1]);
1386 if (!OpTy) return Error("Invalid CE_CAST record");
1387 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
1388 V = ConstantExpr::getCast(Opc, Op, CurTy);
1392 case bitc::CST_CODE_CE_INBOUNDS_GEP:
1393 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
1394 if (Record.size() & 1) return Error("Invalid CE_GEP record");
1395 SmallVector<Constant*, 16> Elts;
1396 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
1397 Type *ElTy = getTypeByID(Record[i]);
1398 if (!ElTy) return Error("Invalid CE_GEP record");
1399 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
1401 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
1402 V = ConstantExpr::getGetElementPtr(Elts[0], Indices,
1404 bitc::CST_CODE_CE_INBOUNDS_GEP);
1407 case bitc::CST_CODE_CE_SELECT: { // CE_SELECT: [opval#, opval#, opval#]
1408 if (Record.size() < 3) return Error("Invalid CE_SELECT record");
1410 Type *SelectorTy = Type::getInt1Ty(Context);
1412 // If CurTy is a vector of length n, then Record[0] must be a <n x i1>
1413 // vector. Otherwise, it must be a single bit.
1414 if (VectorType *VTy = dyn_cast<VectorType>(CurTy))
1415 SelectorTy = VectorType::get(Type::getInt1Ty(Context),
1416 VTy->getNumElements());
1418 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
1420 ValueList.getConstantFwdRef(Record[1],CurTy),
1421 ValueList.getConstantFwdRef(Record[2],CurTy));
1424 case bitc::CST_CODE_CE_EXTRACTELT: { // CE_EXTRACTELT: [opty, opval, opval]
1425 if (Record.size() < 3) return Error("Invalid CE_EXTRACTELT record");
1427 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1428 if (OpTy == 0) return Error("Invalid CE_EXTRACTELT record");
1429 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1430 Constant *Op1 = ValueList.getConstantFwdRef(Record[2],
1431 Type::getInt32Ty(Context));
1432 V = ConstantExpr::getExtractElement(Op0, Op1);
1435 case bitc::CST_CODE_CE_INSERTELT: { // CE_INSERTELT: [opval, opval, opval]
1436 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
1437 if (Record.size() < 3 || OpTy == 0)
1438 return Error("Invalid CE_INSERTELT record");
1439 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1440 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
1441 OpTy->getElementType());
1442 Constant *Op2 = ValueList.getConstantFwdRef(Record[2],
1443 Type::getInt32Ty(Context));
1444 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
1447 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
1448 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
1449 if (Record.size() < 3 || OpTy == 0)
1450 return Error("Invalid CE_SHUFFLEVEC record");
1451 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1452 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
1453 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
1454 OpTy->getNumElements());
1455 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
1456 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
1459 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
1460 VectorType *RTy = dyn_cast<VectorType>(CurTy);
1462 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1463 if (Record.size() < 4 || RTy == 0 || OpTy == 0)
1464 return Error("Invalid CE_SHUFVEC_EX record");
1465 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1466 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1467 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
1468 RTy->getNumElements());
1469 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
1470 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
1473 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
1474 if (Record.size() < 4) return Error("Invalid CE_CMP record");
1475 Type *OpTy = getTypeByID(Record[0]);
1476 if (OpTy == 0) return Error("Invalid CE_CMP record");
1477 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1478 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1480 if (OpTy->isFPOrFPVectorTy())
1481 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
1483 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
1486 // This maintains backward compatibility, pre-asm dialect keywords.
1487 // FIXME: Remove with the 4.0 release.
1488 case bitc::CST_CODE_INLINEASM_OLD: {
1489 if (Record.size() < 2) return Error("Invalid INLINEASM record");
1490 std::string AsmStr, ConstrStr;
1491 bool HasSideEffects = Record[0] & 1;
1492 bool IsAlignStack = Record[0] >> 1;
1493 unsigned AsmStrSize = Record[1];
1494 if (2+AsmStrSize >= Record.size())
1495 return Error("Invalid INLINEASM record");
1496 unsigned ConstStrSize = Record[2+AsmStrSize];
1497 if (3+AsmStrSize+ConstStrSize > Record.size())
1498 return Error("Invalid INLINEASM record");
1500 for (unsigned i = 0; i != AsmStrSize; ++i)
1501 AsmStr += (char)Record[2+i];
1502 for (unsigned i = 0; i != ConstStrSize; ++i)
1503 ConstrStr += (char)Record[3+AsmStrSize+i];
1504 PointerType *PTy = cast<PointerType>(CurTy);
1505 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
1506 AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
1509 // This version adds support for the asm dialect keywords (e.g.,
1511 case bitc::CST_CODE_INLINEASM: {
1512 if (Record.size() < 2) return Error("Invalid INLINEASM record");
1513 std::string AsmStr, ConstrStr;
1514 bool HasSideEffects = Record[0] & 1;
1515 bool IsAlignStack = (Record[0] >> 1) & 1;
1516 unsigned AsmDialect = Record[0] >> 2;
1517 unsigned AsmStrSize = Record[1];
1518 if (2+AsmStrSize >= Record.size())
1519 return Error("Invalid INLINEASM record");
1520 unsigned ConstStrSize = Record[2+AsmStrSize];
1521 if (3+AsmStrSize+ConstStrSize > Record.size())
1522 return Error("Invalid INLINEASM record");
1524 for (unsigned i = 0; i != AsmStrSize; ++i)
1525 AsmStr += (char)Record[2+i];
1526 for (unsigned i = 0; i != ConstStrSize; ++i)
1527 ConstrStr += (char)Record[3+AsmStrSize+i];
1528 PointerType *PTy = cast<PointerType>(CurTy);
1529 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
1530 AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
1531 InlineAsm::AsmDialect(AsmDialect));
1534 case bitc::CST_CODE_BLOCKADDRESS:{
1535 if (Record.size() < 3) return Error("Invalid CE_BLOCKADDRESS record");
1536 Type *FnTy = getTypeByID(Record[0]);
1537 if (FnTy == 0) return Error("Invalid CE_BLOCKADDRESS record");
1539 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
1540 if (Fn == 0) return Error("Invalid CE_BLOCKADDRESS record");
1542 // If the function is already parsed we can insert the block address right
1545 Function::iterator BBI = Fn->begin(), BBE = Fn->end();
1546 for (size_t I = 0, E = Record[2]; I != E; ++I) {
1548 return Error("Invalid blockaddress block #");
1551 V = BlockAddress::get(Fn, BBI);
1553 // Otherwise insert a placeholder and remember it so it can be inserted
1554 // when the function is parsed.
1555 GlobalVariable *FwdRef = new GlobalVariable(*Fn->getParent(),
1556 Type::getInt8Ty(Context),
1557 false, GlobalValue::InternalLinkage,
1559 BlockAddrFwdRefs[Fn].push_back(std::make_pair(Record[2], FwdRef));
1566 ValueList.AssignValue(V, NextCstNo);
1571 bool BitcodeReader::ParseUseLists() {
1572 if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
1573 return Error("Malformed block record");
1575 SmallVector<uint64_t, 64> Record;
1577 // Read all the records.
1579 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1581 switch (Entry.Kind) {
1582 case BitstreamEntry::SubBlock: // Handled for us already.
1583 case BitstreamEntry::Error:
1584 return Error("malformed use list block");
1585 case BitstreamEntry::EndBlock:
1587 case BitstreamEntry::Record:
1588 // The interesting case.
1592 // Read a use list record.
1594 switch (Stream.readRecord(Entry.ID, Record)) {
1595 default: // Default behavior: unknown type.
1597 case bitc::USELIST_CODE_ENTRY: { // USELIST_CODE_ENTRY: TBD.
1598 unsigned RecordLength = Record.size();
1599 if (RecordLength < 1)
1600 return Error ("Invalid UseList reader!");
1601 UseListRecords.push_back(Record);
1608 /// RememberAndSkipFunctionBody - When we see the block for a function body,
1609 /// remember where it is and then skip it. This lets us lazily deserialize the
1611 bool BitcodeReader::RememberAndSkipFunctionBody() {
1612 // Get the function we are talking about.
1613 if (FunctionsWithBodies.empty())
1614 return Error("Insufficient function protos");
1616 Function *Fn = FunctionsWithBodies.back();
1617 FunctionsWithBodies.pop_back();
1619 // Save the current stream state.
1620 uint64_t CurBit = Stream.GetCurrentBitNo();
1621 DeferredFunctionInfo[Fn] = CurBit;
1623 // Skip over the function block for now.
1624 if (Stream.SkipBlock())
1625 return Error("Malformed block record");
1629 bool BitcodeReader::GlobalCleanup() {
1630 // Patch the initializers for globals and aliases up.
1631 ResolveGlobalAndAliasInits();
1632 if (!GlobalInits.empty() || !AliasInits.empty())
1633 return Error("Malformed global initializer set");
1635 // Look for intrinsic functions which need to be upgraded at some point
1636 for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
1639 if (UpgradeIntrinsicFunction(FI, NewFn))
1640 UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
1643 // Look for global variables which need to be renamed.
1644 for (Module::global_iterator
1645 GI = TheModule->global_begin(), GE = TheModule->global_end();
1647 UpgradeGlobalVariable(GI);
1648 // Force deallocation of memory for these vectors to favor the client that
1649 // want lazy deserialization.
1650 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
1651 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
1655 bool BitcodeReader::ParseModule(bool Resume) {
1657 Stream.JumpToBit(NextUnreadBit);
1658 else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
1659 return Error("Malformed block record");
1661 SmallVector<uint64_t, 64> Record;
1662 std::vector<std::string> SectionTable;
1663 std::vector<std::string> GCTable;
1665 // Read all the records for this module.
1667 BitstreamEntry Entry = Stream.advance();
1669 switch (Entry.Kind) {
1670 case BitstreamEntry::Error:
1671 Error("malformed module block");
1673 case BitstreamEntry::EndBlock:
1674 return GlobalCleanup();
1676 case BitstreamEntry::SubBlock:
1678 default: // Skip unknown content.
1679 if (Stream.SkipBlock())
1680 return Error("Malformed block record");
1682 case bitc::BLOCKINFO_BLOCK_ID:
1683 if (Stream.ReadBlockInfoBlock())
1684 return Error("Malformed BlockInfoBlock");
1686 case bitc::PARAMATTR_BLOCK_ID:
1687 if (ParseAttributeBlock())
1690 case bitc::PARAMATTR_GROUP_BLOCK_ID:
1691 if (ParseAttributeGroupBlock())
1694 case bitc::TYPE_BLOCK_ID_NEW:
1695 if (ParseTypeTable())
1698 case bitc::VALUE_SYMTAB_BLOCK_ID:
1699 if (ParseValueSymbolTable())
1701 SeenValueSymbolTable = true;
1703 case bitc::CONSTANTS_BLOCK_ID:
1704 if (ParseConstants() || ResolveGlobalAndAliasInits())
1707 case bitc::METADATA_BLOCK_ID:
1708 if (ParseMetadata())
1711 case bitc::FUNCTION_BLOCK_ID:
1712 // If this is the first function body we've seen, reverse the
1713 // FunctionsWithBodies list.
1714 if (!SeenFirstFunctionBody) {
1715 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
1716 if (GlobalCleanup())
1718 SeenFirstFunctionBody = true;
1721 if (RememberAndSkipFunctionBody())
1723 // For streaming bitcode, suspend parsing when we reach the function
1724 // bodies. Subsequent materialization calls will resume it when
1725 // necessary. For streaming, the function bodies must be at the end of
1726 // the bitcode. If the bitcode file is old, the symbol table will be
1727 // at the end instead and will not have been seen yet. In this case,
1728 // just finish the parse now.
1729 if (LazyStreamer && SeenValueSymbolTable) {
1730 NextUnreadBit = Stream.GetCurrentBitNo();
1734 case bitc::USELIST_BLOCK_ID:
1735 if (ParseUseLists())
1741 case BitstreamEntry::Record:
1742 // The interesting case.
1748 switch (Stream.readRecord(Entry.ID, Record)) {
1749 default: break; // Default behavior, ignore unknown content.
1750 case bitc::MODULE_CODE_VERSION: { // VERSION: [version#]
1751 if (Record.size() < 1)
1752 return Error("Malformed MODULE_CODE_VERSION");
1753 // Only version #0 and #1 are supported so far.
1754 unsigned module_version = Record[0];
1755 switch (module_version) {
1756 default: return Error("Unknown bitstream version!");
1758 UseRelativeIDs = false;
1761 UseRelativeIDs = true;
1766 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
1768 if (ConvertToString(Record, 0, S))
1769 return Error("Invalid MODULE_CODE_TRIPLE record");
1770 TheModule->setTargetTriple(S);
1773 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
1775 if (ConvertToString(Record, 0, S))
1776 return Error("Invalid MODULE_CODE_DATALAYOUT record");
1777 TheModule->setDataLayout(S);
1780 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
1782 if (ConvertToString(Record, 0, S))
1783 return Error("Invalid MODULE_CODE_ASM record");
1784 TheModule->setModuleInlineAsm(S);
1787 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
1788 // FIXME: Remove in 4.0.
1790 if (ConvertToString(Record, 0, S))
1791 return Error("Invalid MODULE_CODE_DEPLIB record");
1795 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
1797 if (ConvertToString(Record, 0, S))
1798 return Error("Invalid MODULE_CODE_SECTIONNAME record");
1799 SectionTable.push_back(S);
1802 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
1804 if (ConvertToString(Record, 0, S))
1805 return Error("Invalid MODULE_CODE_GCNAME record");
1806 GCTable.push_back(S);
1809 // GLOBALVAR: [pointer type, isconst, initid,
1810 // linkage, alignment, section, visibility, threadlocal,
1812 case bitc::MODULE_CODE_GLOBALVAR: {
1813 if (Record.size() < 6)
1814 return Error("Invalid MODULE_CODE_GLOBALVAR record");
1815 Type *Ty = getTypeByID(Record[0]);
1816 if (!Ty) return Error("Invalid MODULE_CODE_GLOBALVAR record");
1817 if (!Ty->isPointerTy())
1818 return Error("Global not a pointer type!");
1819 unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
1820 Ty = cast<PointerType>(Ty)->getElementType();
1822 bool isConstant = Record[1];
1823 GlobalValue::LinkageTypes Linkage = GetDecodedLinkage(Record[3]);
1824 unsigned Alignment = (1 << Record[4]) >> 1;
1825 std::string Section;
1827 if (Record[5]-1 >= SectionTable.size())
1828 return Error("Invalid section ID");
1829 Section = SectionTable[Record[5]-1];
1831 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
1832 if (Record.size() > 6)
1833 Visibility = GetDecodedVisibility(Record[6]);
1835 GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
1836 if (Record.size() > 7)
1837 TLM = GetDecodedThreadLocalMode(Record[7]);
1839 bool UnnamedAddr = false;
1840 if (Record.size() > 8)
1841 UnnamedAddr = Record[8];
1843 bool ExternallyInitialized = false;
1844 if (Record.size() > 9)
1845 ExternallyInitialized = Record[9];
1847 GlobalVariable *NewGV =
1848 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, 0, "", 0,
1849 TLM, AddressSpace, ExternallyInitialized);
1850 NewGV->setAlignment(Alignment);
1851 if (!Section.empty())
1852 NewGV->setSection(Section);
1853 NewGV->setVisibility(Visibility);
1854 NewGV->setUnnamedAddr(UnnamedAddr);
1856 ValueList.push_back(NewGV);
1858 // Remember which value to use for the global initializer.
1859 if (unsigned InitID = Record[2])
1860 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
1863 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
1864 // alignment, section, visibility, gc, unnamed_addr]
1865 case bitc::MODULE_CODE_FUNCTION: {
1866 if (Record.size() < 8)
1867 return Error("Invalid MODULE_CODE_FUNCTION record");
1868 Type *Ty = getTypeByID(Record[0]);
1869 if (!Ty) return Error("Invalid MODULE_CODE_FUNCTION record");
1870 if (!Ty->isPointerTy())
1871 return Error("Function not a pointer type!");
1873 dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
1875 return Error("Function not a pointer to function type!");
1877 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
1880 Func->setCallingConv(static_cast<CallingConv::ID>(Record[1]));
1881 bool isProto = Record[2];
1882 Func->setLinkage(GetDecodedLinkage(Record[3]));
1883 Func->setAttributes(getAttributes(Record[4]));
1885 Func->setAlignment((1 << Record[5]) >> 1);
1887 if (Record[6]-1 >= SectionTable.size())
1888 return Error("Invalid section ID");
1889 Func->setSection(SectionTable[Record[6]-1]);
1891 Func->setVisibility(GetDecodedVisibility(Record[7]));
1892 if (Record.size() > 8 && Record[8]) {
1893 if (Record[8]-1 > GCTable.size())
1894 return Error("Invalid GC ID");
1895 Func->setGC(GCTable[Record[8]-1].c_str());
1897 bool UnnamedAddr = false;
1898 if (Record.size() > 9)
1899 UnnamedAddr = Record[9];
1900 Func->setUnnamedAddr(UnnamedAddr);
1901 if (Record.size() > 10 && Record[10] != 0)
1902 FunctionPrefixes.push_back(std::make_pair(Func, Record[10]-1));
1903 ValueList.push_back(Func);
1905 // If this is a function with a body, remember the prototype we are
1906 // creating now, so that we can match up the body with them later.
1908 FunctionsWithBodies.push_back(Func);
1909 if (LazyStreamer) DeferredFunctionInfo[Func] = 0;
1913 // ALIAS: [alias type, aliasee val#, linkage]
1914 // ALIAS: [alias type, aliasee val#, linkage, visibility]
1915 case bitc::MODULE_CODE_ALIAS: {
1916 if (Record.size() < 3)
1917 return Error("Invalid MODULE_ALIAS record");
1918 Type *Ty = getTypeByID(Record[0]);
1919 if (!Ty) return Error("Invalid MODULE_ALIAS record");
1920 if (!Ty->isPointerTy())
1921 return Error("Function not a pointer type!");
1923 GlobalAlias *NewGA = new GlobalAlias(Ty, GetDecodedLinkage(Record[2]),
1925 // Old bitcode files didn't have visibility field.
1926 if (Record.size() > 3)
1927 NewGA->setVisibility(GetDecodedVisibility(Record[3]));
1928 ValueList.push_back(NewGA);
1929 AliasInits.push_back(std::make_pair(NewGA, Record[1]));
1932 /// MODULE_CODE_PURGEVALS: [numvals]
1933 case bitc::MODULE_CODE_PURGEVALS:
1934 // Trim down the value list to the specified size.
1935 if (Record.size() < 1 || Record[0] > ValueList.size())
1936 return Error("Invalid MODULE_PURGEVALS record");
1937 ValueList.shrinkTo(Record[0]);
1944 bool BitcodeReader::ParseBitcodeInto(Module *M) {
1947 if (InitStream()) return true;
1949 // Sniff for the signature.
1950 if (Stream.Read(8) != 'B' ||
1951 Stream.Read(8) != 'C' ||
1952 Stream.Read(4) != 0x0 ||
1953 Stream.Read(4) != 0xC ||
1954 Stream.Read(4) != 0xE ||
1955 Stream.Read(4) != 0xD)
1956 return Error("Invalid bitcode signature");
1958 // We expect a number of well-defined blocks, though we don't necessarily
1959 // need to understand them all.
1961 if (Stream.AtEndOfStream())
1964 BitstreamEntry Entry =
1965 Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
1967 switch (Entry.Kind) {
1968 case BitstreamEntry::Error:
1969 Error("malformed module file");
1971 case BitstreamEntry::EndBlock:
1974 case BitstreamEntry::SubBlock:
1976 case bitc::BLOCKINFO_BLOCK_ID:
1977 if (Stream.ReadBlockInfoBlock())
1978 return Error("Malformed BlockInfoBlock");
1980 case bitc::MODULE_BLOCK_ID:
1981 // Reject multiple MODULE_BLOCK's in a single bitstream.
1983 return Error("Multiple MODULE_BLOCKs in same stream");
1985 if (ParseModule(false))
1987 if (LazyStreamer) return false;
1990 if (Stream.SkipBlock())
1991 return Error("Malformed block record");
1995 case BitstreamEntry::Record:
1996 // There should be no records in the top-level of blocks.
1998 // The ranlib in Xcode 4 will align archive members by appending newlines
1999 // to the end of them. If this file size is a multiple of 4 but not 8, we
2000 // have to read and ignore these final 4 bytes :-(
2001 if (Stream.getAbbrevIDWidth() == 2 && Entry.ID == 2 &&
2002 Stream.Read(6) == 2 && Stream.Read(24) == 0xa0a0a &&
2003 Stream.AtEndOfStream())
2006 return Error("Invalid record at top-level");
2011 bool BitcodeReader::ParseModuleTriple(std::string &Triple) {
2012 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
2013 return Error("Malformed block record");
2015 SmallVector<uint64_t, 64> Record;
2017 // Read all the records for this module.
2019 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2021 switch (Entry.Kind) {
2022 case BitstreamEntry::SubBlock: // Handled for us already.
2023 case BitstreamEntry::Error:
2024 return Error("malformed module block");
2025 case BitstreamEntry::EndBlock:
2027 case BitstreamEntry::Record:
2028 // The interesting case.
2033 switch (Stream.readRecord(Entry.ID, Record)) {
2034 default: break; // Default behavior, ignore unknown content.
2035 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
2037 if (ConvertToString(Record, 0, S))
2038 return Error("Invalid MODULE_CODE_TRIPLE record");
2047 bool BitcodeReader::ParseTriple(std::string &Triple) {
2048 if (InitStream()) return true;
2050 // Sniff for the signature.
2051 if (Stream.Read(8) != 'B' ||
2052 Stream.Read(8) != 'C' ||
2053 Stream.Read(4) != 0x0 ||
2054 Stream.Read(4) != 0xC ||
2055 Stream.Read(4) != 0xE ||
2056 Stream.Read(4) != 0xD)
2057 return Error("Invalid bitcode signature");
2059 // We expect a number of well-defined blocks, though we don't necessarily
2060 // need to understand them all.
2062 BitstreamEntry Entry = Stream.advance();
2064 switch (Entry.Kind) {
2065 case BitstreamEntry::Error:
2066 Error("malformed module file");
2068 case BitstreamEntry::EndBlock:
2071 case BitstreamEntry::SubBlock:
2072 if (Entry.ID == bitc::MODULE_BLOCK_ID)
2073 return ParseModuleTriple(Triple);
2075 // Ignore other sub-blocks.
2076 if (Stream.SkipBlock()) {
2077 Error("malformed block record in AST file");
2082 case BitstreamEntry::Record:
2083 Stream.skipRecord(Entry.ID);
2089 /// ParseMetadataAttachment - Parse metadata attachments.
2090 bool BitcodeReader::ParseMetadataAttachment() {
2091 if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
2092 return Error("Malformed block record");
2094 SmallVector<uint64_t, 64> Record;
2096 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2098 switch (Entry.Kind) {
2099 case BitstreamEntry::SubBlock: // Handled for us already.
2100 case BitstreamEntry::Error:
2101 return Error("malformed metadata block");
2102 case BitstreamEntry::EndBlock:
2104 case BitstreamEntry::Record:
2105 // The interesting case.
2109 // Read a metadata attachment record.
2111 switch (Stream.readRecord(Entry.ID, Record)) {
2112 default: // Default behavior: ignore.
2114 case bitc::METADATA_ATTACHMENT: {
2115 unsigned RecordLength = Record.size();
2116 if (Record.empty() || (RecordLength - 1) % 2 == 1)
2117 return Error ("Invalid METADATA_ATTACHMENT reader!");
2118 Instruction *Inst = InstructionList[Record[0]];
2119 for (unsigned i = 1; i != RecordLength; i = i+2) {
2120 unsigned Kind = Record[i];
2121 DenseMap<unsigned, unsigned>::iterator I =
2122 MDKindMap.find(Kind);
2123 if (I == MDKindMap.end())
2124 return Error("Invalid metadata kind ID");
2125 Value *Node = MDValueList.getValueFwdRef(Record[i+1]);
2126 Inst->setMetadata(I->second, cast<MDNode>(Node));
2127 if (I->second == LLVMContext::MD_tbaa)
2128 InstsWithTBAATag.push_back(Inst);
2136 /// ParseFunctionBody - Lazily parse the specified function body block.
2137 bool BitcodeReader::ParseFunctionBody(Function *F) {
2138 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
2139 return Error("Malformed block record");
2141 InstructionList.clear();
2142 unsigned ModuleValueListSize = ValueList.size();
2143 unsigned ModuleMDValueListSize = MDValueList.size();
2145 // Add all the function arguments to the value table.
2146 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
2147 ValueList.push_back(I);
2149 unsigned NextValueNo = ValueList.size();
2150 BasicBlock *CurBB = 0;
2151 unsigned CurBBNo = 0;
2155 // Read all the records.
2156 SmallVector<uint64_t, 64> Record;
2158 BitstreamEntry Entry = Stream.advance();
2160 switch (Entry.Kind) {
2161 case BitstreamEntry::Error:
2162 return Error("Bitcode error in function block");
2163 case BitstreamEntry::EndBlock:
2164 goto OutOfRecordLoop;
2166 case BitstreamEntry::SubBlock:
2168 default: // Skip unknown content.
2169 if (Stream.SkipBlock())
2170 return Error("Malformed block record");
2172 case bitc::CONSTANTS_BLOCK_ID:
2173 if (ParseConstants()) return true;
2174 NextValueNo = ValueList.size();
2176 case bitc::VALUE_SYMTAB_BLOCK_ID:
2177 if (ParseValueSymbolTable()) return true;
2179 case bitc::METADATA_ATTACHMENT_ID:
2180 if (ParseMetadataAttachment()) return true;
2182 case bitc::METADATA_BLOCK_ID:
2183 if (ParseMetadata()) return true;
2188 case BitstreamEntry::Record:
2189 // The interesting case.
2196 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
2198 default: // Default behavior: reject
2199 return Error("Unknown instruction");
2200 case bitc::FUNC_CODE_DECLAREBLOCKS: // DECLAREBLOCKS: [nblocks]
2201 if (Record.size() < 1 || Record[0] == 0)
2202 return Error("Invalid DECLAREBLOCKS record");
2203 // Create all the basic blocks for the function.
2204 FunctionBBs.resize(Record[0]);
2205 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
2206 FunctionBBs[i] = BasicBlock::Create(Context, "", F);
2207 CurBB = FunctionBBs[0];
2210 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN
2211 // This record indicates that the last instruction is at the same
2212 // location as the previous instruction with a location.
2215 // Get the last instruction emitted.
2216 if (CurBB && !CurBB->empty())
2218 else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
2219 !FunctionBBs[CurBBNo-1]->empty())
2220 I = &FunctionBBs[CurBBNo-1]->back();
2222 if (I == 0) return Error("Invalid DEBUG_LOC_AGAIN record");
2223 I->setDebugLoc(LastLoc);
2227 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia]
2228 I = 0; // Get the last instruction emitted.
2229 if (CurBB && !CurBB->empty())
2231 else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
2232 !FunctionBBs[CurBBNo-1]->empty())
2233 I = &FunctionBBs[CurBBNo-1]->back();
2234 if (I == 0 || Record.size() < 4)
2235 return Error("Invalid FUNC_CODE_DEBUG_LOC record");
2237 unsigned Line = Record[0], Col = Record[1];
2238 unsigned ScopeID = Record[2], IAID = Record[3];
2240 MDNode *Scope = 0, *IA = 0;
2241 if (ScopeID) Scope = cast<MDNode>(MDValueList.getValueFwdRef(ScopeID-1));
2242 if (IAID) IA = cast<MDNode>(MDValueList.getValueFwdRef(IAID-1));
2243 LastLoc = DebugLoc::get(Line, Col, Scope, IA);
2244 I->setDebugLoc(LastLoc);
2249 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
2252 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
2253 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
2254 OpNum+1 > Record.size())
2255 return Error("Invalid BINOP record");
2257 int Opc = GetDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
2258 if (Opc == -1) return Error("Invalid BINOP record");
2259 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
2260 InstructionList.push_back(I);
2261 if (OpNum < Record.size()) {
2262 if (Opc == Instruction::Add ||
2263 Opc == Instruction::Sub ||
2264 Opc == Instruction::Mul ||
2265 Opc == Instruction::Shl) {
2266 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
2267 cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
2268 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
2269 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
2270 } else if (Opc == Instruction::SDiv ||
2271 Opc == Instruction::UDiv ||
2272 Opc == Instruction::LShr ||
2273 Opc == Instruction::AShr) {
2274 if (Record[OpNum] & (1 << bitc::PEO_EXACT))
2275 cast<BinaryOperator>(I)->setIsExact(true);
2276 } else if (isa<FPMathOperator>(I)) {
2278 if (0 != (Record[OpNum] & FastMathFlags::UnsafeAlgebra))
2279 FMF.setUnsafeAlgebra();
2280 if (0 != (Record[OpNum] & FastMathFlags::NoNaNs))
2282 if (0 != (Record[OpNum] & FastMathFlags::NoInfs))
2284 if (0 != (Record[OpNum] & FastMathFlags::NoSignedZeros))
2285 FMF.setNoSignedZeros();
2286 if (0 != (Record[OpNum] & FastMathFlags::AllowReciprocal))
2287 FMF.setAllowReciprocal();
2289 I->setFastMathFlags(FMF);
2295 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
2298 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2299 OpNum+2 != Record.size())
2300 return Error("Invalid CAST record");
2302 Type *ResTy = getTypeByID(Record[OpNum]);
2303 int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
2304 if (Opc == -1 || ResTy == 0)
2305 return Error("Invalid CAST record");
2306 I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
2307 InstructionList.push_back(I);
2310 case bitc::FUNC_CODE_INST_INBOUNDS_GEP:
2311 case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands]
2314 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
2315 return Error("Invalid GEP record");
2317 SmallVector<Value*, 16> GEPIdx;
2318 while (OpNum != Record.size()) {
2320 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2321 return Error("Invalid GEP record");
2322 GEPIdx.push_back(Op);
2325 I = GetElementPtrInst::Create(BasePtr, GEPIdx);
2326 InstructionList.push_back(I);
2327 if (BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP)
2328 cast<GetElementPtrInst>(I)->setIsInBounds(true);
2332 case bitc::FUNC_CODE_INST_EXTRACTVAL: {
2333 // EXTRACTVAL: [opty, opval, n x indices]
2336 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2337 return Error("Invalid EXTRACTVAL record");
2339 SmallVector<unsigned, 4> EXTRACTVALIdx;
2340 for (unsigned RecSize = Record.size();
2341 OpNum != RecSize; ++OpNum) {
2342 uint64_t Index = Record[OpNum];
2343 if ((unsigned)Index != Index)
2344 return Error("Invalid EXTRACTVAL index");
2345 EXTRACTVALIdx.push_back((unsigned)Index);
2348 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
2349 InstructionList.push_back(I);
2353 case bitc::FUNC_CODE_INST_INSERTVAL: {
2354 // INSERTVAL: [opty, opval, opty, opval, n x indices]
2357 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2358 return Error("Invalid INSERTVAL record");
2360 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
2361 return Error("Invalid INSERTVAL record");
2363 SmallVector<unsigned, 4> INSERTVALIdx;
2364 for (unsigned RecSize = Record.size();
2365 OpNum != RecSize; ++OpNum) {
2366 uint64_t Index = Record[OpNum];
2367 if ((unsigned)Index != Index)
2368 return Error("Invalid INSERTVAL index");
2369 INSERTVALIdx.push_back((unsigned)Index);
2372 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
2373 InstructionList.push_back(I);
2377 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
2378 // obsolete form of select
2379 // handles select i1 ... in old bitcode
2381 Value *TrueVal, *FalseVal, *Cond;
2382 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
2383 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
2384 popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond))
2385 return Error("Invalid SELECT record");
2387 I = SelectInst::Create(Cond, TrueVal, FalseVal);
2388 InstructionList.push_back(I);
2392 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
2393 // new form of select
2394 // handles select i1 or select [N x i1]
2396 Value *TrueVal, *FalseVal, *Cond;
2397 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
2398 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
2399 getValueTypePair(Record, OpNum, NextValueNo, Cond))
2400 return Error("Invalid SELECT record");
2402 // select condition can be either i1 or [N x i1]
2403 if (VectorType* vector_type =
2404 dyn_cast<VectorType>(Cond->getType())) {
2406 if (vector_type->getElementType() != Type::getInt1Ty(Context))
2407 return Error("Invalid SELECT condition type");
2410 if (Cond->getType() != Type::getInt1Ty(Context))
2411 return Error("Invalid SELECT condition type");
2414 I = SelectInst::Create(Cond, TrueVal, FalseVal);
2415 InstructionList.push_back(I);
2419 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
2422 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
2423 popValue(Record, OpNum, NextValueNo, Type::getInt32Ty(Context), Idx))
2424 return Error("Invalid EXTRACTELT record");
2425 I = ExtractElementInst::Create(Vec, Idx);
2426 InstructionList.push_back(I);
2430 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
2432 Value *Vec, *Elt, *Idx;
2433 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
2434 popValue(Record, OpNum, NextValueNo,
2435 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
2436 popValue(Record, OpNum, NextValueNo, Type::getInt32Ty(Context), Idx))
2437 return Error("Invalid INSERTELT record");
2438 I = InsertElementInst::Create(Vec, Elt, Idx);
2439 InstructionList.push_back(I);
2443 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
2445 Value *Vec1, *Vec2, *Mask;
2446 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
2447 popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2))
2448 return Error("Invalid SHUFFLEVEC record");
2450 if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
2451 return Error("Invalid SHUFFLEVEC record");
2452 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
2453 InstructionList.push_back(I);
2457 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
2458 // Old form of ICmp/FCmp returning bool
2459 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
2460 // both legal on vectors but had different behaviour.
2461 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
2462 // FCmp/ICmp returning bool or vector of bool
2466 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
2467 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
2468 OpNum+1 != Record.size())
2469 return Error("Invalid CMP record");
2471 if (LHS->getType()->isFPOrFPVectorTy())
2472 I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
2474 I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
2475 InstructionList.push_back(I);
2479 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
2481 unsigned Size = Record.size();
2483 I = ReturnInst::Create(Context);
2484 InstructionList.push_back(I);
2490 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2491 return Error("Invalid RET record");
2492 if (OpNum != Record.size())
2493 return Error("Invalid RET record");
2495 I = ReturnInst::Create(Context, Op);
2496 InstructionList.push_back(I);
2499 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
2500 if (Record.size() != 1 && Record.size() != 3)
2501 return Error("Invalid BR record");
2502 BasicBlock *TrueDest = getBasicBlock(Record[0]);
2504 return Error("Invalid BR record");
2506 if (Record.size() == 1) {
2507 I = BranchInst::Create(TrueDest);
2508 InstructionList.push_back(I);
2511 BasicBlock *FalseDest = getBasicBlock(Record[1]);
2512 Value *Cond = getValue(Record, 2, NextValueNo,
2513 Type::getInt1Ty(Context));
2514 if (FalseDest == 0 || Cond == 0)
2515 return Error("Invalid BR record");
2516 I = BranchInst::Create(TrueDest, FalseDest, Cond);
2517 InstructionList.push_back(I);
2521 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
2523 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
2524 // "New" SwitchInst format with case ranges. The changes to write this
2525 // format were reverted but we still recognize bitcode that uses it.
2526 // Hopefully someday we will have support for case ranges and can use
2527 // this format again.
2529 Type *OpTy = getTypeByID(Record[1]);
2530 unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
2532 Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
2533 BasicBlock *Default = getBasicBlock(Record[3]);
2534 if (OpTy == 0 || Cond == 0 || Default == 0)
2535 return Error("Invalid SWITCH record");
2537 unsigned NumCases = Record[4];
2539 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
2540 InstructionList.push_back(SI);
2542 unsigned CurIdx = 5;
2543 for (unsigned i = 0; i != NumCases; ++i) {
2544 SmallVector<ConstantInt*, 1> CaseVals;
2545 unsigned NumItems = Record[CurIdx++];
2546 for (unsigned ci = 0; ci != NumItems; ++ci) {
2547 bool isSingleNumber = Record[CurIdx++];
2550 unsigned ActiveWords = 1;
2551 if (ValueBitWidth > 64)
2552 ActiveWords = Record[CurIdx++];
2553 Low = ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
2555 CurIdx += ActiveWords;
2557 if (!isSingleNumber) {
2559 if (ValueBitWidth > 64)
2560 ActiveWords = Record[CurIdx++];
2562 ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
2564 CurIdx += ActiveWords;
2566 // FIXME: It is not clear whether values in the range should be
2567 // compared as signed or unsigned values. The partially
2568 // implemented changes that used this format in the past used
2569 // unsigned comparisons.
2570 for ( ; Low.ule(High); ++Low)
2571 CaseVals.push_back(ConstantInt::get(Context, Low));
2573 CaseVals.push_back(ConstantInt::get(Context, Low));
2575 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
2576 for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(),
2577 cve = CaseVals.end(); cvi != cve; ++cvi)
2578 SI->addCase(*cvi, DestBB);
2584 // Old SwitchInst format without case ranges.
2586 if (Record.size() < 3 || (Record.size() & 1) == 0)
2587 return Error("Invalid SWITCH record");
2588 Type *OpTy = getTypeByID(Record[0]);
2589 Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
2590 BasicBlock *Default = getBasicBlock(Record[2]);
2591 if (OpTy == 0 || Cond == 0 || Default == 0)
2592 return Error("Invalid SWITCH record");
2593 unsigned NumCases = (Record.size()-3)/2;
2594 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
2595 InstructionList.push_back(SI);
2596 for (unsigned i = 0, e = NumCases; i != e; ++i) {
2597 ConstantInt *CaseVal =
2598 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
2599 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
2600 if (CaseVal == 0 || DestBB == 0) {
2602 return Error("Invalid SWITCH record!");
2604 SI->addCase(CaseVal, DestBB);
2609 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
2610 if (Record.size() < 2)
2611 return Error("Invalid INDIRECTBR record");
2612 Type *OpTy = getTypeByID(Record[0]);
2613 Value *Address = getValue(Record, 1, NextValueNo, OpTy);
2614 if (OpTy == 0 || Address == 0)
2615 return Error("Invalid INDIRECTBR record");
2616 unsigned NumDests = Record.size()-2;
2617 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
2618 InstructionList.push_back(IBI);
2619 for (unsigned i = 0, e = NumDests; i != e; ++i) {
2620 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
2621 IBI->addDestination(DestBB);
2624 return Error("Invalid INDIRECTBR record!");
2631 case bitc::FUNC_CODE_INST_INVOKE: {
2632 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
2633 if (Record.size() < 4) return Error("Invalid INVOKE record");
2634 AttributeSet PAL = getAttributes(Record[0]);
2635 unsigned CCInfo = Record[1];
2636 BasicBlock *NormalBB = getBasicBlock(Record[2]);
2637 BasicBlock *UnwindBB = getBasicBlock(Record[3]);
2641 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
2642 return Error("Invalid INVOKE record");
2644 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
2645 FunctionType *FTy = !CalleeTy ? 0 :
2646 dyn_cast<FunctionType>(CalleeTy->getElementType());
2648 // Check that the right number of fixed parameters are here.
2649 if (FTy == 0 || NormalBB == 0 || UnwindBB == 0 ||
2650 Record.size() < OpNum+FTy->getNumParams())
2651 return Error("Invalid INVOKE record");
2653 SmallVector<Value*, 16> Ops;
2654 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
2655 Ops.push_back(getValue(Record, OpNum, NextValueNo,
2656 FTy->getParamType(i)));
2657 if (Ops.back() == 0) return Error("Invalid INVOKE record");
2660 if (!FTy->isVarArg()) {
2661 if (Record.size() != OpNum)
2662 return Error("Invalid INVOKE record");
2664 // Read type/value pairs for varargs params.
2665 while (OpNum != Record.size()) {
2667 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2668 return Error("Invalid INVOKE record");
2673 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops);
2674 InstructionList.push_back(I);
2675 cast<InvokeInst>(I)->setCallingConv(
2676 static_cast<CallingConv::ID>(CCInfo));
2677 cast<InvokeInst>(I)->setAttributes(PAL);
2680 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
2683 if (getValueTypePair(Record, Idx, NextValueNo, Val))
2684 return Error("Invalid RESUME record");
2685 I = ResumeInst::Create(Val);
2686 InstructionList.push_back(I);
2689 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
2690 I = new UnreachableInst(Context);
2691 InstructionList.push_back(I);
2693 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
2694 if (Record.size() < 1 || ((Record.size()-1)&1))
2695 return Error("Invalid PHI record");
2696 Type *Ty = getTypeByID(Record[0]);
2697 if (!Ty) return Error("Invalid PHI record");
2699 PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
2700 InstructionList.push_back(PN);
2702 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
2704 // With the new function encoding, it is possible that operands have
2705 // negative IDs (for forward references). Use a signed VBR
2706 // representation to keep the encoding small.
2708 V = getValueSigned(Record, 1+i, NextValueNo, Ty);
2710 V = getValue(Record, 1+i, NextValueNo, Ty);
2711 BasicBlock *BB = getBasicBlock(Record[2+i]);
2712 if (!V || !BB) return Error("Invalid PHI record");
2713 PN->addIncoming(V, BB);
2719 case bitc::FUNC_CODE_INST_LANDINGPAD: {
2720 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
2722 if (Record.size() < 4)
2723 return Error("Invalid LANDINGPAD record");
2724 Type *Ty = getTypeByID(Record[Idx++]);
2725 if (!Ty) return Error("Invalid LANDINGPAD record");
2727 if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
2728 return Error("Invalid LANDINGPAD record");
2730 bool IsCleanup = !!Record[Idx++];
2731 unsigned NumClauses = Record[Idx++];
2732 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, NumClauses);
2733 LP->setCleanup(IsCleanup);
2734 for (unsigned J = 0; J != NumClauses; ++J) {
2735 LandingPadInst::ClauseType CT =
2736 LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
2739 if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
2741 return Error("Invalid LANDINGPAD record");
2744 assert((CT != LandingPadInst::Catch ||
2745 !isa<ArrayType>(Val->getType())) &&
2746 "Catch clause has a invalid type!");
2747 assert((CT != LandingPadInst::Filter ||
2748 isa<ArrayType>(Val->getType())) &&
2749 "Filter clause has invalid type!");
2754 InstructionList.push_back(I);
2758 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
2759 if (Record.size() != 4)
2760 return Error("Invalid ALLOCA record");
2762 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
2763 Type *OpTy = getTypeByID(Record[1]);
2764 Value *Size = getFnValueByID(Record[2], OpTy);
2765 unsigned Align = Record[3];
2766 if (!Ty || !Size) return Error("Invalid ALLOCA record");
2767 I = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
2768 InstructionList.push_back(I);
2771 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
2774 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2775 OpNum+2 != Record.size())
2776 return Error("Invalid LOAD record");
2778 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1);
2779 InstructionList.push_back(I);
2782 case bitc::FUNC_CODE_INST_LOADATOMIC: {
2783 // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
2786 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2787 OpNum+4 != Record.size())
2788 return Error("Invalid LOADATOMIC record");
2791 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
2792 if (Ordering == NotAtomic || Ordering == Release ||
2793 Ordering == AcquireRelease)
2794 return Error("Invalid LOADATOMIC record");
2795 if (Ordering != NotAtomic && Record[OpNum] == 0)
2796 return Error("Invalid LOADATOMIC record");
2797 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2799 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1,
2800 Ordering, SynchScope);
2801 InstructionList.push_back(I);
2804 case bitc::FUNC_CODE_INST_STORE: { // STORE2:[ptrty, ptr, val, align, vol]
2807 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2808 popValue(Record, OpNum, NextValueNo,
2809 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2810 OpNum+2 != Record.size())
2811 return Error("Invalid STORE record");
2813 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
2814 InstructionList.push_back(I);
2817 case bitc::FUNC_CODE_INST_STOREATOMIC: {
2818 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
2821 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2822 popValue(Record, OpNum, NextValueNo,
2823 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2824 OpNum+4 != Record.size())
2825 return Error("Invalid STOREATOMIC record");
2827 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
2828 if (Ordering == NotAtomic || Ordering == Acquire ||
2829 Ordering == AcquireRelease)
2830 return Error("Invalid STOREATOMIC record");
2831 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2832 if (Ordering != NotAtomic && Record[OpNum] == 0)
2833 return Error("Invalid STOREATOMIC record");
2835 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1,
2836 Ordering, SynchScope);
2837 InstructionList.push_back(I);
2840 case bitc::FUNC_CODE_INST_CMPXCHG: {
2841 // CMPXCHG:[ptrty, ptr, cmp, new, vol, ordering, synchscope]
2843 Value *Ptr, *Cmp, *New;
2844 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2845 popValue(Record, OpNum, NextValueNo,
2846 cast<PointerType>(Ptr->getType())->getElementType(), Cmp) ||
2847 popValue(Record, OpNum, NextValueNo,
2848 cast<PointerType>(Ptr->getType())->getElementType(), New) ||
2849 OpNum+3 != Record.size())
2850 return Error("Invalid CMPXCHG record");
2851 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+1]);
2852 if (Ordering == NotAtomic || Ordering == Unordered)
2853 return Error("Invalid CMPXCHG record");
2854 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+2]);
2855 I = new AtomicCmpXchgInst(Ptr, Cmp, New, Ordering, SynchScope);
2856 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
2857 InstructionList.push_back(I);
2860 case bitc::FUNC_CODE_INST_ATOMICRMW: {
2861 // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
2864 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2865 popValue(Record, OpNum, NextValueNo,
2866 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2867 OpNum+4 != Record.size())
2868 return Error("Invalid ATOMICRMW record");
2869 AtomicRMWInst::BinOp Operation = GetDecodedRMWOperation(Record[OpNum]);
2870 if (Operation < AtomicRMWInst::FIRST_BINOP ||
2871 Operation > AtomicRMWInst::LAST_BINOP)
2872 return Error("Invalid ATOMICRMW record");
2873 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
2874 if (Ordering == NotAtomic || Ordering == Unordered)
2875 return Error("Invalid ATOMICRMW record");
2876 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2877 I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
2878 cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
2879 InstructionList.push_back(I);
2882 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
2883 if (2 != Record.size())
2884 return Error("Invalid FENCE record");
2885 AtomicOrdering Ordering = GetDecodedOrdering(Record[0]);
2886 if (Ordering == NotAtomic || Ordering == Unordered ||
2887 Ordering == Monotonic)
2888 return Error("Invalid FENCE record");
2889 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[1]);
2890 I = new FenceInst(Context, Ordering, SynchScope);
2891 InstructionList.push_back(I);
2894 case bitc::FUNC_CODE_INST_CALL: {
2895 // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
2896 if (Record.size() < 3)
2897 return Error("Invalid CALL record");
2899 AttributeSet PAL = getAttributes(Record[0]);
2900 unsigned CCInfo = Record[1];
2904 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
2905 return Error("Invalid CALL record");
2907 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
2908 FunctionType *FTy = 0;
2909 if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
2910 if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
2911 return Error("Invalid CALL record");
2913 SmallVector<Value*, 16> Args;
2914 // Read the fixed params.
2915 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
2916 if (FTy->getParamType(i)->isLabelTy())
2917 Args.push_back(getBasicBlock(Record[OpNum]));
2919 Args.push_back(getValue(Record, OpNum, NextValueNo,
2920 FTy->getParamType(i)));
2921 if (Args.back() == 0) return Error("Invalid CALL record");
2924 // Read type/value pairs for varargs params.
2925 if (!FTy->isVarArg()) {
2926 if (OpNum != Record.size())
2927 return Error("Invalid CALL record");
2929 while (OpNum != Record.size()) {
2931 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2932 return Error("Invalid CALL record");
2937 I = CallInst::Create(Callee, Args);
2938 InstructionList.push_back(I);
2939 cast<CallInst>(I)->setCallingConv(
2940 static_cast<CallingConv::ID>(CCInfo>>1));
2941 cast<CallInst>(I)->setTailCall(CCInfo & 1);
2942 cast<CallInst>(I)->setAttributes(PAL);
2945 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
2946 if (Record.size() < 3)
2947 return Error("Invalid VAARG record");
2948 Type *OpTy = getTypeByID(Record[0]);
2949 Value *Op = getValue(Record, 1, NextValueNo, OpTy);
2950 Type *ResTy = getTypeByID(Record[2]);
2951 if (!OpTy || !Op || !ResTy)
2952 return Error("Invalid VAARG record");
2953 I = new VAArgInst(Op, ResTy);
2954 InstructionList.push_back(I);
2959 // Add instruction to end of current BB. If there is no current BB, reject
2963 return Error("Invalid instruction with no BB");
2965 CurBB->getInstList().push_back(I);
2967 // If this was a terminator instruction, move to the next block.
2968 if (isa<TerminatorInst>(I)) {
2970 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : 0;
2973 // Non-void values get registered in the value table for future use.
2974 if (I && !I->getType()->isVoidTy())
2975 ValueList.AssignValue(I, NextValueNo++);
2980 // Check the function list for unresolved values.
2981 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
2982 if (A->getParent() == 0) {
2983 // We found at least one unresolved value. Nuke them all to avoid leaks.
2984 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
2985 if ((A = dyn_cast<Argument>(ValueList[i])) && A->getParent() == 0) {
2986 A->replaceAllUsesWith(UndefValue::get(A->getType()));
2990 return Error("Never resolved value found in function!");
2994 // FIXME: Check for unresolved forward-declared metadata references
2995 // and clean up leaks.
2997 // See if anything took the address of blocks in this function. If so,
2998 // resolve them now.
2999 DenseMap<Function*, std::vector<BlockAddrRefTy> >::iterator BAFRI =
3000 BlockAddrFwdRefs.find(F);
3001 if (BAFRI != BlockAddrFwdRefs.end()) {
3002 std::vector<BlockAddrRefTy> &RefList = BAFRI->second;
3003 for (unsigned i = 0, e = RefList.size(); i != e; ++i) {
3004 unsigned BlockIdx = RefList[i].first;
3005 if (BlockIdx >= FunctionBBs.size())
3006 return Error("Invalid blockaddress block #");
3008 GlobalVariable *FwdRef = RefList[i].second;
3009 FwdRef->replaceAllUsesWith(BlockAddress::get(F, FunctionBBs[BlockIdx]));
3010 FwdRef->eraseFromParent();
3013 BlockAddrFwdRefs.erase(BAFRI);
3016 // Trim the value list down to the size it was before we parsed this function.
3017 ValueList.shrinkTo(ModuleValueListSize);
3018 MDValueList.shrinkTo(ModuleMDValueListSize);
3019 std::vector<BasicBlock*>().swap(FunctionBBs);
3023 /// FindFunctionInStream - Find the function body in the bitcode stream
3024 bool BitcodeReader::FindFunctionInStream(Function *F,
3025 DenseMap<Function*, uint64_t>::iterator DeferredFunctionInfoIterator) {
3026 while (DeferredFunctionInfoIterator->second == 0) {
3027 if (Stream.AtEndOfStream())
3028 return Error("Could not find Function in stream");
3029 // ParseModule will parse the next body in the stream and set its
3030 // position in the DeferredFunctionInfo map.
3031 if (ParseModule(true)) return true;
3036 //===----------------------------------------------------------------------===//
3037 // GVMaterializer implementation
3038 //===----------------------------------------------------------------------===//
3041 bool BitcodeReader::isMaterializable(const GlobalValue *GV) const {
3042 if (const Function *F = dyn_cast<Function>(GV)) {
3043 return F->isDeclaration() &&
3044 DeferredFunctionInfo.count(const_cast<Function*>(F));
3049 bool BitcodeReader::Materialize(GlobalValue *GV, std::string *ErrInfo) {
3050 Function *F = dyn_cast<Function>(GV);
3051 // If it's not a function or is already material, ignore the request.
3052 if (!F || !F->isMaterializable()) return false;
3054 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
3055 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
3056 // If its position is recorded as 0, its body is somewhere in the stream
3057 // but we haven't seen it yet.
3058 if (DFII->second == 0)
3059 if (LazyStreamer && FindFunctionInStream(F, DFII)) return true;
3061 // Move the bit stream to the saved position of the deferred function body.
3062 Stream.JumpToBit(DFII->second);
3064 if (ParseFunctionBody(F)) {
3065 if (ErrInfo) *ErrInfo = ErrorString;
3069 // Upgrade any old intrinsic calls in the function.
3070 for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
3071 E = UpgradedIntrinsics.end(); I != E; ++I) {
3072 if (I->first != I->second) {
3073 for (Value::use_iterator UI = I->first->use_begin(),
3074 UE = I->first->use_end(); UI != UE; ) {
3075 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
3076 UpgradeIntrinsicCall(CI, I->second);
3084 bool BitcodeReader::isDematerializable(const GlobalValue *GV) const {
3085 const Function *F = dyn_cast<Function>(GV);
3086 if (!F || F->isDeclaration())
3088 return DeferredFunctionInfo.count(const_cast<Function*>(F));
3091 void BitcodeReader::Dematerialize(GlobalValue *GV) {
3092 Function *F = dyn_cast<Function>(GV);
3093 // If this function isn't dematerializable, this is a noop.
3094 if (!F || !isDematerializable(F))
3097 assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
3099 // Just forget the function body, we can remat it later.
3104 bool BitcodeReader::MaterializeModule(Module *M, std::string *ErrInfo) {
3105 assert(M == TheModule &&
3106 "Can only Materialize the Module this BitcodeReader is attached to.");
3107 // Iterate over the module, deserializing any functions that are still on
3109 for (Module::iterator F = TheModule->begin(), E = TheModule->end();
3111 if (F->isMaterializable() &&
3112 Materialize(F, ErrInfo))
3115 // At this point, if there are any function bodies, the current bit is
3116 // pointing to the END_BLOCK record after them. Now make sure the rest
3117 // of the bits in the module have been read.
3121 // Upgrade any intrinsic calls that slipped through (should not happen!) and
3122 // delete the old functions to clean up. We can't do this unless the entire
3123 // module is materialized because there could always be another function body
3124 // with calls to the old function.
3125 for (std::vector<std::pair<Function*, Function*> >::iterator I =
3126 UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
3127 if (I->first != I->second) {
3128 for (Value::use_iterator UI = I->first->use_begin(),
3129 UE = I->first->use_end(); UI != UE; ) {
3130 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
3131 UpgradeIntrinsicCall(CI, I->second);
3133 if (!I->first->use_empty())
3134 I->first->replaceAllUsesWith(I->second);
3135 I->first->eraseFromParent();
3138 std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
3140 for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
3141 UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
3146 bool BitcodeReader::InitStream() {
3147 if (LazyStreamer) return InitLazyStream();
3148 return InitStreamFromBuffer();
3151 bool BitcodeReader::InitStreamFromBuffer() {
3152 const unsigned char *BufPtr = (const unsigned char*)Buffer->getBufferStart();
3153 const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
3155 if (Buffer->getBufferSize() & 3) {
3156 if (!isRawBitcode(BufPtr, BufEnd) && !isBitcodeWrapper(BufPtr, BufEnd))
3157 return Error("Invalid bitcode signature");
3159 return Error("Bitcode stream should be a multiple of 4 bytes in length");
3162 // If we have a wrapper header, parse it and ignore the non-bc file contents.
3163 // The magic number is 0x0B17C0DE stored in little endian.
3164 if (isBitcodeWrapper(BufPtr, BufEnd))
3165 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
3166 return Error("Invalid bitcode wrapper header");
3168 StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
3169 Stream.init(*StreamFile);
3174 bool BitcodeReader::InitLazyStream() {
3175 // Check and strip off the bitcode wrapper; BitstreamReader expects never to
3177 StreamingMemoryObject *Bytes = new StreamingMemoryObject(LazyStreamer);
3178 StreamFile.reset(new BitstreamReader(Bytes));
3179 Stream.init(*StreamFile);
3181 unsigned char buf[16];
3182 if (Bytes->readBytes(0, 16, buf) == -1)
3183 return Error("Bitcode stream must be at least 16 bytes in length");
3185 if (!isBitcode(buf, buf + 16))
3186 return Error("Invalid bitcode signature");
3188 if (isBitcodeWrapper(buf, buf + 4)) {
3189 const unsigned char *bitcodeStart = buf;
3190 const unsigned char *bitcodeEnd = buf + 16;
3191 SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
3192 Bytes->dropLeadingBytes(bitcodeStart - buf);
3193 Bytes->setKnownObjectSize(bitcodeEnd - bitcodeStart);
3198 //===----------------------------------------------------------------------===//
3199 // External interface
3200 //===----------------------------------------------------------------------===//
3202 /// getLazyBitcodeModule - lazy function-at-a-time loading from a file.
3204 Module *llvm::getLazyBitcodeModule(MemoryBuffer *Buffer,
3205 LLVMContext& Context,
3206 std::string *ErrMsg) {
3207 Module *M = new Module(Buffer->getBufferIdentifier(), Context);
3208 BitcodeReader *R = new BitcodeReader(Buffer, Context);
3209 M->setMaterializer(R);
3210 if (R->ParseBitcodeInto(M)) {
3212 *ErrMsg = R->getErrorString();
3214 delete M; // Also deletes R.
3217 // Have the BitcodeReader dtor delete 'Buffer'.
3218 R->setBufferOwned(true);
3220 R->materializeForwardReferencedFunctions();
3226 Module *llvm::getStreamedBitcodeModule(const std::string &name,
3227 DataStreamer *streamer,
3228 LLVMContext &Context,
3229 std::string *ErrMsg) {
3230 Module *M = new Module(name, Context);
3231 BitcodeReader *R = new BitcodeReader(streamer, Context);
3232 M->setMaterializer(R);
3233 if (R->ParseBitcodeInto(M)) {
3235 *ErrMsg = R->getErrorString();
3236 delete M; // Also deletes R.
3239 R->setBufferOwned(false); // no buffer to delete
3243 /// ParseBitcodeFile - Read the specified bitcode file, returning the module.
3244 /// If an error occurs, return null and fill in *ErrMsg if non-null.
3245 Module *llvm::ParseBitcodeFile(MemoryBuffer *Buffer, LLVMContext& Context,
3246 std::string *ErrMsg){
3247 Module *M = getLazyBitcodeModule(Buffer, Context, ErrMsg);
3250 // Don't let the BitcodeReader dtor delete 'Buffer', regardless of whether
3251 // there was an error.
3252 static_cast<BitcodeReader*>(M->getMaterializer())->setBufferOwned(false);
3254 // Read in the entire module, and destroy the BitcodeReader.
3255 if (M->MaterializeAllPermanently(ErrMsg)) {
3260 // TODO: Restore the use-lists to the in-memory state when the bitcode was
3261 // written. We must defer until the Module has been fully materialized.
3266 std::string llvm::getBitcodeTargetTriple(MemoryBuffer *Buffer,
3267 LLVMContext& Context,
3268 std::string *ErrMsg) {
3269 BitcodeReader *R = new BitcodeReader(Buffer, Context);
3270 // Don't let the BitcodeReader dtor delete 'Buffer'.
3271 R->setBufferOwned(false);
3273 std::string Triple("");
3274 if (R->ParseTriple(Triple))
3276 *ErrMsg = R->getErrorString();