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/Bitcode/LLVMBitCodes.h"
15 #include "llvm/IR/AutoUpgrade.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::ExternalLinkage; // Obsolete DLLImportLinkage
84 case 6: return GlobalValue::ExternalLinkage; // Obsolete 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 GlobalValue::DLLStorageClassTypes
106 GetDecodedDLLStorageClass(unsigned Val) {
108 default: // Map unknown values to default.
109 case 0: return GlobalValue::DefaultStorageClass;
110 case 1: return GlobalValue::DLLImportStorageClass;
111 case 2: return GlobalValue::DLLExportStorageClass;
115 static GlobalVariable::ThreadLocalMode GetDecodedThreadLocalMode(unsigned Val) {
117 case 0: return GlobalVariable::NotThreadLocal;
118 default: // Map unknown non-zero value to general dynamic.
119 case 1: return GlobalVariable::GeneralDynamicTLSModel;
120 case 2: return GlobalVariable::LocalDynamicTLSModel;
121 case 3: return GlobalVariable::InitialExecTLSModel;
122 case 4: return GlobalVariable::LocalExecTLSModel;
126 static int GetDecodedCastOpcode(unsigned Val) {
129 case bitc::CAST_TRUNC : return Instruction::Trunc;
130 case bitc::CAST_ZEXT : return Instruction::ZExt;
131 case bitc::CAST_SEXT : return Instruction::SExt;
132 case bitc::CAST_FPTOUI : return Instruction::FPToUI;
133 case bitc::CAST_FPTOSI : return Instruction::FPToSI;
134 case bitc::CAST_UITOFP : return Instruction::UIToFP;
135 case bitc::CAST_SITOFP : return Instruction::SIToFP;
136 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
137 case bitc::CAST_FPEXT : return Instruction::FPExt;
138 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
139 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
140 case bitc::CAST_BITCAST : return Instruction::BitCast;
141 case bitc::CAST_ADDRSPACECAST: return Instruction::AddrSpaceCast;
144 static int GetDecodedBinaryOpcode(unsigned Val, Type *Ty) {
147 case bitc::BINOP_ADD:
148 return Ty->isFPOrFPVectorTy() ? Instruction::FAdd : Instruction::Add;
149 case bitc::BINOP_SUB:
150 return Ty->isFPOrFPVectorTy() ? Instruction::FSub : Instruction::Sub;
151 case bitc::BINOP_MUL:
152 return Ty->isFPOrFPVectorTy() ? Instruction::FMul : Instruction::Mul;
153 case bitc::BINOP_UDIV: return Instruction::UDiv;
154 case bitc::BINOP_SDIV:
155 return Ty->isFPOrFPVectorTy() ? Instruction::FDiv : Instruction::SDiv;
156 case bitc::BINOP_UREM: return Instruction::URem;
157 case bitc::BINOP_SREM:
158 return Ty->isFPOrFPVectorTy() ? Instruction::FRem : Instruction::SRem;
159 case bitc::BINOP_SHL: return Instruction::Shl;
160 case bitc::BINOP_LSHR: return Instruction::LShr;
161 case bitc::BINOP_ASHR: return Instruction::AShr;
162 case bitc::BINOP_AND: return Instruction::And;
163 case bitc::BINOP_OR: return Instruction::Or;
164 case bitc::BINOP_XOR: return Instruction::Xor;
168 static AtomicRMWInst::BinOp GetDecodedRMWOperation(unsigned Val) {
170 default: return AtomicRMWInst::BAD_BINOP;
171 case bitc::RMW_XCHG: return AtomicRMWInst::Xchg;
172 case bitc::RMW_ADD: return AtomicRMWInst::Add;
173 case bitc::RMW_SUB: return AtomicRMWInst::Sub;
174 case bitc::RMW_AND: return AtomicRMWInst::And;
175 case bitc::RMW_NAND: return AtomicRMWInst::Nand;
176 case bitc::RMW_OR: return AtomicRMWInst::Or;
177 case bitc::RMW_XOR: return AtomicRMWInst::Xor;
178 case bitc::RMW_MAX: return AtomicRMWInst::Max;
179 case bitc::RMW_MIN: return AtomicRMWInst::Min;
180 case bitc::RMW_UMAX: return AtomicRMWInst::UMax;
181 case bitc::RMW_UMIN: return AtomicRMWInst::UMin;
185 static AtomicOrdering GetDecodedOrdering(unsigned Val) {
187 case bitc::ORDERING_NOTATOMIC: return NotAtomic;
188 case bitc::ORDERING_UNORDERED: return Unordered;
189 case bitc::ORDERING_MONOTONIC: return Monotonic;
190 case bitc::ORDERING_ACQUIRE: return Acquire;
191 case bitc::ORDERING_RELEASE: return Release;
192 case bitc::ORDERING_ACQREL: return AcquireRelease;
193 default: // Map unknown orderings to sequentially-consistent.
194 case bitc::ORDERING_SEQCST: return SequentiallyConsistent;
198 static SynchronizationScope GetDecodedSynchScope(unsigned Val) {
200 case bitc::SYNCHSCOPE_SINGLETHREAD: return SingleThread;
201 default: // Map unknown scopes to cross-thread.
202 case bitc::SYNCHSCOPE_CROSSTHREAD: return CrossThread;
206 static void UpgradeDLLImportExportLinkage(llvm::GlobalValue *GV, unsigned Val) {
208 case 5: GV->setDLLStorageClass(GlobalValue::DLLImportStorageClass); break;
209 case 6: GV->setDLLStorageClass(GlobalValue::DLLExportStorageClass); break;
215 /// @brief A class for maintaining the slot number definition
216 /// as a placeholder for the actual definition for forward constants defs.
217 class ConstantPlaceHolder : public ConstantExpr {
218 void operator=(const ConstantPlaceHolder &) LLVM_DELETED_FUNCTION;
220 // allocate space for exactly one operand
221 void *operator new(size_t s) {
222 return User::operator new(s, 1);
224 explicit ConstantPlaceHolder(Type *Ty, LLVMContext& Context)
225 : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
226 Op<0>() = UndefValue::get(Type::getInt32Ty(Context));
229 /// @brief Methods to support type inquiry through isa, cast, and dyn_cast.
230 static bool classof(const Value *V) {
231 return isa<ConstantExpr>(V) &&
232 cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
236 /// Provide fast operand accessors
237 //DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
241 // FIXME: can we inherit this from ConstantExpr?
243 struct OperandTraits<ConstantPlaceHolder> :
244 public FixedNumOperandTraits<ConstantPlaceHolder, 1> {
249 void BitcodeReaderValueList::AssignValue(Value *V, unsigned Idx) {
258 WeakVH &OldV = ValuePtrs[Idx];
264 // Handle constants and non-constants (e.g. instrs) differently for
266 if (Constant *PHC = dyn_cast<Constant>(&*OldV)) {
267 ResolveConstants.push_back(std::make_pair(PHC, Idx));
270 // If there was a forward reference to this value, replace it.
271 Value *PrevVal = OldV;
272 OldV->replaceAllUsesWith(V);
278 Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
283 if (Value *V = ValuePtrs[Idx]) {
284 assert(Ty == V->getType() && "Type mismatch in constant table!");
285 return cast<Constant>(V);
288 // Create and return a placeholder, which will later be RAUW'd.
289 Constant *C = new ConstantPlaceHolder(Ty, Context);
294 Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, Type *Ty) {
298 if (Value *V = ValuePtrs[Idx]) {
299 assert((Ty == 0 || Ty == V->getType()) && "Type mismatch in value table!");
303 // No type specified, must be invalid reference.
304 if (Ty == 0) return 0;
306 // Create and return a placeholder, which will later be RAUW'd.
307 Value *V = new Argument(Ty);
312 /// ResolveConstantForwardRefs - Once all constants are read, this method bulk
313 /// resolves any forward references. The idea behind this is that we sometimes
314 /// get constants (such as large arrays) which reference *many* forward ref
315 /// constants. Replacing each of these causes a lot of thrashing when
316 /// building/reuniquing the constant. Instead of doing this, we look at all the
317 /// uses and rewrite all the place holders at once for any constant that uses
319 void BitcodeReaderValueList::ResolveConstantForwardRefs() {
320 // Sort the values by-pointer so that they are efficient to look up with a
322 std::sort(ResolveConstants.begin(), ResolveConstants.end());
324 SmallVector<Constant*, 64> NewOps;
326 while (!ResolveConstants.empty()) {
327 Value *RealVal = operator[](ResolveConstants.back().second);
328 Constant *Placeholder = ResolveConstants.back().first;
329 ResolveConstants.pop_back();
331 // Loop over all users of the placeholder, updating them to reference the
332 // new value. If they reference more than one placeholder, update them all
334 while (!Placeholder->use_empty()) {
335 Value::use_iterator UI = Placeholder->use_begin();
338 // If the using object isn't uniqued, just update the operands. This
339 // handles instructions and initializers for global variables.
340 if (!isa<Constant>(U) || isa<GlobalValue>(U)) {
341 UI.getUse().set(RealVal);
345 // Otherwise, we have a constant that uses the placeholder. Replace that
346 // constant with a new constant that has *all* placeholder uses updated.
347 Constant *UserC = cast<Constant>(U);
348 for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end();
351 if (!isa<ConstantPlaceHolder>(*I)) {
352 // Not a placeholder reference.
354 } else if (*I == Placeholder) {
355 // Common case is that it just references this one placeholder.
358 // Otherwise, look up the placeholder in ResolveConstants.
359 ResolveConstantsTy::iterator It =
360 std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(),
361 std::pair<Constant*, unsigned>(cast<Constant>(*I),
363 assert(It != ResolveConstants.end() && It->first == *I);
364 NewOp = operator[](It->second);
367 NewOps.push_back(cast<Constant>(NewOp));
370 // Make the new constant.
372 if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
373 NewC = ConstantArray::get(UserCA->getType(), NewOps);
374 } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
375 NewC = ConstantStruct::get(UserCS->getType(), NewOps);
376 } else if (isa<ConstantVector>(UserC)) {
377 NewC = ConstantVector::get(NewOps);
379 assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr.");
380 NewC = cast<ConstantExpr>(UserC)->getWithOperands(NewOps);
383 UserC->replaceAllUsesWith(NewC);
384 UserC->destroyConstant();
388 // Update all ValueHandles, they should be the only users at this point.
389 Placeholder->replaceAllUsesWith(RealVal);
394 void BitcodeReaderMDValueList::AssignValue(Value *V, unsigned Idx) {
403 WeakVH &OldV = MDValuePtrs[Idx];
409 // If there was a forward reference to this value, replace it.
410 MDNode *PrevVal = cast<MDNode>(OldV);
411 OldV->replaceAllUsesWith(V);
412 MDNode::deleteTemporary(PrevVal);
413 // Deleting PrevVal sets Idx value in MDValuePtrs to null. Set new
415 MDValuePtrs[Idx] = V;
418 Value *BitcodeReaderMDValueList::getValueFwdRef(unsigned Idx) {
422 if (Value *V = MDValuePtrs[Idx]) {
423 assert(V->getType()->isMetadataTy() && "Type mismatch in value table!");
427 // Create and return a placeholder, which will later be RAUW'd.
428 Value *V = MDNode::getTemporary(Context, None);
429 MDValuePtrs[Idx] = V;
433 Type *BitcodeReader::getTypeByID(unsigned ID) {
434 // The type table size is always specified correctly.
435 if (ID >= TypeList.size())
438 if (Type *Ty = TypeList[ID])
441 // If we have a forward reference, the only possible case is when it is to a
442 // named struct. Just create a placeholder for now.
443 return TypeList[ID] = StructType::create(Context);
447 //===----------------------------------------------------------------------===//
448 // Functions for parsing blocks from the bitcode file
449 //===----------------------------------------------------------------------===//
452 /// \brief This fills an AttrBuilder object with the LLVM attributes that have
453 /// been decoded from the given integer. This function must stay in sync with
454 /// 'encodeLLVMAttributesForBitcode'.
455 static void decodeLLVMAttributesForBitcode(AttrBuilder &B,
456 uint64_t EncodedAttrs) {
457 // FIXME: Remove in 4.0.
459 // The alignment is stored as a 16-bit raw value from bits 31--16. We shift
460 // the bits above 31 down by 11 bits.
461 unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
462 assert((!Alignment || isPowerOf2_32(Alignment)) &&
463 "Alignment must be a power of two.");
466 B.addAlignmentAttr(Alignment);
467 B.addRawValue(((EncodedAttrs & (0xfffffULL << 32)) >> 11) |
468 (EncodedAttrs & 0xffff));
471 error_code BitcodeReader::ParseAttributeBlock() {
472 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
473 return Error(InvalidRecord);
475 if (!MAttributes.empty())
476 return Error(InvalidMultipleBlocks);
478 SmallVector<uint64_t, 64> Record;
480 SmallVector<AttributeSet, 8> Attrs;
482 // Read all the records.
484 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
486 switch (Entry.Kind) {
487 case BitstreamEntry::SubBlock: // Handled for us already.
488 case BitstreamEntry::Error:
489 return Error(MalformedBlock);
490 case BitstreamEntry::EndBlock:
491 return error_code::success();
492 case BitstreamEntry::Record:
493 // The interesting case.
499 switch (Stream.readRecord(Entry.ID, Record)) {
500 default: // Default behavior: ignore.
502 case bitc::PARAMATTR_CODE_ENTRY_OLD: { // ENTRY: [paramidx0, attr0, ...]
503 // FIXME: Remove in 4.0.
504 if (Record.size() & 1)
505 return Error(InvalidRecord);
507 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
509 decodeLLVMAttributesForBitcode(B, Record[i+1]);
510 Attrs.push_back(AttributeSet::get(Context, Record[i], B));
513 MAttributes.push_back(AttributeSet::get(Context, Attrs));
517 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [attrgrp0, attrgrp1, ...]
518 for (unsigned i = 0, e = Record.size(); i != e; ++i)
519 Attrs.push_back(MAttributeGroups[Record[i]]);
521 MAttributes.push_back(AttributeSet::get(Context, Attrs));
529 // Returns Attribute::None on unrecognized codes.
530 static Attribute::AttrKind GetAttrFromCode(uint64_t Code) {
533 return Attribute::None;
534 case bitc::ATTR_KIND_ALIGNMENT:
535 return Attribute::Alignment;
536 case bitc::ATTR_KIND_ALWAYS_INLINE:
537 return Attribute::AlwaysInline;
538 case bitc::ATTR_KIND_BUILTIN:
539 return Attribute::Builtin;
540 case bitc::ATTR_KIND_BY_VAL:
541 return Attribute::ByVal;
542 case bitc::ATTR_KIND_IN_ALLOCA:
543 return Attribute::InAlloca;
544 case bitc::ATTR_KIND_COLD:
545 return Attribute::Cold;
546 case bitc::ATTR_KIND_INLINE_HINT:
547 return Attribute::InlineHint;
548 case bitc::ATTR_KIND_IN_REG:
549 return Attribute::InReg;
550 case bitc::ATTR_KIND_MIN_SIZE:
551 return Attribute::MinSize;
552 case bitc::ATTR_KIND_NAKED:
553 return Attribute::Naked;
554 case bitc::ATTR_KIND_NEST:
555 return Attribute::Nest;
556 case bitc::ATTR_KIND_NO_ALIAS:
557 return Attribute::NoAlias;
558 case bitc::ATTR_KIND_NO_BUILTIN:
559 return Attribute::NoBuiltin;
560 case bitc::ATTR_KIND_NO_CAPTURE:
561 return Attribute::NoCapture;
562 case bitc::ATTR_KIND_NO_DUPLICATE:
563 return Attribute::NoDuplicate;
564 case bitc::ATTR_KIND_NO_IMPLICIT_FLOAT:
565 return Attribute::NoImplicitFloat;
566 case bitc::ATTR_KIND_NO_INLINE:
567 return Attribute::NoInline;
568 case bitc::ATTR_KIND_NON_LAZY_BIND:
569 return Attribute::NonLazyBind;
570 case bitc::ATTR_KIND_NO_RED_ZONE:
571 return Attribute::NoRedZone;
572 case bitc::ATTR_KIND_NO_RETURN:
573 return Attribute::NoReturn;
574 case bitc::ATTR_KIND_NO_UNWIND:
575 return Attribute::NoUnwind;
576 case bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE:
577 return Attribute::OptimizeForSize;
578 case bitc::ATTR_KIND_OPTIMIZE_NONE:
579 return Attribute::OptimizeNone;
580 case bitc::ATTR_KIND_READ_NONE:
581 return Attribute::ReadNone;
582 case bitc::ATTR_KIND_READ_ONLY:
583 return Attribute::ReadOnly;
584 case bitc::ATTR_KIND_RETURNED:
585 return Attribute::Returned;
586 case bitc::ATTR_KIND_RETURNS_TWICE:
587 return Attribute::ReturnsTwice;
588 case bitc::ATTR_KIND_S_EXT:
589 return Attribute::SExt;
590 case bitc::ATTR_KIND_STACK_ALIGNMENT:
591 return Attribute::StackAlignment;
592 case bitc::ATTR_KIND_STACK_PROTECT:
593 return Attribute::StackProtect;
594 case bitc::ATTR_KIND_STACK_PROTECT_REQ:
595 return Attribute::StackProtectReq;
596 case bitc::ATTR_KIND_STACK_PROTECT_STRONG:
597 return Attribute::StackProtectStrong;
598 case bitc::ATTR_KIND_STRUCT_RET:
599 return Attribute::StructRet;
600 case bitc::ATTR_KIND_SANITIZE_ADDRESS:
601 return Attribute::SanitizeAddress;
602 case bitc::ATTR_KIND_SANITIZE_THREAD:
603 return Attribute::SanitizeThread;
604 case bitc::ATTR_KIND_SANITIZE_MEMORY:
605 return Attribute::SanitizeMemory;
606 case bitc::ATTR_KIND_UW_TABLE:
607 return Attribute::UWTable;
608 case bitc::ATTR_KIND_Z_EXT:
609 return Attribute::ZExt;
613 error_code BitcodeReader::ParseAttrKind(uint64_t Code,
614 Attribute::AttrKind *Kind) {
615 *Kind = GetAttrFromCode(Code);
616 if (*Kind == Attribute::None)
617 return Error(InvalidValue);
618 return error_code::success();
621 error_code BitcodeReader::ParseAttributeGroupBlock() {
622 if (Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID))
623 return Error(InvalidRecord);
625 if (!MAttributeGroups.empty())
626 return Error(InvalidMultipleBlocks);
628 SmallVector<uint64_t, 64> Record;
630 // Read all the records.
632 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
634 switch (Entry.Kind) {
635 case BitstreamEntry::SubBlock: // Handled for us already.
636 case BitstreamEntry::Error:
637 return Error(MalformedBlock);
638 case BitstreamEntry::EndBlock:
639 return error_code::success();
640 case BitstreamEntry::Record:
641 // The interesting case.
647 switch (Stream.readRecord(Entry.ID, Record)) {
648 default: // Default behavior: ignore.
650 case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...]
651 if (Record.size() < 3)
652 return Error(InvalidRecord);
654 uint64_t GrpID = Record[0];
655 uint64_t Idx = Record[1]; // Index of the object this attribute refers to.
658 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
659 if (Record[i] == 0) { // Enum attribute
660 Attribute::AttrKind Kind;
661 if (error_code EC = ParseAttrKind(Record[++i], &Kind))
664 B.addAttribute(Kind);
665 } else if (Record[i] == 1) { // Align attribute
666 Attribute::AttrKind Kind;
667 if (error_code EC = ParseAttrKind(Record[++i], &Kind))
669 if (Kind == Attribute::Alignment)
670 B.addAlignmentAttr(Record[++i]);
672 B.addStackAlignmentAttr(Record[++i]);
673 } else { // String attribute
674 assert((Record[i] == 3 || Record[i] == 4) &&
675 "Invalid attribute group entry");
676 bool HasValue = (Record[i++] == 4);
677 SmallString<64> KindStr;
678 SmallString<64> ValStr;
680 while (Record[i] != 0 && i != e)
681 KindStr += Record[i++];
682 assert(Record[i] == 0 && "Kind string not null terminated");
685 // Has a value associated with it.
686 ++i; // Skip the '0' that terminates the "kind" string.
687 while (Record[i] != 0 && i != e)
688 ValStr += Record[i++];
689 assert(Record[i] == 0 && "Value string not null terminated");
692 B.addAttribute(KindStr.str(), ValStr.str());
696 MAttributeGroups[GrpID] = AttributeSet::get(Context, Idx, B);
703 error_code BitcodeReader::ParseTypeTable() {
704 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
705 return Error(InvalidRecord);
707 return ParseTypeTableBody();
710 error_code BitcodeReader::ParseTypeTableBody() {
711 if (!TypeList.empty())
712 return Error(InvalidMultipleBlocks);
714 SmallVector<uint64_t, 64> Record;
715 unsigned NumRecords = 0;
717 SmallString<64> TypeName;
719 // Read all the records for this type table.
721 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
723 switch (Entry.Kind) {
724 case BitstreamEntry::SubBlock: // Handled for us already.
725 case BitstreamEntry::Error:
726 return Error(MalformedBlock);
727 case BitstreamEntry::EndBlock:
728 if (NumRecords != TypeList.size())
729 return Error(MalformedBlock);
730 return error_code::success();
731 case BitstreamEntry::Record:
732 // The interesting case.
739 switch (Stream.readRecord(Entry.ID, Record)) {
741 return Error(InvalidValue);
742 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
743 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
744 // type list. This allows us to reserve space.
745 if (Record.size() < 1)
746 return Error(InvalidRecord);
747 TypeList.resize(Record[0]);
749 case bitc::TYPE_CODE_VOID: // VOID
750 ResultTy = Type::getVoidTy(Context);
752 case bitc::TYPE_CODE_HALF: // HALF
753 ResultTy = Type::getHalfTy(Context);
755 case bitc::TYPE_CODE_FLOAT: // FLOAT
756 ResultTy = Type::getFloatTy(Context);
758 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
759 ResultTy = Type::getDoubleTy(Context);
761 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
762 ResultTy = Type::getX86_FP80Ty(Context);
764 case bitc::TYPE_CODE_FP128: // FP128
765 ResultTy = Type::getFP128Ty(Context);
767 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
768 ResultTy = Type::getPPC_FP128Ty(Context);
770 case bitc::TYPE_CODE_LABEL: // LABEL
771 ResultTy = Type::getLabelTy(Context);
773 case bitc::TYPE_CODE_METADATA: // METADATA
774 ResultTy = Type::getMetadataTy(Context);
776 case bitc::TYPE_CODE_X86_MMX: // X86_MMX
777 ResultTy = Type::getX86_MMXTy(Context);
779 case bitc::TYPE_CODE_INTEGER: // INTEGER: [width]
780 if (Record.size() < 1)
781 return Error(InvalidRecord);
783 ResultTy = IntegerType::get(Context, Record[0]);
785 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
786 // [pointee type, address space]
787 if (Record.size() < 1)
788 return Error(InvalidRecord);
789 unsigned AddressSpace = 0;
790 if (Record.size() == 2)
791 AddressSpace = Record[1];
792 ResultTy = getTypeByID(Record[0]);
794 return Error(InvalidType);
795 ResultTy = PointerType::get(ResultTy, AddressSpace);
798 case bitc::TYPE_CODE_FUNCTION_OLD: {
799 // FIXME: attrid is dead, remove it in LLVM 4.0
800 // FUNCTION: [vararg, attrid, retty, paramty x N]
801 if (Record.size() < 3)
802 return Error(InvalidRecord);
803 SmallVector<Type*, 8> ArgTys;
804 for (unsigned i = 3, e = Record.size(); i != e; ++i) {
805 if (Type *T = getTypeByID(Record[i]))
811 ResultTy = getTypeByID(Record[2]);
812 if (ResultTy == 0 || ArgTys.size() < Record.size()-3)
813 return Error(InvalidType);
815 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
818 case bitc::TYPE_CODE_FUNCTION: {
819 // FUNCTION: [vararg, retty, paramty x N]
820 if (Record.size() < 2)
821 return Error(InvalidRecord);
822 SmallVector<Type*, 8> ArgTys;
823 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
824 if (Type *T = getTypeByID(Record[i]))
830 ResultTy = getTypeByID(Record[1]);
831 if (ResultTy == 0 || ArgTys.size() < Record.size()-2)
832 return Error(InvalidType);
834 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
837 case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N]
838 if (Record.size() < 1)
839 return Error(InvalidRecord);
840 SmallVector<Type*, 8> EltTys;
841 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
842 if (Type *T = getTypeByID(Record[i]))
847 if (EltTys.size() != Record.size()-1)
848 return Error(InvalidType);
849 ResultTy = StructType::get(Context, EltTys, Record[0]);
852 case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N]
853 if (ConvertToString(Record, 0, TypeName))
854 return Error(InvalidRecord);
857 case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
858 if (Record.size() < 1)
859 return Error(InvalidRecord);
861 if (NumRecords >= TypeList.size())
862 return Error(InvalidTYPETable);
864 // Check to see if this was forward referenced, if so fill in the temp.
865 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
867 Res->setName(TypeName);
868 TypeList[NumRecords] = 0;
869 } else // Otherwise, create a new struct.
870 Res = StructType::create(Context, TypeName);
873 SmallVector<Type*, 8> EltTys;
874 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
875 if (Type *T = getTypeByID(Record[i]))
880 if (EltTys.size() != Record.size()-1)
881 return Error(InvalidRecord);
882 Res->setBody(EltTys, Record[0]);
886 case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: []
887 if (Record.size() != 1)
888 return Error(InvalidRecord);
890 if (NumRecords >= TypeList.size())
891 return Error(InvalidTYPETable);
893 // Check to see if this was forward referenced, if so fill in the temp.
894 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
896 Res->setName(TypeName);
897 TypeList[NumRecords] = 0;
898 } else // Otherwise, create a new struct with no body.
899 Res = StructType::create(Context, TypeName);
904 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
905 if (Record.size() < 2)
906 return Error(InvalidRecord);
907 if ((ResultTy = getTypeByID(Record[1])))
908 ResultTy = ArrayType::get(ResultTy, Record[0]);
910 return Error(InvalidType);
912 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
913 if (Record.size() < 2)
914 return Error(InvalidRecord);
915 if ((ResultTy = getTypeByID(Record[1])))
916 ResultTy = VectorType::get(ResultTy, Record[0]);
918 return Error(InvalidType);
922 if (NumRecords >= TypeList.size())
923 return Error(InvalidTYPETable);
924 assert(ResultTy && "Didn't read a type?");
925 assert(TypeList[NumRecords] == 0 && "Already read type?");
926 TypeList[NumRecords++] = ResultTy;
930 error_code BitcodeReader::ParseValueSymbolTable() {
931 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
932 return Error(InvalidRecord);
934 SmallVector<uint64_t, 64> Record;
936 // Read all the records for this value table.
937 SmallString<128> ValueName;
939 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
941 switch (Entry.Kind) {
942 case BitstreamEntry::SubBlock: // Handled for us already.
943 case BitstreamEntry::Error:
944 return Error(MalformedBlock);
945 case BitstreamEntry::EndBlock:
946 return error_code::success();
947 case BitstreamEntry::Record:
948 // The interesting case.
954 switch (Stream.readRecord(Entry.ID, Record)) {
955 default: // Default behavior: unknown type.
957 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
958 if (ConvertToString(Record, 1, ValueName))
959 return Error(InvalidRecord);
960 unsigned ValueID = Record[0];
961 if (ValueID >= ValueList.size())
962 return Error(InvalidRecord);
963 Value *V = ValueList[ValueID];
965 V->setName(StringRef(ValueName.data(), ValueName.size()));
969 case bitc::VST_CODE_BBENTRY: {
970 if (ConvertToString(Record, 1, ValueName))
971 return Error(InvalidRecord);
972 BasicBlock *BB = getBasicBlock(Record[0]);
974 return Error(InvalidRecord);
976 BB->setName(StringRef(ValueName.data(), ValueName.size()));
984 error_code BitcodeReader::ParseMetadata() {
985 unsigned NextMDValueNo = MDValueList.size();
987 if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
988 return Error(InvalidRecord);
990 SmallVector<uint64_t, 64> Record;
992 // Read all the records.
994 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
996 switch (Entry.Kind) {
997 case BitstreamEntry::SubBlock: // Handled for us already.
998 case BitstreamEntry::Error:
999 return Error(MalformedBlock);
1000 case BitstreamEntry::EndBlock:
1001 return error_code::success();
1002 case BitstreamEntry::Record:
1003 // The interesting case.
1007 bool IsFunctionLocal = false;
1010 unsigned Code = Stream.readRecord(Entry.ID, Record);
1012 default: // Default behavior: ignore.
1014 case bitc::METADATA_NAME: {
1015 // Read name of the named metadata.
1016 SmallString<8> Name(Record.begin(), Record.end());
1018 Code = Stream.ReadCode();
1020 // METADATA_NAME is always followed by METADATA_NAMED_NODE.
1021 unsigned NextBitCode = Stream.readRecord(Code, Record);
1022 assert(NextBitCode == bitc::METADATA_NAMED_NODE); (void)NextBitCode;
1024 // Read named metadata elements.
1025 unsigned Size = Record.size();
1026 NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name);
1027 for (unsigned i = 0; i != Size; ++i) {
1028 MDNode *MD = dyn_cast<MDNode>(MDValueList.getValueFwdRef(Record[i]));
1030 return Error(InvalidRecord);
1031 NMD->addOperand(MD);
1035 case bitc::METADATA_FN_NODE:
1036 IsFunctionLocal = true;
1038 case bitc::METADATA_NODE: {
1039 if (Record.size() % 2 == 1)
1040 return Error(InvalidRecord);
1042 unsigned Size = Record.size();
1043 SmallVector<Value*, 8> Elts;
1044 for (unsigned i = 0; i != Size; i += 2) {
1045 Type *Ty = getTypeByID(Record[i]);
1047 return Error(InvalidRecord);
1048 if (Ty->isMetadataTy())
1049 Elts.push_back(MDValueList.getValueFwdRef(Record[i+1]));
1050 else if (!Ty->isVoidTy())
1051 Elts.push_back(ValueList.getValueFwdRef(Record[i+1], Ty));
1053 Elts.push_back(NULL);
1055 Value *V = MDNode::getWhenValsUnresolved(Context, Elts, IsFunctionLocal);
1056 IsFunctionLocal = false;
1057 MDValueList.AssignValue(V, NextMDValueNo++);
1060 case bitc::METADATA_STRING: {
1061 SmallString<8> String(Record.begin(), Record.end());
1062 Value *V = MDString::get(Context, String);
1063 MDValueList.AssignValue(V, NextMDValueNo++);
1066 case bitc::METADATA_KIND: {
1067 if (Record.size() < 2)
1068 return Error(InvalidRecord);
1070 unsigned Kind = Record[0];
1071 SmallString<8> Name(Record.begin()+1, Record.end());
1073 unsigned NewKind = TheModule->getMDKindID(Name.str());
1074 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
1075 return Error(ConflictingMETADATA_KINDRecords);
1082 /// decodeSignRotatedValue - Decode a signed value stored with the sign bit in
1083 /// the LSB for dense VBR encoding.
1084 uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
1089 // There is no such thing as -0 with integers. "-0" really means MININT.
1093 /// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
1094 /// values and aliases that we can.
1095 error_code BitcodeReader::ResolveGlobalAndAliasInits() {
1096 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
1097 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
1098 std::vector<std::pair<Function*, unsigned> > FunctionPrefixWorklist;
1100 GlobalInitWorklist.swap(GlobalInits);
1101 AliasInitWorklist.swap(AliasInits);
1102 FunctionPrefixWorklist.swap(FunctionPrefixes);
1104 while (!GlobalInitWorklist.empty()) {
1105 unsigned ValID = GlobalInitWorklist.back().second;
1106 if (ValID >= ValueList.size()) {
1107 // Not ready to resolve this yet, it requires something later in the file.
1108 GlobalInits.push_back(GlobalInitWorklist.back());
1110 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
1111 GlobalInitWorklist.back().first->setInitializer(C);
1113 return Error(ExpectedConstant);
1115 GlobalInitWorklist.pop_back();
1118 while (!AliasInitWorklist.empty()) {
1119 unsigned ValID = AliasInitWorklist.back().second;
1120 if (ValID >= ValueList.size()) {
1121 AliasInits.push_back(AliasInitWorklist.back());
1123 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
1124 AliasInitWorklist.back().first->setAliasee(C);
1126 return Error(ExpectedConstant);
1128 AliasInitWorklist.pop_back();
1131 while (!FunctionPrefixWorklist.empty()) {
1132 unsigned ValID = FunctionPrefixWorklist.back().second;
1133 if (ValID >= ValueList.size()) {
1134 FunctionPrefixes.push_back(FunctionPrefixWorklist.back());
1136 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
1137 FunctionPrefixWorklist.back().first->setPrefixData(C);
1139 return Error(ExpectedConstant);
1141 FunctionPrefixWorklist.pop_back();
1144 return error_code::success();
1147 static APInt ReadWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
1148 SmallVector<uint64_t, 8> Words(Vals.size());
1149 std::transform(Vals.begin(), Vals.end(), Words.begin(),
1150 BitcodeReader::decodeSignRotatedValue);
1152 return APInt(TypeBits, Words);
1155 error_code BitcodeReader::ParseConstants() {
1156 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
1157 return Error(InvalidRecord);
1159 SmallVector<uint64_t, 64> Record;
1161 // Read all the records for this value table.
1162 Type *CurTy = Type::getInt32Ty(Context);
1163 unsigned NextCstNo = ValueList.size();
1165 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1167 switch (Entry.Kind) {
1168 case BitstreamEntry::SubBlock: // Handled for us already.
1169 case BitstreamEntry::Error:
1170 return Error(MalformedBlock);
1171 case BitstreamEntry::EndBlock:
1172 if (NextCstNo != ValueList.size())
1173 return Error(InvalidConstantReference);
1175 // Once all the constants have been read, go through and resolve forward
1177 ValueList.ResolveConstantForwardRefs();
1178 return error_code::success();
1179 case BitstreamEntry::Record:
1180 // The interesting case.
1187 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
1189 default: // Default behavior: unknown constant
1190 case bitc::CST_CODE_UNDEF: // UNDEF
1191 V = UndefValue::get(CurTy);
1193 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
1195 return Error(InvalidRecord);
1196 if (Record[0] >= TypeList.size())
1197 return Error(InvalidRecord);
1198 CurTy = TypeList[Record[0]];
1199 continue; // Skip the ValueList manipulation.
1200 case bitc::CST_CODE_NULL: // NULL
1201 V = Constant::getNullValue(CurTy);
1203 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
1204 if (!CurTy->isIntegerTy() || Record.empty())
1205 return Error(InvalidRecord);
1206 V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
1208 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
1209 if (!CurTy->isIntegerTy() || Record.empty())
1210 return Error(InvalidRecord);
1212 APInt VInt = ReadWideAPInt(Record,
1213 cast<IntegerType>(CurTy)->getBitWidth());
1214 V = ConstantInt::get(Context, VInt);
1218 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
1220 return Error(InvalidRecord);
1221 if (CurTy->isHalfTy())
1222 V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf,
1223 APInt(16, (uint16_t)Record[0])));
1224 else if (CurTy->isFloatTy())
1225 V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle,
1226 APInt(32, (uint32_t)Record[0])));
1227 else if (CurTy->isDoubleTy())
1228 V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble,
1229 APInt(64, Record[0])));
1230 else if (CurTy->isX86_FP80Ty()) {
1231 // Bits are not stored the same way as a normal i80 APInt, compensate.
1232 uint64_t Rearrange[2];
1233 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
1234 Rearrange[1] = Record[0] >> 48;
1235 V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended,
1236 APInt(80, Rearrange)));
1237 } else if (CurTy->isFP128Ty())
1238 V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad,
1239 APInt(128, Record)));
1240 else if (CurTy->isPPC_FP128Ty())
1241 V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble,
1242 APInt(128, Record)));
1244 V = UndefValue::get(CurTy);
1248 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
1250 return Error(InvalidRecord);
1252 unsigned Size = Record.size();
1253 SmallVector<Constant*, 16> Elts;
1255 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
1256 for (unsigned i = 0; i != Size; ++i)
1257 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
1258 STy->getElementType(i)));
1259 V = ConstantStruct::get(STy, Elts);
1260 } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
1261 Type *EltTy = ATy->getElementType();
1262 for (unsigned i = 0; i != Size; ++i)
1263 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
1264 V = ConstantArray::get(ATy, Elts);
1265 } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
1266 Type *EltTy = VTy->getElementType();
1267 for (unsigned i = 0; i != Size; ++i)
1268 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
1269 V = ConstantVector::get(Elts);
1271 V = UndefValue::get(CurTy);
1275 case bitc::CST_CODE_STRING: // STRING: [values]
1276 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
1278 return Error(InvalidRecord);
1280 SmallString<16> Elts(Record.begin(), Record.end());
1281 V = ConstantDataArray::getString(Context, Elts,
1282 BitCode == bitc::CST_CODE_CSTRING);
1285 case bitc::CST_CODE_DATA: {// DATA: [n x value]
1287 return Error(InvalidRecord);
1289 Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
1290 unsigned Size = Record.size();
1292 if (EltTy->isIntegerTy(8)) {
1293 SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
1294 if (isa<VectorType>(CurTy))
1295 V = ConstantDataVector::get(Context, Elts);
1297 V = ConstantDataArray::get(Context, Elts);
1298 } else if (EltTy->isIntegerTy(16)) {
1299 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
1300 if (isa<VectorType>(CurTy))
1301 V = ConstantDataVector::get(Context, Elts);
1303 V = ConstantDataArray::get(Context, Elts);
1304 } else if (EltTy->isIntegerTy(32)) {
1305 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
1306 if (isa<VectorType>(CurTy))
1307 V = ConstantDataVector::get(Context, Elts);
1309 V = ConstantDataArray::get(Context, Elts);
1310 } else if (EltTy->isIntegerTy(64)) {
1311 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
1312 if (isa<VectorType>(CurTy))
1313 V = ConstantDataVector::get(Context, Elts);
1315 V = ConstantDataArray::get(Context, Elts);
1316 } else if (EltTy->isFloatTy()) {
1317 SmallVector<float, 16> Elts(Size);
1318 std::transform(Record.begin(), Record.end(), Elts.begin(), BitsToFloat);
1319 if (isa<VectorType>(CurTy))
1320 V = ConstantDataVector::get(Context, Elts);
1322 V = ConstantDataArray::get(Context, Elts);
1323 } else if (EltTy->isDoubleTy()) {
1324 SmallVector<double, 16> Elts(Size);
1325 std::transform(Record.begin(), Record.end(), Elts.begin(),
1327 if (isa<VectorType>(CurTy))
1328 V = ConstantDataVector::get(Context, Elts);
1330 V = ConstantDataArray::get(Context, Elts);
1332 return Error(InvalidTypeForValue);
1337 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
1338 if (Record.size() < 3)
1339 return Error(InvalidRecord);
1340 int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
1342 V = UndefValue::get(CurTy); // Unknown binop.
1344 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
1345 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
1347 if (Record.size() >= 4) {
1348 if (Opc == Instruction::Add ||
1349 Opc == Instruction::Sub ||
1350 Opc == Instruction::Mul ||
1351 Opc == Instruction::Shl) {
1352 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
1353 Flags |= OverflowingBinaryOperator::NoSignedWrap;
1354 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
1355 Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
1356 } else if (Opc == Instruction::SDiv ||
1357 Opc == Instruction::UDiv ||
1358 Opc == Instruction::LShr ||
1359 Opc == Instruction::AShr) {
1360 if (Record[3] & (1 << bitc::PEO_EXACT))
1361 Flags |= SDivOperator::IsExact;
1364 V = ConstantExpr::get(Opc, LHS, RHS, Flags);
1368 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
1369 if (Record.size() < 3)
1370 return Error(InvalidRecord);
1371 int Opc = GetDecodedCastOpcode(Record[0]);
1373 V = UndefValue::get(CurTy); // Unknown cast.
1375 Type *OpTy = getTypeByID(Record[1]);
1377 return Error(InvalidRecord);
1378 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
1379 V = UpgradeBitCastExpr(Opc, Op, CurTy);
1380 if (!V) V = ConstantExpr::getCast(Opc, Op, CurTy);
1384 case bitc::CST_CODE_CE_INBOUNDS_GEP:
1385 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
1386 if (Record.size() & 1)
1387 return Error(InvalidRecord);
1388 SmallVector<Constant*, 16> Elts;
1389 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
1390 Type *ElTy = getTypeByID(Record[i]);
1392 return Error(InvalidRecord);
1393 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
1395 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
1396 V = ConstantExpr::getGetElementPtr(Elts[0], Indices,
1398 bitc::CST_CODE_CE_INBOUNDS_GEP);
1401 case bitc::CST_CODE_CE_SELECT: { // CE_SELECT: [opval#, opval#, opval#]
1402 if (Record.size() < 3)
1403 return Error(InvalidRecord);
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)
1421 return Error(InvalidRecord);
1423 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1425 return Error(InvalidRecord);
1426 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1427 Constant *Op1 = ValueList.getConstantFwdRef(Record[2],
1428 Type::getInt32Ty(Context));
1429 V = ConstantExpr::getExtractElement(Op0, Op1);
1432 case bitc::CST_CODE_CE_INSERTELT: { // CE_INSERTELT: [opval, opval, opval]
1433 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
1434 if (Record.size() < 3 || OpTy == 0)
1435 return Error(InvalidRecord);
1436 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1437 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
1438 OpTy->getElementType());
1439 Constant *Op2 = ValueList.getConstantFwdRef(Record[2],
1440 Type::getInt32Ty(Context));
1441 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
1444 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
1445 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
1446 if (Record.size() < 3 || OpTy == 0)
1447 return Error(InvalidRecord);
1448 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1449 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
1450 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
1451 OpTy->getNumElements());
1452 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
1453 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
1456 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
1457 VectorType *RTy = dyn_cast<VectorType>(CurTy);
1459 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1460 if (Record.size() < 4 || RTy == 0 || OpTy == 0)
1461 return Error(InvalidRecord);
1462 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1463 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1464 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
1465 RTy->getNumElements());
1466 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
1467 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
1470 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
1471 if (Record.size() < 4)
1472 return Error(InvalidRecord);
1473 Type *OpTy = getTypeByID(Record[0]);
1475 return Error(InvalidRecord);
1476 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1477 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1479 if (OpTy->isFPOrFPVectorTy())
1480 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
1482 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
1485 // This maintains backward compatibility, pre-asm dialect keywords.
1486 // FIXME: Remove with the 4.0 release.
1487 case bitc::CST_CODE_INLINEASM_OLD: {
1488 if (Record.size() < 2)
1489 return Error(InvalidRecord);
1490 std::string AsmStr, ConstrStr;
1491 bool HasSideEffects = Record[0] & 1;
1492 bool IsAlignStack = Record[0] >> 1;
1493 unsigned AsmStrSize = Record[1];
1494 if (2+AsmStrSize >= Record.size())
1495 return Error(InvalidRecord);
1496 unsigned ConstStrSize = Record[2+AsmStrSize];
1497 if (3+AsmStrSize+ConstStrSize > Record.size())
1498 return Error(InvalidRecord);
1500 for (unsigned i = 0; i != AsmStrSize; ++i)
1501 AsmStr += (char)Record[2+i];
1502 for (unsigned i = 0; i != ConstStrSize; ++i)
1503 ConstrStr += (char)Record[3+AsmStrSize+i];
1504 PointerType *PTy = cast<PointerType>(CurTy);
1505 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
1506 AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
1509 // This version adds support for the asm dialect keywords (e.g.,
1511 case bitc::CST_CODE_INLINEASM: {
1512 if (Record.size() < 2)
1513 return Error(InvalidRecord);
1514 std::string AsmStr, ConstrStr;
1515 bool HasSideEffects = Record[0] & 1;
1516 bool IsAlignStack = (Record[0] >> 1) & 1;
1517 unsigned AsmDialect = Record[0] >> 2;
1518 unsigned AsmStrSize = Record[1];
1519 if (2+AsmStrSize >= Record.size())
1520 return Error(InvalidRecord);
1521 unsigned ConstStrSize = Record[2+AsmStrSize];
1522 if (3+AsmStrSize+ConstStrSize > Record.size())
1523 return Error(InvalidRecord);
1525 for (unsigned i = 0; i != AsmStrSize; ++i)
1526 AsmStr += (char)Record[2+i];
1527 for (unsigned i = 0; i != ConstStrSize; ++i)
1528 ConstrStr += (char)Record[3+AsmStrSize+i];
1529 PointerType *PTy = cast<PointerType>(CurTy);
1530 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
1531 AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
1532 InlineAsm::AsmDialect(AsmDialect));
1535 case bitc::CST_CODE_BLOCKADDRESS:{
1536 if (Record.size() < 3)
1537 return Error(InvalidRecord);
1538 Type *FnTy = getTypeByID(Record[0]);
1540 return Error(InvalidRecord);
1542 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
1544 return Error(InvalidRecord);
1546 // If the function is already parsed we can insert the block address right
1549 Function::iterator BBI = Fn->begin(), BBE = Fn->end();
1550 for (size_t I = 0, E = Record[2]; I != E; ++I) {
1552 return Error(InvalidID);
1555 V = BlockAddress::get(Fn, BBI);
1557 // Otherwise insert a placeholder and remember it so it can be inserted
1558 // when the function is parsed.
1559 GlobalVariable *FwdRef = new GlobalVariable(*Fn->getParent(),
1560 Type::getInt8Ty(Context),
1561 false, GlobalValue::InternalLinkage,
1563 BlockAddrFwdRefs[Fn].push_back(std::make_pair(Record[2], FwdRef));
1570 ValueList.AssignValue(V, NextCstNo);
1575 error_code BitcodeReader::ParseUseLists() {
1576 if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
1577 return Error(InvalidRecord);
1579 SmallVector<uint64_t, 64> Record;
1581 // Read all the records.
1583 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1585 switch (Entry.Kind) {
1586 case BitstreamEntry::SubBlock: // Handled for us already.
1587 case BitstreamEntry::Error:
1588 return Error(MalformedBlock);
1589 case BitstreamEntry::EndBlock:
1590 return error_code::success();
1591 case BitstreamEntry::Record:
1592 // The interesting case.
1596 // Read a use list record.
1598 switch (Stream.readRecord(Entry.ID, Record)) {
1599 default: // Default behavior: unknown type.
1601 case bitc::USELIST_CODE_ENTRY: { // USELIST_CODE_ENTRY: TBD.
1602 unsigned RecordLength = Record.size();
1603 if (RecordLength < 1)
1604 return Error(InvalidRecord);
1605 UseListRecords.push_back(Record);
1612 /// RememberAndSkipFunctionBody - When we see the block for a function body,
1613 /// remember where it is and then skip it. This lets us lazily deserialize the
1615 error_code BitcodeReader::RememberAndSkipFunctionBody() {
1616 // Get the function we are talking about.
1617 if (FunctionsWithBodies.empty())
1618 return Error(InsufficientFunctionProtos);
1620 Function *Fn = FunctionsWithBodies.back();
1621 FunctionsWithBodies.pop_back();
1623 // Save the current stream state.
1624 uint64_t CurBit = Stream.GetCurrentBitNo();
1625 DeferredFunctionInfo[Fn] = CurBit;
1627 // Skip over the function block for now.
1628 if (Stream.SkipBlock())
1629 return Error(InvalidRecord);
1630 return error_code::success();
1633 error_code BitcodeReader::GlobalCleanup() {
1634 // Patch the initializers for globals and aliases up.
1635 ResolveGlobalAndAliasInits();
1636 if (!GlobalInits.empty() || !AliasInits.empty())
1637 return Error(MalformedGlobalInitializerSet);
1639 // Look for intrinsic functions which need to be upgraded at some point
1640 for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
1643 if (UpgradeIntrinsicFunction(FI, NewFn))
1644 UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
1647 // Look for global variables which need to be renamed.
1648 for (Module::global_iterator
1649 GI = TheModule->global_begin(), GE = TheModule->global_end();
1651 UpgradeGlobalVariable(GI);
1652 // Force deallocation of memory for these vectors to favor the client that
1653 // want lazy deserialization.
1654 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
1655 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
1656 return error_code::success();
1659 error_code BitcodeReader::ParseModule(bool Resume) {
1661 Stream.JumpToBit(NextUnreadBit);
1662 else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
1663 return Error(InvalidRecord);
1665 SmallVector<uint64_t, 64> Record;
1666 std::vector<std::string> SectionTable;
1667 std::vector<std::string> GCTable;
1669 // Read all the records for this module.
1671 BitstreamEntry Entry = Stream.advance();
1673 switch (Entry.Kind) {
1674 case BitstreamEntry::Error:
1675 return Error(MalformedBlock);
1676 case BitstreamEntry::EndBlock:
1677 return GlobalCleanup();
1679 case BitstreamEntry::SubBlock:
1681 default: // Skip unknown content.
1682 if (Stream.SkipBlock())
1683 return Error(InvalidRecord);
1685 case bitc::BLOCKINFO_BLOCK_ID:
1686 if (Stream.ReadBlockInfoBlock())
1687 return Error(MalformedBlock);
1689 case bitc::PARAMATTR_BLOCK_ID:
1690 if (error_code EC = ParseAttributeBlock())
1693 case bitc::PARAMATTR_GROUP_BLOCK_ID:
1694 if (error_code EC = ParseAttributeGroupBlock())
1697 case bitc::TYPE_BLOCK_ID_NEW:
1698 if (error_code EC = ParseTypeTable())
1701 case bitc::VALUE_SYMTAB_BLOCK_ID:
1702 if (error_code EC = ParseValueSymbolTable())
1704 SeenValueSymbolTable = true;
1706 case bitc::CONSTANTS_BLOCK_ID:
1707 if (error_code EC = ParseConstants())
1709 if (error_code EC = ResolveGlobalAndAliasInits())
1712 case bitc::METADATA_BLOCK_ID:
1713 if (error_code EC = ParseMetadata())
1716 case bitc::FUNCTION_BLOCK_ID:
1717 // If this is the first function body we've seen, reverse the
1718 // FunctionsWithBodies list.
1719 if (!SeenFirstFunctionBody) {
1720 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
1721 if (error_code EC = GlobalCleanup())
1723 SeenFirstFunctionBody = true;
1726 if (error_code EC = RememberAndSkipFunctionBody())
1728 // For streaming bitcode, suspend parsing when we reach the function
1729 // bodies. Subsequent materialization calls will resume it when
1730 // necessary. For streaming, the function bodies must be at the end of
1731 // the bitcode. If the bitcode file is old, the symbol table will be
1732 // at the end instead and will not have been seen yet. In this case,
1733 // just finish the parse now.
1734 if (LazyStreamer && SeenValueSymbolTable) {
1735 NextUnreadBit = Stream.GetCurrentBitNo();
1736 return error_code::success();
1739 case bitc::USELIST_BLOCK_ID:
1740 if (error_code EC = ParseUseLists())
1746 case BitstreamEntry::Record:
1747 // The interesting case.
1753 switch (Stream.readRecord(Entry.ID, Record)) {
1754 default: break; // Default behavior, ignore unknown content.
1755 case bitc::MODULE_CODE_VERSION: { // VERSION: [version#]
1756 if (Record.size() < 1)
1757 return Error(InvalidRecord);
1758 // Only version #0 and #1 are supported so far.
1759 unsigned module_version = Record[0];
1760 switch (module_version) {
1762 return Error(InvalidValue);
1764 UseRelativeIDs = false;
1767 UseRelativeIDs = true;
1772 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
1774 if (ConvertToString(Record, 0, S))
1775 return Error(InvalidRecord);
1776 TheModule->setTargetTriple(S);
1779 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
1781 if (ConvertToString(Record, 0, S))
1782 return Error(InvalidRecord);
1783 TheModule->setDataLayout(S);
1786 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
1788 if (ConvertToString(Record, 0, S))
1789 return Error(InvalidRecord);
1790 TheModule->setModuleInlineAsm(S);
1793 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
1794 // FIXME: Remove in 4.0.
1796 if (ConvertToString(Record, 0, S))
1797 return Error(InvalidRecord);
1801 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
1803 if (ConvertToString(Record, 0, S))
1804 return Error(InvalidRecord);
1805 SectionTable.push_back(S);
1808 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
1810 if (ConvertToString(Record, 0, S))
1811 return Error(InvalidRecord);
1812 GCTable.push_back(S);
1815 // GLOBALVAR: [pointer type, isconst, initid,
1816 // linkage, alignment, section, visibility, threadlocal,
1817 // unnamed_addr, dllstorageclass]
1818 case bitc::MODULE_CODE_GLOBALVAR: {
1819 if (Record.size() < 6)
1820 return Error(InvalidRecord);
1821 Type *Ty = getTypeByID(Record[0]);
1823 return Error(InvalidRecord);
1824 if (!Ty->isPointerTy())
1825 return Error(InvalidTypeForValue);
1826 unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
1827 Ty = cast<PointerType>(Ty)->getElementType();
1829 bool isConstant = Record[1];
1830 GlobalValue::LinkageTypes Linkage = GetDecodedLinkage(Record[3]);
1831 unsigned Alignment = (1 << Record[4]) >> 1;
1832 std::string Section;
1834 if (Record[5]-1 >= SectionTable.size())
1835 return Error(InvalidID);
1836 Section = SectionTable[Record[5]-1];
1838 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
1839 if (Record.size() > 6)
1840 Visibility = GetDecodedVisibility(Record[6]);
1842 GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
1843 if (Record.size() > 7)
1844 TLM = GetDecodedThreadLocalMode(Record[7]);
1846 bool UnnamedAddr = false;
1847 if (Record.size() > 8)
1848 UnnamedAddr = Record[8];
1850 bool ExternallyInitialized = false;
1851 if (Record.size() > 9)
1852 ExternallyInitialized = Record[9];
1854 GlobalVariable *NewGV =
1855 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, 0, "", 0,
1856 TLM, AddressSpace, ExternallyInitialized);
1857 NewGV->setAlignment(Alignment);
1858 if (!Section.empty())
1859 NewGV->setSection(Section);
1860 NewGV->setVisibility(Visibility);
1861 NewGV->setUnnamedAddr(UnnamedAddr);
1863 if (Record.size() > 10)
1864 NewGV->setDLLStorageClass(GetDecodedDLLStorageClass(Record[10]));
1866 UpgradeDLLImportExportLinkage(NewGV, Record[3]);
1868 ValueList.push_back(NewGV);
1870 // Remember which value to use for the global initializer.
1871 if (unsigned InitID = Record[2])
1872 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
1875 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
1876 // alignment, section, visibility, gc, unnamed_addr,
1878 case bitc::MODULE_CODE_FUNCTION: {
1879 if (Record.size() < 8)
1880 return Error(InvalidRecord);
1881 Type *Ty = getTypeByID(Record[0]);
1883 return Error(InvalidRecord);
1884 if (!Ty->isPointerTy())
1885 return Error(InvalidTypeForValue);
1887 dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
1889 return Error(InvalidTypeForValue);
1891 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
1894 Func->setCallingConv(static_cast<CallingConv::ID>(Record[1]));
1895 bool isProto = Record[2];
1896 Func->setLinkage(GetDecodedLinkage(Record[3]));
1897 Func->setAttributes(getAttributes(Record[4]));
1899 Func->setAlignment((1 << Record[5]) >> 1);
1901 if (Record[6]-1 >= SectionTable.size())
1902 return Error(InvalidID);
1903 Func->setSection(SectionTable[Record[6]-1]);
1905 Func->setVisibility(GetDecodedVisibility(Record[7]));
1906 if (Record.size() > 8 && Record[8]) {
1907 if (Record[8]-1 > GCTable.size())
1908 return Error(InvalidID);
1909 Func->setGC(GCTable[Record[8]-1].c_str());
1911 bool UnnamedAddr = false;
1912 if (Record.size() > 9)
1913 UnnamedAddr = Record[9];
1914 Func->setUnnamedAddr(UnnamedAddr);
1915 if (Record.size() > 10 && Record[10] != 0)
1916 FunctionPrefixes.push_back(std::make_pair(Func, Record[10]-1));
1918 if (Record.size() > 11)
1919 Func->setDLLStorageClass(GetDecodedDLLStorageClass(Record[11]));
1921 UpgradeDLLImportExportLinkage(Func, Record[3]);
1923 ValueList.push_back(Func);
1925 // If this is a function with a body, remember the prototype we are
1926 // creating now, so that we can match up the body with them later.
1928 FunctionsWithBodies.push_back(Func);
1929 if (LazyStreamer) DeferredFunctionInfo[Func] = 0;
1933 // ALIAS: [alias type, aliasee val#, linkage]
1934 // ALIAS: [alias type, aliasee val#, linkage, visibility, dllstorageclass]
1935 case bitc::MODULE_CODE_ALIAS: {
1936 if (Record.size() < 3)
1937 return Error(InvalidRecord);
1938 Type *Ty = getTypeByID(Record[0]);
1940 return Error(InvalidRecord);
1941 if (!Ty->isPointerTy())
1942 return Error(InvalidTypeForValue);
1944 GlobalAlias *NewGA = new GlobalAlias(Ty, GetDecodedLinkage(Record[2]),
1946 // Old bitcode files didn't have visibility field.
1947 if (Record.size() > 3)
1948 NewGA->setVisibility(GetDecodedVisibility(Record[3]));
1949 if (Record.size() > 4)
1950 NewGA->setDLLStorageClass(GetDecodedDLLStorageClass(Record[4]));
1952 UpgradeDLLImportExportLinkage(NewGA, Record[2]);
1953 ValueList.push_back(NewGA);
1954 AliasInits.push_back(std::make_pair(NewGA, Record[1]));
1957 /// MODULE_CODE_PURGEVALS: [numvals]
1958 case bitc::MODULE_CODE_PURGEVALS:
1959 // Trim down the value list to the specified size.
1960 if (Record.size() < 1 || Record[0] > ValueList.size())
1961 return Error(InvalidRecord);
1962 ValueList.shrinkTo(Record[0]);
1969 error_code BitcodeReader::ParseBitcodeInto(Module *M) {
1972 if (error_code EC = InitStream())
1975 // Sniff for the signature.
1976 if (Stream.Read(8) != 'B' ||
1977 Stream.Read(8) != 'C' ||
1978 Stream.Read(4) != 0x0 ||
1979 Stream.Read(4) != 0xC ||
1980 Stream.Read(4) != 0xE ||
1981 Stream.Read(4) != 0xD)
1982 return Error(InvalidBitcodeSignature);
1984 // We expect a number of well-defined blocks, though we don't necessarily
1985 // need to understand them all.
1987 if (Stream.AtEndOfStream())
1988 return error_code::success();
1990 BitstreamEntry Entry =
1991 Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
1993 switch (Entry.Kind) {
1994 case BitstreamEntry::Error:
1995 return Error(MalformedBlock);
1996 case BitstreamEntry::EndBlock:
1997 return error_code::success();
1999 case BitstreamEntry::SubBlock:
2001 case bitc::BLOCKINFO_BLOCK_ID:
2002 if (Stream.ReadBlockInfoBlock())
2003 return Error(MalformedBlock);
2005 case bitc::MODULE_BLOCK_ID:
2006 // Reject multiple MODULE_BLOCK's in a single bitstream.
2008 return Error(InvalidMultipleBlocks);
2010 if (error_code EC = ParseModule(false))
2013 return error_code::success();
2016 if (Stream.SkipBlock())
2017 return Error(InvalidRecord);
2021 case BitstreamEntry::Record:
2022 // There should be no records in the top-level of blocks.
2024 // The ranlib in Xcode 4 will align archive members by appending newlines
2025 // to the end of them. If this file size is a multiple of 4 but not 8, we
2026 // have to read and ignore these final 4 bytes :-(
2027 if (Stream.getAbbrevIDWidth() == 2 && Entry.ID == 2 &&
2028 Stream.Read(6) == 2 && Stream.Read(24) == 0xa0a0a &&
2029 Stream.AtEndOfStream())
2030 return error_code::success();
2032 return Error(InvalidRecord);
2037 error_code BitcodeReader::ParseModuleTriple(std::string &Triple) {
2038 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
2039 return Error(InvalidRecord);
2041 SmallVector<uint64_t, 64> Record;
2043 // Read all the records for this module.
2045 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2047 switch (Entry.Kind) {
2048 case BitstreamEntry::SubBlock: // Handled for us already.
2049 case BitstreamEntry::Error:
2050 return Error(MalformedBlock);
2051 case BitstreamEntry::EndBlock:
2052 return error_code::success();
2053 case BitstreamEntry::Record:
2054 // The interesting case.
2059 switch (Stream.readRecord(Entry.ID, Record)) {
2060 default: break; // Default behavior, ignore unknown content.
2061 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
2063 if (ConvertToString(Record, 0, S))
2064 return Error(InvalidRecord);
2073 error_code BitcodeReader::ParseTriple(std::string &Triple) {
2074 if (error_code EC = InitStream())
2077 // Sniff for the signature.
2078 if (Stream.Read(8) != 'B' ||
2079 Stream.Read(8) != 'C' ||
2080 Stream.Read(4) != 0x0 ||
2081 Stream.Read(4) != 0xC ||
2082 Stream.Read(4) != 0xE ||
2083 Stream.Read(4) != 0xD)
2084 return Error(InvalidBitcodeSignature);
2086 // We expect a number of well-defined blocks, though we don't necessarily
2087 // need to understand them all.
2089 BitstreamEntry Entry = Stream.advance();
2091 switch (Entry.Kind) {
2092 case BitstreamEntry::Error:
2093 return Error(MalformedBlock);
2094 case BitstreamEntry::EndBlock:
2095 return error_code::success();
2097 case BitstreamEntry::SubBlock:
2098 if (Entry.ID == bitc::MODULE_BLOCK_ID)
2099 return ParseModuleTriple(Triple);
2101 // Ignore other sub-blocks.
2102 if (Stream.SkipBlock())
2103 return Error(MalformedBlock);
2106 case BitstreamEntry::Record:
2107 Stream.skipRecord(Entry.ID);
2113 /// ParseMetadataAttachment - Parse metadata attachments.
2114 error_code BitcodeReader::ParseMetadataAttachment() {
2115 if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
2116 return Error(InvalidRecord);
2118 SmallVector<uint64_t, 64> Record;
2120 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2122 switch (Entry.Kind) {
2123 case BitstreamEntry::SubBlock: // Handled for us already.
2124 case BitstreamEntry::Error:
2125 return Error(MalformedBlock);
2126 case BitstreamEntry::EndBlock:
2127 return error_code::success();
2128 case BitstreamEntry::Record:
2129 // The interesting case.
2133 // Read a metadata attachment record.
2135 switch (Stream.readRecord(Entry.ID, Record)) {
2136 default: // Default behavior: ignore.
2138 case bitc::METADATA_ATTACHMENT: {
2139 unsigned RecordLength = Record.size();
2140 if (Record.empty() || (RecordLength - 1) % 2 == 1)
2141 return Error(InvalidRecord);
2142 Instruction *Inst = InstructionList[Record[0]];
2143 for (unsigned i = 1; i != RecordLength; i = i+2) {
2144 unsigned Kind = Record[i];
2145 DenseMap<unsigned, unsigned>::iterator I =
2146 MDKindMap.find(Kind);
2147 if (I == MDKindMap.end())
2148 return Error(InvalidID);
2149 Value *Node = MDValueList.getValueFwdRef(Record[i+1]);
2150 Inst->setMetadata(I->second, cast<MDNode>(Node));
2151 if (I->second == LLVMContext::MD_tbaa)
2152 InstsWithTBAATag.push_back(Inst);
2160 /// ParseFunctionBody - Lazily parse the specified function body block.
2161 error_code BitcodeReader::ParseFunctionBody(Function *F) {
2162 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
2163 return Error(InvalidRecord);
2165 InstructionList.clear();
2166 unsigned ModuleValueListSize = ValueList.size();
2167 unsigned ModuleMDValueListSize = MDValueList.size();
2169 // Add all the function arguments to the value table.
2170 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
2171 ValueList.push_back(I);
2173 unsigned NextValueNo = ValueList.size();
2174 BasicBlock *CurBB = 0;
2175 unsigned CurBBNo = 0;
2179 // Read all the records.
2180 SmallVector<uint64_t, 64> Record;
2182 BitstreamEntry Entry = Stream.advance();
2184 switch (Entry.Kind) {
2185 case BitstreamEntry::Error:
2186 return Error(MalformedBlock);
2187 case BitstreamEntry::EndBlock:
2188 goto OutOfRecordLoop;
2190 case BitstreamEntry::SubBlock:
2192 default: // Skip unknown content.
2193 if (Stream.SkipBlock())
2194 return Error(InvalidRecord);
2196 case bitc::CONSTANTS_BLOCK_ID:
2197 if (error_code EC = ParseConstants())
2199 NextValueNo = ValueList.size();
2201 case bitc::VALUE_SYMTAB_BLOCK_ID:
2202 if (error_code EC = ParseValueSymbolTable())
2205 case bitc::METADATA_ATTACHMENT_ID:
2206 if (error_code EC = ParseMetadataAttachment())
2209 case bitc::METADATA_BLOCK_ID:
2210 if (error_code EC = ParseMetadata())
2216 case BitstreamEntry::Record:
2217 // The interesting case.
2224 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
2226 default: // Default behavior: reject
2227 return Error(InvalidValue);
2228 case bitc::FUNC_CODE_DECLAREBLOCKS: // DECLAREBLOCKS: [nblocks]
2229 if (Record.size() < 1 || Record[0] == 0)
2230 return Error(InvalidRecord);
2231 // Create all the basic blocks for the function.
2232 FunctionBBs.resize(Record[0]);
2233 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
2234 FunctionBBs[i] = BasicBlock::Create(Context, "", F);
2235 CurBB = FunctionBBs[0];
2238 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN
2239 // This record indicates that the last instruction is at the same
2240 // location as the previous instruction with a location.
2243 // Get the last instruction emitted.
2244 if (CurBB && !CurBB->empty())
2246 else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
2247 !FunctionBBs[CurBBNo-1]->empty())
2248 I = &FunctionBBs[CurBBNo-1]->back();
2251 return Error(InvalidRecord);
2252 I->setDebugLoc(LastLoc);
2256 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia]
2257 I = 0; // Get the last instruction emitted.
2258 if (CurBB && !CurBB->empty())
2260 else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
2261 !FunctionBBs[CurBBNo-1]->empty())
2262 I = &FunctionBBs[CurBBNo-1]->back();
2263 if (I == 0 || Record.size() < 4)
2264 return Error(InvalidRecord);
2266 unsigned Line = Record[0], Col = Record[1];
2267 unsigned ScopeID = Record[2], IAID = Record[3];
2269 MDNode *Scope = 0, *IA = 0;
2270 if (ScopeID) Scope = cast<MDNode>(MDValueList.getValueFwdRef(ScopeID-1));
2271 if (IAID) IA = cast<MDNode>(MDValueList.getValueFwdRef(IAID-1));
2272 LastLoc = DebugLoc::get(Line, Col, Scope, IA);
2273 I->setDebugLoc(LastLoc);
2278 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
2281 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
2282 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
2283 OpNum+1 > Record.size())
2284 return Error(InvalidRecord);
2286 int Opc = GetDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
2288 return Error(InvalidRecord);
2289 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
2290 InstructionList.push_back(I);
2291 if (OpNum < Record.size()) {
2292 if (Opc == Instruction::Add ||
2293 Opc == Instruction::Sub ||
2294 Opc == Instruction::Mul ||
2295 Opc == Instruction::Shl) {
2296 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
2297 cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
2298 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
2299 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
2300 } else if (Opc == Instruction::SDiv ||
2301 Opc == Instruction::UDiv ||
2302 Opc == Instruction::LShr ||
2303 Opc == Instruction::AShr) {
2304 if (Record[OpNum] & (1 << bitc::PEO_EXACT))
2305 cast<BinaryOperator>(I)->setIsExact(true);
2306 } else if (isa<FPMathOperator>(I)) {
2308 if (0 != (Record[OpNum] & FastMathFlags::UnsafeAlgebra))
2309 FMF.setUnsafeAlgebra();
2310 if (0 != (Record[OpNum] & FastMathFlags::NoNaNs))
2312 if (0 != (Record[OpNum] & FastMathFlags::NoInfs))
2314 if (0 != (Record[OpNum] & FastMathFlags::NoSignedZeros))
2315 FMF.setNoSignedZeros();
2316 if (0 != (Record[OpNum] & FastMathFlags::AllowReciprocal))
2317 FMF.setAllowReciprocal();
2319 I->setFastMathFlags(FMF);
2325 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
2328 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2329 OpNum+2 != Record.size())
2330 return Error(InvalidRecord);
2332 Type *ResTy = getTypeByID(Record[OpNum]);
2333 int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
2334 if (Opc == -1 || ResTy == 0)
2335 return Error(InvalidRecord);
2336 Instruction *Temp = 0;
2337 if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) {
2339 InstructionList.push_back(Temp);
2340 CurBB->getInstList().push_back(Temp);
2343 I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
2345 InstructionList.push_back(I);
2348 case bitc::FUNC_CODE_INST_INBOUNDS_GEP:
2349 case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands]
2352 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
2353 return Error(InvalidRecord);
2355 SmallVector<Value*, 16> GEPIdx;
2356 while (OpNum != Record.size()) {
2358 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2359 return Error(InvalidRecord);
2360 GEPIdx.push_back(Op);
2363 I = GetElementPtrInst::Create(BasePtr, GEPIdx);
2364 InstructionList.push_back(I);
2365 if (BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP)
2366 cast<GetElementPtrInst>(I)->setIsInBounds(true);
2370 case bitc::FUNC_CODE_INST_EXTRACTVAL: {
2371 // EXTRACTVAL: [opty, opval, n x indices]
2374 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2375 return Error(InvalidRecord);
2377 SmallVector<unsigned, 4> EXTRACTVALIdx;
2378 for (unsigned RecSize = Record.size();
2379 OpNum != RecSize; ++OpNum) {
2380 uint64_t Index = Record[OpNum];
2381 if ((unsigned)Index != Index)
2382 return Error(InvalidValue);
2383 EXTRACTVALIdx.push_back((unsigned)Index);
2386 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
2387 InstructionList.push_back(I);
2391 case bitc::FUNC_CODE_INST_INSERTVAL: {
2392 // INSERTVAL: [opty, opval, opty, opval, n x indices]
2395 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2396 return Error(InvalidRecord);
2398 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
2399 return Error(InvalidRecord);
2401 SmallVector<unsigned, 4> INSERTVALIdx;
2402 for (unsigned RecSize = Record.size();
2403 OpNum != RecSize; ++OpNum) {
2404 uint64_t Index = Record[OpNum];
2405 if ((unsigned)Index != Index)
2406 return Error(InvalidValue);
2407 INSERTVALIdx.push_back((unsigned)Index);
2410 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
2411 InstructionList.push_back(I);
2415 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
2416 // obsolete form of select
2417 // handles select i1 ... in old bitcode
2419 Value *TrueVal, *FalseVal, *Cond;
2420 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
2421 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
2422 popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond))
2423 return Error(InvalidRecord);
2425 I = SelectInst::Create(Cond, TrueVal, FalseVal);
2426 InstructionList.push_back(I);
2430 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
2431 // new form of select
2432 // handles select i1 or select [N x i1]
2434 Value *TrueVal, *FalseVal, *Cond;
2435 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
2436 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
2437 getValueTypePair(Record, OpNum, NextValueNo, Cond))
2438 return Error(InvalidRecord);
2440 // select condition can be either i1 or [N x i1]
2441 if (VectorType* vector_type =
2442 dyn_cast<VectorType>(Cond->getType())) {
2444 if (vector_type->getElementType() != Type::getInt1Ty(Context))
2445 return Error(InvalidTypeForValue);
2448 if (Cond->getType() != Type::getInt1Ty(Context))
2449 return Error(InvalidTypeForValue);
2452 I = SelectInst::Create(Cond, TrueVal, FalseVal);
2453 InstructionList.push_back(I);
2457 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
2460 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
2461 popValue(Record, OpNum, NextValueNo, Type::getInt32Ty(Context), Idx))
2462 return Error(InvalidRecord);
2463 I = ExtractElementInst::Create(Vec, Idx);
2464 InstructionList.push_back(I);
2468 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
2470 Value *Vec, *Elt, *Idx;
2471 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
2472 popValue(Record, OpNum, NextValueNo,
2473 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
2474 popValue(Record, OpNum, NextValueNo, Type::getInt32Ty(Context), Idx))
2475 return Error(InvalidRecord);
2476 I = InsertElementInst::Create(Vec, Elt, Idx);
2477 InstructionList.push_back(I);
2481 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
2483 Value *Vec1, *Vec2, *Mask;
2484 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
2485 popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2))
2486 return Error(InvalidRecord);
2488 if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
2489 return Error(InvalidRecord);
2490 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
2491 InstructionList.push_back(I);
2495 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
2496 // Old form of ICmp/FCmp returning bool
2497 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
2498 // both legal on vectors but had different behaviour.
2499 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
2500 // FCmp/ICmp returning bool or vector of bool
2504 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
2505 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
2506 OpNum+1 != Record.size())
2507 return Error(InvalidRecord);
2509 if (LHS->getType()->isFPOrFPVectorTy())
2510 I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
2512 I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
2513 InstructionList.push_back(I);
2517 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
2519 unsigned Size = Record.size();
2521 I = ReturnInst::Create(Context);
2522 InstructionList.push_back(I);
2528 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2529 return Error(InvalidRecord);
2530 if (OpNum != Record.size())
2531 return Error(InvalidRecord);
2533 I = ReturnInst::Create(Context, Op);
2534 InstructionList.push_back(I);
2537 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
2538 if (Record.size() != 1 && Record.size() != 3)
2539 return Error(InvalidRecord);
2540 BasicBlock *TrueDest = getBasicBlock(Record[0]);
2542 return Error(InvalidRecord);
2544 if (Record.size() == 1) {
2545 I = BranchInst::Create(TrueDest);
2546 InstructionList.push_back(I);
2549 BasicBlock *FalseDest = getBasicBlock(Record[1]);
2550 Value *Cond = getValue(Record, 2, NextValueNo,
2551 Type::getInt1Ty(Context));
2552 if (FalseDest == 0 || Cond == 0)
2553 return Error(InvalidRecord);
2554 I = BranchInst::Create(TrueDest, FalseDest, Cond);
2555 InstructionList.push_back(I);
2559 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
2561 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
2562 // "New" SwitchInst format with case ranges. The changes to write this
2563 // format were reverted but we still recognize bitcode that uses it.
2564 // Hopefully someday we will have support for case ranges and can use
2565 // this format again.
2567 Type *OpTy = getTypeByID(Record[1]);
2568 unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
2570 Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
2571 BasicBlock *Default = getBasicBlock(Record[3]);
2572 if (OpTy == 0 || Cond == 0 || Default == 0)
2573 return Error(InvalidRecord);
2575 unsigned NumCases = Record[4];
2577 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
2578 InstructionList.push_back(SI);
2580 unsigned CurIdx = 5;
2581 for (unsigned i = 0; i != NumCases; ++i) {
2582 SmallVector<ConstantInt*, 1> CaseVals;
2583 unsigned NumItems = Record[CurIdx++];
2584 for (unsigned ci = 0; ci != NumItems; ++ci) {
2585 bool isSingleNumber = Record[CurIdx++];
2588 unsigned ActiveWords = 1;
2589 if (ValueBitWidth > 64)
2590 ActiveWords = Record[CurIdx++];
2591 Low = ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
2593 CurIdx += ActiveWords;
2595 if (!isSingleNumber) {
2597 if (ValueBitWidth > 64)
2598 ActiveWords = Record[CurIdx++];
2600 ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
2602 CurIdx += ActiveWords;
2604 // FIXME: It is not clear whether values in the range should be
2605 // compared as signed or unsigned values. The partially
2606 // implemented changes that used this format in the past used
2607 // unsigned comparisons.
2608 for ( ; Low.ule(High); ++Low)
2609 CaseVals.push_back(ConstantInt::get(Context, Low));
2611 CaseVals.push_back(ConstantInt::get(Context, Low));
2613 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
2614 for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(),
2615 cve = CaseVals.end(); cvi != cve; ++cvi)
2616 SI->addCase(*cvi, DestBB);
2622 // Old SwitchInst format without case ranges.
2624 if (Record.size() < 3 || (Record.size() & 1) == 0)
2625 return Error(InvalidRecord);
2626 Type *OpTy = getTypeByID(Record[0]);
2627 Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
2628 BasicBlock *Default = getBasicBlock(Record[2]);
2629 if (OpTy == 0 || Cond == 0 || Default == 0)
2630 return Error(InvalidRecord);
2631 unsigned NumCases = (Record.size()-3)/2;
2632 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
2633 InstructionList.push_back(SI);
2634 for (unsigned i = 0, e = NumCases; i != e; ++i) {
2635 ConstantInt *CaseVal =
2636 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
2637 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
2638 if (CaseVal == 0 || DestBB == 0) {
2640 return Error(InvalidRecord);
2642 SI->addCase(CaseVal, DestBB);
2647 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
2648 if (Record.size() < 2)
2649 return Error(InvalidRecord);
2650 Type *OpTy = getTypeByID(Record[0]);
2651 Value *Address = getValue(Record, 1, NextValueNo, OpTy);
2652 if (OpTy == 0 || Address == 0)
2653 return Error(InvalidRecord);
2654 unsigned NumDests = Record.size()-2;
2655 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
2656 InstructionList.push_back(IBI);
2657 for (unsigned i = 0, e = NumDests; i != e; ++i) {
2658 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
2659 IBI->addDestination(DestBB);
2662 return Error(InvalidRecord);
2669 case bitc::FUNC_CODE_INST_INVOKE: {
2670 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
2671 if (Record.size() < 4)
2672 return Error(InvalidRecord);
2673 AttributeSet PAL = getAttributes(Record[0]);
2674 unsigned CCInfo = Record[1];
2675 BasicBlock *NormalBB = getBasicBlock(Record[2]);
2676 BasicBlock *UnwindBB = getBasicBlock(Record[3]);
2680 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
2681 return Error(InvalidRecord);
2683 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
2684 FunctionType *FTy = !CalleeTy ? 0 :
2685 dyn_cast<FunctionType>(CalleeTy->getElementType());
2687 // Check that the right number of fixed parameters are here.
2688 if (FTy == 0 || NormalBB == 0 || UnwindBB == 0 ||
2689 Record.size() < OpNum+FTy->getNumParams())
2690 return Error(InvalidRecord);
2692 SmallVector<Value*, 16> Ops;
2693 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
2694 Ops.push_back(getValue(Record, OpNum, NextValueNo,
2695 FTy->getParamType(i)));
2696 if (Ops.back() == 0)
2697 return Error(InvalidRecord);
2700 if (!FTy->isVarArg()) {
2701 if (Record.size() != OpNum)
2702 return Error(InvalidRecord);
2704 // Read type/value pairs for varargs params.
2705 while (OpNum != Record.size()) {
2707 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2708 return Error(InvalidRecord);
2713 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops);
2714 InstructionList.push_back(I);
2715 cast<InvokeInst>(I)->setCallingConv(
2716 static_cast<CallingConv::ID>(CCInfo));
2717 cast<InvokeInst>(I)->setAttributes(PAL);
2720 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
2723 if (getValueTypePair(Record, Idx, NextValueNo, Val))
2724 return Error(InvalidRecord);
2725 I = ResumeInst::Create(Val);
2726 InstructionList.push_back(I);
2729 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
2730 I = new UnreachableInst(Context);
2731 InstructionList.push_back(I);
2733 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
2734 if (Record.size() < 1 || ((Record.size()-1)&1))
2735 return Error(InvalidRecord);
2736 Type *Ty = getTypeByID(Record[0]);
2738 return Error(InvalidRecord);
2740 PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
2741 InstructionList.push_back(PN);
2743 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
2745 // With the new function encoding, it is possible that operands have
2746 // negative IDs (for forward references). Use a signed VBR
2747 // representation to keep the encoding small.
2749 V = getValueSigned(Record, 1+i, NextValueNo, Ty);
2751 V = getValue(Record, 1+i, NextValueNo, Ty);
2752 BasicBlock *BB = getBasicBlock(Record[2+i]);
2754 return Error(InvalidRecord);
2755 PN->addIncoming(V, BB);
2761 case bitc::FUNC_CODE_INST_LANDINGPAD: {
2762 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
2764 if (Record.size() < 4)
2765 return Error(InvalidRecord);
2766 Type *Ty = getTypeByID(Record[Idx++]);
2768 return Error(InvalidRecord);
2770 if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
2771 return Error(InvalidRecord);
2773 bool IsCleanup = !!Record[Idx++];
2774 unsigned NumClauses = Record[Idx++];
2775 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, NumClauses);
2776 LP->setCleanup(IsCleanup);
2777 for (unsigned J = 0; J != NumClauses; ++J) {
2778 LandingPadInst::ClauseType CT =
2779 LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
2782 if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
2784 return Error(InvalidRecord);
2787 assert((CT != LandingPadInst::Catch ||
2788 !isa<ArrayType>(Val->getType())) &&
2789 "Catch clause has a invalid type!");
2790 assert((CT != LandingPadInst::Filter ||
2791 isa<ArrayType>(Val->getType())) &&
2792 "Filter clause has invalid type!");
2797 InstructionList.push_back(I);
2801 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
2802 if (Record.size() != 4)
2803 return Error(InvalidRecord);
2805 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
2806 Type *OpTy = getTypeByID(Record[1]);
2807 Value *Size = getFnValueByID(Record[2], OpTy);
2808 unsigned Align = Record[3];
2810 return Error(InvalidRecord);
2811 I = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
2812 InstructionList.push_back(I);
2815 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
2818 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2819 OpNum+2 != Record.size())
2820 return Error(InvalidRecord);
2822 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1);
2823 InstructionList.push_back(I);
2826 case bitc::FUNC_CODE_INST_LOADATOMIC: {
2827 // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
2830 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2831 OpNum+4 != Record.size())
2832 return Error(InvalidRecord);
2835 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
2836 if (Ordering == NotAtomic || Ordering == Release ||
2837 Ordering == AcquireRelease)
2838 return Error(InvalidRecord);
2839 if (Ordering != NotAtomic && Record[OpNum] == 0)
2840 return Error(InvalidRecord);
2841 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2843 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1,
2844 Ordering, SynchScope);
2845 InstructionList.push_back(I);
2848 case bitc::FUNC_CODE_INST_STORE: { // STORE2:[ptrty, ptr, val, align, vol]
2851 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2852 popValue(Record, OpNum, NextValueNo,
2853 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2854 OpNum+2 != Record.size())
2855 return Error(InvalidRecord);
2857 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
2858 InstructionList.push_back(I);
2861 case bitc::FUNC_CODE_INST_STOREATOMIC: {
2862 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
2865 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2866 popValue(Record, OpNum, NextValueNo,
2867 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2868 OpNum+4 != Record.size())
2869 return Error(InvalidRecord);
2871 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
2872 if (Ordering == NotAtomic || Ordering == Acquire ||
2873 Ordering == AcquireRelease)
2874 return Error(InvalidRecord);
2875 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2876 if (Ordering != NotAtomic && Record[OpNum] == 0)
2877 return Error(InvalidRecord);
2879 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1,
2880 Ordering, SynchScope);
2881 InstructionList.push_back(I);
2884 case bitc::FUNC_CODE_INST_CMPXCHG: {
2885 // CMPXCHG:[ptrty, ptr, cmp, new, vol, ordering, synchscope]
2887 Value *Ptr, *Cmp, *New;
2888 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2889 popValue(Record, OpNum, NextValueNo,
2890 cast<PointerType>(Ptr->getType())->getElementType(), Cmp) ||
2891 popValue(Record, OpNum, NextValueNo,
2892 cast<PointerType>(Ptr->getType())->getElementType(), New) ||
2893 OpNum+3 != Record.size())
2894 return Error(InvalidRecord);
2895 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+1]);
2896 if (Ordering == NotAtomic || Ordering == Unordered)
2897 return Error(InvalidRecord);
2898 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+2]);
2899 I = new AtomicCmpXchgInst(Ptr, Cmp, New, Ordering, SynchScope);
2900 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
2901 InstructionList.push_back(I);
2904 case bitc::FUNC_CODE_INST_ATOMICRMW: {
2905 // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
2908 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2909 popValue(Record, OpNum, NextValueNo,
2910 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2911 OpNum+4 != Record.size())
2912 return Error(InvalidRecord);
2913 AtomicRMWInst::BinOp Operation = GetDecodedRMWOperation(Record[OpNum]);
2914 if (Operation < AtomicRMWInst::FIRST_BINOP ||
2915 Operation > AtomicRMWInst::LAST_BINOP)
2916 return Error(InvalidRecord);
2917 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
2918 if (Ordering == NotAtomic || Ordering == Unordered)
2919 return Error(InvalidRecord);
2920 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2921 I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
2922 cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
2923 InstructionList.push_back(I);
2926 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
2927 if (2 != Record.size())
2928 return Error(InvalidRecord);
2929 AtomicOrdering Ordering = GetDecodedOrdering(Record[0]);
2930 if (Ordering == NotAtomic || Ordering == Unordered ||
2931 Ordering == Monotonic)
2932 return Error(InvalidRecord);
2933 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[1]);
2934 I = new FenceInst(Context, Ordering, SynchScope);
2935 InstructionList.push_back(I);
2938 case bitc::FUNC_CODE_INST_CALL: {
2939 // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
2940 if (Record.size() < 3)
2941 return Error(InvalidRecord);
2943 AttributeSet PAL = getAttributes(Record[0]);
2944 unsigned CCInfo = Record[1];
2948 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
2949 return Error(InvalidRecord);
2951 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
2952 FunctionType *FTy = 0;
2953 if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
2954 if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
2955 return Error(InvalidRecord);
2957 SmallVector<Value*, 16> Args;
2958 // Read the fixed params.
2959 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
2960 if (FTy->getParamType(i)->isLabelTy())
2961 Args.push_back(getBasicBlock(Record[OpNum]));
2963 Args.push_back(getValue(Record, OpNum, NextValueNo,
2964 FTy->getParamType(i)));
2965 if (Args.back() == 0)
2966 return Error(InvalidRecord);
2969 // Read type/value pairs for varargs params.
2970 if (!FTy->isVarArg()) {
2971 if (OpNum != Record.size())
2972 return Error(InvalidRecord);
2974 while (OpNum != Record.size()) {
2976 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2977 return Error(InvalidRecord);
2982 I = CallInst::Create(Callee, Args);
2983 InstructionList.push_back(I);
2984 cast<CallInst>(I)->setCallingConv(
2985 static_cast<CallingConv::ID>(CCInfo>>1));
2986 cast<CallInst>(I)->setTailCall(CCInfo & 1);
2987 cast<CallInst>(I)->setAttributes(PAL);
2990 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
2991 if (Record.size() < 3)
2992 return Error(InvalidRecord);
2993 Type *OpTy = getTypeByID(Record[0]);
2994 Value *Op = getValue(Record, 1, NextValueNo, OpTy);
2995 Type *ResTy = getTypeByID(Record[2]);
2996 if (!OpTy || !Op || !ResTy)
2997 return Error(InvalidRecord);
2998 I = new VAArgInst(Op, ResTy);
2999 InstructionList.push_back(I);
3004 // Add instruction to end of current BB. If there is no current BB, reject
3008 return Error(InvalidInstructionWithNoBB);
3010 CurBB->getInstList().push_back(I);
3012 // If this was a terminator instruction, move to the next block.
3013 if (isa<TerminatorInst>(I)) {
3015 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : 0;
3018 // Non-void values get registered in the value table for future use.
3019 if (I && !I->getType()->isVoidTy())
3020 ValueList.AssignValue(I, NextValueNo++);
3025 // Check the function list for unresolved values.
3026 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
3027 if (A->getParent() == 0) {
3028 // We found at least one unresolved value. Nuke them all to avoid leaks.
3029 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
3030 if ((A = dyn_cast<Argument>(ValueList[i])) && A->getParent() == 0) {
3031 A->replaceAllUsesWith(UndefValue::get(A->getType()));
3035 return Error(NeverResolvedValueFoundInFunction);
3039 // FIXME: Check for unresolved forward-declared metadata references
3040 // and clean up leaks.
3042 // See if anything took the address of blocks in this function. If so,
3043 // resolve them now.
3044 DenseMap<Function*, std::vector<BlockAddrRefTy> >::iterator BAFRI =
3045 BlockAddrFwdRefs.find(F);
3046 if (BAFRI != BlockAddrFwdRefs.end()) {
3047 std::vector<BlockAddrRefTy> &RefList = BAFRI->second;
3048 for (unsigned i = 0, e = RefList.size(); i != e; ++i) {
3049 unsigned BlockIdx = RefList[i].first;
3050 if (BlockIdx >= FunctionBBs.size())
3051 return Error(InvalidID);
3053 GlobalVariable *FwdRef = RefList[i].second;
3054 FwdRef->replaceAllUsesWith(BlockAddress::get(F, FunctionBBs[BlockIdx]));
3055 FwdRef->eraseFromParent();
3058 BlockAddrFwdRefs.erase(BAFRI);
3061 // Trim the value list down to the size it was before we parsed this function.
3062 ValueList.shrinkTo(ModuleValueListSize);
3063 MDValueList.shrinkTo(ModuleMDValueListSize);
3064 std::vector<BasicBlock*>().swap(FunctionBBs);
3065 return error_code::success();
3068 /// Find the function body in the bitcode stream
3069 error_code BitcodeReader::FindFunctionInStream(Function *F,
3070 DenseMap<Function*, uint64_t>::iterator DeferredFunctionInfoIterator) {
3071 while (DeferredFunctionInfoIterator->second == 0) {
3072 if (Stream.AtEndOfStream())
3073 return Error(CouldNotFindFunctionInStream);
3074 // ParseModule will parse the next body in the stream and set its
3075 // position in the DeferredFunctionInfo map.
3076 if (error_code EC = ParseModule(true))
3079 return error_code::success();
3082 //===----------------------------------------------------------------------===//
3083 // GVMaterializer implementation
3084 //===----------------------------------------------------------------------===//
3087 bool BitcodeReader::isMaterializable(const GlobalValue *GV) const {
3088 if (const Function *F = dyn_cast<Function>(GV)) {
3089 return F->isDeclaration() &&
3090 DeferredFunctionInfo.count(const_cast<Function*>(F));
3095 error_code BitcodeReader::Materialize(GlobalValue *GV) {
3096 Function *F = dyn_cast<Function>(GV);
3097 // If it's not a function or is already material, ignore the request.
3098 if (!F || !F->isMaterializable())
3099 return error_code::success();
3101 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
3102 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
3103 // If its position is recorded as 0, its body is somewhere in the stream
3104 // but we haven't seen it yet.
3105 if (DFII->second == 0 && LazyStreamer)
3106 if (error_code EC = FindFunctionInStream(F, DFII))
3109 // Move the bit stream to the saved position of the deferred function body.
3110 Stream.JumpToBit(DFII->second);
3112 if (error_code EC = ParseFunctionBody(F))
3115 // Upgrade any old intrinsic calls in the function.
3116 for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
3117 E = UpgradedIntrinsics.end(); I != E; ++I) {
3118 if (I->first != I->second) {
3119 for (Value::use_iterator UI = I->first->use_begin(),
3120 UE = I->first->use_end(); UI != UE; ) {
3121 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
3122 UpgradeIntrinsicCall(CI, I->second);
3127 return error_code::success();
3130 bool BitcodeReader::isDematerializable(const GlobalValue *GV) const {
3131 const Function *F = dyn_cast<Function>(GV);
3132 if (!F || F->isDeclaration())
3134 return DeferredFunctionInfo.count(const_cast<Function*>(F));
3137 void BitcodeReader::Dematerialize(GlobalValue *GV) {
3138 Function *F = dyn_cast<Function>(GV);
3139 // If this function isn't dematerializable, this is a noop.
3140 if (!F || !isDematerializable(F))
3143 assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
3145 // Just forget the function body, we can remat it later.
3150 error_code BitcodeReader::MaterializeModule(Module *M) {
3151 assert(M == TheModule &&
3152 "Can only Materialize the Module this BitcodeReader is attached to.");
3153 // Iterate over the module, deserializing any functions that are still on
3155 for (Module::iterator F = TheModule->begin(), E = TheModule->end();
3157 if (F->isMaterializable()) {
3158 if (error_code EC = Materialize(F))
3162 // At this point, if there are any function bodies, the current bit is
3163 // pointing to the END_BLOCK record after them. Now make sure the rest
3164 // of the bits in the module have been read.
3168 // Upgrade any intrinsic calls that slipped through (should not happen!) and
3169 // delete the old functions to clean up. We can't do this unless the entire
3170 // module is materialized because there could always be another function body
3171 // with calls to the old function.
3172 for (std::vector<std::pair<Function*, Function*> >::iterator I =
3173 UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
3174 if (I->first != I->second) {
3175 for (Value::use_iterator UI = I->first->use_begin(),
3176 UE = I->first->use_end(); UI != UE; ) {
3177 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
3178 UpgradeIntrinsicCall(CI, I->second);
3180 if (!I->first->use_empty())
3181 I->first->replaceAllUsesWith(I->second);
3182 I->first->eraseFromParent();
3185 std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
3187 for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
3188 UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
3190 UpgradeDebugInfo(*M);
3191 return error_code::success();
3194 error_code BitcodeReader::InitStream() {
3196 return InitLazyStream();
3197 return InitStreamFromBuffer();
3200 error_code BitcodeReader::InitStreamFromBuffer() {
3201 const unsigned char *BufPtr = (const unsigned char*)Buffer->getBufferStart();
3202 const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
3204 if (Buffer->getBufferSize() & 3) {
3205 if (!isRawBitcode(BufPtr, BufEnd) && !isBitcodeWrapper(BufPtr, BufEnd))
3206 return Error(InvalidBitcodeSignature);
3208 return Error(BitcodeStreamInvalidSize);
3211 // If we have a wrapper header, parse it and ignore the non-bc file contents.
3212 // The magic number is 0x0B17C0DE stored in little endian.
3213 if (isBitcodeWrapper(BufPtr, BufEnd))
3214 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
3215 return Error(InvalidBitcodeWrapperHeader);
3217 StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
3218 Stream.init(*StreamFile);
3220 return error_code::success();
3223 error_code BitcodeReader::InitLazyStream() {
3224 // Check and strip off the bitcode wrapper; BitstreamReader expects never to
3226 StreamingMemoryObject *Bytes = new StreamingMemoryObject(LazyStreamer);
3227 StreamFile.reset(new BitstreamReader(Bytes));
3228 Stream.init(*StreamFile);
3230 unsigned char buf[16];
3231 if (Bytes->readBytes(0, 16, buf) == -1)
3232 return Error(BitcodeStreamInvalidSize);
3234 if (!isBitcode(buf, buf + 16))
3235 return Error(InvalidBitcodeSignature);
3237 if (isBitcodeWrapper(buf, buf + 4)) {
3238 const unsigned char *bitcodeStart = buf;
3239 const unsigned char *bitcodeEnd = buf + 16;
3240 SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
3241 Bytes->dropLeadingBytes(bitcodeStart - buf);
3242 Bytes->setKnownObjectSize(bitcodeEnd - bitcodeStart);
3244 return error_code::success();
3248 class BitcodeErrorCategoryType : public _do_message {
3249 const char *name() const override {
3250 return "llvm.bitcode";
3252 std::string message(int IE) const override {
3253 BitcodeReader::ErrorType E = static_cast<BitcodeReader::ErrorType>(IE);
3255 case BitcodeReader::BitcodeStreamInvalidSize:
3256 return "Bitcode stream length should be >= 16 bytes and a multiple of 4";
3257 case BitcodeReader::ConflictingMETADATA_KINDRecords:
3258 return "Conflicting METADATA_KIND records";
3259 case BitcodeReader::CouldNotFindFunctionInStream:
3260 return "Could not find function in stream";
3261 case BitcodeReader::ExpectedConstant:
3262 return "Expected a constant";
3263 case BitcodeReader::InsufficientFunctionProtos:
3264 return "Insufficient function protos";
3265 case BitcodeReader::InvalidBitcodeSignature:
3266 return "Invalid bitcode signature";
3267 case BitcodeReader::InvalidBitcodeWrapperHeader:
3268 return "Invalid bitcode wrapper header";
3269 case BitcodeReader::InvalidConstantReference:
3270 return "Invalid ronstant reference";
3271 case BitcodeReader::InvalidID:
3272 return "Invalid ID";
3273 case BitcodeReader::InvalidInstructionWithNoBB:
3274 return "Invalid instruction with no BB";
3275 case BitcodeReader::InvalidRecord:
3276 return "Invalid record";
3277 case BitcodeReader::InvalidTypeForValue:
3278 return "Invalid type for value";
3279 case BitcodeReader::InvalidTYPETable:
3280 return "Invalid TYPE table";
3281 case BitcodeReader::InvalidType:
3282 return "Invalid type";
3283 case BitcodeReader::MalformedBlock:
3284 return "Malformed block";
3285 case BitcodeReader::MalformedGlobalInitializerSet:
3286 return "Malformed global initializer set";
3287 case BitcodeReader::InvalidMultipleBlocks:
3288 return "Invalid multiple blocks";
3289 case BitcodeReader::NeverResolvedValueFoundInFunction:
3290 return "Never resolved value found in function";
3291 case BitcodeReader::InvalidValue:
3292 return "Invalid value";
3294 llvm_unreachable("Unknown error type!");
3299 const error_category &BitcodeReader::BitcodeErrorCategory() {
3300 static BitcodeErrorCategoryType O;
3304 //===----------------------------------------------------------------------===//
3305 // External interface
3306 //===----------------------------------------------------------------------===//
3308 /// getLazyBitcodeModule - lazy function-at-a-time loading from a file.
3310 ErrorOr<Module *> llvm::getLazyBitcodeModule(MemoryBuffer *Buffer,
3311 LLVMContext &Context) {
3312 Module *M = new Module(Buffer->getBufferIdentifier(), Context);
3313 BitcodeReader *R = new BitcodeReader(Buffer, Context);
3314 M->setMaterializer(R);
3315 if (error_code EC = R->ParseBitcodeInto(M)) {
3316 delete M; // Also deletes R.
3319 // Have the BitcodeReader dtor delete 'Buffer'.
3320 R->setBufferOwned(true);
3322 R->materializeForwardReferencedFunctions();
3328 Module *llvm::getStreamedBitcodeModule(const std::string &name,
3329 DataStreamer *streamer,
3330 LLVMContext &Context,
3331 std::string *ErrMsg) {
3332 Module *M = new Module(name, Context);
3333 BitcodeReader *R = new BitcodeReader(streamer, Context);
3334 M->setMaterializer(R);
3335 if (error_code EC = R->ParseBitcodeInto(M)) {
3337 *ErrMsg = EC.message();
3338 delete M; // Also deletes R.
3341 R->setBufferOwned(false); // no buffer to delete
3345 ErrorOr<Module *> llvm::parseBitcodeFile(MemoryBuffer *Buffer,
3346 LLVMContext &Context) {
3347 ErrorOr<Module *> ModuleOrErr = getLazyBitcodeModule(Buffer, Context);
3350 Module *M = ModuleOrErr.get();
3352 // Don't let the BitcodeReader dtor delete 'Buffer', regardless of whether
3353 // there was an error.
3354 static_cast<BitcodeReader*>(M->getMaterializer())->setBufferOwned(false);
3356 // Read in the entire module, and destroy the BitcodeReader.
3357 if (error_code EC = M->materializeAllPermanently()) {
3362 // TODO: Restore the use-lists to the in-memory state when the bitcode was
3363 // written. We must defer until the Module has been fully materialized.
3368 std::string llvm::getBitcodeTargetTriple(MemoryBuffer *Buffer,
3369 LLVMContext& Context,
3370 std::string *ErrMsg) {
3371 BitcodeReader *R = new BitcodeReader(Buffer, Context);
3372 // Don't let the BitcodeReader dtor delete 'Buffer'.
3373 R->setBufferOwned(false);
3375 std::string Triple("");
3376 if (error_code EC = R->ParseTriple(Triple))
3378 *ErrMsg = EC.message();