1 //===- BitcodeReader.cpp - Internal BitcodeReader implementation ----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "llvm/Bitcode/ReaderWriter.h"
11 #include "BitcodeReader.h"
12 #include "llvm/ADT/SmallString.h"
13 #include "llvm/ADT/SmallVector.h"
14 #include "llvm/AutoUpgrade.h"
15 #include "llvm/Bitcode/LLVMBitCodes.h"
16 #include "llvm/IR/Constants.h"
17 #include "llvm/IR/DerivedTypes.h"
18 #include "llvm/IR/InlineAsm.h"
19 #include "llvm/IR/IntrinsicInst.h"
20 #include "llvm/IR/LLVMContext.h"
21 #include "llvm/IR/Module.h"
22 #include "llvm/IR/OperandTraits.h"
23 #include "llvm/IR/Operator.h"
24 #include "llvm/Support/DataStream.h"
25 #include "llvm/Support/MathExtras.h"
26 #include "llvm/Support/MemoryBuffer.h"
27 #include "llvm/Support/raw_ostream.h"
31 SWITCH_INST_MAGIC = 0x4B5 // May 2012 => 1205 => Hex
34 void BitcodeReader::materializeForwardReferencedFunctions() {
35 while (!BlockAddrFwdRefs.empty()) {
36 Function *F = BlockAddrFwdRefs.begin()->first;
41 void BitcodeReader::FreeState() {
45 std::vector<Type*>().swap(TypeList);
49 std::vector<AttributeSet>().swap(MAttributes);
50 std::vector<BasicBlock*>().swap(FunctionBBs);
51 std::vector<Function*>().swap(FunctionsWithBodies);
52 DeferredFunctionInfo.clear();
55 assert(BlockAddrFwdRefs.empty() && "Unresolved blockaddress fwd references");
58 //===----------------------------------------------------------------------===//
59 // Helper functions to implement forward reference resolution, etc.
60 //===----------------------------------------------------------------------===//
62 /// ConvertToString - Convert a string from a record into an std::string, return
64 template<typename StrTy>
65 static bool ConvertToString(ArrayRef<uint64_t> Record, unsigned Idx,
67 if (Idx > Record.size())
70 for (unsigned i = Idx, e = Record.size(); i != e; ++i)
71 Result += (char)Record[i];
75 static GlobalValue::LinkageTypes GetDecodedLinkage(unsigned Val) {
77 default: // Map unknown/new linkages to external
78 case 0: return GlobalValue::ExternalLinkage;
79 case 1: return GlobalValue::WeakAnyLinkage;
80 case 2: return GlobalValue::AppendingLinkage;
81 case 3: return GlobalValue::InternalLinkage;
82 case 4: return GlobalValue::LinkOnceAnyLinkage;
83 case 5: return GlobalValue::DLLImportLinkage;
84 case 6: return GlobalValue::DLLExportLinkage;
85 case 7: return GlobalValue::ExternalWeakLinkage;
86 case 8: return GlobalValue::CommonLinkage;
87 case 9: return GlobalValue::PrivateLinkage;
88 case 10: return GlobalValue::WeakODRLinkage;
89 case 11: return GlobalValue::LinkOnceODRLinkage;
90 case 12: return GlobalValue::AvailableExternallyLinkage;
91 case 13: return GlobalValue::LinkerPrivateLinkage;
92 case 14: return GlobalValue::LinkerPrivateWeakLinkage;
96 static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned Val) {
98 default: // Map unknown visibilities to default.
99 case 0: return GlobalValue::DefaultVisibility;
100 case 1: return GlobalValue::HiddenVisibility;
101 case 2: return GlobalValue::ProtectedVisibility;
105 static GlobalVariable::ThreadLocalMode GetDecodedThreadLocalMode(unsigned Val) {
107 case 0: return GlobalVariable::NotThreadLocal;
108 default: // Map unknown non-zero value to general dynamic.
109 case 1: return GlobalVariable::GeneralDynamicTLSModel;
110 case 2: return GlobalVariable::LocalDynamicTLSModel;
111 case 3: return GlobalVariable::InitialExecTLSModel;
112 case 4: return GlobalVariable::LocalExecTLSModel;
116 static int GetDecodedCastOpcode(unsigned Val) {
119 case bitc::CAST_TRUNC : return Instruction::Trunc;
120 case bitc::CAST_ZEXT : return Instruction::ZExt;
121 case bitc::CAST_SEXT : return Instruction::SExt;
122 case bitc::CAST_FPTOUI : return Instruction::FPToUI;
123 case bitc::CAST_FPTOSI : return Instruction::FPToSI;
124 case bitc::CAST_UITOFP : return Instruction::UIToFP;
125 case bitc::CAST_SITOFP : return Instruction::SIToFP;
126 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
127 case bitc::CAST_FPEXT : return Instruction::FPExt;
128 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
129 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
130 case bitc::CAST_BITCAST : return Instruction::BitCast;
131 case bitc::CAST_ADDRSPACECAST: return Instruction::AddrSpaceCast;
134 static int GetDecodedBinaryOpcode(unsigned Val, Type *Ty) {
137 case bitc::BINOP_ADD:
138 return Ty->isFPOrFPVectorTy() ? Instruction::FAdd : Instruction::Add;
139 case bitc::BINOP_SUB:
140 return Ty->isFPOrFPVectorTy() ? Instruction::FSub : Instruction::Sub;
141 case bitc::BINOP_MUL:
142 return Ty->isFPOrFPVectorTy() ? Instruction::FMul : Instruction::Mul;
143 case bitc::BINOP_UDIV: return Instruction::UDiv;
144 case bitc::BINOP_SDIV:
145 return Ty->isFPOrFPVectorTy() ? Instruction::FDiv : Instruction::SDiv;
146 case bitc::BINOP_UREM: return Instruction::URem;
147 case bitc::BINOP_SREM:
148 return Ty->isFPOrFPVectorTy() ? Instruction::FRem : Instruction::SRem;
149 case bitc::BINOP_SHL: return Instruction::Shl;
150 case bitc::BINOP_LSHR: return Instruction::LShr;
151 case bitc::BINOP_ASHR: return Instruction::AShr;
152 case bitc::BINOP_AND: return Instruction::And;
153 case bitc::BINOP_OR: return Instruction::Or;
154 case bitc::BINOP_XOR: return Instruction::Xor;
158 static AtomicRMWInst::BinOp GetDecodedRMWOperation(unsigned Val) {
160 default: return AtomicRMWInst::BAD_BINOP;
161 case bitc::RMW_XCHG: return AtomicRMWInst::Xchg;
162 case bitc::RMW_ADD: return AtomicRMWInst::Add;
163 case bitc::RMW_SUB: return AtomicRMWInst::Sub;
164 case bitc::RMW_AND: return AtomicRMWInst::And;
165 case bitc::RMW_NAND: return AtomicRMWInst::Nand;
166 case bitc::RMW_OR: return AtomicRMWInst::Or;
167 case bitc::RMW_XOR: return AtomicRMWInst::Xor;
168 case bitc::RMW_MAX: return AtomicRMWInst::Max;
169 case bitc::RMW_MIN: return AtomicRMWInst::Min;
170 case bitc::RMW_UMAX: return AtomicRMWInst::UMax;
171 case bitc::RMW_UMIN: return AtomicRMWInst::UMin;
175 static AtomicOrdering GetDecodedOrdering(unsigned Val) {
177 case bitc::ORDERING_NOTATOMIC: return NotAtomic;
178 case bitc::ORDERING_UNORDERED: return Unordered;
179 case bitc::ORDERING_MONOTONIC: return Monotonic;
180 case bitc::ORDERING_ACQUIRE: return Acquire;
181 case bitc::ORDERING_RELEASE: return Release;
182 case bitc::ORDERING_ACQREL: return AcquireRelease;
183 default: // Map unknown orderings to sequentially-consistent.
184 case bitc::ORDERING_SEQCST: return SequentiallyConsistent;
188 static SynchronizationScope GetDecodedSynchScope(unsigned Val) {
190 case bitc::SYNCHSCOPE_SINGLETHREAD: return SingleThread;
191 default: // Map unknown scopes to cross-thread.
192 case bitc::SYNCHSCOPE_CROSSTHREAD: return CrossThread;
198 /// @brief A class for maintaining the slot number definition
199 /// as a placeholder for the actual definition for forward constants defs.
200 class ConstantPlaceHolder : public ConstantExpr {
201 void operator=(const ConstantPlaceHolder &) LLVM_DELETED_FUNCTION;
203 // allocate space for exactly one operand
204 void *operator new(size_t s) {
205 return User::operator new(s, 1);
207 explicit ConstantPlaceHolder(Type *Ty, LLVMContext& Context)
208 : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
209 Op<0>() = UndefValue::get(Type::getInt32Ty(Context));
212 /// @brief Methods to support type inquiry through isa, cast, and dyn_cast.
213 static bool classof(const Value *V) {
214 return isa<ConstantExpr>(V) &&
215 cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
219 /// Provide fast operand accessors
220 //DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
224 // FIXME: can we inherit this from ConstantExpr?
226 struct OperandTraits<ConstantPlaceHolder> :
227 public FixedNumOperandTraits<ConstantPlaceHolder, 1> {
232 void BitcodeReaderValueList::AssignValue(Value *V, unsigned Idx) {
241 WeakVH &OldV = ValuePtrs[Idx];
247 // Handle constants and non-constants (e.g. instrs) differently for
249 if (Constant *PHC = dyn_cast<Constant>(&*OldV)) {
250 ResolveConstants.push_back(std::make_pair(PHC, Idx));
253 // If there was a forward reference to this value, replace it.
254 Value *PrevVal = OldV;
255 OldV->replaceAllUsesWith(V);
261 Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
266 if (Value *V = ValuePtrs[Idx]) {
267 assert(Ty == V->getType() && "Type mismatch in constant table!");
268 return cast<Constant>(V);
271 // Create and return a placeholder, which will later be RAUW'd.
272 Constant *C = new ConstantPlaceHolder(Ty, Context);
277 Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, Type *Ty) {
281 if (Value *V = ValuePtrs[Idx]) {
282 assert((Ty == 0 || Ty == V->getType()) && "Type mismatch in value table!");
286 // No type specified, must be invalid reference.
287 if (Ty == 0) return 0;
289 // Create and return a placeholder, which will later be RAUW'd.
290 Value *V = new Argument(Ty);
295 /// ResolveConstantForwardRefs - Once all constants are read, this method bulk
296 /// resolves any forward references. The idea behind this is that we sometimes
297 /// get constants (such as large arrays) which reference *many* forward ref
298 /// constants. Replacing each of these causes a lot of thrashing when
299 /// building/reuniquing the constant. Instead of doing this, we look at all the
300 /// uses and rewrite all the place holders at once for any constant that uses
302 void BitcodeReaderValueList::ResolveConstantForwardRefs() {
303 // Sort the values by-pointer so that they are efficient to look up with a
305 std::sort(ResolveConstants.begin(), ResolveConstants.end());
307 SmallVector<Constant*, 64> NewOps;
309 while (!ResolveConstants.empty()) {
310 Value *RealVal = operator[](ResolveConstants.back().second);
311 Constant *Placeholder = ResolveConstants.back().first;
312 ResolveConstants.pop_back();
314 // Loop over all users of the placeholder, updating them to reference the
315 // new value. If they reference more than one placeholder, update them all
317 while (!Placeholder->use_empty()) {
318 Value::use_iterator UI = Placeholder->use_begin();
321 // If the using object isn't uniqued, just update the operands. This
322 // handles instructions and initializers for global variables.
323 if (!isa<Constant>(U) || isa<GlobalValue>(U)) {
324 UI.getUse().set(RealVal);
328 // Otherwise, we have a constant that uses the placeholder. Replace that
329 // constant with a new constant that has *all* placeholder uses updated.
330 Constant *UserC = cast<Constant>(U);
331 for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end();
334 if (!isa<ConstantPlaceHolder>(*I)) {
335 // Not a placeholder reference.
337 } else if (*I == Placeholder) {
338 // Common case is that it just references this one placeholder.
341 // Otherwise, look up the placeholder in ResolveConstants.
342 ResolveConstantsTy::iterator It =
343 std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(),
344 std::pair<Constant*, unsigned>(cast<Constant>(*I),
346 assert(It != ResolveConstants.end() && It->first == *I);
347 NewOp = operator[](It->second);
350 NewOps.push_back(cast<Constant>(NewOp));
353 // Make the new constant.
355 if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
356 NewC = ConstantArray::get(UserCA->getType(), NewOps);
357 } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
358 NewC = ConstantStruct::get(UserCS->getType(), NewOps);
359 } else if (isa<ConstantVector>(UserC)) {
360 NewC = ConstantVector::get(NewOps);
362 assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr.");
363 NewC = cast<ConstantExpr>(UserC)->getWithOperands(NewOps);
366 UserC->replaceAllUsesWith(NewC);
367 UserC->destroyConstant();
371 // Update all ValueHandles, they should be the only users at this point.
372 Placeholder->replaceAllUsesWith(RealVal);
377 void BitcodeReaderMDValueList::AssignValue(Value *V, unsigned Idx) {
386 WeakVH &OldV = MDValuePtrs[Idx];
392 // If there was a forward reference to this value, replace it.
393 MDNode *PrevVal = cast<MDNode>(OldV);
394 OldV->replaceAllUsesWith(V);
395 MDNode::deleteTemporary(PrevVal);
396 // Deleting PrevVal sets Idx value in MDValuePtrs to null. Set new
398 MDValuePtrs[Idx] = V;
401 Value *BitcodeReaderMDValueList::getValueFwdRef(unsigned Idx) {
405 if (Value *V = MDValuePtrs[Idx]) {
406 assert(V->getType()->isMetadataTy() && "Type mismatch in value table!");
410 // Create and return a placeholder, which will later be RAUW'd.
411 Value *V = MDNode::getTemporary(Context, None);
412 MDValuePtrs[Idx] = V;
416 Type *BitcodeReader::getTypeByID(unsigned ID) {
417 // The type table size is always specified correctly.
418 if (ID >= TypeList.size())
421 if (Type *Ty = TypeList[ID])
424 // If we have a forward reference, the only possible case is when it is to a
425 // named struct. Just create a placeholder for now.
426 return TypeList[ID] = StructType::create(Context);
430 //===----------------------------------------------------------------------===//
431 // Functions for parsing blocks from the bitcode file
432 //===----------------------------------------------------------------------===//
435 /// \brief This fills an AttrBuilder object with the LLVM attributes that have
436 /// been decoded from the given integer. This function must stay in sync with
437 /// 'encodeLLVMAttributesForBitcode'.
438 static void decodeLLVMAttributesForBitcode(AttrBuilder &B,
439 uint64_t EncodedAttrs) {
440 // FIXME: Remove in 4.0.
442 // The alignment is stored as a 16-bit raw value from bits 31--16. We shift
443 // the bits above 31 down by 11 bits.
444 unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
445 assert((!Alignment || isPowerOf2_32(Alignment)) &&
446 "Alignment must be a power of two.");
449 B.addAlignmentAttr(Alignment);
450 B.addRawValue(((EncodedAttrs & (0xfffffULL << 32)) >> 11) |
451 (EncodedAttrs & 0xffff));
454 error_code BitcodeReader::ParseAttributeBlock() {
455 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
456 return Error(InvalidRecord);
458 if (!MAttributes.empty())
459 return Error(InvalidMultipleBlocks);
461 SmallVector<uint64_t, 64> Record;
463 SmallVector<AttributeSet, 8> Attrs;
465 // Read all the records.
467 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
469 switch (Entry.Kind) {
470 case BitstreamEntry::SubBlock: // Handled for us already.
471 case BitstreamEntry::Error:
472 return Error(MalformedBlock);
473 case BitstreamEntry::EndBlock:
474 return error_code::success();
475 case BitstreamEntry::Record:
476 // The interesting case.
482 switch (Stream.readRecord(Entry.ID, Record)) {
483 default: // Default behavior: ignore.
485 case bitc::PARAMATTR_CODE_ENTRY_OLD: { // ENTRY: [paramidx0, attr0, ...]
486 // FIXME: Remove in 4.0.
487 if (Record.size() & 1)
488 return Error(InvalidRecord);
490 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
492 decodeLLVMAttributesForBitcode(B, Record[i+1]);
493 Attrs.push_back(AttributeSet::get(Context, Record[i], B));
496 MAttributes.push_back(AttributeSet::get(Context, Attrs));
500 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [attrgrp0, attrgrp1, ...]
501 for (unsigned i = 0, e = Record.size(); i != e; ++i)
502 Attrs.push_back(MAttributeGroups[Record[i]]);
504 MAttributes.push_back(AttributeSet::get(Context, Attrs));
512 // Returns Attribute::None on unrecognized codes.
513 static Attribute::AttrKind GetAttrFromCode(uint64_t Code) {
516 return Attribute::None;
517 case bitc::ATTR_KIND_ALIGNMENT:
518 return Attribute::Alignment;
519 case bitc::ATTR_KIND_ALWAYS_INLINE:
520 return Attribute::AlwaysInline;
521 case bitc::ATTR_KIND_BUILTIN:
522 return Attribute::Builtin;
523 case bitc::ATTR_KIND_BY_VAL:
524 return Attribute::ByVal;
525 case bitc::ATTR_KIND_IN_ALLOCA:
526 return Attribute::InAlloca;
527 case bitc::ATTR_KIND_COLD:
528 return Attribute::Cold;
529 case bitc::ATTR_KIND_INLINE_HINT:
530 return Attribute::InlineHint;
531 case bitc::ATTR_KIND_IN_REG:
532 return Attribute::InReg;
533 case bitc::ATTR_KIND_MIN_SIZE:
534 return Attribute::MinSize;
535 case bitc::ATTR_KIND_NAKED:
536 return Attribute::Naked;
537 case bitc::ATTR_KIND_NEST:
538 return Attribute::Nest;
539 case bitc::ATTR_KIND_NO_ALIAS:
540 return Attribute::NoAlias;
541 case bitc::ATTR_KIND_NO_BUILTIN:
542 return Attribute::NoBuiltin;
543 case bitc::ATTR_KIND_NO_CAPTURE:
544 return Attribute::NoCapture;
545 case bitc::ATTR_KIND_NO_DUPLICATE:
546 return Attribute::NoDuplicate;
547 case bitc::ATTR_KIND_NO_IMPLICIT_FLOAT:
548 return Attribute::NoImplicitFloat;
549 case bitc::ATTR_KIND_NO_INLINE:
550 return Attribute::NoInline;
551 case bitc::ATTR_KIND_NON_LAZY_BIND:
552 return Attribute::NonLazyBind;
553 case bitc::ATTR_KIND_NO_RED_ZONE:
554 return Attribute::NoRedZone;
555 case bitc::ATTR_KIND_NO_RETURN:
556 return Attribute::NoReturn;
557 case bitc::ATTR_KIND_NO_UNWIND:
558 return Attribute::NoUnwind;
559 case bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE:
560 return Attribute::OptimizeForSize;
561 case bitc::ATTR_KIND_OPTIMIZE_NONE:
562 return Attribute::OptimizeNone;
563 case bitc::ATTR_KIND_READ_NONE:
564 return Attribute::ReadNone;
565 case bitc::ATTR_KIND_READ_ONLY:
566 return Attribute::ReadOnly;
567 case bitc::ATTR_KIND_RETURNED:
568 return Attribute::Returned;
569 case bitc::ATTR_KIND_RETURNS_TWICE:
570 return Attribute::ReturnsTwice;
571 case bitc::ATTR_KIND_S_EXT:
572 return Attribute::SExt;
573 case bitc::ATTR_KIND_STACK_ALIGNMENT:
574 return Attribute::StackAlignment;
575 case bitc::ATTR_KIND_STACK_PROTECT:
576 return Attribute::StackProtect;
577 case bitc::ATTR_KIND_STACK_PROTECT_REQ:
578 return Attribute::StackProtectReq;
579 case bitc::ATTR_KIND_STACK_PROTECT_STRONG:
580 return Attribute::StackProtectStrong;
581 case bitc::ATTR_KIND_STRUCT_RET:
582 return Attribute::StructRet;
583 case bitc::ATTR_KIND_SANITIZE_ADDRESS:
584 return Attribute::SanitizeAddress;
585 case bitc::ATTR_KIND_SANITIZE_THREAD:
586 return Attribute::SanitizeThread;
587 case bitc::ATTR_KIND_SANITIZE_MEMORY:
588 return Attribute::SanitizeMemory;
589 case bitc::ATTR_KIND_UW_TABLE:
590 return Attribute::UWTable;
591 case bitc::ATTR_KIND_Z_EXT:
592 return Attribute::ZExt;
596 error_code BitcodeReader::ParseAttrKind(uint64_t Code,
597 Attribute::AttrKind *Kind) {
598 *Kind = GetAttrFromCode(Code);
599 if (*Kind == Attribute::None)
600 return Error(InvalidValue);
601 return error_code::success();
604 error_code BitcodeReader::ParseAttributeGroupBlock() {
605 if (Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID))
606 return Error(InvalidRecord);
608 if (!MAttributeGroups.empty())
609 return Error(InvalidMultipleBlocks);
611 SmallVector<uint64_t, 64> Record;
613 // Read all the records.
615 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
617 switch (Entry.Kind) {
618 case BitstreamEntry::SubBlock: // Handled for us already.
619 case BitstreamEntry::Error:
620 return Error(MalformedBlock);
621 case BitstreamEntry::EndBlock:
622 return error_code::success();
623 case BitstreamEntry::Record:
624 // The interesting case.
630 switch (Stream.readRecord(Entry.ID, Record)) {
631 default: // Default behavior: ignore.
633 case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...]
634 if (Record.size() < 3)
635 return Error(InvalidRecord);
637 uint64_t GrpID = Record[0];
638 uint64_t Idx = Record[1]; // Index of the object this attribute refers to.
641 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
642 if (Record[i] == 0) { // Enum attribute
643 Attribute::AttrKind Kind;
644 if (error_code EC = ParseAttrKind(Record[++i], &Kind))
647 B.addAttribute(Kind);
648 } else if (Record[i] == 1) { // Align attribute
649 Attribute::AttrKind Kind;
650 if (error_code EC = ParseAttrKind(Record[++i], &Kind))
652 if (Kind == Attribute::Alignment)
653 B.addAlignmentAttr(Record[++i]);
655 B.addStackAlignmentAttr(Record[++i]);
656 } else { // String attribute
657 assert((Record[i] == 3 || Record[i] == 4) &&
658 "Invalid attribute group entry");
659 bool HasValue = (Record[i++] == 4);
660 SmallString<64> KindStr;
661 SmallString<64> ValStr;
663 while (Record[i] != 0 && i != e)
664 KindStr += Record[i++];
665 assert(Record[i] == 0 && "Kind string not null terminated");
668 // Has a value associated with it.
669 ++i; // Skip the '0' that terminates the "kind" string.
670 while (Record[i] != 0 && i != e)
671 ValStr += Record[i++];
672 assert(Record[i] == 0 && "Value string not null terminated");
675 B.addAttribute(KindStr.str(), ValStr.str());
679 MAttributeGroups[GrpID] = AttributeSet::get(Context, Idx, B);
686 error_code BitcodeReader::ParseTypeTable() {
687 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
688 return Error(InvalidRecord);
690 return ParseTypeTableBody();
693 error_code BitcodeReader::ParseTypeTableBody() {
694 if (!TypeList.empty())
695 return Error(InvalidMultipleBlocks);
697 SmallVector<uint64_t, 64> Record;
698 unsigned NumRecords = 0;
700 SmallString<64> TypeName;
702 // Read all the records for this type table.
704 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
706 switch (Entry.Kind) {
707 case BitstreamEntry::SubBlock: // Handled for us already.
708 case BitstreamEntry::Error:
709 return Error(MalformedBlock);
710 case BitstreamEntry::EndBlock:
711 if (NumRecords != TypeList.size())
712 return Error(MalformedBlock);
713 return error_code::success();
714 case BitstreamEntry::Record:
715 // The interesting case.
722 switch (Stream.readRecord(Entry.ID, Record)) {
724 return Error(InvalidValue);
725 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
726 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
727 // type list. This allows us to reserve space.
728 if (Record.size() < 1)
729 return Error(InvalidRecord);
730 TypeList.resize(Record[0]);
732 case bitc::TYPE_CODE_VOID: // VOID
733 ResultTy = Type::getVoidTy(Context);
735 case bitc::TYPE_CODE_HALF: // HALF
736 ResultTy = Type::getHalfTy(Context);
738 case bitc::TYPE_CODE_FLOAT: // FLOAT
739 ResultTy = Type::getFloatTy(Context);
741 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
742 ResultTy = Type::getDoubleTy(Context);
744 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
745 ResultTy = Type::getX86_FP80Ty(Context);
747 case bitc::TYPE_CODE_FP128: // FP128
748 ResultTy = Type::getFP128Ty(Context);
750 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
751 ResultTy = Type::getPPC_FP128Ty(Context);
753 case bitc::TYPE_CODE_LABEL: // LABEL
754 ResultTy = Type::getLabelTy(Context);
756 case bitc::TYPE_CODE_METADATA: // METADATA
757 ResultTy = Type::getMetadataTy(Context);
759 case bitc::TYPE_CODE_X86_MMX: // X86_MMX
760 ResultTy = Type::getX86_MMXTy(Context);
762 case bitc::TYPE_CODE_INTEGER: // INTEGER: [width]
763 if (Record.size() < 1)
764 return Error(InvalidRecord);
766 ResultTy = IntegerType::get(Context, Record[0]);
768 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
769 // [pointee type, address space]
770 if (Record.size() < 1)
771 return Error(InvalidRecord);
772 unsigned AddressSpace = 0;
773 if (Record.size() == 2)
774 AddressSpace = Record[1];
775 ResultTy = getTypeByID(Record[0]);
777 return Error(InvalidType);
778 ResultTy = PointerType::get(ResultTy, AddressSpace);
781 case bitc::TYPE_CODE_FUNCTION_OLD: {
782 // FIXME: attrid is dead, remove it in LLVM 4.0
783 // FUNCTION: [vararg, attrid, retty, paramty x N]
784 if (Record.size() < 3)
785 return Error(InvalidRecord);
786 SmallVector<Type*, 8> ArgTys;
787 for (unsigned i = 3, e = Record.size(); i != e; ++i) {
788 if (Type *T = getTypeByID(Record[i]))
794 ResultTy = getTypeByID(Record[2]);
795 if (ResultTy == 0 || ArgTys.size() < Record.size()-3)
796 return Error(InvalidType);
798 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
801 case bitc::TYPE_CODE_FUNCTION: {
802 // FUNCTION: [vararg, retty, paramty x N]
803 if (Record.size() < 2)
804 return Error(InvalidRecord);
805 SmallVector<Type*, 8> ArgTys;
806 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
807 if (Type *T = getTypeByID(Record[i]))
813 ResultTy = getTypeByID(Record[1]);
814 if (ResultTy == 0 || ArgTys.size() < Record.size()-2)
815 return Error(InvalidType);
817 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
820 case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N]
821 if (Record.size() < 1)
822 return Error(InvalidRecord);
823 SmallVector<Type*, 8> EltTys;
824 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
825 if (Type *T = getTypeByID(Record[i]))
830 if (EltTys.size() != Record.size()-1)
831 return Error(InvalidType);
832 ResultTy = StructType::get(Context, EltTys, Record[0]);
835 case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N]
836 if (ConvertToString(Record, 0, TypeName))
837 return Error(InvalidRecord);
840 case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
841 if (Record.size() < 1)
842 return Error(InvalidRecord);
844 if (NumRecords >= TypeList.size())
845 return Error(InvalidTYPETable);
847 // Check to see if this was forward referenced, if so fill in the temp.
848 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
850 Res->setName(TypeName);
851 TypeList[NumRecords] = 0;
852 } else // Otherwise, create a new struct.
853 Res = StructType::create(Context, TypeName);
856 SmallVector<Type*, 8> EltTys;
857 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
858 if (Type *T = getTypeByID(Record[i]))
863 if (EltTys.size() != Record.size()-1)
864 return Error(InvalidRecord);
865 Res->setBody(EltTys, Record[0]);
869 case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: []
870 if (Record.size() != 1)
871 return Error(InvalidRecord);
873 if (NumRecords >= TypeList.size())
874 return Error(InvalidTYPETable);
876 // Check to see if this was forward referenced, if so fill in the temp.
877 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
879 Res->setName(TypeName);
880 TypeList[NumRecords] = 0;
881 } else // Otherwise, create a new struct with no body.
882 Res = StructType::create(Context, TypeName);
887 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
888 if (Record.size() < 2)
889 return Error(InvalidRecord);
890 if ((ResultTy = getTypeByID(Record[1])))
891 ResultTy = ArrayType::get(ResultTy, Record[0]);
893 return Error(InvalidType);
895 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
896 if (Record.size() < 2)
897 return Error(InvalidRecord);
898 if ((ResultTy = getTypeByID(Record[1])))
899 ResultTy = VectorType::get(ResultTy, Record[0]);
901 return Error(InvalidType);
905 if (NumRecords >= TypeList.size())
906 return Error(InvalidTYPETable);
907 assert(ResultTy && "Didn't read a type?");
908 assert(TypeList[NumRecords] == 0 && "Already read type?");
909 TypeList[NumRecords++] = ResultTy;
913 error_code BitcodeReader::ParseValueSymbolTable() {
914 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
915 return Error(InvalidRecord);
917 SmallVector<uint64_t, 64> Record;
919 // Read all the records for this value table.
920 SmallString<128> ValueName;
922 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
924 switch (Entry.Kind) {
925 case BitstreamEntry::SubBlock: // Handled for us already.
926 case BitstreamEntry::Error:
927 return Error(MalformedBlock);
928 case BitstreamEntry::EndBlock:
929 return error_code::success();
930 case BitstreamEntry::Record:
931 // The interesting case.
937 switch (Stream.readRecord(Entry.ID, Record)) {
938 default: // Default behavior: unknown type.
940 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
941 if (ConvertToString(Record, 1, ValueName))
942 return Error(InvalidRecord);
943 unsigned ValueID = Record[0];
944 if (ValueID >= ValueList.size())
945 return Error(InvalidRecord);
946 Value *V = ValueList[ValueID];
948 V->setName(StringRef(ValueName.data(), ValueName.size()));
952 case bitc::VST_CODE_BBENTRY: {
953 if (ConvertToString(Record, 1, ValueName))
954 return Error(InvalidRecord);
955 BasicBlock *BB = getBasicBlock(Record[0]);
957 return Error(InvalidRecord);
959 BB->setName(StringRef(ValueName.data(), ValueName.size()));
967 error_code BitcodeReader::ParseMetadata() {
968 unsigned NextMDValueNo = MDValueList.size();
970 if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
971 return Error(InvalidRecord);
973 SmallVector<uint64_t, 64> Record;
975 // Read all the records.
977 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
979 switch (Entry.Kind) {
980 case BitstreamEntry::SubBlock: // Handled for us already.
981 case BitstreamEntry::Error:
982 return Error(MalformedBlock);
983 case BitstreamEntry::EndBlock:
984 return error_code::success();
985 case BitstreamEntry::Record:
986 // The interesting case.
990 bool IsFunctionLocal = false;
993 unsigned Code = Stream.readRecord(Entry.ID, Record);
995 default: // Default behavior: ignore.
997 case bitc::METADATA_NAME: {
998 // Read name of the named metadata.
999 SmallString<8> Name(Record.begin(), Record.end());
1001 Code = Stream.ReadCode();
1003 // METADATA_NAME is always followed by METADATA_NAMED_NODE.
1004 unsigned NextBitCode = Stream.readRecord(Code, Record);
1005 assert(NextBitCode == bitc::METADATA_NAMED_NODE); (void)NextBitCode;
1007 // Read named metadata elements.
1008 unsigned Size = Record.size();
1009 NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name);
1010 for (unsigned i = 0; i != Size; ++i) {
1011 MDNode *MD = dyn_cast<MDNode>(MDValueList.getValueFwdRef(Record[i]));
1013 return Error(InvalidRecord);
1014 NMD->addOperand(MD);
1018 case bitc::METADATA_FN_NODE:
1019 IsFunctionLocal = true;
1021 case bitc::METADATA_NODE: {
1022 if (Record.size() % 2 == 1)
1023 return Error(InvalidRecord);
1025 unsigned Size = Record.size();
1026 SmallVector<Value*, 8> Elts;
1027 for (unsigned i = 0; i != Size; i += 2) {
1028 Type *Ty = getTypeByID(Record[i]);
1030 return Error(InvalidRecord);
1031 if (Ty->isMetadataTy())
1032 Elts.push_back(MDValueList.getValueFwdRef(Record[i+1]));
1033 else if (!Ty->isVoidTy())
1034 Elts.push_back(ValueList.getValueFwdRef(Record[i+1], Ty));
1036 Elts.push_back(NULL);
1038 Value *V = MDNode::getWhenValsUnresolved(Context, Elts, IsFunctionLocal);
1039 IsFunctionLocal = false;
1040 MDValueList.AssignValue(V, NextMDValueNo++);
1043 case bitc::METADATA_STRING: {
1044 SmallString<8> String(Record.begin(), Record.end());
1045 Value *V = MDString::get(Context, String);
1046 MDValueList.AssignValue(V, NextMDValueNo++);
1049 case bitc::METADATA_KIND: {
1050 if (Record.size() < 2)
1051 return Error(InvalidRecord);
1053 unsigned Kind = Record[0];
1054 SmallString<8> Name(Record.begin()+1, Record.end());
1056 unsigned NewKind = TheModule->getMDKindID(Name.str());
1057 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
1058 return Error(ConflictingMETADATA_KINDRecords);
1065 /// decodeSignRotatedValue - Decode a signed value stored with the sign bit in
1066 /// the LSB for dense VBR encoding.
1067 uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
1072 // There is no such thing as -0 with integers. "-0" really means MININT.
1076 /// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
1077 /// values and aliases that we can.
1078 error_code BitcodeReader::ResolveGlobalAndAliasInits() {
1079 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
1080 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
1081 std::vector<std::pair<Function*, unsigned> > FunctionPrefixWorklist;
1083 GlobalInitWorklist.swap(GlobalInits);
1084 AliasInitWorklist.swap(AliasInits);
1085 FunctionPrefixWorklist.swap(FunctionPrefixes);
1087 while (!GlobalInitWorklist.empty()) {
1088 unsigned ValID = GlobalInitWorklist.back().second;
1089 if (ValID >= ValueList.size()) {
1090 // Not ready to resolve this yet, it requires something later in the file.
1091 GlobalInits.push_back(GlobalInitWorklist.back());
1093 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
1094 GlobalInitWorklist.back().first->setInitializer(C);
1096 return Error(ExpectedConstant);
1098 GlobalInitWorklist.pop_back();
1101 while (!AliasInitWorklist.empty()) {
1102 unsigned ValID = AliasInitWorklist.back().second;
1103 if (ValID >= ValueList.size()) {
1104 AliasInits.push_back(AliasInitWorklist.back());
1106 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
1107 AliasInitWorklist.back().first->setAliasee(C);
1109 return Error(ExpectedConstant);
1111 AliasInitWorklist.pop_back();
1114 while (!FunctionPrefixWorklist.empty()) {
1115 unsigned ValID = FunctionPrefixWorklist.back().second;
1116 if (ValID >= ValueList.size()) {
1117 FunctionPrefixes.push_back(FunctionPrefixWorklist.back());
1119 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
1120 FunctionPrefixWorklist.back().first->setPrefixData(C);
1122 return Error(ExpectedConstant);
1124 FunctionPrefixWorklist.pop_back();
1127 return error_code::success();
1130 static APInt ReadWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
1131 SmallVector<uint64_t, 8> Words(Vals.size());
1132 std::transform(Vals.begin(), Vals.end(), Words.begin(),
1133 BitcodeReader::decodeSignRotatedValue);
1135 return APInt(TypeBits, Words);
1138 error_code BitcodeReader::ParseConstants() {
1139 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
1140 return Error(InvalidRecord);
1142 SmallVector<uint64_t, 64> Record;
1144 // Read all the records for this value table.
1145 Type *CurTy = Type::getInt32Ty(Context);
1146 unsigned NextCstNo = ValueList.size();
1148 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1150 switch (Entry.Kind) {
1151 case BitstreamEntry::SubBlock: // Handled for us already.
1152 case BitstreamEntry::Error:
1153 return Error(MalformedBlock);
1154 case BitstreamEntry::EndBlock:
1155 if (NextCstNo != ValueList.size())
1156 return Error(InvalidConstantReference);
1158 // Once all the constants have been read, go through and resolve forward
1160 ValueList.ResolveConstantForwardRefs();
1161 return error_code::success();
1162 case BitstreamEntry::Record:
1163 // The interesting case.
1170 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
1172 default: // Default behavior: unknown constant
1173 case bitc::CST_CODE_UNDEF: // UNDEF
1174 V = UndefValue::get(CurTy);
1176 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
1178 return Error(InvalidRecord);
1179 if (Record[0] >= TypeList.size())
1180 return Error(InvalidRecord);
1181 CurTy = TypeList[Record[0]];
1182 continue; // Skip the ValueList manipulation.
1183 case bitc::CST_CODE_NULL: // NULL
1184 V = Constant::getNullValue(CurTy);
1186 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
1187 if (!CurTy->isIntegerTy() || Record.empty())
1188 return Error(InvalidRecord);
1189 V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
1191 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
1192 if (!CurTy->isIntegerTy() || Record.empty())
1193 return Error(InvalidRecord);
1195 APInt VInt = ReadWideAPInt(Record,
1196 cast<IntegerType>(CurTy)->getBitWidth());
1197 V = ConstantInt::get(Context, VInt);
1201 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
1203 return Error(InvalidRecord);
1204 if (CurTy->isHalfTy())
1205 V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf,
1206 APInt(16, (uint16_t)Record[0])));
1207 else if (CurTy->isFloatTy())
1208 V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle,
1209 APInt(32, (uint32_t)Record[0])));
1210 else if (CurTy->isDoubleTy())
1211 V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble,
1212 APInt(64, Record[0])));
1213 else if (CurTy->isX86_FP80Ty()) {
1214 // Bits are not stored the same way as a normal i80 APInt, compensate.
1215 uint64_t Rearrange[2];
1216 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
1217 Rearrange[1] = Record[0] >> 48;
1218 V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended,
1219 APInt(80, Rearrange)));
1220 } else if (CurTy->isFP128Ty())
1221 V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad,
1222 APInt(128, Record)));
1223 else if (CurTy->isPPC_FP128Ty())
1224 V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble,
1225 APInt(128, Record)));
1227 V = UndefValue::get(CurTy);
1231 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
1233 return Error(InvalidRecord);
1235 unsigned Size = Record.size();
1236 SmallVector<Constant*, 16> Elts;
1238 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
1239 for (unsigned i = 0; i != Size; ++i)
1240 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
1241 STy->getElementType(i)));
1242 V = ConstantStruct::get(STy, Elts);
1243 } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
1244 Type *EltTy = ATy->getElementType();
1245 for (unsigned i = 0; i != Size; ++i)
1246 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
1247 V = ConstantArray::get(ATy, Elts);
1248 } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
1249 Type *EltTy = VTy->getElementType();
1250 for (unsigned i = 0; i != Size; ++i)
1251 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
1252 V = ConstantVector::get(Elts);
1254 V = UndefValue::get(CurTy);
1258 case bitc::CST_CODE_STRING: // STRING: [values]
1259 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
1261 return Error(InvalidRecord);
1263 SmallString<16> Elts(Record.begin(), Record.end());
1264 V = ConstantDataArray::getString(Context, Elts,
1265 BitCode == bitc::CST_CODE_CSTRING);
1268 case bitc::CST_CODE_DATA: {// DATA: [n x value]
1270 return Error(InvalidRecord);
1272 Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
1273 unsigned Size = Record.size();
1275 if (EltTy->isIntegerTy(8)) {
1276 SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
1277 if (isa<VectorType>(CurTy))
1278 V = ConstantDataVector::get(Context, Elts);
1280 V = ConstantDataArray::get(Context, Elts);
1281 } else if (EltTy->isIntegerTy(16)) {
1282 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
1283 if (isa<VectorType>(CurTy))
1284 V = ConstantDataVector::get(Context, Elts);
1286 V = ConstantDataArray::get(Context, Elts);
1287 } else if (EltTy->isIntegerTy(32)) {
1288 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
1289 if (isa<VectorType>(CurTy))
1290 V = ConstantDataVector::get(Context, Elts);
1292 V = ConstantDataArray::get(Context, Elts);
1293 } else if (EltTy->isIntegerTy(64)) {
1294 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
1295 if (isa<VectorType>(CurTy))
1296 V = ConstantDataVector::get(Context, Elts);
1298 V = ConstantDataArray::get(Context, Elts);
1299 } else if (EltTy->isFloatTy()) {
1300 SmallVector<float, 16> Elts(Size);
1301 std::transform(Record.begin(), Record.end(), Elts.begin(), BitsToFloat);
1302 if (isa<VectorType>(CurTy))
1303 V = ConstantDataVector::get(Context, Elts);
1305 V = ConstantDataArray::get(Context, Elts);
1306 } else if (EltTy->isDoubleTy()) {
1307 SmallVector<double, 16> Elts(Size);
1308 std::transform(Record.begin(), Record.end(), Elts.begin(),
1310 if (isa<VectorType>(CurTy))
1311 V = ConstantDataVector::get(Context, Elts);
1313 V = ConstantDataArray::get(Context, Elts);
1315 return Error(InvalidTypeForValue);
1320 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
1321 if (Record.size() < 3)
1322 return Error(InvalidRecord);
1323 int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
1325 V = UndefValue::get(CurTy); // Unknown binop.
1327 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
1328 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
1330 if (Record.size() >= 4) {
1331 if (Opc == Instruction::Add ||
1332 Opc == Instruction::Sub ||
1333 Opc == Instruction::Mul ||
1334 Opc == Instruction::Shl) {
1335 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
1336 Flags |= OverflowingBinaryOperator::NoSignedWrap;
1337 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
1338 Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
1339 } else if (Opc == Instruction::SDiv ||
1340 Opc == Instruction::UDiv ||
1341 Opc == Instruction::LShr ||
1342 Opc == Instruction::AShr) {
1343 if (Record[3] & (1 << bitc::PEO_EXACT))
1344 Flags |= SDivOperator::IsExact;
1347 V = ConstantExpr::get(Opc, LHS, RHS, Flags);
1351 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
1352 if (Record.size() < 3)
1353 return Error(InvalidRecord);
1354 int Opc = GetDecodedCastOpcode(Record[0]);
1356 V = UndefValue::get(CurTy); // Unknown cast.
1358 Type *OpTy = getTypeByID(Record[1]);
1360 return Error(InvalidRecord);
1361 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
1362 V = UpgradeBitCastExpr(Opc, Op, CurTy);
1363 if (!V) V = ConstantExpr::getCast(Opc, Op, CurTy);
1367 case bitc::CST_CODE_CE_INBOUNDS_GEP:
1368 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
1369 if (Record.size() & 1)
1370 return Error(InvalidRecord);
1371 SmallVector<Constant*, 16> Elts;
1372 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
1373 Type *ElTy = getTypeByID(Record[i]);
1375 return Error(InvalidRecord);
1376 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
1378 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
1379 V = ConstantExpr::getGetElementPtr(Elts[0], Indices,
1381 bitc::CST_CODE_CE_INBOUNDS_GEP);
1384 case bitc::CST_CODE_CE_SELECT: { // CE_SELECT: [opval#, opval#, opval#]
1385 if (Record.size() < 3)
1386 return Error(InvalidRecord);
1388 Type *SelectorTy = Type::getInt1Ty(Context);
1390 // If CurTy is a vector of length n, then Record[0] must be a <n x i1>
1391 // vector. Otherwise, it must be a single bit.
1392 if (VectorType *VTy = dyn_cast<VectorType>(CurTy))
1393 SelectorTy = VectorType::get(Type::getInt1Ty(Context),
1394 VTy->getNumElements());
1396 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
1398 ValueList.getConstantFwdRef(Record[1],CurTy),
1399 ValueList.getConstantFwdRef(Record[2],CurTy));
1402 case bitc::CST_CODE_CE_EXTRACTELT: { // CE_EXTRACTELT: [opty, opval, opval]
1403 if (Record.size() < 3)
1404 return Error(InvalidRecord);
1406 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1408 return Error(InvalidRecord);
1409 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1410 Constant *Op1 = ValueList.getConstantFwdRef(Record[2],
1411 Type::getInt32Ty(Context));
1412 V = ConstantExpr::getExtractElement(Op0, Op1);
1415 case bitc::CST_CODE_CE_INSERTELT: { // CE_INSERTELT: [opval, opval, opval]
1416 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
1417 if (Record.size() < 3 || OpTy == 0)
1418 return Error(InvalidRecord);
1419 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1420 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
1421 OpTy->getElementType());
1422 Constant *Op2 = ValueList.getConstantFwdRef(Record[2],
1423 Type::getInt32Ty(Context));
1424 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
1427 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
1428 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
1429 if (Record.size() < 3 || OpTy == 0)
1430 return Error(InvalidRecord);
1431 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1432 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
1433 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
1434 OpTy->getNumElements());
1435 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
1436 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
1439 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
1440 VectorType *RTy = dyn_cast<VectorType>(CurTy);
1442 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1443 if (Record.size() < 4 || RTy == 0 || OpTy == 0)
1444 return Error(InvalidRecord);
1445 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1446 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1447 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
1448 RTy->getNumElements());
1449 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
1450 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
1453 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
1454 if (Record.size() < 4)
1455 return Error(InvalidRecord);
1456 Type *OpTy = getTypeByID(Record[0]);
1458 return Error(InvalidRecord);
1459 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1460 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1462 if (OpTy->isFPOrFPVectorTy())
1463 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
1465 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
1468 // This maintains backward compatibility, pre-asm dialect keywords.
1469 // FIXME: Remove with the 4.0 release.
1470 case bitc::CST_CODE_INLINEASM_OLD: {
1471 if (Record.size() < 2)
1472 return Error(InvalidRecord);
1473 std::string AsmStr, ConstrStr;
1474 bool HasSideEffects = Record[0] & 1;
1475 bool IsAlignStack = Record[0] >> 1;
1476 unsigned AsmStrSize = Record[1];
1477 if (2+AsmStrSize >= Record.size())
1478 return Error(InvalidRecord);
1479 unsigned ConstStrSize = Record[2+AsmStrSize];
1480 if (3+AsmStrSize+ConstStrSize > Record.size())
1481 return Error(InvalidRecord);
1483 for (unsigned i = 0; i != AsmStrSize; ++i)
1484 AsmStr += (char)Record[2+i];
1485 for (unsigned i = 0; i != ConstStrSize; ++i)
1486 ConstrStr += (char)Record[3+AsmStrSize+i];
1487 PointerType *PTy = cast<PointerType>(CurTy);
1488 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
1489 AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
1492 // This version adds support for the asm dialect keywords (e.g.,
1494 case bitc::CST_CODE_INLINEASM: {
1495 if (Record.size() < 2)
1496 return Error(InvalidRecord);
1497 std::string AsmStr, ConstrStr;
1498 bool HasSideEffects = Record[0] & 1;
1499 bool IsAlignStack = (Record[0] >> 1) & 1;
1500 unsigned AsmDialect = Record[0] >> 2;
1501 unsigned AsmStrSize = Record[1];
1502 if (2+AsmStrSize >= Record.size())
1503 return Error(InvalidRecord);
1504 unsigned ConstStrSize = Record[2+AsmStrSize];
1505 if (3+AsmStrSize+ConstStrSize > Record.size())
1506 return Error(InvalidRecord);
1508 for (unsigned i = 0; i != AsmStrSize; ++i)
1509 AsmStr += (char)Record[2+i];
1510 for (unsigned i = 0; i != ConstStrSize; ++i)
1511 ConstrStr += (char)Record[3+AsmStrSize+i];
1512 PointerType *PTy = cast<PointerType>(CurTy);
1513 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
1514 AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
1515 InlineAsm::AsmDialect(AsmDialect));
1518 case bitc::CST_CODE_BLOCKADDRESS:{
1519 if (Record.size() < 3)
1520 return Error(InvalidRecord);
1521 Type *FnTy = getTypeByID(Record[0]);
1523 return Error(InvalidRecord);
1525 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
1527 return Error(InvalidRecord);
1529 // If the function is already parsed we can insert the block address right
1532 Function::iterator BBI = Fn->begin(), BBE = Fn->end();
1533 for (size_t I = 0, E = Record[2]; I != E; ++I) {
1535 return Error(InvalidID);
1538 V = BlockAddress::get(Fn, BBI);
1540 // Otherwise insert a placeholder and remember it so it can be inserted
1541 // when the function is parsed.
1542 GlobalVariable *FwdRef = new GlobalVariable(*Fn->getParent(),
1543 Type::getInt8Ty(Context),
1544 false, GlobalValue::InternalLinkage,
1546 BlockAddrFwdRefs[Fn].push_back(std::make_pair(Record[2], FwdRef));
1553 ValueList.AssignValue(V, NextCstNo);
1558 error_code BitcodeReader::ParseUseLists() {
1559 if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
1560 return Error(InvalidRecord);
1562 SmallVector<uint64_t, 64> Record;
1564 // Read all the records.
1566 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1568 switch (Entry.Kind) {
1569 case BitstreamEntry::SubBlock: // Handled for us already.
1570 case BitstreamEntry::Error:
1571 return Error(MalformedBlock);
1572 case BitstreamEntry::EndBlock:
1573 return error_code::success();
1574 case BitstreamEntry::Record:
1575 // The interesting case.
1579 // Read a use list record.
1581 switch (Stream.readRecord(Entry.ID, Record)) {
1582 default: // Default behavior: unknown type.
1584 case bitc::USELIST_CODE_ENTRY: { // USELIST_CODE_ENTRY: TBD.
1585 unsigned RecordLength = Record.size();
1586 if (RecordLength < 1)
1587 return Error(InvalidRecord);
1588 UseListRecords.push_back(Record);
1595 /// RememberAndSkipFunctionBody - When we see the block for a function body,
1596 /// remember where it is and then skip it. This lets us lazily deserialize the
1598 error_code BitcodeReader::RememberAndSkipFunctionBody() {
1599 // Get the function we are talking about.
1600 if (FunctionsWithBodies.empty())
1601 return Error(InsufficientFunctionProtos);
1603 Function *Fn = FunctionsWithBodies.back();
1604 FunctionsWithBodies.pop_back();
1606 // Save the current stream state.
1607 uint64_t CurBit = Stream.GetCurrentBitNo();
1608 DeferredFunctionInfo[Fn] = CurBit;
1610 // Skip over the function block for now.
1611 if (Stream.SkipBlock())
1612 return Error(InvalidRecord);
1613 return error_code::success();
1616 error_code BitcodeReader::GlobalCleanup() {
1617 // Patch the initializers for globals and aliases up.
1618 ResolveGlobalAndAliasInits();
1619 if (!GlobalInits.empty() || !AliasInits.empty())
1620 return Error(MalformedGlobalInitializerSet);
1622 // Look for intrinsic functions which need to be upgraded at some point
1623 for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
1626 if (UpgradeIntrinsicFunction(FI, NewFn))
1627 UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
1630 // Look for global variables which need to be renamed.
1631 for (Module::global_iterator
1632 GI = TheModule->global_begin(), GE = TheModule->global_end();
1634 UpgradeGlobalVariable(GI);
1635 // Force deallocation of memory for these vectors to favor the client that
1636 // want lazy deserialization.
1637 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
1638 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
1639 return error_code::success();
1642 error_code BitcodeReader::ParseModule(bool Resume) {
1644 Stream.JumpToBit(NextUnreadBit);
1645 else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
1646 return Error(InvalidRecord);
1648 SmallVector<uint64_t, 64> Record;
1649 std::vector<std::string> SectionTable;
1650 std::vector<std::string> GCTable;
1652 // Read all the records for this module.
1654 BitstreamEntry Entry = Stream.advance();
1656 switch (Entry.Kind) {
1657 case BitstreamEntry::Error:
1658 return Error(MalformedBlock);
1659 case BitstreamEntry::EndBlock:
1660 return GlobalCleanup();
1662 case BitstreamEntry::SubBlock:
1664 default: // Skip unknown content.
1665 if (Stream.SkipBlock())
1666 return Error(InvalidRecord);
1668 case bitc::BLOCKINFO_BLOCK_ID:
1669 if (Stream.ReadBlockInfoBlock())
1670 return Error(MalformedBlock);
1672 case bitc::PARAMATTR_BLOCK_ID:
1673 if (error_code EC = ParseAttributeBlock())
1676 case bitc::PARAMATTR_GROUP_BLOCK_ID:
1677 if (error_code EC = ParseAttributeGroupBlock())
1680 case bitc::TYPE_BLOCK_ID_NEW:
1681 if (error_code EC = ParseTypeTable())
1684 case bitc::VALUE_SYMTAB_BLOCK_ID:
1685 if (error_code EC = ParseValueSymbolTable())
1687 SeenValueSymbolTable = true;
1689 case bitc::CONSTANTS_BLOCK_ID:
1690 if (error_code EC = ParseConstants())
1692 if (error_code EC = ResolveGlobalAndAliasInits())
1695 case bitc::METADATA_BLOCK_ID:
1696 if (error_code EC = ParseMetadata())
1699 case bitc::FUNCTION_BLOCK_ID:
1700 // If this is the first function body we've seen, reverse the
1701 // FunctionsWithBodies list.
1702 if (!SeenFirstFunctionBody) {
1703 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
1704 if (error_code EC = GlobalCleanup())
1706 SeenFirstFunctionBody = true;
1709 if (error_code EC = RememberAndSkipFunctionBody())
1711 // For streaming bitcode, suspend parsing when we reach the function
1712 // bodies. Subsequent materialization calls will resume it when
1713 // necessary. For streaming, the function bodies must be at the end of
1714 // the bitcode. If the bitcode file is old, the symbol table will be
1715 // at the end instead and will not have been seen yet. In this case,
1716 // just finish the parse now.
1717 if (LazyStreamer && SeenValueSymbolTable) {
1718 NextUnreadBit = Stream.GetCurrentBitNo();
1719 return error_code::success();
1722 case bitc::USELIST_BLOCK_ID:
1723 if (error_code EC = ParseUseLists())
1729 case BitstreamEntry::Record:
1730 // The interesting case.
1736 switch (Stream.readRecord(Entry.ID, Record)) {
1737 default: break; // Default behavior, ignore unknown content.
1738 case bitc::MODULE_CODE_VERSION: { // VERSION: [version#]
1739 if (Record.size() < 1)
1740 return Error(InvalidRecord);
1741 // Only version #0 and #1 are supported so far.
1742 unsigned module_version = Record[0];
1743 switch (module_version) {
1745 return Error(InvalidValue);
1747 UseRelativeIDs = false;
1750 UseRelativeIDs = true;
1755 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
1757 if (ConvertToString(Record, 0, S))
1758 return Error(InvalidRecord);
1759 TheModule->setTargetTriple(S);
1762 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
1764 if (ConvertToString(Record, 0, S))
1765 return Error(InvalidRecord);
1766 TheModule->setDataLayout(S);
1769 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
1771 if (ConvertToString(Record, 0, S))
1772 return Error(InvalidRecord);
1773 TheModule->setModuleInlineAsm(S);
1776 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
1777 // FIXME: Remove in 4.0.
1779 if (ConvertToString(Record, 0, S))
1780 return Error(InvalidRecord);
1784 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
1786 if (ConvertToString(Record, 0, S))
1787 return Error(InvalidRecord);
1788 SectionTable.push_back(S);
1791 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
1793 if (ConvertToString(Record, 0, S))
1794 return Error(InvalidRecord);
1795 GCTable.push_back(S);
1798 // GLOBALVAR: [pointer type, isconst, initid,
1799 // linkage, alignment, section, visibility, threadlocal,
1801 case bitc::MODULE_CODE_GLOBALVAR: {
1802 if (Record.size() < 6)
1803 return Error(InvalidRecord);
1804 Type *Ty = getTypeByID(Record[0]);
1806 return Error(InvalidRecord);
1807 if (!Ty->isPointerTy())
1808 return Error(InvalidTypeForValue);
1809 unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
1810 Ty = cast<PointerType>(Ty)->getElementType();
1812 bool isConstant = Record[1];
1813 GlobalValue::LinkageTypes Linkage = GetDecodedLinkage(Record[3]);
1814 unsigned Alignment = (1 << Record[4]) >> 1;
1815 std::string Section;
1817 if (Record[5]-1 >= SectionTable.size())
1818 return Error(InvalidID);
1819 Section = SectionTable[Record[5]-1];
1821 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
1822 if (Record.size() > 6)
1823 Visibility = GetDecodedVisibility(Record[6]);
1825 GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
1826 if (Record.size() > 7)
1827 TLM = GetDecodedThreadLocalMode(Record[7]);
1829 bool UnnamedAddr = false;
1830 if (Record.size() > 8)
1831 UnnamedAddr = Record[8];
1833 bool ExternallyInitialized = false;
1834 if (Record.size() > 9)
1835 ExternallyInitialized = Record[9];
1837 GlobalVariable *NewGV =
1838 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, 0, "", 0,
1839 TLM, AddressSpace, ExternallyInitialized);
1840 NewGV->setAlignment(Alignment);
1841 if (!Section.empty())
1842 NewGV->setSection(Section);
1843 NewGV->setVisibility(Visibility);
1844 NewGV->setUnnamedAddr(UnnamedAddr);
1846 ValueList.push_back(NewGV);
1848 // Remember which value to use for the global initializer.
1849 if (unsigned InitID = Record[2])
1850 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
1853 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
1854 // alignment, section, visibility, gc, unnamed_addr]
1855 case bitc::MODULE_CODE_FUNCTION: {
1856 if (Record.size() < 8)
1857 return Error(InvalidRecord);
1858 Type *Ty = getTypeByID(Record[0]);
1860 return Error(InvalidRecord);
1861 if (!Ty->isPointerTy())
1862 return Error(InvalidTypeForValue);
1864 dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
1866 return Error(InvalidTypeForValue);
1868 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
1871 Func->setCallingConv(static_cast<CallingConv::ID>(Record[1]));
1872 bool isProto = Record[2];
1873 Func->setLinkage(GetDecodedLinkage(Record[3]));
1874 Func->setAttributes(getAttributes(Record[4]));
1876 Func->setAlignment((1 << Record[5]) >> 1);
1878 if (Record[6]-1 >= SectionTable.size())
1879 return Error(InvalidID);
1880 Func->setSection(SectionTable[Record[6]-1]);
1882 Func->setVisibility(GetDecodedVisibility(Record[7]));
1883 if (Record.size() > 8 && Record[8]) {
1884 if (Record[8]-1 > GCTable.size())
1885 return Error(InvalidID);
1886 Func->setGC(GCTable[Record[8]-1].c_str());
1888 bool UnnamedAddr = false;
1889 if (Record.size() > 9)
1890 UnnamedAddr = Record[9];
1891 Func->setUnnamedAddr(UnnamedAddr);
1892 if (Record.size() > 10 && Record[10] != 0)
1893 FunctionPrefixes.push_back(std::make_pair(Func, Record[10]-1));
1894 ValueList.push_back(Func);
1896 // If this is a function with a body, remember the prototype we are
1897 // creating now, so that we can match up the body with them later.
1899 FunctionsWithBodies.push_back(Func);
1900 if (LazyStreamer) DeferredFunctionInfo[Func] = 0;
1904 // ALIAS: [alias type, aliasee val#, linkage]
1905 // ALIAS: [alias type, aliasee val#, linkage, visibility]
1906 case bitc::MODULE_CODE_ALIAS: {
1907 if (Record.size() < 3)
1908 return Error(InvalidRecord);
1909 Type *Ty = getTypeByID(Record[0]);
1911 return Error(InvalidRecord);
1912 if (!Ty->isPointerTy())
1913 return Error(InvalidTypeForValue);
1915 GlobalAlias *NewGA = new GlobalAlias(Ty, GetDecodedLinkage(Record[2]),
1917 // Old bitcode files didn't have visibility field.
1918 if (Record.size() > 3)
1919 NewGA->setVisibility(GetDecodedVisibility(Record[3]));
1920 ValueList.push_back(NewGA);
1921 AliasInits.push_back(std::make_pair(NewGA, Record[1]));
1924 /// MODULE_CODE_PURGEVALS: [numvals]
1925 case bitc::MODULE_CODE_PURGEVALS:
1926 // Trim down the value list to the specified size.
1927 if (Record.size() < 1 || Record[0] > ValueList.size())
1928 return Error(InvalidRecord);
1929 ValueList.shrinkTo(Record[0]);
1936 error_code BitcodeReader::ParseBitcodeInto(Module *M) {
1939 if (error_code EC = InitStream())
1942 // Sniff for the signature.
1943 if (Stream.Read(8) != 'B' ||
1944 Stream.Read(8) != 'C' ||
1945 Stream.Read(4) != 0x0 ||
1946 Stream.Read(4) != 0xC ||
1947 Stream.Read(4) != 0xE ||
1948 Stream.Read(4) != 0xD)
1949 return Error(InvalidBitcodeSignature);
1951 // We expect a number of well-defined blocks, though we don't necessarily
1952 // need to understand them all.
1954 if (Stream.AtEndOfStream())
1955 return error_code::success();
1957 BitstreamEntry Entry =
1958 Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
1960 switch (Entry.Kind) {
1961 case BitstreamEntry::Error:
1962 return Error(MalformedBlock);
1963 case BitstreamEntry::EndBlock:
1964 return error_code::success();
1966 case BitstreamEntry::SubBlock:
1968 case bitc::BLOCKINFO_BLOCK_ID:
1969 if (Stream.ReadBlockInfoBlock())
1970 return Error(MalformedBlock);
1972 case bitc::MODULE_BLOCK_ID:
1973 // Reject multiple MODULE_BLOCK's in a single bitstream.
1975 return Error(InvalidMultipleBlocks);
1977 if (error_code EC = ParseModule(false))
1980 return error_code::success();
1983 if (Stream.SkipBlock())
1984 return Error(InvalidRecord);
1988 case BitstreamEntry::Record:
1989 // There should be no records in the top-level of blocks.
1991 // The ranlib in Xcode 4 will align archive members by appending newlines
1992 // to the end of them. If this file size is a multiple of 4 but not 8, we
1993 // have to read and ignore these final 4 bytes :-(
1994 if (Stream.getAbbrevIDWidth() == 2 && Entry.ID == 2 &&
1995 Stream.Read(6) == 2 && Stream.Read(24) == 0xa0a0a &&
1996 Stream.AtEndOfStream())
1997 return error_code::success();
1999 return Error(InvalidRecord);
2004 error_code BitcodeReader::ParseModuleTriple(std::string &Triple) {
2005 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
2006 return Error(InvalidRecord);
2008 SmallVector<uint64_t, 64> Record;
2010 // Read all the records for this module.
2012 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2014 switch (Entry.Kind) {
2015 case BitstreamEntry::SubBlock: // Handled for us already.
2016 case BitstreamEntry::Error:
2017 return Error(MalformedBlock);
2018 case BitstreamEntry::EndBlock:
2019 return error_code::success();
2020 case BitstreamEntry::Record:
2021 // The interesting case.
2026 switch (Stream.readRecord(Entry.ID, Record)) {
2027 default: break; // Default behavior, ignore unknown content.
2028 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
2030 if (ConvertToString(Record, 0, S))
2031 return Error(InvalidRecord);
2040 error_code BitcodeReader::ParseTriple(std::string &Triple) {
2041 if (error_code EC = InitStream())
2044 // Sniff for the signature.
2045 if (Stream.Read(8) != 'B' ||
2046 Stream.Read(8) != 'C' ||
2047 Stream.Read(4) != 0x0 ||
2048 Stream.Read(4) != 0xC ||
2049 Stream.Read(4) != 0xE ||
2050 Stream.Read(4) != 0xD)
2051 return Error(InvalidBitcodeSignature);
2053 // We expect a number of well-defined blocks, though we don't necessarily
2054 // need to understand them all.
2056 BitstreamEntry Entry = Stream.advance();
2058 switch (Entry.Kind) {
2059 case BitstreamEntry::Error:
2060 return Error(MalformedBlock);
2061 case BitstreamEntry::EndBlock:
2062 return error_code::success();
2064 case BitstreamEntry::SubBlock:
2065 if (Entry.ID == bitc::MODULE_BLOCK_ID)
2066 return ParseModuleTriple(Triple);
2068 // Ignore other sub-blocks.
2069 if (Stream.SkipBlock())
2070 return Error(MalformedBlock);
2073 case BitstreamEntry::Record:
2074 Stream.skipRecord(Entry.ID);
2080 /// ParseMetadataAttachment - Parse metadata attachments.
2081 error_code BitcodeReader::ParseMetadataAttachment() {
2082 if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
2083 return Error(InvalidRecord);
2085 SmallVector<uint64_t, 64> Record;
2087 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2089 switch (Entry.Kind) {
2090 case BitstreamEntry::SubBlock: // Handled for us already.
2091 case BitstreamEntry::Error:
2092 return Error(MalformedBlock);
2093 case BitstreamEntry::EndBlock:
2094 return error_code::success();
2095 case BitstreamEntry::Record:
2096 // The interesting case.
2100 // Read a metadata attachment record.
2102 switch (Stream.readRecord(Entry.ID, Record)) {
2103 default: // Default behavior: ignore.
2105 case bitc::METADATA_ATTACHMENT: {
2106 unsigned RecordLength = Record.size();
2107 if (Record.empty() || (RecordLength - 1) % 2 == 1)
2108 return Error(InvalidRecord);
2109 Instruction *Inst = InstructionList[Record[0]];
2110 for (unsigned i = 1; i != RecordLength; i = i+2) {
2111 unsigned Kind = Record[i];
2112 DenseMap<unsigned, unsigned>::iterator I =
2113 MDKindMap.find(Kind);
2114 if (I == MDKindMap.end())
2115 return Error(InvalidID);
2116 Value *Node = MDValueList.getValueFwdRef(Record[i+1]);
2117 Inst->setMetadata(I->second, cast<MDNode>(Node));
2118 if (I->second == LLVMContext::MD_tbaa)
2119 InstsWithTBAATag.push_back(Inst);
2127 /// ParseFunctionBody - Lazily parse the specified function body block.
2128 error_code BitcodeReader::ParseFunctionBody(Function *F) {
2129 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
2130 return Error(InvalidRecord);
2132 InstructionList.clear();
2133 unsigned ModuleValueListSize = ValueList.size();
2134 unsigned ModuleMDValueListSize = MDValueList.size();
2136 // Add all the function arguments to the value table.
2137 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
2138 ValueList.push_back(I);
2140 unsigned NextValueNo = ValueList.size();
2141 BasicBlock *CurBB = 0;
2142 unsigned CurBBNo = 0;
2146 // Read all the records.
2147 SmallVector<uint64_t, 64> Record;
2149 BitstreamEntry Entry = Stream.advance();
2151 switch (Entry.Kind) {
2152 case BitstreamEntry::Error:
2153 return Error(MalformedBlock);
2154 case BitstreamEntry::EndBlock:
2155 goto OutOfRecordLoop;
2157 case BitstreamEntry::SubBlock:
2159 default: // Skip unknown content.
2160 if (Stream.SkipBlock())
2161 return Error(InvalidRecord);
2163 case bitc::CONSTANTS_BLOCK_ID:
2164 if (error_code EC = ParseConstants())
2166 NextValueNo = ValueList.size();
2168 case bitc::VALUE_SYMTAB_BLOCK_ID:
2169 if (error_code EC = ParseValueSymbolTable())
2172 case bitc::METADATA_ATTACHMENT_ID:
2173 if (error_code EC = ParseMetadataAttachment())
2176 case bitc::METADATA_BLOCK_ID:
2177 if (error_code EC = ParseMetadata())
2183 case BitstreamEntry::Record:
2184 // The interesting case.
2191 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
2193 default: // Default behavior: reject
2194 return Error(InvalidValue);
2195 case bitc::FUNC_CODE_DECLAREBLOCKS: // DECLAREBLOCKS: [nblocks]
2196 if (Record.size() < 1 || Record[0] == 0)
2197 return Error(InvalidRecord);
2198 // Create all the basic blocks for the function.
2199 FunctionBBs.resize(Record[0]);
2200 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
2201 FunctionBBs[i] = BasicBlock::Create(Context, "", F);
2202 CurBB = FunctionBBs[0];
2205 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN
2206 // This record indicates that the last instruction is at the same
2207 // location as the previous instruction with a location.
2210 // Get the last instruction emitted.
2211 if (CurBB && !CurBB->empty())
2213 else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
2214 !FunctionBBs[CurBBNo-1]->empty())
2215 I = &FunctionBBs[CurBBNo-1]->back();
2218 return Error(InvalidRecord);
2219 I->setDebugLoc(LastLoc);
2223 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia]
2224 I = 0; // Get the last instruction emitted.
2225 if (CurBB && !CurBB->empty())
2227 else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
2228 !FunctionBBs[CurBBNo-1]->empty())
2229 I = &FunctionBBs[CurBBNo-1]->back();
2230 if (I == 0 || Record.size() < 4)
2231 return Error(InvalidRecord);
2233 unsigned Line = Record[0], Col = Record[1];
2234 unsigned ScopeID = Record[2], IAID = Record[3];
2236 MDNode *Scope = 0, *IA = 0;
2237 if (ScopeID) Scope = cast<MDNode>(MDValueList.getValueFwdRef(ScopeID-1));
2238 if (IAID) IA = cast<MDNode>(MDValueList.getValueFwdRef(IAID-1));
2239 LastLoc = DebugLoc::get(Line, Col, Scope, IA);
2240 I->setDebugLoc(LastLoc);
2245 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
2248 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
2249 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
2250 OpNum+1 > Record.size())
2251 return Error(InvalidRecord);
2253 int Opc = GetDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
2255 return Error(InvalidRecord);
2256 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
2257 InstructionList.push_back(I);
2258 if (OpNum < Record.size()) {
2259 if (Opc == Instruction::Add ||
2260 Opc == Instruction::Sub ||
2261 Opc == Instruction::Mul ||
2262 Opc == Instruction::Shl) {
2263 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
2264 cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
2265 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
2266 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
2267 } else if (Opc == Instruction::SDiv ||
2268 Opc == Instruction::UDiv ||
2269 Opc == Instruction::LShr ||
2270 Opc == Instruction::AShr) {
2271 if (Record[OpNum] & (1 << bitc::PEO_EXACT))
2272 cast<BinaryOperator>(I)->setIsExact(true);
2273 } else if (isa<FPMathOperator>(I)) {
2275 if (0 != (Record[OpNum] & FastMathFlags::UnsafeAlgebra))
2276 FMF.setUnsafeAlgebra();
2277 if (0 != (Record[OpNum] & FastMathFlags::NoNaNs))
2279 if (0 != (Record[OpNum] & FastMathFlags::NoInfs))
2281 if (0 != (Record[OpNum] & FastMathFlags::NoSignedZeros))
2282 FMF.setNoSignedZeros();
2283 if (0 != (Record[OpNum] & FastMathFlags::AllowReciprocal))
2284 FMF.setAllowReciprocal();
2286 I->setFastMathFlags(FMF);
2292 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
2295 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2296 OpNum+2 != Record.size())
2297 return Error(InvalidRecord);
2299 Type *ResTy = getTypeByID(Record[OpNum]);
2300 int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
2301 if (Opc == -1 || ResTy == 0)
2302 return Error(InvalidRecord);
2303 Instruction *Temp = 0;
2304 if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) {
2306 InstructionList.push_back(Temp);
2307 CurBB->getInstList().push_back(Temp);
2310 I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
2312 InstructionList.push_back(I);
2315 case bitc::FUNC_CODE_INST_INBOUNDS_GEP:
2316 case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands]
2319 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
2320 return Error(InvalidRecord);
2322 SmallVector<Value*, 16> GEPIdx;
2323 while (OpNum != Record.size()) {
2325 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2326 return Error(InvalidRecord);
2327 GEPIdx.push_back(Op);
2330 I = GetElementPtrInst::Create(BasePtr, GEPIdx);
2331 InstructionList.push_back(I);
2332 if (BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP)
2333 cast<GetElementPtrInst>(I)->setIsInBounds(true);
2337 case bitc::FUNC_CODE_INST_EXTRACTVAL: {
2338 // EXTRACTVAL: [opty, opval, n x indices]
2341 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2342 return Error(InvalidRecord);
2344 SmallVector<unsigned, 4> EXTRACTVALIdx;
2345 for (unsigned RecSize = Record.size();
2346 OpNum != RecSize; ++OpNum) {
2347 uint64_t Index = Record[OpNum];
2348 if ((unsigned)Index != Index)
2349 return Error(InvalidValue);
2350 EXTRACTVALIdx.push_back((unsigned)Index);
2353 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
2354 InstructionList.push_back(I);
2358 case bitc::FUNC_CODE_INST_INSERTVAL: {
2359 // INSERTVAL: [opty, opval, opty, opval, n x indices]
2362 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2363 return Error(InvalidRecord);
2365 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
2366 return Error(InvalidRecord);
2368 SmallVector<unsigned, 4> INSERTVALIdx;
2369 for (unsigned RecSize = Record.size();
2370 OpNum != RecSize; ++OpNum) {
2371 uint64_t Index = Record[OpNum];
2372 if ((unsigned)Index != Index)
2373 return Error(InvalidValue);
2374 INSERTVALIdx.push_back((unsigned)Index);
2377 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
2378 InstructionList.push_back(I);
2382 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
2383 // obsolete form of select
2384 // handles select i1 ... in old bitcode
2386 Value *TrueVal, *FalseVal, *Cond;
2387 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
2388 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
2389 popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond))
2390 return Error(InvalidRecord);
2392 I = SelectInst::Create(Cond, TrueVal, FalseVal);
2393 InstructionList.push_back(I);
2397 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
2398 // new form of select
2399 // handles select i1 or select [N x i1]
2401 Value *TrueVal, *FalseVal, *Cond;
2402 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
2403 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
2404 getValueTypePair(Record, OpNum, NextValueNo, Cond))
2405 return Error(InvalidRecord);
2407 // select condition can be either i1 or [N x i1]
2408 if (VectorType* vector_type =
2409 dyn_cast<VectorType>(Cond->getType())) {
2411 if (vector_type->getElementType() != Type::getInt1Ty(Context))
2412 return Error(InvalidTypeForValue);
2415 if (Cond->getType() != Type::getInt1Ty(Context))
2416 return Error(InvalidTypeForValue);
2419 I = SelectInst::Create(Cond, TrueVal, FalseVal);
2420 InstructionList.push_back(I);
2424 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
2427 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
2428 popValue(Record, OpNum, NextValueNo, Type::getInt32Ty(Context), Idx))
2429 return Error(InvalidRecord);
2430 I = ExtractElementInst::Create(Vec, Idx);
2431 InstructionList.push_back(I);
2435 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
2437 Value *Vec, *Elt, *Idx;
2438 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
2439 popValue(Record, OpNum, NextValueNo,
2440 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
2441 popValue(Record, OpNum, NextValueNo, Type::getInt32Ty(Context), Idx))
2442 return Error(InvalidRecord);
2443 I = InsertElementInst::Create(Vec, Elt, Idx);
2444 InstructionList.push_back(I);
2448 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
2450 Value *Vec1, *Vec2, *Mask;
2451 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
2452 popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2))
2453 return Error(InvalidRecord);
2455 if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
2456 return Error(InvalidRecord);
2457 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
2458 InstructionList.push_back(I);
2462 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
2463 // Old form of ICmp/FCmp returning bool
2464 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
2465 // both legal on vectors but had different behaviour.
2466 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
2467 // FCmp/ICmp returning bool or vector of bool
2471 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
2472 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
2473 OpNum+1 != Record.size())
2474 return Error(InvalidRecord);
2476 if (LHS->getType()->isFPOrFPVectorTy())
2477 I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
2479 I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
2480 InstructionList.push_back(I);
2484 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
2486 unsigned Size = Record.size();
2488 I = ReturnInst::Create(Context);
2489 InstructionList.push_back(I);
2495 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2496 return Error(InvalidRecord);
2497 if (OpNum != Record.size())
2498 return Error(InvalidRecord);
2500 I = ReturnInst::Create(Context, Op);
2501 InstructionList.push_back(I);
2504 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
2505 if (Record.size() != 1 && Record.size() != 3)
2506 return Error(InvalidRecord);
2507 BasicBlock *TrueDest = getBasicBlock(Record[0]);
2509 return Error(InvalidRecord);
2511 if (Record.size() == 1) {
2512 I = BranchInst::Create(TrueDest);
2513 InstructionList.push_back(I);
2516 BasicBlock *FalseDest = getBasicBlock(Record[1]);
2517 Value *Cond = getValue(Record, 2, NextValueNo,
2518 Type::getInt1Ty(Context));
2519 if (FalseDest == 0 || Cond == 0)
2520 return Error(InvalidRecord);
2521 I = BranchInst::Create(TrueDest, FalseDest, Cond);
2522 InstructionList.push_back(I);
2526 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
2528 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
2529 // "New" SwitchInst format with case ranges. The changes to write this
2530 // format were reverted but we still recognize bitcode that uses it.
2531 // Hopefully someday we will have support for case ranges and can use
2532 // this format again.
2534 Type *OpTy = getTypeByID(Record[1]);
2535 unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
2537 Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
2538 BasicBlock *Default = getBasicBlock(Record[3]);
2539 if (OpTy == 0 || Cond == 0 || Default == 0)
2540 return Error(InvalidRecord);
2542 unsigned NumCases = Record[4];
2544 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
2545 InstructionList.push_back(SI);
2547 unsigned CurIdx = 5;
2548 for (unsigned i = 0; i != NumCases; ++i) {
2549 SmallVector<ConstantInt*, 1> CaseVals;
2550 unsigned NumItems = Record[CurIdx++];
2551 for (unsigned ci = 0; ci != NumItems; ++ci) {
2552 bool isSingleNumber = Record[CurIdx++];
2555 unsigned ActiveWords = 1;
2556 if (ValueBitWidth > 64)
2557 ActiveWords = Record[CurIdx++];
2558 Low = ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
2560 CurIdx += ActiveWords;
2562 if (!isSingleNumber) {
2564 if (ValueBitWidth > 64)
2565 ActiveWords = Record[CurIdx++];
2567 ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
2569 CurIdx += ActiveWords;
2571 // FIXME: It is not clear whether values in the range should be
2572 // compared as signed or unsigned values. The partially
2573 // implemented changes that used this format in the past used
2574 // unsigned comparisons.
2575 for ( ; Low.ule(High); ++Low)
2576 CaseVals.push_back(ConstantInt::get(Context, Low));
2578 CaseVals.push_back(ConstantInt::get(Context, Low));
2580 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
2581 for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(),
2582 cve = CaseVals.end(); cvi != cve; ++cvi)
2583 SI->addCase(*cvi, DestBB);
2589 // Old SwitchInst format without case ranges.
2591 if (Record.size() < 3 || (Record.size() & 1) == 0)
2592 return Error(InvalidRecord);
2593 Type *OpTy = getTypeByID(Record[0]);
2594 Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
2595 BasicBlock *Default = getBasicBlock(Record[2]);
2596 if (OpTy == 0 || Cond == 0 || Default == 0)
2597 return Error(InvalidRecord);
2598 unsigned NumCases = (Record.size()-3)/2;
2599 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
2600 InstructionList.push_back(SI);
2601 for (unsigned i = 0, e = NumCases; i != e; ++i) {
2602 ConstantInt *CaseVal =
2603 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
2604 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
2605 if (CaseVal == 0 || DestBB == 0) {
2607 return Error(InvalidRecord);
2609 SI->addCase(CaseVal, DestBB);
2614 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
2615 if (Record.size() < 2)
2616 return Error(InvalidRecord);
2617 Type *OpTy = getTypeByID(Record[0]);
2618 Value *Address = getValue(Record, 1, NextValueNo, OpTy);
2619 if (OpTy == 0 || Address == 0)
2620 return Error(InvalidRecord);
2621 unsigned NumDests = Record.size()-2;
2622 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
2623 InstructionList.push_back(IBI);
2624 for (unsigned i = 0, e = NumDests; i != e; ++i) {
2625 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
2626 IBI->addDestination(DestBB);
2629 return Error(InvalidRecord);
2636 case bitc::FUNC_CODE_INST_INVOKE: {
2637 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
2638 if (Record.size() < 4)
2639 return Error(InvalidRecord);
2640 AttributeSet PAL = getAttributes(Record[0]);
2641 unsigned CCInfo = Record[1];
2642 BasicBlock *NormalBB = getBasicBlock(Record[2]);
2643 BasicBlock *UnwindBB = getBasicBlock(Record[3]);
2647 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
2648 return Error(InvalidRecord);
2650 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
2651 FunctionType *FTy = !CalleeTy ? 0 :
2652 dyn_cast<FunctionType>(CalleeTy->getElementType());
2654 // Check that the right number of fixed parameters are here.
2655 if (FTy == 0 || NormalBB == 0 || UnwindBB == 0 ||
2656 Record.size() < OpNum+FTy->getNumParams())
2657 return Error(InvalidRecord);
2659 SmallVector<Value*, 16> Ops;
2660 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
2661 Ops.push_back(getValue(Record, OpNum, NextValueNo,
2662 FTy->getParamType(i)));
2663 if (Ops.back() == 0)
2664 return Error(InvalidRecord);
2667 if (!FTy->isVarArg()) {
2668 if (Record.size() != OpNum)
2669 return Error(InvalidRecord);
2671 // Read type/value pairs for varargs params.
2672 while (OpNum != Record.size()) {
2674 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2675 return Error(InvalidRecord);
2680 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops);
2681 InstructionList.push_back(I);
2682 cast<InvokeInst>(I)->setCallingConv(
2683 static_cast<CallingConv::ID>(CCInfo));
2684 cast<InvokeInst>(I)->setAttributes(PAL);
2687 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
2690 if (getValueTypePair(Record, Idx, NextValueNo, Val))
2691 return Error(InvalidRecord);
2692 I = ResumeInst::Create(Val);
2693 InstructionList.push_back(I);
2696 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
2697 I = new UnreachableInst(Context);
2698 InstructionList.push_back(I);
2700 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
2701 if (Record.size() < 1 || ((Record.size()-1)&1))
2702 return Error(InvalidRecord);
2703 Type *Ty = getTypeByID(Record[0]);
2705 return Error(InvalidRecord);
2707 PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
2708 InstructionList.push_back(PN);
2710 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
2712 // With the new function encoding, it is possible that operands have
2713 // negative IDs (for forward references). Use a signed VBR
2714 // representation to keep the encoding small.
2716 V = getValueSigned(Record, 1+i, NextValueNo, Ty);
2718 V = getValue(Record, 1+i, NextValueNo, Ty);
2719 BasicBlock *BB = getBasicBlock(Record[2+i]);
2721 return Error(InvalidRecord);
2722 PN->addIncoming(V, BB);
2728 case bitc::FUNC_CODE_INST_LANDINGPAD: {
2729 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
2731 if (Record.size() < 4)
2732 return Error(InvalidRecord);
2733 Type *Ty = getTypeByID(Record[Idx++]);
2735 return Error(InvalidRecord);
2737 if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
2738 return Error(InvalidRecord);
2740 bool IsCleanup = !!Record[Idx++];
2741 unsigned NumClauses = Record[Idx++];
2742 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, NumClauses);
2743 LP->setCleanup(IsCleanup);
2744 for (unsigned J = 0; J != NumClauses; ++J) {
2745 LandingPadInst::ClauseType CT =
2746 LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
2749 if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
2751 return Error(InvalidRecord);
2754 assert((CT != LandingPadInst::Catch ||
2755 !isa<ArrayType>(Val->getType())) &&
2756 "Catch clause has a invalid type!");
2757 assert((CT != LandingPadInst::Filter ||
2758 isa<ArrayType>(Val->getType())) &&
2759 "Filter clause has invalid type!");
2764 InstructionList.push_back(I);
2768 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
2769 if (Record.size() != 4)
2770 return Error(InvalidRecord);
2772 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
2773 Type *OpTy = getTypeByID(Record[1]);
2774 Value *Size = getFnValueByID(Record[2], OpTy);
2775 unsigned Align = Record[3];
2777 return Error(InvalidRecord);
2778 I = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
2779 InstructionList.push_back(I);
2782 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
2785 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2786 OpNum+2 != Record.size())
2787 return Error(InvalidRecord);
2789 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1);
2790 InstructionList.push_back(I);
2793 case bitc::FUNC_CODE_INST_LOADATOMIC: {
2794 // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
2797 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2798 OpNum+4 != Record.size())
2799 return Error(InvalidRecord);
2802 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
2803 if (Ordering == NotAtomic || Ordering == Release ||
2804 Ordering == AcquireRelease)
2805 return Error(InvalidRecord);
2806 if (Ordering != NotAtomic && Record[OpNum] == 0)
2807 return Error(InvalidRecord);
2808 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2810 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1,
2811 Ordering, SynchScope);
2812 InstructionList.push_back(I);
2815 case bitc::FUNC_CODE_INST_STORE: { // STORE2:[ptrty, ptr, val, align, vol]
2818 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2819 popValue(Record, OpNum, NextValueNo,
2820 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2821 OpNum+2 != Record.size())
2822 return Error(InvalidRecord);
2824 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
2825 InstructionList.push_back(I);
2828 case bitc::FUNC_CODE_INST_STOREATOMIC: {
2829 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
2832 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2833 popValue(Record, OpNum, NextValueNo,
2834 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2835 OpNum+4 != Record.size())
2836 return Error(InvalidRecord);
2838 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
2839 if (Ordering == NotAtomic || Ordering == Acquire ||
2840 Ordering == AcquireRelease)
2841 return Error(InvalidRecord);
2842 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2843 if (Ordering != NotAtomic && Record[OpNum] == 0)
2844 return Error(InvalidRecord);
2846 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1,
2847 Ordering, SynchScope);
2848 InstructionList.push_back(I);
2851 case bitc::FUNC_CODE_INST_CMPXCHG: {
2852 // CMPXCHG:[ptrty, ptr, cmp, new, vol, ordering, synchscope]
2854 Value *Ptr, *Cmp, *New;
2855 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2856 popValue(Record, OpNum, NextValueNo,
2857 cast<PointerType>(Ptr->getType())->getElementType(), Cmp) ||
2858 popValue(Record, OpNum, NextValueNo,
2859 cast<PointerType>(Ptr->getType())->getElementType(), New) ||
2860 OpNum+3 != Record.size())
2861 return Error(InvalidRecord);
2862 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+1]);
2863 if (Ordering == NotAtomic || Ordering == Unordered)
2864 return Error(InvalidRecord);
2865 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+2]);
2866 I = new AtomicCmpXchgInst(Ptr, Cmp, New, Ordering, SynchScope);
2867 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
2868 InstructionList.push_back(I);
2871 case bitc::FUNC_CODE_INST_ATOMICRMW: {
2872 // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
2875 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2876 popValue(Record, OpNum, NextValueNo,
2877 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2878 OpNum+4 != Record.size())
2879 return Error(InvalidRecord);
2880 AtomicRMWInst::BinOp Operation = GetDecodedRMWOperation(Record[OpNum]);
2881 if (Operation < AtomicRMWInst::FIRST_BINOP ||
2882 Operation > AtomicRMWInst::LAST_BINOP)
2883 return Error(InvalidRecord);
2884 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
2885 if (Ordering == NotAtomic || Ordering == Unordered)
2886 return Error(InvalidRecord);
2887 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2888 I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
2889 cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
2890 InstructionList.push_back(I);
2893 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
2894 if (2 != Record.size())
2895 return Error(InvalidRecord);
2896 AtomicOrdering Ordering = GetDecodedOrdering(Record[0]);
2897 if (Ordering == NotAtomic || Ordering == Unordered ||
2898 Ordering == Monotonic)
2899 return Error(InvalidRecord);
2900 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[1]);
2901 I = new FenceInst(Context, Ordering, SynchScope);
2902 InstructionList.push_back(I);
2905 case bitc::FUNC_CODE_INST_CALL: {
2906 // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
2907 if (Record.size() < 3)
2908 return Error(InvalidRecord);
2910 AttributeSet PAL = getAttributes(Record[0]);
2911 unsigned CCInfo = Record[1];
2915 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
2916 return Error(InvalidRecord);
2918 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
2919 FunctionType *FTy = 0;
2920 if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
2921 if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
2922 return Error(InvalidRecord);
2924 SmallVector<Value*, 16> Args;
2925 // Read the fixed params.
2926 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
2927 if (FTy->getParamType(i)->isLabelTy())
2928 Args.push_back(getBasicBlock(Record[OpNum]));
2930 Args.push_back(getValue(Record, OpNum, NextValueNo,
2931 FTy->getParamType(i)));
2932 if (Args.back() == 0)
2933 return Error(InvalidRecord);
2936 // Read type/value pairs for varargs params.
2937 if (!FTy->isVarArg()) {
2938 if (OpNum != Record.size())
2939 return Error(InvalidRecord);
2941 while (OpNum != Record.size()) {
2943 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2944 return Error(InvalidRecord);
2949 I = CallInst::Create(Callee, Args);
2950 InstructionList.push_back(I);
2951 cast<CallInst>(I)->setCallingConv(
2952 static_cast<CallingConv::ID>(CCInfo>>1));
2953 cast<CallInst>(I)->setTailCall(CCInfo & 1);
2954 cast<CallInst>(I)->setAttributes(PAL);
2957 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
2958 if (Record.size() < 3)
2959 return Error(InvalidRecord);
2960 Type *OpTy = getTypeByID(Record[0]);
2961 Value *Op = getValue(Record, 1, NextValueNo, OpTy);
2962 Type *ResTy = getTypeByID(Record[2]);
2963 if (!OpTy || !Op || !ResTy)
2964 return Error(InvalidRecord);
2965 I = new VAArgInst(Op, ResTy);
2966 InstructionList.push_back(I);
2971 // Add instruction to end of current BB. If there is no current BB, reject
2975 return Error(InvalidInstructionWithNoBB);
2977 CurBB->getInstList().push_back(I);
2979 // If this was a terminator instruction, move to the next block.
2980 if (isa<TerminatorInst>(I)) {
2982 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : 0;
2985 // Non-void values get registered in the value table for future use.
2986 if (I && !I->getType()->isVoidTy())
2987 ValueList.AssignValue(I, NextValueNo++);
2992 // Check the function list for unresolved values.
2993 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
2994 if (A->getParent() == 0) {
2995 // We found at least one unresolved value. Nuke them all to avoid leaks.
2996 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
2997 if ((A = dyn_cast<Argument>(ValueList[i])) && A->getParent() == 0) {
2998 A->replaceAllUsesWith(UndefValue::get(A->getType()));
3002 return Error(NeverResolvedValueFoundInFunction);
3006 // FIXME: Check for unresolved forward-declared metadata references
3007 // and clean up leaks.
3009 // See if anything took the address of blocks in this function. If so,
3010 // resolve them now.
3011 DenseMap<Function*, std::vector<BlockAddrRefTy> >::iterator BAFRI =
3012 BlockAddrFwdRefs.find(F);
3013 if (BAFRI != BlockAddrFwdRefs.end()) {
3014 std::vector<BlockAddrRefTy> &RefList = BAFRI->second;
3015 for (unsigned i = 0, e = RefList.size(); i != e; ++i) {
3016 unsigned BlockIdx = RefList[i].first;
3017 if (BlockIdx >= FunctionBBs.size())
3018 return Error(InvalidID);
3020 GlobalVariable *FwdRef = RefList[i].second;
3021 FwdRef->replaceAllUsesWith(BlockAddress::get(F, FunctionBBs[BlockIdx]));
3022 FwdRef->eraseFromParent();
3025 BlockAddrFwdRefs.erase(BAFRI);
3028 // Trim the value list down to the size it was before we parsed this function.
3029 ValueList.shrinkTo(ModuleValueListSize);
3030 MDValueList.shrinkTo(ModuleMDValueListSize);
3031 std::vector<BasicBlock*>().swap(FunctionBBs);
3032 return error_code::success();
3035 /// Find the function body in the bitcode stream
3036 error_code BitcodeReader::FindFunctionInStream(Function *F,
3037 DenseMap<Function*, uint64_t>::iterator DeferredFunctionInfoIterator) {
3038 while (DeferredFunctionInfoIterator->second == 0) {
3039 if (Stream.AtEndOfStream())
3040 return Error(CouldNotFindFunctionInStream);
3041 // ParseModule will parse the next body in the stream and set its
3042 // position in the DeferredFunctionInfo map.
3043 if (error_code EC = ParseModule(true))
3046 return error_code::success();
3049 //===----------------------------------------------------------------------===//
3050 // GVMaterializer implementation
3051 //===----------------------------------------------------------------------===//
3054 bool BitcodeReader::isMaterializable(const GlobalValue *GV) const {
3055 if (const Function *F = dyn_cast<Function>(GV)) {
3056 return F->isDeclaration() &&
3057 DeferredFunctionInfo.count(const_cast<Function*>(F));
3062 error_code BitcodeReader::Materialize(GlobalValue *GV) {
3063 Function *F = dyn_cast<Function>(GV);
3064 // If it's not a function or is already material, ignore the request.
3065 if (!F || !F->isMaterializable())
3066 return error_code::success();
3068 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
3069 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
3070 // If its position is recorded as 0, its body is somewhere in the stream
3071 // but we haven't seen it yet.
3072 if (DFII->second == 0 && LazyStreamer)
3073 if (error_code EC = FindFunctionInStream(F, DFII))
3076 // Move the bit stream to the saved position of the deferred function body.
3077 Stream.JumpToBit(DFII->second);
3079 if (error_code EC = ParseFunctionBody(F))
3082 // Upgrade any old intrinsic calls in the function.
3083 for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
3084 E = UpgradedIntrinsics.end(); I != E; ++I) {
3085 if (I->first != I->second) {
3086 for (Value::use_iterator UI = I->first->use_begin(),
3087 UE = I->first->use_end(); UI != UE; ) {
3088 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
3089 UpgradeIntrinsicCall(CI, I->second);
3094 return error_code::success();
3097 bool BitcodeReader::isDematerializable(const GlobalValue *GV) const {
3098 const Function *F = dyn_cast<Function>(GV);
3099 if (!F || F->isDeclaration())
3101 return DeferredFunctionInfo.count(const_cast<Function*>(F));
3104 void BitcodeReader::Dematerialize(GlobalValue *GV) {
3105 Function *F = dyn_cast<Function>(GV);
3106 // If this function isn't dematerializable, this is a noop.
3107 if (!F || !isDematerializable(F))
3110 assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
3112 // Just forget the function body, we can remat it later.
3117 error_code BitcodeReader::MaterializeModule(Module *M) {
3118 assert(M == TheModule &&
3119 "Can only Materialize the Module this BitcodeReader is attached to.");
3120 // Iterate over the module, deserializing any functions that are still on
3122 for (Module::iterator F = TheModule->begin(), E = TheModule->end();
3124 if (F->isMaterializable()) {
3125 if (error_code EC = Materialize(F))
3129 // At this point, if there are any function bodies, the current bit is
3130 // pointing to the END_BLOCK record after them. Now make sure the rest
3131 // of the bits in the module have been read.
3135 // Upgrade any intrinsic calls that slipped through (should not happen!) and
3136 // delete the old functions to clean up. We can't do this unless the entire
3137 // module is materialized because there could always be another function body
3138 // with calls to the old function.
3139 for (std::vector<std::pair<Function*, Function*> >::iterator I =
3140 UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
3141 if (I->first != I->second) {
3142 for (Value::use_iterator UI = I->first->use_begin(),
3143 UE = I->first->use_end(); UI != UE; ) {
3144 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
3145 UpgradeIntrinsicCall(CI, I->second);
3147 if (!I->first->use_empty())
3148 I->first->replaceAllUsesWith(I->second);
3149 I->first->eraseFromParent();
3152 std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
3154 for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
3155 UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
3157 UpgradeDebugInfo(*M);
3158 return error_code::success();
3161 error_code BitcodeReader::InitStream() {
3163 return InitLazyStream();
3164 return InitStreamFromBuffer();
3167 error_code BitcodeReader::InitStreamFromBuffer() {
3168 const unsigned char *BufPtr = (const unsigned char*)Buffer->getBufferStart();
3169 const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
3171 if (Buffer->getBufferSize() & 3) {
3172 if (!isRawBitcode(BufPtr, BufEnd) && !isBitcodeWrapper(BufPtr, BufEnd))
3173 return Error(InvalidBitcodeSignature);
3175 return Error(BitcodeStreamInvalidSize);
3178 // If we have a wrapper header, parse it and ignore the non-bc file contents.
3179 // The magic number is 0x0B17C0DE stored in little endian.
3180 if (isBitcodeWrapper(BufPtr, BufEnd))
3181 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
3182 return Error(InvalidBitcodeWrapperHeader);
3184 StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
3185 Stream.init(*StreamFile);
3187 return error_code::success();
3190 error_code BitcodeReader::InitLazyStream() {
3191 // Check and strip off the bitcode wrapper; BitstreamReader expects never to
3193 StreamingMemoryObject *Bytes = new StreamingMemoryObject(LazyStreamer);
3194 StreamFile.reset(new BitstreamReader(Bytes));
3195 Stream.init(*StreamFile);
3197 unsigned char buf[16];
3198 if (Bytes->readBytes(0, 16, buf) == -1)
3199 return Error(BitcodeStreamInvalidSize);
3201 if (!isBitcode(buf, buf + 16))
3202 return Error(InvalidBitcodeSignature);
3204 if (isBitcodeWrapper(buf, buf + 4)) {
3205 const unsigned char *bitcodeStart = buf;
3206 const unsigned char *bitcodeEnd = buf + 16;
3207 SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
3208 Bytes->dropLeadingBytes(bitcodeStart - buf);
3209 Bytes->setKnownObjectSize(bitcodeEnd - bitcodeStart);
3211 return error_code::success();
3215 class BitcodeErrorCategoryType : public _do_message {
3216 const char *name() const LLVM_OVERRIDE {
3217 return "llvm.bitcode";
3219 std::string message(int IE) const LLVM_OVERRIDE {
3220 BitcodeReader::ErrorType E = static_cast<BitcodeReader::ErrorType>(IE);
3222 case BitcodeReader::BitcodeStreamInvalidSize:
3223 return "Bitcode stream length should be >= 16 bytes and a multiple of 4";
3224 case BitcodeReader::ConflictingMETADATA_KINDRecords:
3225 return "Conflicting METADATA_KIND records";
3226 case BitcodeReader::CouldNotFindFunctionInStream:
3227 return "Could not find function in stream";
3228 case BitcodeReader::ExpectedConstant:
3229 return "Expected a constant";
3230 case BitcodeReader::InsufficientFunctionProtos:
3231 return "Insufficient function protos";
3232 case BitcodeReader::InvalidBitcodeSignature:
3233 return "Invalid bitcode signature";
3234 case BitcodeReader::InvalidBitcodeWrapperHeader:
3235 return "Invalid bitcode wrapper header";
3236 case BitcodeReader::InvalidConstantReference:
3237 return "Invalid ronstant reference";
3238 case BitcodeReader::InvalidID:
3239 return "Invalid ID";
3240 case BitcodeReader::InvalidInstructionWithNoBB:
3241 return "Invalid instruction with no BB";
3242 case BitcodeReader::InvalidRecord:
3243 return "Invalid record";
3244 case BitcodeReader::InvalidTypeForValue:
3245 return "Invalid type for value";
3246 case BitcodeReader::InvalidTYPETable:
3247 return "Invalid TYPE table";
3248 case BitcodeReader::InvalidType:
3249 return "Invalid type";
3250 case BitcodeReader::MalformedBlock:
3251 return "Malformed block";
3252 case BitcodeReader::MalformedGlobalInitializerSet:
3253 return "Malformed global initializer set";
3254 case BitcodeReader::InvalidMultipleBlocks:
3255 return "Invalid multiple blocks";
3256 case BitcodeReader::NeverResolvedValueFoundInFunction:
3257 return "Never resolved value found in function";
3258 case BitcodeReader::InvalidValue:
3259 return "Invalid value";
3261 llvm_unreachable("Unknown error type!");
3266 const error_category &BitcodeReader::BitcodeErrorCategory() {
3267 static BitcodeErrorCategoryType O;
3271 //===----------------------------------------------------------------------===//
3272 // External interface
3273 //===----------------------------------------------------------------------===//
3275 /// getLazyBitcodeModule - lazy function-at-a-time loading from a file.
3277 ErrorOr<Module *> llvm::getLazyBitcodeModule(MemoryBuffer *Buffer,
3278 LLVMContext &Context) {
3279 Module *M = new Module(Buffer->getBufferIdentifier(), Context);
3280 BitcodeReader *R = new BitcodeReader(Buffer, Context);
3281 M->setMaterializer(R);
3282 if (error_code EC = R->ParseBitcodeInto(M)) {
3283 delete M; // Also deletes R.
3286 // Have the BitcodeReader dtor delete 'Buffer'.
3287 R->setBufferOwned(true);
3289 R->materializeForwardReferencedFunctions();
3295 Module *llvm::getStreamedBitcodeModule(const std::string &name,
3296 DataStreamer *streamer,
3297 LLVMContext &Context,
3298 std::string *ErrMsg) {
3299 Module *M = new Module(name, Context);
3300 BitcodeReader *R = new BitcodeReader(streamer, Context);
3301 M->setMaterializer(R);
3302 if (error_code EC = R->ParseBitcodeInto(M)) {
3304 *ErrMsg = EC.message();
3305 delete M; // Also deletes R.
3308 R->setBufferOwned(false); // no buffer to delete
3312 /// ParseBitcodeFile - Read the specified bitcode file, returning the module.
3313 /// If an error occurs, return null and fill in *ErrMsg if non-null.
3314 Module *llvm::ParseBitcodeFile(MemoryBuffer *Buffer, LLVMContext& Context,
3315 std::string *ErrMsg){
3316 ErrorOr<Module *> ModuleOrErr = getLazyBitcodeModule(Buffer, Context);
3317 if (error_code EC = ModuleOrErr.getError()) {
3319 *ErrMsg = EC.message();
3322 Module *M = ModuleOrErr.get();
3324 // Don't let the BitcodeReader dtor delete 'Buffer', regardless of whether
3325 // there was an error.
3326 static_cast<BitcodeReader*>(M->getMaterializer())->setBufferOwned(false);
3328 // Read in the entire module, and destroy the BitcodeReader.
3329 if (M->MaterializeAllPermanently(ErrMsg)) {
3334 // TODO: Restore the use-lists to the in-memory state when the bitcode was
3335 // written. We must defer until the Module has been fully materialized.
3340 std::string llvm::getBitcodeTargetTriple(MemoryBuffer *Buffer,
3341 LLVMContext& Context,
3342 std::string *ErrMsg) {
3343 BitcodeReader *R = new BitcodeReader(Buffer, Context);
3344 // Don't let the BitcodeReader dtor delete 'Buffer'.
3345 R->setBufferOwned(false);
3347 std::string Triple("");
3348 if (error_code EC = R->ParseTriple(Triple))
3350 *ErrMsg = EC.message();