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;
96 static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned Val) {
98 default: // Map unknown visibilities to default.
99 case 0: return GlobalValue::DefaultVisibility;
100 case 1: return GlobalValue::HiddenVisibility;
101 case 2: return GlobalValue::ProtectedVisibility;
105 static GlobalVariable::ThreadLocalMode GetDecodedThreadLocalMode(unsigned Val) {
107 case 0: return GlobalVariable::NotThreadLocal;
108 default: // Map unknown non-zero value to general dynamic.
109 case 1: return GlobalVariable::GeneralDynamicTLSModel;
110 case 2: return GlobalVariable::LocalDynamicTLSModel;
111 case 3: return GlobalVariable::InitialExecTLSModel;
112 case 4: return GlobalVariable::LocalExecTLSModel;
116 static int GetDecodedCastOpcode(unsigned Val) {
119 case bitc::CAST_TRUNC : return Instruction::Trunc;
120 case bitc::CAST_ZEXT : return Instruction::ZExt;
121 case bitc::CAST_SEXT : return Instruction::SExt;
122 case bitc::CAST_FPTOUI : return Instruction::FPToUI;
123 case bitc::CAST_FPTOSI : return Instruction::FPToSI;
124 case bitc::CAST_UITOFP : return Instruction::UIToFP;
125 case bitc::CAST_SITOFP : return Instruction::SIToFP;
126 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
127 case bitc::CAST_FPEXT : return Instruction::FPExt;
128 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
129 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
130 case bitc::CAST_BITCAST : return Instruction::BitCast;
133 static int GetDecodedBinaryOpcode(unsigned Val, Type *Ty) {
136 case bitc::BINOP_ADD:
137 return Ty->isFPOrFPVectorTy() ? Instruction::FAdd : Instruction::Add;
138 case bitc::BINOP_SUB:
139 return Ty->isFPOrFPVectorTy() ? Instruction::FSub : Instruction::Sub;
140 case bitc::BINOP_MUL:
141 return Ty->isFPOrFPVectorTy() ? Instruction::FMul : Instruction::Mul;
142 case bitc::BINOP_UDIV: return Instruction::UDiv;
143 case bitc::BINOP_SDIV:
144 return Ty->isFPOrFPVectorTy() ? Instruction::FDiv : Instruction::SDiv;
145 case bitc::BINOP_UREM: return Instruction::URem;
146 case bitc::BINOP_SREM:
147 return Ty->isFPOrFPVectorTy() ? Instruction::FRem : Instruction::SRem;
148 case bitc::BINOP_SHL: return Instruction::Shl;
149 case bitc::BINOP_LSHR: return Instruction::LShr;
150 case bitc::BINOP_ASHR: return Instruction::AShr;
151 case bitc::BINOP_AND: return Instruction::And;
152 case bitc::BINOP_OR: return Instruction::Or;
153 case bitc::BINOP_XOR: return Instruction::Xor;
157 static AtomicRMWInst::BinOp GetDecodedRMWOperation(unsigned Val) {
159 default: return AtomicRMWInst::BAD_BINOP;
160 case bitc::RMW_XCHG: return AtomicRMWInst::Xchg;
161 case bitc::RMW_ADD: return AtomicRMWInst::Add;
162 case bitc::RMW_SUB: return AtomicRMWInst::Sub;
163 case bitc::RMW_AND: return AtomicRMWInst::And;
164 case bitc::RMW_NAND: return AtomicRMWInst::Nand;
165 case bitc::RMW_OR: return AtomicRMWInst::Or;
166 case bitc::RMW_XOR: return AtomicRMWInst::Xor;
167 case bitc::RMW_MAX: return AtomicRMWInst::Max;
168 case bitc::RMW_MIN: return AtomicRMWInst::Min;
169 case bitc::RMW_UMAX: return AtomicRMWInst::UMax;
170 case bitc::RMW_UMIN: return AtomicRMWInst::UMin;
174 static AtomicOrdering GetDecodedOrdering(unsigned Val) {
176 case bitc::ORDERING_NOTATOMIC: return NotAtomic;
177 case bitc::ORDERING_UNORDERED: return Unordered;
178 case bitc::ORDERING_MONOTONIC: return Monotonic;
179 case bitc::ORDERING_ACQUIRE: return Acquire;
180 case bitc::ORDERING_RELEASE: return Release;
181 case bitc::ORDERING_ACQREL: return AcquireRelease;
182 default: // Map unknown orderings to sequentially-consistent.
183 case bitc::ORDERING_SEQCST: return SequentiallyConsistent;
187 static SynchronizationScope GetDecodedSynchScope(unsigned Val) {
189 case bitc::SYNCHSCOPE_SINGLETHREAD: return SingleThread;
190 default: // Map unknown scopes to cross-thread.
191 case bitc::SYNCHSCOPE_CROSSTHREAD: return CrossThread;
197 /// @brief A class for maintaining the slot number definition
198 /// as a placeholder for the actual definition for forward constants defs.
199 class ConstantPlaceHolder : public ConstantExpr {
200 void operator=(const ConstantPlaceHolder &) LLVM_DELETED_FUNCTION;
202 // allocate space for exactly one operand
203 void *operator new(size_t s) {
204 return User::operator new(s, 1);
206 explicit ConstantPlaceHolder(Type *Ty, LLVMContext& Context)
207 : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
208 Op<0>() = UndefValue::get(Type::getInt32Ty(Context));
211 /// @brief Methods to support type inquiry through isa, cast, and dyn_cast.
212 static bool classof(const Value *V) {
213 return isa<ConstantExpr>(V) &&
214 cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
218 /// Provide fast operand accessors
219 //DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
223 // FIXME: can we inherit this from ConstantExpr?
225 struct OperandTraits<ConstantPlaceHolder> :
226 public FixedNumOperandTraits<ConstantPlaceHolder, 1> {
231 void BitcodeReaderValueList::AssignValue(Value *V, unsigned Idx) {
240 WeakVH &OldV = ValuePtrs[Idx];
246 // Handle constants and non-constants (e.g. instrs) differently for
248 if (Constant *PHC = dyn_cast<Constant>(&*OldV)) {
249 ResolveConstants.push_back(std::make_pair(PHC, Idx));
252 // If there was a forward reference to this value, replace it.
253 Value *PrevVal = OldV;
254 OldV->replaceAllUsesWith(V);
260 Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
265 if (Value *V = ValuePtrs[Idx]) {
266 assert(Ty == V->getType() && "Type mismatch in constant table!");
267 return cast<Constant>(V);
270 // Create and return a placeholder, which will later be RAUW'd.
271 Constant *C = new ConstantPlaceHolder(Ty, Context);
276 Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, Type *Ty) {
280 if (Value *V = ValuePtrs[Idx]) {
281 assert((Ty == 0 || Ty == V->getType()) && "Type mismatch in value table!");
285 // No type specified, must be invalid reference.
286 if (Ty == 0) return 0;
288 // Create and return a placeholder, which will later be RAUW'd.
289 Value *V = new Argument(Ty);
294 /// ResolveConstantForwardRefs - Once all constants are read, this method bulk
295 /// resolves any forward references. The idea behind this is that we sometimes
296 /// get constants (such as large arrays) which reference *many* forward ref
297 /// constants. Replacing each of these causes a lot of thrashing when
298 /// building/reuniquing the constant. Instead of doing this, we look at all the
299 /// uses and rewrite all the place holders at once for any constant that uses
301 void BitcodeReaderValueList::ResolveConstantForwardRefs() {
302 // Sort the values by-pointer so that they are efficient to look up with a
304 std::sort(ResolveConstants.begin(), ResolveConstants.end());
306 SmallVector<Constant*, 64> NewOps;
308 while (!ResolveConstants.empty()) {
309 Value *RealVal = operator[](ResolveConstants.back().second);
310 Constant *Placeholder = ResolveConstants.back().first;
311 ResolveConstants.pop_back();
313 // Loop over all users of the placeholder, updating them to reference the
314 // new value. If they reference more than one placeholder, update them all
316 while (!Placeholder->use_empty()) {
317 Value::use_iterator UI = Placeholder->use_begin();
320 // If the using object isn't uniqued, just update the operands. This
321 // handles instructions and initializers for global variables.
322 if (!isa<Constant>(U) || isa<GlobalValue>(U)) {
323 UI.getUse().set(RealVal);
327 // Otherwise, we have a constant that uses the placeholder. Replace that
328 // constant with a new constant that has *all* placeholder uses updated.
329 Constant *UserC = cast<Constant>(U);
330 for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end();
333 if (!isa<ConstantPlaceHolder>(*I)) {
334 // Not a placeholder reference.
336 } else if (*I == Placeholder) {
337 // Common case is that it just references this one placeholder.
340 // Otherwise, look up the placeholder in ResolveConstants.
341 ResolveConstantsTy::iterator It =
342 std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(),
343 std::pair<Constant*, unsigned>(cast<Constant>(*I),
345 assert(It != ResolveConstants.end() && It->first == *I);
346 NewOp = operator[](It->second);
349 NewOps.push_back(cast<Constant>(NewOp));
352 // Make the new constant.
354 if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
355 NewC = ConstantArray::get(UserCA->getType(), NewOps);
356 } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
357 NewC = ConstantStruct::get(UserCS->getType(), NewOps);
358 } else if (isa<ConstantVector>(UserC)) {
359 NewC = ConstantVector::get(NewOps);
361 assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr.");
362 NewC = cast<ConstantExpr>(UserC)->getWithOperands(NewOps);
365 UserC->replaceAllUsesWith(NewC);
366 UserC->destroyConstant();
370 // Update all ValueHandles, they should be the only users at this point.
371 Placeholder->replaceAllUsesWith(RealVal);
376 void BitcodeReaderMDValueList::AssignValue(Value *V, unsigned Idx) {
385 WeakVH &OldV = MDValuePtrs[Idx];
391 // If there was a forward reference to this value, replace it.
392 MDNode *PrevVal = cast<MDNode>(OldV);
393 OldV->replaceAllUsesWith(V);
394 MDNode::deleteTemporary(PrevVal);
395 // Deleting PrevVal sets Idx value in MDValuePtrs to null. Set new
397 MDValuePtrs[Idx] = V;
400 Value *BitcodeReaderMDValueList::getValueFwdRef(unsigned Idx) {
404 if (Value *V = MDValuePtrs[Idx]) {
405 assert(V->getType()->isMetadataTy() && "Type mismatch in value table!");
409 // Create and return a placeholder, which will later be RAUW'd.
410 Value *V = MDNode::getTemporary(Context, None);
411 MDValuePtrs[Idx] = V;
415 Type *BitcodeReader::getTypeByID(unsigned ID) {
416 // The type table size is always specified correctly.
417 if (ID >= TypeList.size())
420 if (Type *Ty = TypeList[ID])
423 // If we have a forward reference, the only possible case is when it is to a
424 // named struct. Just create a placeholder for now.
425 return TypeList[ID] = StructType::create(Context);
429 //===----------------------------------------------------------------------===//
430 // Functions for parsing blocks from the bitcode file
431 //===----------------------------------------------------------------------===//
434 /// \brief This fills an AttrBuilder object with the LLVM attributes that have
435 /// been decoded from the given integer. This function must stay in sync with
436 /// 'encodeLLVMAttributesForBitcode'.
437 static void decodeLLVMAttributesForBitcode(AttrBuilder &B,
438 uint64_t EncodedAttrs) {
439 // FIXME: Remove in 4.0.
441 // The alignment is stored as a 16-bit raw value from bits 31--16. We shift
442 // the bits above 31 down by 11 bits.
443 unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
444 assert((!Alignment || isPowerOf2_32(Alignment)) &&
445 "Alignment must be a power of two.");
448 B.addAlignmentAttr(Alignment);
449 B.addRawValue(((EncodedAttrs & (0xfffffULL << 32)) >> 11) |
450 (EncodedAttrs & 0xffff));
453 bool BitcodeReader::ParseAttributeBlock() {
454 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
455 return Error("Malformed block record");
457 if (!MAttributes.empty())
458 return Error("Multiple PARAMATTR blocks found!");
460 SmallVector<uint64_t, 64> Record;
462 SmallVector<AttributeSet, 8> Attrs;
464 // Read all the records.
466 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
468 switch (Entry.Kind) {
469 case BitstreamEntry::SubBlock: // Handled for us already.
470 case BitstreamEntry::Error:
471 return Error("Error at end of PARAMATTR block");
472 case BitstreamEntry::EndBlock:
474 case BitstreamEntry::Record:
475 // The interesting case.
481 switch (Stream.readRecord(Entry.ID, Record)) {
482 default: // Default behavior: ignore.
484 case bitc::PARAMATTR_CODE_ENTRY_OLD: { // ENTRY: [paramidx0, attr0, ...]
485 // FIXME: Remove in 4.0.
486 if (Record.size() & 1)
487 return Error("Invalid ENTRY record");
489 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
491 decodeLLVMAttributesForBitcode(B, Record[i+1]);
492 Attrs.push_back(AttributeSet::get(Context, Record[i], B));
495 MAttributes.push_back(AttributeSet::get(Context, Attrs));
499 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [attrgrp0, attrgrp1, ...]
500 for (unsigned i = 0, e = Record.size(); i != e; ++i)
501 Attrs.push_back(MAttributeGroups[Record[i]]);
503 MAttributes.push_back(AttributeSet::get(Context, Attrs));
511 bool BitcodeReader::ParseAttrKind(uint64_t Code, Attribute::AttrKind *Kind) {
513 case bitc::ATTR_KIND_ALIGNMENT:
514 *Kind = Attribute::Alignment;
516 case bitc::ATTR_KIND_ALWAYS_INLINE:
517 *Kind = Attribute::AlwaysInline;
519 case bitc::ATTR_KIND_BUILTIN:
520 *Kind = Attribute::Builtin;
522 case bitc::ATTR_KIND_BY_VAL:
523 *Kind = Attribute::ByVal;
525 case bitc::ATTR_KIND_COLD:
526 *Kind = Attribute::Cold;
528 case bitc::ATTR_KIND_INLINE_HINT:
529 *Kind = Attribute::InlineHint;
531 case bitc::ATTR_KIND_IN_REG:
532 *Kind = Attribute::InReg;
534 case bitc::ATTR_KIND_MIN_SIZE:
535 *Kind = Attribute::MinSize;
537 case bitc::ATTR_KIND_NAKED:
538 *Kind = Attribute::Naked;
540 case bitc::ATTR_KIND_NEST:
541 *Kind = Attribute::Nest;
543 case bitc::ATTR_KIND_NO_ALIAS:
544 *Kind = Attribute::NoAlias;
546 case bitc::ATTR_KIND_NO_BUILTIN:
547 *Kind = Attribute::NoBuiltin;
549 case bitc::ATTR_KIND_NO_CAPTURE:
550 *Kind = Attribute::NoCapture;
552 case bitc::ATTR_KIND_NO_DUPLICATE:
553 *Kind = Attribute::NoDuplicate;
555 case bitc::ATTR_KIND_NO_IMPLICIT_FLOAT:
556 *Kind = Attribute::NoImplicitFloat;
558 case bitc::ATTR_KIND_NO_INLINE:
559 *Kind = Attribute::NoInline;
561 case bitc::ATTR_KIND_NON_LAZY_BIND:
562 *Kind = Attribute::NonLazyBind;
564 case bitc::ATTR_KIND_NO_RED_ZONE:
565 *Kind = Attribute::NoRedZone;
567 case bitc::ATTR_KIND_NO_RETURN:
568 *Kind = Attribute::NoReturn;
570 case bitc::ATTR_KIND_NO_UNWIND:
571 *Kind = Attribute::NoUnwind;
573 case bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE:
574 *Kind = Attribute::OptimizeForSize;
576 case bitc::ATTR_KIND_OPTIMIZE_NONE:
577 *Kind = Attribute::OptimizeNone;
579 case bitc::ATTR_KIND_READ_NONE:
580 *Kind = Attribute::ReadNone;
582 case bitc::ATTR_KIND_READ_ONLY:
583 *Kind = Attribute::ReadOnly;
585 case bitc::ATTR_KIND_RETURNED:
586 *Kind = Attribute::Returned;
588 case bitc::ATTR_KIND_RETURNS_TWICE:
589 *Kind = Attribute::ReturnsTwice;
591 case bitc::ATTR_KIND_S_EXT:
592 *Kind = Attribute::SExt;
594 case bitc::ATTR_KIND_STACK_ALIGNMENT:
595 *Kind = Attribute::StackAlignment;
597 case bitc::ATTR_KIND_STACK_PROTECT:
598 *Kind = Attribute::StackProtect;
600 case bitc::ATTR_KIND_STACK_PROTECT_REQ:
601 *Kind = Attribute::StackProtectReq;
603 case bitc::ATTR_KIND_STACK_PROTECT_STRONG:
604 *Kind = Attribute::StackProtectStrong;
606 case bitc::ATTR_KIND_STRUCT_RET:
607 *Kind = Attribute::StructRet;
609 case bitc::ATTR_KIND_SANITIZE_ADDRESS:
610 *Kind = Attribute::SanitizeAddress;
612 case bitc::ATTR_KIND_SANITIZE_THREAD:
613 *Kind = Attribute::SanitizeThread;
615 case bitc::ATTR_KIND_SANITIZE_MEMORY:
616 *Kind = Attribute::SanitizeMemory;
618 case bitc::ATTR_KIND_UW_TABLE:
619 *Kind = Attribute::UWTable;
621 case bitc::ATTR_KIND_Z_EXT:
622 *Kind = Attribute::ZExt;
625 return Error("Unknown attribute kind");
629 bool BitcodeReader::ParseAttributeGroupBlock() {
630 if (Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID))
631 return Error("Malformed block record");
633 if (!MAttributeGroups.empty())
634 return Error("Multiple PARAMATTR_GROUP blocks found!");
636 SmallVector<uint64_t, 64> Record;
638 // Read all the records.
640 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
642 switch (Entry.Kind) {
643 case BitstreamEntry::SubBlock: // Handled for us already.
644 case BitstreamEntry::Error:
645 return Error("Error at end of PARAMATTR_GROUP block");
646 case BitstreamEntry::EndBlock:
648 case BitstreamEntry::Record:
649 // The interesting case.
655 switch (Stream.readRecord(Entry.ID, Record)) {
656 default: // Default behavior: ignore.
658 case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...]
659 if (Record.size() < 3)
660 return Error("Invalid ENTRY record");
662 uint64_t GrpID = Record[0];
663 uint64_t Idx = Record[1]; // Index of the object this attribute refers to.
666 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
667 if (Record[i] == 0) { // Enum attribute
668 Attribute::AttrKind Kind;
669 if (ParseAttrKind(Record[++i], &Kind))
672 B.addAttribute(Kind);
673 } else if (Record[i] == 1) { // Align attribute
674 Attribute::AttrKind Kind;
675 if (ParseAttrKind(Record[++i], &Kind))
677 if (Kind == Attribute::Alignment)
678 B.addAlignmentAttr(Record[++i]);
680 B.addStackAlignmentAttr(Record[++i]);
681 } else { // String attribute
682 assert((Record[i] == 3 || Record[i] == 4) &&
683 "Invalid attribute group entry");
684 bool HasValue = (Record[i++] == 4);
685 SmallString<64> KindStr;
686 SmallString<64> ValStr;
688 while (Record[i] != 0 && i != e)
689 KindStr += Record[i++];
690 assert(Record[i] == 0 && "Kind string not null terminated");
693 // Has a value associated with it.
694 ++i; // Skip the '0' that terminates the "kind" string.
695 while (Record[i] != 0 && i != e)
696 ValStr += Record[i++];
697 assert(Record[i] == 0 && "Value string not null terminated");
700 B.addAttribute(KindStr.str(), ValStr.str());
704 MAttributeGroups[GrpID] = AttributeSet::get(Context, Idx, B);
711 bool BitcodeReader::ParseTypeTable() {
712 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
713 return Error("Malformed block record");
715 return ParseTypeTableBody();
718 bool BitcodeReader::ParseTypeTableBody() {
719 if (!TypeList.empty())
720 return Error("Multiple TYPE_BLOCKs found!");
722 SmallVector<uint64_t, 64> Record;
723 unsigned NumRecords = 0;
725 SmallString<64> TypeName;
727 // Read all the records for this type table.
729 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
731 switch (Entry.Kind) {
732 case BitstreamEntry::SubBlock: // Handled for us already.
733 case BitstreamEntry::Error:
734 Error("Error in the type table block");
736 case BitstreamEntry::EndBlock:
737 if (NumRecords != TypeList.size())
738 return Error("Invalid type forward reference in TYPE_BLOCK");
740 case BitstreamEntry::Record:
741 // The interesting case.
748 switch (Stream.readRecord(Entry.ID, Record)) {
749 default: return Error("unknown type in type table");
750 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
751 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
752 // type list. This allows us to reserve space.
753 if (Record.size() < 1)
754 return Error("Invalid TYPE_CODE_NUMENTRY record");
755 TypeList.resize(Record[0]);
757 case bitc::TYPE_CODE_VOID: // VOID
758 ResultTy = Type::getVoidTy(Context);
760 case bitc::TYPE_CODE_HALF: // HALF
761 ResultTy = Type::getHalfTy(Context);
763 case bitc::TYPE_CODE_FLOAT: // FLOAT
764 ResultTy = Type::getFloatTy(Context);
766 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
767 ResultTy = Type::getDoubleTy(Context);
769 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
770 ResultTy = Type::getX86_FP80Ty(Context);
772 case bitc::TYPE_CODE_FP128: // FP128
773 ResultTy = Type::getFP128Ty(Context);
775 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
776 ResultTy = Type::getPPC_FP128Ty(Context);
778 case bitc::TYPE_CODE_LABEL: // LABEL
779 ResultTy = Type::getLabelTy(Context);
781 case bitc::TYPE_CODE_METADATA: // METADATA
782 ResultTy = Type::getMetadataTy(Context);
784 case bitc::TYPE_CODE_X86_MMX: // X86_MMX
785 ResultTy = Type::getX86_MMXTy(Context);
787 case bitc::TYPE_CODE_INTEGER: // INTEGER: [width]
788 if (Record.size() < 1)
789 return Error("Invalid Integer type record");
791 ResultTy = IntegerType::get(Context, Record[0]);
793 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
794 // [pointee type, address space]
795 if (Record.size() < 1)
796 return Error("Invalid POINTER type record");
797 unsigned AddressSpace = 0;
798 if (Record.size() == 2)
799 AddressSpace = Record[1];
800 ResultTy = getTypeByID(Record[0]);
801 if (ResultTy == 0) return Error("invalid element type in pointer type");
802 ResultTy = PointerType::get(ResultTy, AddressSpace);
805 case bitc::TYPE_CODE_FUNCTION_OLD: {
806 // FIXME: attrid is dead, remove it in LLVM 4.0
807 // FUNCTION: [vararg, attrid, retty, paramty x N]
808 if (Record.size() < 3)
809 return Error("Invalid FUNCTION type record");
810 SmallVector<Type*, 8> ArgTys;
811 for (unsigned i = 3, e = Record.size(); i != e; ++i) {
812 if (Type *T = getTypeByID(Record[i]))
818 ResultTy = getTypeByID(Record[2]);
819 if (ResultTy == 0 || ArgTys.size() < Record.size()-3)
820 return Error("invalid type in function type");
822 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
825 case bitc::TYPE_CODE_FUNCTION: {
826 // FUNCTION: [vararg, retty, paramty x N]
827 if (Record.size() < 2)
828 return Error("Invalid FUNCTION type record");
829 SmallVector<Type*, 8> ArgTys;
830 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
831 if (Type *T = getTypeByID(Record[i]))
837 ResultTy = getTypeByID(Record[1]);
838 if (ResultTy == 0 || ArgTys.size() < Record.size()-2)
839 return Error("invalid type in function type");
841 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
844 case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N]
845 if (Record.size() < 1)
846 return Error("Invalid STRUCT type record");
847 SmallVector<Type*, 8> EltTys;
848 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
849 if (Type *T = getTypeByID(Record[i]))
854 if (EltTys.size() != Record.size()-1)
855 return Error("invalid type in struct type");
856 ResultTy = StructType::get(Context, EltTys, Record[0]);
859 case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N]
860 if (ConvertToString(Record, 0, TypeName))
861 return Error("Invalid STRUCT_NAME record");
864 case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
865 if (Record.size() < 1)
866 return Error("Invalid STRUCT type record");
868 if (NumRecords >= TypeList.size())
869 return Error("invalid TYPE table");
871 // Check to see if this was forward referenced, if so fill in the temp.
872 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
874 Res->setName(TypeName);
875 TypeList[NumRecords] = 0;
876 } else // Otherwise, create a new struct.
877 Res = StructType::create(Context, TypeName);
880 SmallVector<Type*, 8> EltTys;
881 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
882 if (Type *T = getTypeByID(Record[i]))
887 if (EltTys.size() != Record.size()-1)
888 return Error("invalid STRUCT type record");
889 Res->setBody(EltTys, Record[0]);
893 case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: []
894 if (Record.size() != 1)
895 return Error("Invalid OPAQUE type record");
897 if (NumRecords >= TypeList.size())
898 return Error("invalid TYPE table");
900 // Check to see if this was forward referenced, if so fill in the temp.
901 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
903 Res->setName(TypeName);
904 TypeList[NumRecords] = 0;
905 } else // Otherwise, create a new struct with no body.
906 Res = StructType::create(Context, TypeName);
911 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
912 if (Record.size() < 2)
913 return Error("Invalid ARRAY type record");
914 if ((ResultTy = getTypeByID(Record[1])))
915 ResultTy = ArrayType::get(ResultTy, Record[0]);
917 return Error("Invalid ARRAY type element");
919 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
920 if (Record.size() < 2)
921 return Error("Invalid VECTOR type record");
922 if ((ResultTy = getTypeByID(Record[1])))
923 ResultTy = VectorType::get(ResultTy, Record[0]);
925 return Error("Invalid ARRAY type element");
929 if (NumRecords >= TypeList.size())
930 return Error("invalid TYPE table");
931 assert(ResultTy && "Didn't read a type?");
932 assert(TypeList[NumRecords] == 0 && "Already read type?");
933 TypeList[NumRecords++] = ResultTy;
937 bool BitcodeReader::ParseValueSymbolTable() {
938 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
939 return Error("Malformed block record");
941 SmallVector<uint64_t, 64> Record;
943 // Read all the records for this value table.
944 SmallString<128> ValueName;
946 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
948 switch (Entry.Kind) {
949 case BitstreamEntry::SubBlock: // Handled for us already.
950 case BitstreamEntry::Error:
951 return Error("malformed value symbol table block");
952 case BitstreamEntry::EndBlock:
954 case BitstreamEntry::Record:
955 // The interesting case.
961 switch (Stream.readRecord(Entry.ID, Record)) {
962 default: // Default behavior: unknown type.
964 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
965 if (ConvertToString(Record, 1, ValueName))
966 return Error("Invalid VST_ENTRY record");
967 unsigned ValueID = Record[0];
968 if (ValueID >= ValueList.size())
969 return Error("Invalid Value ID in VST_ENTRY record");
970 Value *V = ValueList[ValueID];
972 V->setName(StringRef(ValueName.data(), ValueName.size()));
976 case bitc::VST_CODE_BBENTRY: {
977 if (ConvertToString(Record, 1, ValueName))
978 return Error("Invalid VST_BBENTRY record");
979 BasicBlock *BB = getBasicBlock(Record[0]);
981 return Error("Invalid BB ID in VST_BBENTRY record");
983 BB->setName(StringRef(ValueName.data(), ValueName.size()));
991 bool BitcodeReader::ParseMetadata() {
992 unsigned NextMDValueNo = MDValueList.size();
994 if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
995 return Error("Malformed block record");
997 SmallVector<uint64_t, 64> Record;
999 // Read all the records.
1001 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1003 switch (Entry.Kind) {
1004 case BitstreamEntry::SubBlock: // Handled for us already.
1005 case BitstreamEntry::Error:
1006 Error("malformed metadata block");
1008 case BitstreamEntry::EndBlock:
1010 case BitstreamEntry::Record:
1011 // The interesting case.
1015 bool IsFunctionLocal = false;
1018 unsigned Code = Stream.readRecord(Entry.ID, Record);
1020 default: // Default behavior: ignore.
1022 case bitc::METADATA_NAME: {
1023 // Read name of the named metadata.
1024 SmallString<8> Name(Record.begin(), Record.end());
1026 Code = Stream.ReadCode();
1028 // METADATA_NAME is always followed by METADATA_NAMED_NODE.
1029 unsigned NextBitCode = Stream.readRecord(Code, Record);
1030 assert(NextBitCode == bitc::METADATA_NAMED_NODE); (void)NextBitCode;
1032 // Read named metadata elements.
1033 unsigned Size = Record.size();
1034 NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name);
1035 for (unsigned i = 0; i != Size; ++i) {
1036 MDNode *MD = dyn_cast<MDNode>(MDValueList.getValueFwdRef(Record[i]));
1038 return Error("Malformed metadata record");
1039 NMD->addOperand(MD);
1043 case bitc::METADATA_FN_NODE:
1044 IsFunctionLocal = true;
1046 case bitc::METADATA_NODE: {
1047 if (Record.size() % 2 == 1)
1048 return Error("Invalid METADATA_NODE record");
1050 unsigned Size = Record.size();
1051 SmallVector<Value*, 8> Elts;
1052 for (unsigned i = 0; i != Size; i += 2) {
1053 Type *Ty = getTypeByID(Record[i]);
1054 if (!Ty) return Error("Invalid METADATA_NODE record");
1055 if (Ty->isMetadataTy())
1056 Elts.push_back(MDValueList.getValueFwdRef(Record[i+1]));
1057 else if (!Ty->isVoidTy())
1058 Elts.push_back(ValueList.getValueFwdRef(Record[i+1], Ty));
1060 Elts.push_back(NULL);
1062 Value *V = MDNode::getWhenValsUnresolved(Context, Elts, IsFunctionLocal);
1063 IsFunctionLocal = false;
1064 MDValueList.AssignValue(V, NextMDValueNo++);
1067 case bitc::METADATA_STRING: {
1068 SmallString<8> String(Record.begin(), Record.end());
1069 Value *V = MDString::get(Context, String);
1070 MDValueList.AssignValue(V, NextMDValueNo++);
1073 case bitc::METADATA_KIND: {
1074 if (Record.size() < 2)
1075 return Error("Invalid METADATA_KIND record");
1077 unsigned Kind = Record[0];
1078 SmallString<8> Name(Record.begin()+1, Record.end());
1080 unsigned NewKind = TheModule->getMDKindID(Name.str());
1081 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
1082 return Error("Conflicting METADATA_KIND records");
1089 /// decodeSignRotatedValue - Decode a signed value stored with the sign bit in
1090 /// the LSB for dense VBR encoding.
1091 uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
1096 // There is no such thing as -0 with integers. "-0" really means MININT.
1100 /// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
1101 /// values and aliases that we can.
1102 bool BitcodeReader::ResolveGlobalAndAliasInits() {
1103 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
1104 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
1105 std::vector<std::pair<Function*, unsigned> > FunctionPrefixWorklist;
1107 GlobalInitWorklist.swap(GlobalInits);
1108 AliasInitWorklist.swap(AliasInits);
1109 FunctionPrefixWorklist.swap(FunctionPrefixes);
1111 while (!GlobalInitWorklist.empty()) {
1112 unsigned ValID = GlobalInitWorklist.back().second;
1113 if (ValID >= ValueList.size()) {
1114 // Not ready to resolve this yet, it requires something later in the file.
1115 GlobalInits.push_back(GlobalInitWorklist.back());
1117 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
1118 GlobalInitWorklist.back().first->setInitializer(C);
1120 return Error("Global variable initializer is not a constant!");
1122 GlobalInitWorklist.pop_back();
1125 while (!AliasInitWorklist.empty()) {
1126 unsigned ValID = AliasInitWorklist.back().second;
1127 if (ValID >= ValueList.size()) {
1128 AliasInits.push_back(AliasInitWorklist.back());
1130 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
1131 AliasInitWorklist.back().first->setAliasee(C);
1133 return Error("Alias initializer is not a constant!");
1135 AliasInitWorklist.pop_back();
1138 while (!FunctionPrefixWorklist.empty()) {
1139 unsigned ValID = FunctionPrefixWorklist.back().second;
1140 if (ValID >= ValueList.size()) {
1141 FunctionPrefixes.push_back(FunctionPrefixWorklist.back());
1143 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
1144 FunctionPrefixWorklist.back().first->setPrefixData(C);
1146 return Error("Function prefix is not a constant!");
1148 FunctionPrefixWorklist.pop_back();
1154 static APInt ReadWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
1155 SmallVector<uint64_t, 8> Words(Vals.size());
1156 std::transform(Vals.begin(), Vals.end(), Words.begin(),
1157 BitcodeReader::decodeSignRotatedValue);
1159 return APInt(TypeBits, Words);
1162 bool BitcodeReader::ParseConstants() {
1163 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
1164 return Error("Malformed block record");
1166 SmallVector<uint64_t, 64> Record;
1168 // Read all the records for this value table.
1169 Type *CurTy = Type::getInt32Ty(Context);
1170 unsigned NextCstNo = ValueList.size();
1172 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1174 switch (Entry.Kind) {
1175 case BitstreamEntry::SubBlock: // Handled for us already.
1176 case BitstreamEntry::Error:
1177 return Error("malformed block record in AST file");
1178 case BitstreamEntry::EndBlock:
1179 if (NextCstNo != ValueList.size())
1180 return Error("Invalid constant reference!");
1182 // Once all the constants have been read, go through and resolve forward
1184 ValueList.ResolveConstantForwardRefs();
1186 case BitstreamEntry::Record:
1187 // The interesting case.
1194 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
1196 default: // Default behavior: unknown constant
1197 case bitc::CST_CODE_UNDEF: // UNDEF
1198 V = UndefValue::get(CurTy);
1200 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
1202 return Error("Malformed CST_SETTYPE record");
1203 if (Record[0] >= TypeList.size())
1204 return Error("Invalid Type ID in CST_SETTYPE record");
1205 CurTy = TypeList[Record[0]];
1206 continue; // Skip the ValueList manipulation.
1207 case bitc::CST_CODE_NULL: // NULL
1208 V = Constant::getNullValue(CurTy);
1210 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
1211 if (!CurTy->isIntegerTy() || Record.empty())
1212 return Error("Invalid CST_INTEGER record");
1213 V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
1215 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
1216 if (!CurTy->isIntegerTy() || Record.empty())
1217 return Error("Invalid WIDE_INTEGER record");
1219 APInt VInt = ReadWideAPInt(Record,
1220 cast<IntegerType>(CurTy)->getBitWidth());
1221 V = ConstantInt::get(Context, VInt);
1225 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
1227 return Error("Invalid FLOAT record");
1228 if (CurTy->isHalfTy())
1229 V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf,
1230 APInt(16, (uint16_t)Record[0])));
1231 else if (CurTy->isFloatTy())
1232 V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle,
1233 APInt(32, (uint32_t)Record[0])));
1234 else if (CurTy->isDoubleTy())
1235 V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble,
1236 APInt(64, Record[0])));
1237 else if (CurTy->isX86_FP80Ty()) {
1238 // Bits are not stored the same way as a normal i80 APInt, compensate.
1239 uint64_t Rearrange[2];
1240 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
1241 Rearrange[1] = Record[0] >> 48;
1242 V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended,
1243 APInt(80, Rearrange)));
1244 } else if (CurTy->isFP128Ty())
1245 V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad,
1246 APInt(128, Record)));
1247 else if (CurTy->isPPC_FP128Ty())
1248 V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble,
1249 APInt(128, Record)));
1251 V = UndefValue::get(CurTy);
1255 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
1257 return Error("Invalid CST_AGGREGATE record");
1259 unsigned Size = Record.size();
1260 SmallVector<Constant*, 16> Elts;
1262 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
1263 for (unsigned i = 0; i != Size; ++i)
1264 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
1265 STy->getElementType(i)));
1266 V = ConstantStruct::get(STy, Elts);
1267 } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
1268 Type *EltTy = ATy->getElementType();
1269 for (unsigned i = 0; i != Size; ++i)
1270 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
1271 V = ConstantArray::get(ATy, Elts);
1272 } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
1273 Type *EltTy = VTy->getElementType();
1274 for (unsigned i = 0; i != Size; ++i)
1275 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
1276 V = ConstantVector::get(Elts);
1278 V = UndefValue::get(CurTy);
1282 case bitc::CST_CODE_STRING: // STRING: [values]
1283 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
1285 return Error("Invalid CST_STRING record");
1287 SmallString<16> Elts(Record.begin(), Record.end());
1288 V = ConstantDataArray::getString(Context, Elts,
1289 BitCode == bitc::CST_CODE_CSTRING);
1292 case bitc::CST_CODE_DATA: {// DATA: [n x value]
1294 return Error("Invalid CST_DATA record");
1296 Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
1297 unsigned Size = Record.size();
1299 if (EltTy->isIntegerTy(8)) {
1300 SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
1301 if (isa<VectorType>(CurTy))
1302 V = ConstantDataVector::get(Context, Elts);
1304 V = ConstantDataArray::get(Context, Elts);
1305 } else if (EltTy->isIntegerTy(16)) {
1306 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
1307 if (isa<VectorType>(CurTy))
1308 V = ConstantDataVector::get(Context, Elts);
1310 V = ConstantDataArray::get(Context, Elts);
1311 } else if (EltTy->isIntegerTy(32)) {
1312 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
1313 if (isa<VectorType>(CurTy))
1314 V = ConstantDataVector::get(Context, Elts);
1316 V = ConstantDataArray::get(Context, Elts);
1317 } else if (EltTy->isIntegerTy(64)) {
1318 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
1319 if (isa<VectorType>(CurTy))
1320 V = ConstantDataVector::get(Context, Elts);
1322 V = ConstantDataArray::get(Context, Elts);
1323 } else if (EltTy->isFloatTy()) {
1324 SmallVector<float, 16> Elts(Size);
1325 std::transform(Record.begin(), Record.end(), Elts.begin(), BitsToFloat);
1326 if (isa<VectorType>(CurTy))
1327 V = ConstantDataVector::get(Context, Elts);
1329 V = ConstantDataArray::get(Context, Elts);
1330 } else if (EltTy->isDoubleTy()) {
1331 SmallVector<double, 16> Elts(Size);
1332 std::transform(Record.begin(), Record.end(), Elts.begin(),
1334 if (isa<VectorType>(CurTy))
1335 V = ConstantDataVector::get(Context, Elts);
1337 V = ConstantDataArray::get(Context, Elts);
1339 return Error("Unknown element type in CE_DATA");
1344 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
1345 if (Record.size() < 3) return Error("Invalid CE_BINOP record");
1346 int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
1348 V = UndefValue::get(CurTy); // Unknown binop.
1350 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
1351 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
1353 if (Record.size() >= 4) {
1354 if (Opc == Instruction::Add ||
1355 Opc == Instruction::Sub ||
1356 Opc == Instruction::Mul ||
1357 Opc == Instruction::Shl) {
1358 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
1359 Flags |= OverflowingBinaryOperator::NoSignedWrap;
1360 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
1361 Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
1362 } else if (Opc == Instruction::SDiv ||
1363 Opc == Instruction::UDiv ||
1364 Opc == Instruction::LShr ||
1365 Opc == Instruction::AShr) {
1366 if (Record[3] & (1 << bitc::PEO_EXACT))
1367 Flags |= SDivOperator::IsExact;
1370 V = ConstantExpr::get(Opc, LHS, RHS, Flags);
1374 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
1375 if (Record.size() < 3) return Error("Invalid CE_CAST record");
1376 int Opc = GetDecodedCastOpcode(Record[0]);
1378 V = UndefValue::get(CurTy); // Unknown cast.
1380 Type *OpTy = getTypeByID(Record[1]);
1381 if (!OpTy) return Error("Invalid CE_CAST record");
1382 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
1383 V = ConstantExpr::getCast(Opc, Op, CurTy);
1387 case bitc::CST_CODE_CE_INBOUNDS_GEP:
1388 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
1389 if (Record.size() & 1) return Error("Invalid CE_GEP record");
1390 SmallVector<Constant*, 16> Elts;
1391 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
1392 Type *ElTy = getTypeByID(Record[i]);
1393 if (!ElTy) return Error("Invalid CE_GEP record");
1394 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
1396 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
1397 V = ConstantExpr::getGetElementPtr(Elts[0], Indices,
1399 bitc::CST_CODE_CE_INBOUNDS_GEP);
1402 case bitc::CST_CODE_CE_SELECT: { // CE_SELECT: [opval#, opval#, opval#]
1403 if (Record.size() < 3) return Error("Invalid CE_SELECT record");
1405 Type *SelectorTy = Type::getInt1Ty(Context);
1407 // If CurTy is a vector of length n, then Record[0] must be a <n x i1>
1408 // vector. Otherwise, it must be a single bit.
1409 if (VectorType *VTy = dyn_cast<VectorType>(CurTy))
1410 SelectorTy = VectorType::get(Type::getInt1Ty(Context),
1411 VTy->getNumElements());
1413 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
1415 ValueList.getConstantFwdRef(Record[1],CurTy),
1416 ValueList.getConstantFwdRef(Record[2],CurTy));
1419 case bitc::CST_CODE_CE_EXTRACTELT: { // CE_EXTRACTELT: [opty, opval, opval]
1420 if (Record.size() < 3) return Error("Invalid CE_EXTRACTELT record");
1422 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1423 if (OpTy == 0) return Error("Invalid CE_EXTRACTELT record");
1424 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1425 Constant *Op1 = ValueList.getConstantFwdRef(Record[2],
1426 Type::getInt32Ty(Context));
1427 V = ConstantExpr::getExtractElement(Op0, Op1);
1430 case bitc::CST_CODE_CE_INSERTELT: { // CE_INSERTELT: [opval, opval, opval]
1431 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
1432 if (Record.size() < 3 || OpTy == 0)
1433 return Error("Invalid CE_INSERTELT record");
1434 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1435 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
1436 OpTy->getElementType());
1437 Constant *Op2 = ValueList.getConstantFwdRef(Record[2],
1438 Type::getInt32Ty(Context));
1439 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
1442 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
1443 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
1444 if (Record.size() < 3 || OpTy == 0)
1445 return Error("Invalid CE_SHUFFLEVEC record");
1446 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1447 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
1448 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
1449 OpTy->getNumElements());
1450 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
1451 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
1454 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
1455 VectorType *RTy = dyn_cast<VectorType>(CurTy);
1457 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1458 if (Record.size() < 4 || RTy == 0 || OpTy == 0)
1459 return Error("Invalid CE_SHUFVEC_EX record");
1460 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1461 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1462 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
1463 RTy->getNumElements());
1464 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
1465 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
1468 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
1469 if (Record.size() < 4) return Error("Invalid CE_CMP record");
1470 Type *OpTy = getTypeByID(Record[0]);
1471 if (OpTy == 0) return Error("Invalid CE_CMP record");
1472 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1473 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1475 if (OpTy->isFPOrFPVectorTy())
1476 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
1478 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
1481 // This maintains backward compatibility, pre-asm dialect keywords.
1482 // FIXME: Remove with the 4.0 release.
1483 case bitc::CST_CODE_INLINEASM_OLD: {
1484 if (Record.size() < 2) return Error("Invalid INLINEASM record");
1485 std::string AsmStr, ConstrStr;
1486 bool HasSideEffects = Record[0] & 1;
1487 bool IsAlignStack = Record[0] >> 1;
1488 unsigned AsmStrSize = Record[1];
1489 if (2+AsmStrSize >= Record.size())
1490 return Error("Invalid INLINEASM record");
1491 unsigned ConstStrSize = Record[2+AsmStrSize];
1492 if (3+AsmStrSize+ConstStrSize > Record.size())
1493 return Error("Invalid INLINEASM record");
1495 for (unsigned i = 0; i != AsmStrSize; ++i)
1496 AsmStr += (char)Record[2+i];
1497 for (unsigned i = 0; i != ConstStrSize; ++i)
1498 ConstrStr += (char)Record[3+AsmStrSize+i];
1499 PointerType *PTy = cast<PointerType>(CurTy);
1500 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
1501 AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
1504 // This version adds support for the asm dialect keywords (e.g.,
1506 case bitc::CST_CODE_INLINEASM: {
1507 if (Record.size() < 2) return Error("Invalid INLINEASM record");
1508 std::string AsmStr, ConstrStr;
1509 bool HasSideEffects = Record[0] & 1;
1510 bool IsAlignStack = (Record[0] >> 1) & 1;
1511 unsigned AsmDialect = Record[0] >> 2;
1512 unsigned AsmStrSize = Record[1];
1513 if (2+AsmStrSize >= Record.size())
1514 return Error("Invalid INLINEASM record");
1515 unsigned ConstStrSize = Record[2+AsmStrSize];
1516 if (3+AsmStrSize+ConstStrSize > Record.size())
1517 return Error("Invalid INLINEASM record");
1519 for (unsigned i = 0; i != AsmStrSize; ++i)
1520 AsmStr += (char)Record[2+i];
1521 for (unsigned i = 0; i != ConstStrSize; ++i)
1522 ConstrStr += (char)Record[3+AsmStrSize+i];
1523 PointerType *PTy = cast<PointerType>(CurTy);
1524 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
1525 AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
1526 InlineAsm::AsmDialect(AsmDialect));
1529 case bitc::CST_CODE_BLOCKADDRESS:{
1530 if (Record.size() < 3) return Error("Invalid CE_BLOCKADDRESS record");
1531 Type *FnTy = getTypeByID(Record[0]);
1532 if (FnTy == 0) return Error("Invalid CE_BLOCKADDRESS record");
1534 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
1535 if (Fn == 0) return Error("Invalid CE_BLOCKADDRESS record");
1537 // If the function is already parsed we can insert the block address right
1540 Function::iterator BBI = Fn->begin(), BBE = Fn->end();
1541 for (size_t I = 0, E = Record[2]; I != E; ++I) {
1543 return Error("Invalid blockaddress block #");
1546 V = BlockAddress::get(Fn, BBI);
1548 // Otherwise insert a placeholder and remember it so it can be inserted
1549 // when the function is parsed.
1550 GlobalVariable *FwdRef = new GlobalVariable(*Fn->getParent(),
1551 Type::getInt8Ty(Context),
1552 false, GlobalValue::InternalLinkage,
1554 BlockAddrFwdRefs[Fn].push_back(std::make_pair(Record[2], FwdRef));
1561 ValueList.AssignValue(V, NextCstNo);
1566 bool BitcodeReader::ParseUseLists() {
1567 if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
1568 return Error("Malformed block record");
1570 SmallVector<uint64_t, 64> Record;
1572 // Read all the records.
1574 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1576 switch (Entry.Kind) {
1577 case BitstreamEntry::SubBlock: // Handled for us already.
1578 case BitstreamEntry::Error:
1579 return Error("malformed use list block");
1580 case BitstreamEntry::EndBlock:
1582 case BitstreamEntry::Record:
1583 // The interesting case.
1587 // Read a use list record.
1589 switch (Stream.readRecord(Entry.ID, Record)) {
1590 default: // Default behavior: unknown type.
1592 case bitc::USELIST_CODE_ENTRY: { // USELIST_CODE_ENTRY: TBD.
1593 unsigned RecordLength = Record.size();
1594 if (RecordLength < 1)
1595 return Error ("Invalid UseList reader!");
1596 UseListRecords.push_back(Record);
1603 /// RememberAndSkipFunctionBody - When we see the block for a function body,
1604 /// remember where it is and then skip it. This lets us lazily deserialize the
1606 bool BitcodeReader::RememberAndSkipFunctionBody() {
1607 // Get the function we are talking about.
1608 if (FunctionsWithBodies.empty())
1609 return Error("Insufficient function protos");
1611 Function *Fn = FunctionsWithBodies.back();
1612 FunctionsWithBodies.pop_back();
1614 // Save the current stream state.
1615 uint64_t CurBit = Stream.GetCurrentBitNo();
1616 DeferredFunctionInfo[Fn] = CurBit;
1618 // Skip over the function block for now.
1619 if (Stream.SkipBlock())
1620 return Error("Malformed block record");
1624 bool BitcodeReader::GlobalCleanup() {
1625 // Patch the initializers for globals and aliases up.
1626 ResolveGlobalAndAliasInits();
1627 if (!GlobalInits.empty() || !AliasInits.empty())
1628 return Error("Malformed global initializer set");
1630 // Look for intrinsic functions which need to be upgraded at some point
1631 for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
1634 if (UpgradeIntrinsicFunction(FI, NewFn))
1635 UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
1638 // Look for global variables which need to be renamed.
1639 for (Module::global_iterator
1640 GI = TheModule->global_begin(), GE = TheModule->global_end();
1642 UpgradeGlobalVariable(GI);
1643 // Force deallocation of memory for these vectors to favor the client that
1644 // want lazy deserialization.
1645 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
1646 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
1650 bool BitcodeReader::ParseModule(bool Resume) {
1652 Stream.JumpToBit(NextUnreadBit);
1653 else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
1654 return Error("Malformed block record");
1656 SmallVector<uint64_t, 64> Record;
1657 std::vector<std::string> SectionTable;
1658 std::vector<std::string> GCTable;
1660 // Read all the records for this module.
1662 BitstreamEntry Entry = Stream.advance();
1664 switch (Entry.Kind) {
1665 case BitstreamEntry::Error:
1666 Error("malformed module block");
1668 case BitstreamEntry::EndBlock:
1669 return GlobalCleanup();
1671 case BitstreamEntry::SubBlock:
1673 default: // Skip unknown content.
1674 if (Stream.SkipBlock())
1675 return Error("Malformed block record");
1677 case bitc::BLOCKINFO_BLOCK_ID:
1678 if (Stream.ReadBlockInfoBlock())
1679 return Error("Malformed BlockInfoBlock");
1681 case bitc::PARAMATTR_BLOCK_ID:
1682 if (ParseAttributeBlock())
1685 case bitc::PARAMATTR_GROUP_BLOCK_ID:
1686 if (ParseAttributeGroupBlock())
1689 case bitc::TYPE_BLOCK_ID_NEW:
1690 if (ParseTypeTable())
1693 case bitc::VALUE_SYMTAB_BLOCK_ID:
1694 if (ParseValueSymbolTable())
1696 SeenValueSymbolTable = true;
1698 case bitc::CONSTANTS_BLOCK_ID:
1699 if (ParseConstants() || ResolveGlobalAndAliasInits())
1702 case bitc::METADATA_BLOCK_ID:
1703 if (ParseMetadata())
1706 case bitc::FUNCTION_BLOCK_ID:
1707 // If this is the first function body we've seen, reverse the
1708 // FunctionsWithBodies list.
1709 if (!SeenFirstFunctionBody) {
1710 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
1711 if (GlobalCleanup())
1713 SeenFirstFunctionBody = true;
1716 if (RememberAndSkipFunctionBody())
1718 // For streaming bitcode, suspend parsing when we reach the function
1719 // bodies. Subsequent materialization calls will resume it when
1720 // necessary. For streaming, the function bodies must be at the end of
1721 // the bitcode. If the bitcode file is old, the symbol table will be
1722 // at the end instead and will not have been seen yet. In this case,
1723 // just finish the parse now.
1724 if (LazyStreamer && SeenValueSymbolTable) {
1725 NextUnreadBit = Stream.GetCurrentBitNo();
1729 case bitc::USELIST_BLOCK_ID:
1730 if (ParseUseLists())
1736 case BitstreamEntry::Record:
1737 // The interesting case.
1743 switch (Stream.readRecord(Entry.ID, Record)) {
1744 default: break; // Default behavior, ignore unknown content.
1745 case bitc::MODULE_CODE_VERSION: { // VERSION: [version#]
1746 if (Record.size() < 1)
1747 return Error("Malformed MODULE_CODE_VERSION");
1748 // Only version #0 and #1 are supported so far.
1749 unsigned module_version = Record[0];
1750 switch (module_version) {
1751 default: return Error("Unknown bitstream version!");
1753 UseRelativeIDs = false;
1756 UseRelativeIDs = true;
1761 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
1763 if (ConvertToString(Record, 0, S))
1764 return Error("Invalid MODULE_CODE_TRIPLE record");
1765 TheModule->setTargetTriple(S);
1768 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
1770 if (ConvertToString(Record, 0, S))
1771 return Error("Invalid MODULE_CODE_DATALAYOUT record");
1772 TheModule->setDataLayout(S);
1775 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
1777 if (ConvertToString(Record, 0, S))
1778 return Error("Invalid MODULE_CODE_ASM record");
1779 TheModule->setModuleInlineAsm(S);
1782 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
1783 // FIXME: Remove in 4.0.
1785 if (ConvertToString(Record, 0, S))
1786 return Error("Invalid MODULE_CODE_DEPLIB record");
1790 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
1792 if (ConvertToString(Record, 0, S))
1793 return Error("Invalid MODULE_CODE_SECTIONNAME record");
1794 SectionTable.push_back(S);
1797 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
1799 if (ConvertToString(Record, 0, S))
1800 return Error("Invalid MODULE_CODE_GCNAME record");
1801 GCTable.push_back(S);
1804 // GLOBALVAR: [pointer type, isconst, initid,
1805 // linkage, alignment, section, visibility, threadlocal,
1807 case bitc::MODULE_CODE_GLOBALVAR: {
1808 if (Record.size() < 6)
1809 return Error("Invalid MODULE_CODE_GLOBALVAR record");
1810 Type *Ty = getTypeByID(Record[0]);
1811 if (!Ty) return Error("Invalid MODULE_CODE_GLOBALVAR record");
1812 if (!Ty->isPointerTy())
1813 return Error("Global not a pointer type!");
1814 unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
1815 Ty = cast<PointerType>(Ty)->getElementType();
1817 bool isConstant = Record[1];
1818 GlobalValue::LinkageTypes Linkage = GetDecodedLinkage(Record[3]);
1819 unsigned Alignment = (1 << Record[4]) >> 1;
1820 std::string Section;
1822 if (Record[5]-1 >= SectionTable.size())
1823 return Error("Invalid section ID");
1824 Section = SectionTable[Record[5]-1];
1826 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
1827 if (Record.size() > 6)
1828 Visibility = GetDecodedVisibility(Record[6]);
1830 GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
1831 if (Record.size() > 7)
1832 TLM = GetDecodedThreadLocalMode(Record[7]);
1834 bool UnnamedAddr = false;
1835 if (Record.size() > 8)
1836 UnnamedAddr = Record[8];
1838 bool ExternallyInitialized = false;
1839 if (Record.size() > 9)
1840 ExternallyInitialized = Record[9];
1842 GlobalVariable *NewGV =
1843 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, 0, "", 0,
1844 TLM, AddressSpace, ExternallyInitialized);
1845 NewGV->setAlignment(Alignment);
1846 if (!Section.empty())
1847 NewGV->setSection(Section);
1848 NewGV->setVisibility(Visibility);
1849 NewGV->setUnnamedAddr(UnnamedAddr);
1851 ValueList.push_back(NewGV);
1853 // Remember which value to use for the global initializer.
1854 if (unsigned InitID = Record[2])
1855 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
1858 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
1859 // alignment, section, visibility, gc, unnamed_addr]
1860 case bitc::MODULE_CODE_FUNCTION: {
1861 if (Record.size() < 8)
1862 return Error("Invalid MODULE_CODE_FUNCTION record");
1863 Type *Ty = getTypeByID(Record[0]);
1864 if (!Ty) return Error("Invalid MODULE_CODE_FUNCTION record");
1865 if (!Ty->isPointerTy())
1866 return Error("Function not a pointer type!");
1868 dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
1870 return Error("Function not a pointer to function type!");
1872 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
1875 Func->setCallingConv(static_cast<CallingConv::ID>(Record[1]));
1876 bool isProto = Record[2];
1877 Func->setLinkage(GetDecodedLinkage(Record[3]));
1878 Func->setAttributes(getAttributes(Record[4]));
1880 Func->setAlignment((1 << Record[5]) >> 1);
1882 if (Record[6]-1 >= SectionTable.size())
1883 return Error("Invalid section ID");
1884 Func->setSection(SectionTable[Record[6]-1]);
1886 Func->setVisibility(GetDecodedVisibility(Record[7]));
1887 if (Record.size() > 8 && Record[8]) {
1888 if (Record[8]-1 > GCTable.size())
1889 return Error("Invalid GC ID");
1890 Func->setGC(GCTable[Record[8]-1].c_str());
1892 bool UnnamedAddr = false;
1893 if (Record.size() > 9)
1894 UnnamedAddr = Record[9];
1895 Func->setUnnamedAddr(UnnamedAddr);
1896 if (Record.size() > 10 && Record[10] != 0)
1897 FunctionPrefixes.push_back(std::make_pair(Func, Record[10]-1));
1898 ValueList.push_back(Func);
1900 // If this is a function with a body, remember the prototype we are
1901 // creating now, so that we can match up the body with them later.
1903 FunctionsWithBodies.push_back(Func);
1904 if (LazyStreamer) DeferredFunctionInfo[Func] = 0;
1908 // ALIAS: [alias type, aliasee val#, linkage]
1909 // ALIAS: [alias type, aliasee val#, linkage, visibility]
1910 case bitc::MODULE_CODE_ALIAS: {
1911 if (Record.size() < 3)
1912 return Error("Invalid MODULE_ALIAS record");
1913 Type *Ty = getTypeByID(Record[0]);
1914 if (!Ty) return Error("Invalid MODULE_ALIAS record");
1915 if (!Ty->isPointerTy())
1916 return Error("Function not a pointer type!");
1918 GlobalAlias *NewGA = new GlobalAlias(Ty, GetDecodedLinkage(Record[2]),
1920 // Old bitcode files didn't have visibility field.
1921 if (Record.size() > 3)
1922 NewGA->setVisibility(GetDecodedVisibility(Record[3]));
1923 ValueList.push_back(NewGA);
1924 AliasInits.push_back(std::make_pair(NewGA, Record[1]));
1927 /// MODULE_CODE_PURGEVALS: [numvals]
1928 case bitc::MODULE_CODE_PURGEVALS:
1929 // Trim down the value list to the specified size.
1930 if (Record.size() < 1 || Record[0] > ValueList.size())
1931 return Error("Invalid MODULE_PURGEVALS record");
1932 ValueList.shrinkTo(Record[0]);
1939 bool BitcodeReader::ParseBitcodeInto(Module *M) {
1942 if (InitStream()) return true;
1944 // Sniff for the signature.
1945 if (Stream.Read(8) != 'B' ||
1946 Stream.Read(8) != 'C' ||
1947 Stream.Read(4) != 0x0 ||
1948 Stream.Read(4) != 0xC ||
1949 Stream.Read(4) != 0xE ||
1950 Stream.Read(4) != 0xD)
1951 return Error("Invalid bitcode signature");
1953 // We expect a number of well-defined blocks, though we don't necessarily
1954 // need to understand them all.
1956 if (Stream.AtEndOfStream())
1959 BitstreamEntry Entry =
1960 Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
1962 switch (Entry.Kind) {
1963 case BitstreamEntry::Error:
1964 Error("malformed module file");
1966 case BitstreamEntry::EndBlock:
1969 case BitstreamEntry::SubBlock:
1971 case bitc::BLOCKINFO_BLOCK_ID:
1972 if (Stream.ReadBlockInfoBlock())
1973 return Error("Malformed BlockInfoBlock");
1975 case bitc::MODULE_BLOCK_ID:
1976 // Reject multiple MODULE_BLOCK's in a single bitstream.
1978 return Error("Multiple MODULE_BLOCKs in same stream");
1980 if (ParseModule(false))
1982 if (LazyStreamer) return false;
1985 if (Stream.SkipBlock())
1986 return Error("Malformed block record");
1990 case BitstreamEntry::Record:
1991 // There should be no records in the top-level of blocks.
1993 // The ranlib in Xcode 4 will align archive members by appending newlines
1994 // to the end of them. If this file size is a multiple of 4 but not 8, we
1995 // have to read and ignore these final 4 bytes :-(
1996 if (Stream.getAbbrevIDWidth() == 2 && Entry.ID == 2 &&
1997 Stream.Read(6) == 2 && Stream.Read(24) == 0xa0a0a &&
1998 Stream.AtEndOfStream())
2001 return Error("Invalid record at top-level");
2006 bool BitcodeReader::ParseModuleTriple(std::string &Triple) {
2007 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
2008 return Error("Malformed block record");
2010 SmallVector<uint64_t, 64> Record;
2012 // Read all the records for this module.
2014 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2016 switch (Entry.Kind) {
2017 case BitstreamEntry::SubBlock: // Handled for us already.
2018 case BitstreamEntry::Error:
2019 return Error("malformed module block");
2020 case BitstreamEntry::EndBlock:
2022 case BitstreamEntry::Record:
2023 // The interesting case.
2028 switch (Stream.readRecord(Entry.ID, Record)) {
2029 default: break; // Default behavior, ignore unknown content.
2030 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
2032 if (ConvertToString(Record, 0, S))
2033 return Error("Invalid MODULE_CODE_TRIPLE record");
2042 bool BitcodeReader::ParseTriple(std::string &Triple) {
2043 if (InitStream()) return true;
2045 // Sniff for the signature.
2046 if (Stream.Read(8) != 'B' ||
2047 Stream.Read(8) != 'C' ||
2048 Stream.Read(4) != 0x0 ||
2049 Stream.Read(4) != 0xC ||
2050 Stream.Read(4) != 0xE ||
2051 Stream.Read(4) != 0xD)
2052 return Error("Invalid bitcode signature");
2054 // We expect a number of well-defined blocks, though we don't necessarily
2055 // need to understand them all.
2057 BitstreamEntry Entry = Stream.advance();
2059 switch (Entry.Kind) {
2060 case BitstreamEntry::Error:
2061 Error("malformed module file");
2063 case BitstreamEntry::EndBlock:
2066 case BitstreamEntry::SubBlock:
2067 if (Entry.ID == bitc::MODULE_BLOCK_ID)
2068 return ParseModuleTriple(Triple);
2070 // Ignore other sub-blocks.
2071 if (Stream.SkipBlock()) {
2072 Error("malformed block record in AST file");
2077 case BitstreamEntry::Record:
2078 Stream.skipRecord(Entry.ID);
2084 /// ParseMetadataAttachment - Parse metadata attachments.
2085 bool BitcodeReader::ParseMetadataAttachment() {
2086 if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
2087 return Error("Malformed block record");
2089 SmallVector<uint64_t, 64> Record;
2091 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2093 switch (Entry.Kind) {
2094 case BitstreamEntry::SubBlock: // Handled for us already.
2095 case BitstreamEntry::Error:
2096 return Error("malformed metadata block");
2097 case BitstreamEntry::EndBlock:
2099 case BitstreamEntry::Record:
2100 // The interesting case.
2104 // Read a metadata attachment record.
2106 switch (Stream.readRecord(Entry.ID, Record)) {
2107 default: // Default behavior: ignore.
2109 case bitc::METADATA_ATTACHMENT: {
2110 unsigned RecordLength = Record.size();
2111 if (Record.empty() || (RecordLength - 1) % 2 == 1)
2112 return Error ("Invalid METADATA_ATTACHMENT reader!");
2113 Instruction *Inst = InstructionList[Record[0]];
2114 for (unsigned i = 1; i != RecordLength; i = i+2) {
2115 unsigned Kind = Record[i];
2116 DenseMap<unsigned, unsigned>::iterator I =
2117 MDKindMap.find(Kind);
2118 if (I == MDKindMap.end())
2119 return Error("Invalid metadata kind ID");
2120 Value *Node = MDValueList.getValueFwdRef(Record[i+1]);
2121 Inst->setMetadata(I->second, cast<MDNode>(Node));
2122 if (I->second == LLVMContext::MD_tbaa)
2123 InstsWithTBAATag.push_back(Inst);
2131 /// ParseFunctionBody - Lazily parse the specified function body block.
2132 bool BitcodeReader::ParseFunctionBody(Function *F) {
2133 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
2134 return Error("Malformed block record");
2136 InstructionList.clear();
2137 unsigned ModuleValueListSize = ValueList.size();
2138 unsigned ModuleMDValueListSize = MDValueList.size();
2140 // Add all the function arguments to the value table.
2141 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
2142 ValueList.push_back(I);
2144 unsigned NextValueNo = ValueList.size();
2145 BasicBlock *CurBB = 0;
2146 unsigned CurBBNo = 0;
2150 // Read all the records.
2151 SmallVector<uint64_t, 64> Record;
2153 BitstreamEntry Entry = Stream.advance();
2155 switch (Entry.Kind) {
2156 case BitstreamEntry::Error:
2157 return Error("Bitcode error in function block");
2158 case BitstreamEntry::EndBlock:
2159 goto OutOfRecordLoop;
2161 case BitstreamEntry::SubBlock:
2163 default: // Skip unknown content.
2164 if (Stream.SkipBlock())
2165 return Error("Malformed block record");
2167 case bitc::CONSTANTS_BLOCK_ID:
2168 if (ParseConstants()) return true;
2169 NextValueNo = ValueList.size();
2171 case bitc::VALUE_SYMTAB_BLOCK_ID:
2172 if (ParseValueSymbolTable()) return true;
2174 case bitc::METADATA_ATTACHMENT_ID:
2175 if (ParseMetadataAttachment()) return true;
2177 case bitc::METADATA_BLOCK_ID:
2178 if (ParseMetadata()) return true;
2183 case BitstreamEntry::Record:
2184 // The interesting case.
2191 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
2193 default: // Default behavior: reject
2194 return Error("Unknown instruction");
2195 case bitc::FUNC_CODE_DECLAREBLOCKS: // DECLAREBLOCKS: [nblocks]
2196 if (Record.size() < 1 || Record[0] == 0)
2197 return Error("Invalid DECLAREBLOCKS record");
2198 // Create all the basic blocks for the function.
2199 FunctionBBs.resize(Record[0]);
2200 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
2201 FunctionBBs[i] = BasicBlock::Create(Context, "", F);
2202 CurBB = FunctionBBs[0];
2205 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN
2206 // This record indicates that the last instruction is at the same
2207 // location as the previous instruction with a location.
2210 // Get the last instruction emitted.
2211 if (CurBB && !CurBB->empty())
2213 else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
2214 !FunctionBBs[CurBBNo-1]->empty())
2215 I = &FunctionBBs[CurBBNo-1]->back();
2217 if (I == 0) return Error("Invalid DEBUG_LOC_AGAIN record");
2218 I->setDebugLoc(LastLoc);
2222 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia]
2223 I = 0; // Get the last instruction emitted.
2224 if (CurBB && !CurBB->empty())
2226 else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
2227 !FunctionBBs[CurBBNo-1]->empty())
2228 I = &FunctionBBs[CurBBNo-1]->back();
2229 if (I == 0 || Record.size() < 4)
2230 return Error("Invalid FUNC_CODE_DEBUG_LOC record");
2232 unsigned Line = Record[0], Col = Record[1];
2233 unsigned ScopeID = Record[2], IAID = Record[3];
2235 MDNode *Scope = 0, *IA = 0;
2236 if (ScopeID) Scope = cast<MDNode>(MDValueList.getValueFwdRef(ScopeID-1));
2237 if (IAID) IA = cast<MDNode>(MDValueList.getValueFwdRef(IAID-1));
2238 LastLoc = DebugLoc::get(Line, Col, Scope, IA);
2239 I->setDebugLoc(LastLoc);
2244 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
2247 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
2248 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
2249 OpNum+1 > Record.size())
2250 return Error("Invalid BINOP record");
2252 int Opc = GetDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
2253 if (Opc == -1) return Error("Invalid BINOP record");
2254 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
2255 InstructionList.push_back(I);
2256 if (OpNum < Record.size()) {
2257 if (Opc == Instruction::Add ||
2258 Opc == Instruction::Sub ||
2259 Opc == Instruction::Mul ||
2260 Opc == Instruction::Shl) {
2261 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
2262 cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
2263 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
2264 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
2265 } else if (Opc == Instruction::SDiv ||
2266 Opc == Instruction::UDiv ||
2267 Opc == Instruction::LShr ||
2268 Opc == Instruction::AShr) {
2269 if (Record[OpNum] & (1 << bitc::PEO_EXACT))
2270 cast<BinaryOperator>(I)->setIsExact(true);
2271 } else if (isa<FPMathOperator>(I)) {
2273 if (0 != (Record[OpNum] & FastMathFlags::UnsafeAlgebra))
2274 FMF.setUnsafeAlgebra();
2275 if (0 != (Record[OpNum] & FastMathFlags::NoNaNs))
2277 if (0 != (Record[OpNum] & FastMathFlags::NoInfs))
2279 if (0 != (Record[OpNum] & FastMathFlags::NoSignedZeros))
2280 FMF.setNoSignedZeros();
2281 if (0 != (Record[OpNum] & FastMathFlags::AllowReciprocal))
2282 FMF.setAllowReciprocal();
2284 I->setFastMathFlags(FMF);
2290 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
2293 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2294 OpNum+2 != Record.size())
2295 return Error("Invalid CAST record");
2297 Type *ResTy = getTypeByID(Record[OpNum]);
2298 int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
2299 if (Opc == -1 || ResTy == 0)
2300 return Error("Invalid CAST record");
2301 I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
2302 InstructionList.push_back(I);
2305 case bitc::FUNC_CODE_INST_INBOUNDS_GEP:
2306 case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands]
2309 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
2310 return Error("Invalid GEP record");
2312 SmallVector<Value*, 16> GEPIdx;
2313 while (OpNum != Record.size()) {
2315 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2316 return Error("Invalid GEP record");
2317 GEPIdx.push_back(Op);
2320 I = GetElementPtrInst::Create(BasePtr, GEPIdx);
2321 InstructionList.push_back(I);
2322 if (BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP)
2323 cast<GetElementPtrInst>(I)->setIsInBounds(true);
2327 case bitc::FUNC_CODE_INST_EXTRACTVAL: {
2328 // EXTRACTVAL: [opty, opval, n x indices]
2331 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2332 return Error("Invalid EXTRACTVAL record");
2334 SmallVector<unsigned, 4> EXTRACTVALIdx;
2335 for (unsigned RecSize = Record.size();
2336 OpNum != RecSize; ++OpNum) {
2337 uint64_t Index = Record[OpNum];
2338 if ((unsigned)Index != Index)
2339 return Error("Invalid EXTRACTVAL index");
2340 EXTRACTVALIdx.push_back((unsigned)Index);
2343 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
2344 InstructionList.push_back(I);
2348 case bitc::FUNC_CODE_INST_INSERTVAL: {
2349 // INSERTVAL: [opty, opval, opty, opval, n x indices]
2352 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2353 return Error("Invalid INSERTVAL record");
2355 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
2356 return Error("Invalid INSERTVAL record");
2358 SmallVector<unsigned, 4> INSERTVALIdx;
2359 for (unsigned RecSize = Record.size();
2360 OpNum != RecSize; ++OpNum) {
2361 uint64_t Index = Record[OpNum];
2362 if ((unsigned)Index != Index)
2363 return Error("Invalid INSERTVAL index");
2364 INSERTVALIdx.push_back((unsigned)Index);
2367 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
2368 InstructionList.push_back(I);
2372 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
2373 // obsolete form of select
2374 // handles select i1 ... in old bitcode
2376 Value *TrueVal, *FalseVal, *Cond;
2377 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
2378 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
2379 popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond))
2380 return Error("Invalid SELECT record");
2382 I = SelectInst::Create(Cond, TrueVal, FalseVal);
2383 InstructionList.push_back(I);
2387 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
2388 // new form of select
2389 // handles select i1 or select [N x i1]
2391 Value *TrueVal, *FalseVal, *Cond;
2392 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
2393 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
2394 getValueTypePair(Record, OpNum, NextValueNo, Cond))
2395 return Error("Invalid SELECT record");
2397 // select condition can be either i1 or [N x i1]
2398 if (VectorType* vector_type =
2399 dyn_cast<VectorType>(Cond->getType())) {
2401 if (vector_type->getElementType() != Type::getInt1Ty(Context))
2402 return Error("Invalid SELECT condition type");
2405 if (Cond->getType() != Type::getInt1Ty(Context))
2406 return Error("Invalid SELECT condition type");
2409 I = SelectInst::Create(Cond, TrueVal, FalseVal);
2410 InstructionList.push_back(I);
2414 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
2417 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
2418 popValue(Record, OpNum, NextValueNo, Type::getInt32Ty(Context), Idx))
2419 return Error("Invalid EXTRACTELT record");
2420 I = ExtractElementInst::Create(Vec, Idx);
2421 InstructionList.push_back(I);
2425 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
2427 Value *Vec, *Elt, *Idx;
2428 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
2429 popValue(Record, OpNum, NextValueNo,
2430 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
2431 popValue(Record, OpNum, NextValueNo, Type::getInt32Ty(Context), Idx))
2432 return Error("Invalid INSERTELT record");
2433 I = InsertElementInst::Create(Vec, Elt, Idx);
2434 InstructionList.push_back(I);
2438 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
2440 Value *Vec1, *Vec2, *Mask;
2441 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
2442 popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2))
2443 return Error("Invalid SHUFFLEVEC record");
2445 if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
2446 return Error("Invalid SHUFFLEVEC record");
2447 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
2448 InstructionList.push_back(I);
2452 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
2453 // Old form of ICmp/FCmp returning bool
2454 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
2455 // both legal on vectors but had different behaviour.
2456 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
2457 // FCmp/ICmp returning bool or vector of bool
2461 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
2462 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
2463 OpNum+1 != Record.size())
2464 return Error("Invalid CMP record");
2466 if (LHS->getType()->isFPOrFPVectorTy())
2467 I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
2469 I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
2470 InstructionList.push_back(I);
2474 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
2476 unsigned Size = Record.size();
2478 I = ReturnInst::Create(Context);
2479 InstructionList.push_back(I);
2485 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2486 return Error("Invalid RET record");
2487 if (OpNum != Record.size())
2488 return Error("Invalid RET record");
2490 I = ReturnInst::Create(Context, Op);
2491 InstructionList.push_back(I);
2494 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
2495 if (Record.size() != 1 && Record.size() != 3)
2496 return Error("Invalid BR record");
2497 BasicBlock *TrueDest = getBasicBlock(Record[0]);
2499 return Error("Invalid BR record");
2501 if (Record.size() == 1) {
2502 I = BranchInst::Create(TrueDest);
2503 InstructionList.push_back(I);
2506 BasicBlock *FalseDest = getBasicBlock(Record[1]);
2507 Value *Cond = getValue(Record, 2, NextValueNo,
2508 Type::getInt1Ty(Context));
2509 if (FalseDest == 0 || Cond == 0)
2510 return Error("Invalid BR record");
2511 I = BranchInst::Create(TrueDest, FalseDest, Cond);
2512 InstructionList.push_back(I);
2516 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
2518 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
2519 // "New" SwitchInst format with case ranges. The changes to write this
2520 // format were reverted but we still recognize bitcode that uses it.
2521 // Hopefully someday we will have support for case ranges and can use
2522 // this format again.
2524 Type *OpTy = getTypeByID(Record[1]);
2525 unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
2527 Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
2528 BasicBlock *Default = getBasicBlock(Record[3]);
2529 if (OpTy == 0 || Cond == 0 || Default == 0)
2530 return Error("Invalid SWITCH record");
2532 unsigned NumCases = Record[4];
2534 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
2535 InstructionList.push_back(SI);
2537 unsigned CurIdx = 5;
2538 for (unsigned i = 0; i != NumCases; ++i) {
2539 SmallVector<ConstantInt*, 1> CaseVals;
2540 unsigned NumItems = Record[CurIdx++];
2541 for (unsigned ci = 0; ci != NumItems; ++ci) {
2542 bool isSingleNumber = Record[CurIdx++];
2545 unsigned ActiveWords = 1;
2546 if (ValueBitWidth > 64)
2547 ActiveWords = Record[CurIdx++];
2548 Low = ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
2550 CurIdx += ActiveWords;
2552 if (!isSingleNumber) {
2554 if (ValueBitWidth > 64)
2555 ActiveWords = Record[CurIdx++];
2557 ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
2559 CurIdx += ActiveWords;
2561 // FIXME: It is not clear whether values in the range should be
2562 // compared as signed or unsigned values. The partially
2563 // implemented changes that used this format in the past used
2564 // unsigned comparisons.
2565 for ( ; Low.ule(High); ++Low)
2566 CaseVals.push_back(ConstantInt::get(Context, Low));
2568 CaseVals.push_back(ConstantInt::get(Context, Low));
2570 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
2571 for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(),
2572 cve = CaseVals.end(); cvi != cve; ++cvi)
2573 SI->addCase(*cvi, DestBB);
2579 // Old SwitchInst format without case ranges.
2581 if (Record.size() < 3 || (Record.size() & 1) == 0)
2582 return Error("Invalid SWITCH record");
2583 Type *OpTy = getTypeByID(Record[0]);
2584 Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
2585 BasicBlock *Default = getBasicBlock(Record[2]);
2586 if (OpTy == 0 || Cond == 0 || Default == 0)
2587 return Error("Invalid SWITCH record");
2588 unsigned NumCases = (Record.size()-3)/2;
2589 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
2590 InstructionList.push_back(SI);
2591 for (unsigned i = 0, e = NumCases; i != e; ++i) {
2592 ConstantInt *CaseVal =
2593 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
2594 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
2595 if (CaseVal == 0 || DestBB == 0) {
2597 return Error("Invalid SWITCH record!");
2599 SI->addCase(CaseVal, DestBB);
2604 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
2605 if (Record.size() < 2)
2606 return Error("Invalid INDIRECTBR record");
2607 Type *OpTy = getTypeByID(Record[0]);
2608 Value *Address = getValue(Record, 1, NextValueNo, OpTy);
2609 if (OpTy == 0 || Address == 0)
2610 return Error("Invalid INDIRECTBR record");
2611 unsigned NumDests = Record.size()-2;
2612 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
2613 InstructionList.push_back(IBI);
2614 for (unsigned i = 0, e = NumDests; i != e; ++i) {
2615 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
2616 IBI->addDestination(DestBB);
2619 return Error("Invalid INDIRECTBR record!");
2626 case bitc::FUNC_CODE_INST_INVOKE: {
2627 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
2628 if (Record.size() < 4) return Error("Invalid INVOKE record");
2629 AttributeSet PAL = getAttributes(Record[0]);
2630 unsigned CCInfo = Record[1];
2631 BasicBlock *NormalBB = getBasicBlock(Record[2]);
2632 BasicBlock *UnwindBB = getBasicBlock(Record[3]);
2636 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
2637 return Error("Invalid INVOKE record");
2639 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
2640 FunctionType *FTy = !CalleeTy ? 0 :
2641 dyn_cast<FunctionType>(CalleeTy->getElementType());
2643 // Check that the right number of fixed parameters are here.
2644 if (FTy == 0 || NormalBB == 0 || UnwindBB == 0 ||
2645 Record.size() < OpNum+FTy->getNumParams())
2646 return Error("Invalid INVOKE record");
2648 SmallVector<Value*, 16> Ops;
2649 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
2650 Ops.push_back(getValue(Record, OpNum, NextValueNo,
2651 FTy->getParamType(i)));
2652 if (Ops.back() == 0) return Error("Invalid INVOKE record");
2655 if (!FTy->isVarArg()) {
2656 if (Record.size() != OpNum)
2657 return Error("Invalid INVOKE record");
2659 // Read type/value pairs for varargs params.
2660 while (OpNum != Record.size()) {
2662 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2663 return Error("Invalid INVOKE record");
2668 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops);
2669 InstructionList.push_back(I);
2670 cast<InvokeInst>(I)->setCallingConv(
2671 static_cast<CallingConv::ID>(CCInfo));
2672 cast<InvokeInst>(I)->setAttributes(PAL);
2675 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
2678 if (getValueTypePair(Record, Idx, NextValueNo, Val))
2679 return Error("Invalid RESUME record");
2680 I = ResumeInst::Create(Val);
2681 InstructionList.push_back(I);
2684 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
2685 I = new UnreachableInst(Context);
2686 InstructionList.push_back(I);
2688 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
2689 if (Record.size() < 1 || ((Record.size()-1)&1))
2690 return Error("Invalid PHI record");
2691 Type *Ty = getTypeByID(Record[0]);
2692 if (!Ty) return Error("Invalid PHI record");
2694 PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
2695 InstructionList.push_back(PN);
2697 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
2699 // With the new function encoding, it is possible that operands have
2700 // negative IDs (for forward references). Use a signed VBR
2701 // representation to keep the encoding small.
2703 V = getValueSigned(Record, 1+i, NextValueNo, Ty);
2705 V = getValue(Record, 1+i, NextValueNo, Ty);
2706 BasicBlock *BB = getBasicBlock(Record[2+i]);
2707 if (!V || !BB) return Error("Invalid PHI record");
2708 PN->addIncoming(V, BB);
2714 case bitc::FUNC_CODE_INST_LANDINGPAD: {
2715 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
2717 if (Record.size() < 4)
2718 return Error("Invalid LANDINGPAD record");
2719 Type *Ty = getTypeByID(Record[Idx++]);
2720 if (!Ty) return Error("Invalid LANDINGPAD record");
2722 if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
2723 return Error("Invalid LANDINGPAD record");
2725 bool IsCleanup = !!Record[Idx++];
2726 unsigned NumClauses = Record[Idx++];
2727 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, NumClauses);
2728 LP->setCleanup(IsCleanup);
2729 for (unsigned J = 0; J != NumClauses; ++J) {
2730 LandingPadInst::ClauseType CT =
2731 LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
2734 if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
2736 return Error("Invalid LANDINGPAD record");
2739 assert((CT != LandingPadInst::Catch ||
2740 !isa<ArrayType>(Val->getType())) &&
2741 "Catch clause has a invalid type!");
2742 assert((CT != LandingPadInst::Filter ||
2743 isa<ArrayType>(Val->getType())) &&
2744 "Filter clause has invalid type!");
2749 InstructionList.push_back(I);
2753 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
2754 if (Record.size() != 4)
2755 return Error("Invalid ALLOCA record");
2757 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
2758 Type *OpTy = getTypeByID(Record[1]);
2759 Value *Size = getFnValueByID(Record[2], OpTy);
2760 unsigned Align = Record[3];
2761 if (!Ty || !Size) return Error("Invalid ALLOCA record");
2762 I = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
2763 InstructionList.push_back(I);
2766 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
2769 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2770 OpNum+2 != Record.size())
2771 return Error("Invalid LOAD record");
2773 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1);
2774 InstructionList.push_back(I);
2777 case bitc::FUNC_CODE_INST_LOADATOMIC: {
2778 // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
2781 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2782 OpNum+4 != Record.size())
2783 return Error("Invalid LOADATOMIC record");
2786 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
2787 if (Ordering == NotAtomic || Ordering == Release ||
2788 Ordering == AcquireRelease)
2789 return Error("Invalid LOADATOMIC record");
2790 if (Ordering != NotAtomic && Record[OpNum] == 0)
2791 return Error("Invalid LOADATOMIC record");
2792 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2794 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1,
2795 Ordering, SynchScope);
2796 InstructionList.push_back(I);
2799 case bitc::FUNC_CODE_INST_STORE: { // STORE2:[ptrty, ptr, val, align, vol]
2802 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2803 popValue(Record, OpNum, NextValueNo,
2804 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2805 OpNum+2 != Record.size())
2806 return Error("Invalid STORE record");
2808 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
2809 InstructionList.push_back(I);
2812 case bitc::FUNC_CODE_INST_STOREATOMIC: {
2813 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
2816 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2817 popValue(Record, OpNum, NextValueNo,
2818 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2819 OpNum+4 != Record.size())
2820 return Error("Invalid STOREATOMIC record");
2822 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
2823 if (Ordering == NotAtomic || Ordering == Acquire ||
2824 Ordering == AcquireRelease)
2825 return Error("Invalid STOREATOMIC record");
2826 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2827 if (Ordering != NotAtomic && Record[OpNum] == 0)
2828 return Error("Invalid STOREATOMIC record");
2830 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1,
2831 Ordering, SynchScope);
2832 InstructionList.push_back(I);
2835 case bitc::FUNC_CODE_INST_CMPXCHG: {
2836 // CMPXCHG:[ptrty, ptr, cmp, new, vol, ordering, synchscope]
2838 Value *Ptr, *Cmp, *New;
2839 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2840 popValue(Record, OpNum, NextValueNo,
2841 cast<PointerType>(Ptr->getType())->getElementType(), Cmp) ||
2842 popValue(Record, OpNum, NextValueNo,
2843 cast<PointerType>(Ptr->getType())->getElementType(), New) ||
2844 OpNum+3 != Record.size())
2845 return Error("Invalid CMPXCHG record");
2846 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+1]);
2847 if (Ordering == NotAtomic || Ordering == Unordered)
2848 return Error("Invalid CMPXCHG record");
2849 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+2]);
2850 I = new AtomicCmpXchgInst(Ptr, Cmp, New, Ordering, SynchScope);
2851 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
2852 InstructionList.push_back(I);
2855 case bitc::FUNC_CODE_INST_ATOMICRMW: {
2856 // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
2859 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2860 popValue(Record, OpNum, NextValueNo,
2861 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2862 OpNum+4 != Record.size())
2863 return Error("Invalid ATOMICRMW record");
2864 AtomicRMWInst::BinOp Operation = GetDecodedRMWOperation(Record[OpNum]);
2865 if (Operation < AtomicRMWInst::FIRST_BINOP ||
2866 Operation > AtomicRMWInst::LAST_BINOP)
2867 return Error("Invalid ATOMICRMW record");
2868 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
2869 if (Ordering == NotAtomic || Ordering == Unordered)
2870 return Error("Invalid ATOMICRMW record");
2871 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2872 I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
2873 cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
2874 InstructionList.push_back(I);
2877 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
2878 if (2 != Record.size())
2879 return Error("Invalid FENCE record");
2880 AtomicOrdering Ordering = GetDecodedOrdering(Record[0]);
2881 if (Ordering == NotAtomic || Ordering == Unordered ||
2882 Ordering == Monotonic)
2883 return Error("Invalid FENCE record");
2884 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[1]);
2885 I = new FenceInst(Context, Ordering, SynchScope);
2886 InstructionList.push_back(I);
2889 case bitc::FUNC_CODE_INST_CALL: {
2890 // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
2891 if (Record.size() < 3)
2892 return Error("Invalid CALL record");
2894 AttributeSet PAL = getAttributes(Record[0]);
2895 unsigned CCInfo = Record[1];
2899 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
2900 return Error("Invalid CALL record");
2902 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
2903 FunctionType *FTy = 0;
2904 if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
2905 if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
2906 return Error("Invalid CALL record");
2908 SmallVector<Value*, 16> Args;
2909 // Read the fixed params.
2910 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
2911 if (FTy->getParamType(i)->isLabelTy())
2912 Args.push_back(getBasicBlock(Record[OpNum]));
2914 Args.push_back(getValue(Record, OpNum, NextValueNo,
2915 FTy->getParamType(i)));
2916 if (Args.back() == 0) return Error("Invalid CALL record");
2919 // Read type/value pairs for varargs params.
2920 if (!FTy->isVarArg()) {
2921 if (OpNum != Record.size())
2922 return Error("Invalid CALL record");
2924 while (OpNum != Record.size()) {
2926 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2927 return Error("Invalid CALL record");
2932 I = CallInst::Create(Callee, Args);
2933 InstructionList.push_back(I);
2934 cast<CallInst>(I)->setCallingConv(
2935 static_cast<CallingConv::ID>(CCInfo>>1));
2936 cast<CallInst>(I)->setTailCall(CCInfo & 1);
2937 cast<CallInst>(I)->setAttributes(PAL);
2940 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
2941 if (Record.size() < 3)
2942 return Error("Invalid VAARG record");
2943 Type *OpTy = getTypeByID(Record[0]);
2944 Value *Op = getValue(Record, 1, NextValueNo, OpTy);
2945 Type *ResTy = getTypeByID(Record[2]);
2946 if (!OpTy || !Op || !ResTy)
2947 return Error("Invalid VAARG record");
2948 I = new VAArgInst(Op, ResTy);
2949 InstructionList.push_back(I);
2954 // Add instruction to end of current BB. If there is no current BB, reject
2958 return Error("Invalid instruction with no BB");
2960 CurBB->getInstList().push_back(I);
2962 // If this was a terminator instruction, move to the next block.
2963 if (isa<TerminatorInst>(I)) {
2965 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : 0;
2968 // Non-void values get registered in the value table for future use.
2969 if (I && !I->getType()->isVoidTy())
2970 ValueList.AssignValue(I, NextValueNo++);
2975 // Check the function list for unresolved values.
2976 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
2977 if (A->getParent() == 0) {
2978 // We found at least one unresolved value. Nuke them all to avoid leaks.
2979 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
2980 if ((A = dyn_cast<Argument>(ValueList[i])) && A->getParent() == 0) {
2981 A->replaceAllUsesWith(UndefValue::get(A->getType()));
2985 return Error("Never resolved value found in function!");
2989 // FIXME: Check for unresolved forward-declared metadata references
2990 // and clean up leaks.
2992 // See if anything took the address of blocks in this function. If so,
2993 // resolve them now.
2994 DenseMap<Function*, std::vector<BlockAddrRefTy> >::iterator BAFRI =
2995 BlockAddrFwdRefs.find(F);
2996 if (BAFRI != BlockAddrFwdRefs.end()) {
2997 std::vector<BlockAddrRefTy> &RefList = BAFRI->second;
2998 for (unsigned i = 0, e = RefList.size(); i != e; ++i) {
2999 unsigned BlockIdx = RefList[i].first;
3000 if (BlockIdx >= FunctionBBs.size())
3001 return Error("Invalid blockaddress block #");
3003 GlobalVariable *FwdRef = RefList[i].second;
3004 FwdRef->replaceAllUsesWith(BlockAddress::get(F, FunctionBBs[BlockIdx]));
3005 FwdRef->eraseFromParent();
3008 BlockAddrFwdRefs.erase(BAFRI);
3011 // Trim the value list down to the size it was before we parsed this function.
3012 ValueList.shrinkTo(ModuleValueListSize);
3013 MDValueList.shrinkTo(ModuleMDValueListSize);
3014 std::vector<BasicBlock*>().swap(FunctionBBs);
3018 /// FindFunctionInStream - Find the function body in the bitcode stream
3019 bool BitcodeReader::FindFunctionInStream(Function *F,
3020 DenseMap<Function*, uint64_t>::iterator DeferredFunctionInfoIterator) {
3021 while (DeferredFunctionInfoIterator->second == 0) {
3022 if (Stream.AtEndOfStream())
3023 return Error("Could not find Function in stream");
3024 // ParseModule will parse the next body in the stream and set its
3025 // position in the DeferredFunctionInfo map.
3026 if (ParseModule(true)) return true;
3031 //===----------------------------------------------------------------------===//
3032 // GVMaterializer implementation
3033 //===----------------------------------------------------------------------===//
3036 bool BitcodeReader::isMaterializable(const GlobalValue *GV) const {
3037 if (const Function *F = dyn_cast<Function>(GV)) {
3038 return F->isDeclaration() &&
3039 DeferredFunctionInfo.count(const_cast<Function*>(F));
3044 bool BitcodeReader::Materialize(GlobalValue *GV, std::string *ErrInfo) {
3045 Function *F = dyn_cast<Function>(GV);
3046 // If it's not a function or is already material, ignore the request.
3047 if (!F || !F->isMaterializable()) return false;
3049 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
3050 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
3051 // If its position is recorded as 0, its body is somewhere in the stream
3052 // but we haven't seen it yet.
3053 if (DFII->second == 0)
3054 if (LazyStreamer && FindFunctionInStream(F, DFII)) return true;
3056 // Move the bit stream to the saved position of the deferred function body.
3057 Stream.JumpToBit(DFII->second);
3059 if (ParseFunctionBody(F)) {
3060 if (ErrInfo) *ErrInfo = ErrorString;
3064 // Upgrade any old intrinsic calls in the function.
3065 for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
3066 E = UpgradedIntrinsics.end(); I != E; ++I) {
3067 if (I->first != I->second) {
3068 for (Value::use_iterator UI = I->first->use_begin(),
3069 UE = I->first->use_end(); UI != UE; ) {
3070 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
3071 UpgradeIntrinsicCall(CI, I->second);
3079 bool BitcodeReader::isDematerializable(const GlobalValue *GV) const {
3080 const Function *F = dyn_cast<Function>(GV);
3081 if (!F || F->isDeclaration())
3083 return DeferredFunctionInfo.count(const_cast<Function*>(F));
3086 void BitcodeReader::Dematerialize(GlobalValue *GV) {
3087 Function *F = dyn_cast<Function>(GV);
3088 // If this function isn't dematerializable, this is a noop.
3089 if (!F || !isDematerializable(F))
3092 assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
3094 // Just forget the function body, we can remat it later.
3099 bool BitcodeReader::MaterializeModule(Module *M, std::string *ErrInfo) {
3100 assert(M == TheModule &&
3101 "Can only Materialize the Module this BitcodeReader is attached to.");
3102 // Iterate over the module, deserializing any functions that are still on
3104 for (Module::iterator F = TheModule->begin(), E = TheModule->end();
3106 if (F->isMaterializable() &&
3107 Materialize(F, ErrInfo))
3110 // At this point, if there are any function bodies, the current bit is
3111 // pointing to the END_BLOCK record after them. Now make sure the rest
3112 // of the bits in the module have been read.
3116 // Upgrade any intrinsic calls that slipped through (should not happen!) and
3117 // delete the old functions to clean up. We can't do this unless the entire
3118 // module is materialized because there could always be another function body
3119 // with calls to the old function.
3120 for (std::vector<std::pair<Function*, Function*> >::iterator I =
3121 UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
3122 if (I->first != I->second) {
3123 for (Value::use_iterator UI = I->first->use_begin(),
3124 UE = I->first->use_end(); UI != UE; ) {
3125 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
3126 UpgradeIntrinsicCall(CI, I->second);
3128 if (!I->first->use_empty())
3129 I->first->replaceAllUsesWith(I->second);
3130 I->first->eraseFromParent();
3133 std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
3135 for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
3136 UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
3141 bool BitcodeReader::InitStream() {
3142 if (LazyStreamer) return InitLazyStream();
3143 return InitStreamFromBuffer();
3146 bool BitcodeReader::InitStreamFromBuffer() {
3147 const unsigned char *BufPtr = (const unsigned char*)Buffer->getBufferStart();
3148 const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
3150 if (Buffer->getBufferSize() & 3) {
3151 if (!isRawBitcode(BufPtr, BufEnd) && !isBitcodeWrapper(BufPtr, BufEnd))
3152 return Error("Invalid bitcode signature");
3154 return Error("Bitcode stream should be a multiple of 4 bytes in length");
3157 // If we have a wrapper header, parse it and ignore the non-bc file contents.
3158 // The magic number is 0x0B17C0DE stored in little endian.
3159 if (isBitcodeWrapper(BufPtr, BufEnd))
3160 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
3161 return Error("Invalid bitcode wrapper header");
3163 StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
3164 Stream.init(*StreamFile);
3169 bool BitcodeReader::InitLazyStream() {
3170 // Check and strip off the bitcode wrapper; BitstreamReader expects never to
3172 StreamingMemoryObject *Bytes = new StreamingMemoryObject(LazyStreamer);
3173 StreamFile.reset(new BitstreamReader(Bytes));
3174 Stream.init(*StreamFile);
3176 unsigned char buf[16];
3177 if (Bytes->readBytes(0, 16, buf) == -1)
3178 return Error("Bitcode stream must be at least 16 bytes in length");
3180 if (!isBitcode(buf, buf + 16))
3181 return Error("Invalid bitcode signature");
3183 if (isBitcodeWrapper(buf, buf + 4)) {
3184 const unsigned char *bitcodeStart = buf;
3185 const unsigned char *bitcodeEnd = buf + 16;
3186 SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
3187 Bytes->dropLeadingBytes(bitcodeStart - buf);
3188 Bytes->setKnownObjectSize(bitcodeEnd - bitcodeStart);
3193 //===----------------------------------------------------------------------===//
3194 // External interface
3195 //===----------------------------------------------------------------------===//
3197 /// getLazyBitcodeModule - lazy function-at-a-time loading from a file.
3199 Module *llvm::getLazyBitcodeModule(MemoryBuffer *Buffer,
3200 LLVMContext& Context,
3201 std::string *ErrMsg) {
3202 Module *M = new Module(Buffer->getBufferIdentifier(), Context);
3203 BitcodeReader *R = new BitcodeReader(Buffer, Context);
3204 M->setMaterializer(R);
3205 if (R->ParseBitcodeInto(M)) {
3207 *ErrMsg = R->getErrorString();
3209 delete M; // Also deletes R.
3212 // Have the BitcodeReader dtor delete 'Buffer'.
3213 R->setBufferOwned(true);
3215 R->materializeForwardReferencedFunctions();
3221 Module *llvm::getStreamedBitcodeModule(const std::string &name,
3222 DataStreamer *streamer,
3223 LLVMContext &Context,
3224 std::string *ErrMsg) {
3225 Module *M = new Module(name, Context);
3226 BitcodeReader *R = new BitcodeReader(streamer, Context);
3227 M->setMaterializer(R);
3228 if (R->ParseBitcodeInto(M)) {
3230 *ErrMsg = R->getErrorString();
3231 delete M; // Also deletes R.
3234 R->setBufferOwned(false); // no buffer to delete
3238 /// ParseBitcodeFile - Read the specified bitcode file, returning the module.
3239 /// If an error occurs, return null and fill in *ErrMsg if non-null.
3240 Module *llvm::ParseBitcodeFile(MemoryBuffer *Buffer, LLVMContext& Context,
3241 std::string *ErrMsg){
3242 Module *M = getLazyBitcodeModule(Buffer, Context, ErrMsg);
3245 // Don't let the BitcodeReader dtor delete 'Buffer', regardless of whether
3246 // there was an error.
3247 static_cast<BitcodeReader*>(M->getMaterializer())->setBufferOwned(false);
3249 // Read in the entire module, and destroy the BitcodeReader.
3250 if (M->MaterializeAllPermanently(ErrMsg)) {
3255 // TODO: Restore the use-lists to the in-memory state when the bitcode was
3256 // written. We must defer until the Module has been fully materialized.
3261 std::string llvm::getBitcodeTargetTriple(MemoryBuffer *Buffer,
3262 LLVMContext& Context,
3263 std::string *ErrMsg) {
3264 BitcodeReader *R = new BitcodeReader(Buffer, Context);
3265 // Don't let the BitcodeReader dtor delete 'Buffer'.
3266 R->setBufferOwned(false);
3268 std::string Triple("");
3269 if (R->ParseTriple(Triple))
3271 *ErrMsg = R->getErrorString();