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_COLD:
526 return Attribute::Cold;
527 case bitc::ATTR_KIND_INLINE_HINT:
528 return Attribute::InlineHint;
529 case bitc::ATTR_KIND_IN_REG:
530 return Attribute::InReg;
531 case bitc::ATTR_KIND_MIN_SIZE:
532 return Attribute::MinSize;
533 case bitc::ATTR_KIND_NAKED:
534 return Attribute::Naked;
535 case bitc::ATTR_KIND_NEST:
536 return Attribute::Nest;
537 case bitc::ATTR_KIND_NO_ALIAS:
538 return Attribute::NoAlias;
539 case bitc::ATTR_KIND_NO_BUILTIN:
540 return Attribute::NoBuiltin;
541 case bitc::ATTR_KIND_NO_CAPTURE:
542 return Attribute::NoCapture;
543 case bitc::ATTR_KIND_NO_DUPLICATE:
544 return Attribute::NoDuplicate;
545 case bitc::ATTR_KIND_NO_IMPLICIT_FLOAT:
546 return Attribute::NoImplicitFloat;
547 case bitc::ATTR_KIND_NO_INLINE:
548 return Attribute::NoInline;
549 case bitc::ATTR_KIND_NON_LAZY_BIND:
550 return Attribute::NonLazyBind;
551 case bitc::ATTR_KIND_NO_RED_ZONE:
552 return Attribute::NoRedZone;
553 case bitc::ATTR_KIND_NO_RETURN:
554 return Attribute::NoReturn;
555 case bitc::ATTR_KIND_NO_UNWIND:
556 return Attribute::NoUnwind;
557 case bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE:
558 return Attribute::OptimizeForSize;
559 case bitc::ATTR_KIND_OPTIMIZE_NONE:
560 return Attribute::OptimizeNone;
561 case bitc::ATTR_KIND_READ_NONE:
562 return Attribute::ReadNone;
563 case bitc::ATTR_KIND_READ_ONLY:
564 return Attribute::ReadOnly;
565 case bitc::ATTR_KIND_RETURNED:
566 return Attribute::Returned;
567 case bitc::ATTR_KIND_RETURNS_TWICE:
568 return Attribute::ReturnsTwice;
569 case bitc::ATTR_KIND_S_EXT:
570 return Attribute::SExt;
571 case bitc::ATTR_KIND_STACK_ALIGNMENT:
572 return Attribute::StackAlignment;
573 case bitc::ATTR_KIND_STACK_PROTECT:
574 return Attribute::StackProtect;
575 case bitc::ATTR_KIND_STACK_PROTECT_REQ:
576 return Attribute::StackProtectReq;
577 case bitc::ATTR_KIND_STACK_PROTECT_STRONG:
578 return Attribute::StackProtectStrong;
579 case bitc::ATTR_KIND_STRUCT_RET:
580 return Attribute::StructRet;
581 case bitc::ATTR_KIND_SANITIZE_ADDRESS:
582 return Attribute::SanitizeAddress;
583 case bitc::ATTR_KIND_SANITIZE_THREAD:
584 return Attribute::SanitizeThread;
585 case bitc::ATTR_KIND_SANITIZE_MEMORY:
586 return Attribute::SanitizeMemory;
587 case bitc::ATTR_KIND_UW_TABLE:
588 return Attribute::UWTable;
589 case bitc::ATTR_KIND_Z_EXT:
590 return Attribute::ZExt;
594 error_code BitcodeReader::ParseAttrKind(uint64_t Code,
595 Attribute::AttrKind *Kind) {
596 *Kind = GetAttrFromCode(Code);
597 if (*Kind == Attribute::None)
598 return Error(InvalidValue);
599 return error_code::success();
602 error_code BitcodeReader::ParseAttributeGroupBlock() {
603 if (Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID))
604 return Error(InvalidRecord);
606 if (!MAttributeGroups.empty())
607 return Error(InvalidMultipleBlocks);
609 SmallVector<uint64_t, 64> Record;
611 // Read all the records.
613 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
615 switch (Entry.Kind) {
616 case BitstreamEntry::SubBlock: // Handled for us already.
617 case BitstreamEntry::Error:
618 return Error(MalformedBlock);
619 case BitstreamEntry::EndBlock:
620 return error_code::success();
621 case BitstreamEntry::Record:
622 // The interesting case.
628 switch (Stream.readRecord(Entry.ID, Record)) {
629 default: // Default behavior: ignore.
631 case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...]
632 if (Record.size() < 3)
633 return Error(InvalidRecord);
635 uint64_t GrpID = Record[0];
636 uint64_t Idx = Record[1]; // Index of the object this attribute refers to.
639 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
640 if (Record[i] == 0) { // Enum attribute
641 Attribute::AttrKind Kind;
642 if (error_code EC = ParseAttrKind(Record[++i], &Kind))
645 B.addAttribute(Kind);
646 } else if (Record[i] == 1) { // Align attribute
647 Attribute::AttrKind Kind;
648 if (error_code EC = ParseAttrKind(Record[++i], &Kind))
650 if (Kind == Attribute::Alignment)
651 B.addAlignmentAttr(Record[++i]);
653 B.addStackAlignmentAttr(Record[++i]);
654 } else { // String attribute
655 assert((Record[i] == 3 || Record[i] == 4) &&
656 "Invalid attribute group entry");
657 bool HasValue = (Record[i++] == 4);
658 SmallString<64> KindStr;
659 SmallString<64> ValStr;
661 while (Record[i] != 0 && i != e)
662 KindStr += Record[i++];
663 assert(Record[i] == 0 && "Kind string not null terminated");
666 // Has a value associated with it.
667 ++i; // Skip the '0' that terminates the "kind" string.
668 while (Record[i] != 0 && i != e)
669 ValStr += Record[i++];
670 assert(Record[i] == 0 && "Value string not null terminated");
673 B.addAttribute(KindStr.str(), ValStr.str());
677 MAttributeGroups[GrpID] = AttributeSet::get(Context, Idx, B);
684 error_code BitcodeReader::ParseTypeTable() {
685 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
686 return Error(InvalidRecord);
688 return ParseTypeTableBody();
691 error_code BitcodeReader::ParseTypeTableBody() {
692 if (!TypeList.empty())
693 return Error(InvalidMultipleBlocks);
695 SmallVector<uint64_t, 64> Record;
696 unsigned NumRecords = 0;
698 SmallString<64> TypeName;
700 // Read all the records for this type table.
702 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
704 switch (Entry.Kind) {
705 case BitstreamEntry::SubBlock: // Handled for us already.
706 case BitstreamEntry::Error:
707 return Error(MalformedBlock);
708 case BitstreamEntry::EndBlock:
709 if (NumRecords != TypeList.size())
710 return Error(MalformedBlock);
711 return error_code::success();
712 case BitstreamEntry::Record:
713 // The interesting case.
720 switch (Stream.readRecord(Entry.ID, Record)) {
722 return Error(InvalidValue);
723 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
724 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
725 // type list. This allows us to reserve space.
726 if (Record.size() < 1)
727 return Error(InvalidRecord);
728 TypeList.resize(Record[0]);
730 case bitc::TYPE_CODE_VOID: // VOID
731 ResultTy = Type::getVoidTy(Context);
733 case bitc::TYPE_CODE_HALF: // HALF
734 ResultTy = Type::getHalfTy(Context);
736 case bitc::TYPE_CODE_FLOAT: // FLOAT
737 ResultTy = Type::getFloatTy(Context);
739 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
740 ResultTy = Type::getDoubleTy(Context);
742 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
743 ResultTy = Type::getX86_FP80Ty(Context);
745 case bitc::TYPE_CODE_FP128: // FP128
746 ResultTy = Type::getFP128Ty(Context);
748 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
749 ResultTy = Type::getPPC_FP128Ty(Context);
751 case bitc::TYPE_CODE_LABEL: // LABEL
752 ResultTy = Type::getLabelTy(Context);
754 case bitc::TYPE_CODE_METADATA: // METADATA
755 ResultTy = Type::getMetadataTy(Context);
757 case bitc::TYPE_CODE_X86_MMX: // X86_MMX
758 ResultTy = Type::getX86_MMXTy(Context);
760 case bitc::TYPE_CODE_INTEGER: // INTEGER: [width]
761 if (Record.size() < 1)
762 return Error(InvalidRecord);
764 ResultTy = IntegerType::get(Context, Record[0]);
766 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
767 // [pointee type, address space]
768 if (Record.size() < 1)
769 return Error(InvalidRecord);
770 unsigned AddressSpace = 0;
771 if (Record.size() == 2)
772 AddressSpace = Record[1];
773 ResultTy = getTypeByID(Record[0]);
775 return Error(InvalidType);
776 ResultTy = PointerType::get(ResultTy, AddressSpace);
779 case bitc::TYPE_CODE_FUNCTION_OLD: {
780 // FIXME: attrid is dead, remove it in LLVM 4.0
781 // FUNCTION: [vararg, attrid, retty, paramty x N]
782 if (Record.size() < 3)
783 return Error(InvalidRecord);
784 SmallVector<Type*, 8> ArgTys;
785 for (unsigned i = 3, e = Record.size(); i != e; ++i) {
786 if (Type *T = getTypeByID(Record[i]))
792 ResultTy = getTypeByID(Record[2]);
793 if (ResultTy == 0 || ArgTys.size() < Record.size()-3)
794 return Error(InvalidType);
796 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
799 case bitc::TYPE_CODE_FUNCTION: {
800 // FUNCTION: [vararg, retty, paramty x N]
801 if (Record.size() < 2)
802 return Error(InvalidRecord);
803 SmallVector<Type*, 8> ArgTys;
804 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
805 if (Type *T = getTypeByID(Record[i]))
811 ResultTy = getTypeByID(Record[1]);
812 if (ResultTy == 0 || ArgTys.size() < Record.size()-2)
813 return Error(InvalidType);
815 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
818 case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N]
819 if (Record.size() < 1)
820 return Error(InvalidRecord);
821 SmallVector<Type*, 8> EltTys;
822 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
823 if (Type *T = getTypeByID(Record[i]))
828 if (EltTys.size() != Record.size()-1)
829 return Error(InvalidType);
830 ResultTy = StructType::get(Context, EltTys, Record[0]);
833 case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N]
834 if (ConvertToString(Record, 0, TypeName))
835 return Error(InvalidRecord);
838 case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
839 if (Record.size() < 1)
840 return Error(InvalidRecord);
842 if (NumRecords >= TypeList.size())
843 return Error(InvalidTYPETable);
845 // Check to see if this was forward referenced, if so fill in the temp.
846 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
848 Res->setName(TypeName);
849 TypeList[NumRecords] = 0;
850 } else // Otherwise, create a new struct.
851 Res = StructType::create(Context, TypeName);
854 SmallVector<Type*, 8> EltTys;
855 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
856 if (Type *T = getTypeByID(Record[i]))
861 if (EltTys.size() != Record.size()-1)
862 return Error(InvalidRecord);
863 Res->setBody(EltTys, Record[0]);
867 case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: []
868 if (Record.size() != 1)
869 return Error(InvalidRecord);
871 if (NumRecords >= TypeList.size())
872 return Error(InvalidTYPETable);
874 // Check to see if this was forward referenced, if so fill in the temp.
875 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
877 Res->setName(TypeName);
878 TypeList[NumRecords] = 0;
879 } else // Otherwise, create a new struct with no body.
880 Res = StructType::create(Context, TypeName);
885 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
886 if (Record.size() < 2)
887 return Error(InvalidRecord);
888 if ((ResultTy = getTypeByID(Record[1])))
889 ResultTy = ArrayType::get(ResultTy, Record[0]);
891 return Error(InvalidType);
893 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
894 if (Record.size() < 2)
895 return Error(InvalidRecord);
896 if ((ResultTy = getTypeByID(Record[1])))
897 ResultTy = VectorType::get(ResultTy, Record[0]);
899 return Error(InvalidType);
903 if (NumRecords >= TypeList.size())
904 return Error(InvalidTYPETable);
905 assert(ResultTy && "Didn't read a type?");
906 assert(TypeList[NumRecords] == 0 && "Already read type?");
907 TypeList[NumRecords++] = ResultTy;
911 error_code BitcodeReader::ParseValueSymbolTable() {
912 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
913 return Error(InvalidRecord);
915 SmallVector<uint64_t, 64> Record;
917 // Read all the records for this value table.
918 SmallString<128> ValueName;
920 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
922 switch (Entry.Kind) {
923 case BitstreamEntry::SubBlock: // Handled for us already.
924 case BitstreamEntry::Error:
925 return Error(MalformedBlock);
926 case BitstreamEntry::EndBlock:
927 return error_code::success();
928 case BitstreamEntry::Record:
929 // The interesting case.
935 switch (Stream.readRecord(Entry.ID, Record)) {
936 default: // Default behavior: unknown type.
938 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
939 if (ConvertToString(Record, 1, ValueName))
940 return Error(InvalidRecord);
941 unsigned ValueID = Record[0];
942 if (ValueID >= ValueList.size())
943 return Error(InvalidRecord);
944 Value *V = ValueList[ValueID];
946 V->setName(StringRef(ValueName.data(), ValueName.size()));
950 case bitc::VST_CODE_BBENTRY: {
951 if (ConvertToString(Record, 1, ValueName))
952 return Error(InvalidRecord);
953 BasicBlock *BB = getBasicBlock(Record[0]);
955 return Error(InvalidRecord);
957 BB->setName(StringRef(ValueName.data(), ValueName.size()));
965 error_code BitcodeReader::ParseMetadata() {
966 unsigned NextMDValueNo = MDValueList.size();
968 if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
969 return Error(InvalidRecord);
971 SmallVector<uint64_t, 64> Record;
973 // Read all the records.
975 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
977 switch (Entry.Kind) {
978 case BitstreamEntry::SubBlock: // Handled for us already.
979 case BitstreamEntry::Error:
980 return Error(MalformedBlock);
981 case BitstreamEntry::EndBlock:
982 return error_code::success();
983 case BitstreamEntry::Record:
984 // The interesting case.
988 bool IsFunctionLocal = false;
991 unsigned Code = Stream.readRecord(Entry.ID, Record);
993 default: // Default behavior: ignore.
995 case bitc::METADATA_NAME: {
996 // Read name of the named metadata.
997 SmallString<8> Name(Record.begin(), Record.end());
999 Code = Stream.ReadCode();
1001 // METADATA_NAME is always followed by METADATA_NAMED_NODE.
1002 unsigned NextBitCode = Stream.readRecord(Code, Record);
1003 assert(NextBitCode == bitc::METADATA_NAMED_NODE); (void)NextBitCode;
1005 // Read named metadata elements.
1006 unsigned Size = Record.size();
1007 NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name);
1008 for (unsigned i = 0; i != Size; ++i) {
1009 MDNode *MD = dyn_cast<MDNode>(MDValueList.getValueFwdRef(Record[i]));
1011 return Error(InvalidRecord);
1012 NMD->addOperand(MD);
1016 case bitc::METADATA_FN_NODE:
1017 IsFunctionLocal = true;
1019 case bitc::METADATA_NODE: {
1020 if (Record.size() % 2 == 1)
1021 return Error(InvalidRecord);
1023 unsigned Size = Record.size();
1024 SmallVector<Value*, 8> Elts;
1025 for (unsigned i = 0; i != Size; i += 2) {
1026 Type *Ty = getTypeByID(Record[i]);
1028 return Error(InvalidRecord);
1029 if (Ty->isMetadataTy())
1030 Elts.push_back(MDValueList.getValueFwdRef(Record[i+1]));
1031 else if (!Ty->isVoidTy())
1032 Elts.push_back(ValueList.getValueFwdRef(Record[i+1], Ty));
1034 Elts.push_back(NULL);
1036 Value *V = MDNode::getWhenValsUnresolved(Context, Elts, IsFunctionLocal);
1037 IsFunctionLocal = false;
1038 MDValueList.AssignValue(V, NextMDValueNo++);
1041 case bitc::METADATA_STRING: {
1042 SmallString<8> String(Record.begin(), Record.end());
1043 Value *V = MDString::get(Context, String);
1044 MDValueList.AssignValue(V, NextMDValueNo++);
1047 case bitc::METADATA_KIND: {
1048 if (Record.size() < 2)
1049 return Error(InvalidRecord);
1051 unsigned Kind = Record[0];
1052 SmallString<8> Name(Record.begin()+1, Record.end());
1054 unsigned NewKind = TheModule->getMDKindID(Name.str());
1055 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
1056 return Error(ConflictingMETADATA_KINDRecords);
1063 /// decodeSignRotatedValue - Decode a signed value stored with the sign bit in
1064 /// the LSB for dense VBR encoding.
1065 uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
1070 // There is no such thing as -0 with integers. "-0" really means MININT.
1074 /// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
1075 /// values and aliases that we can.
1076 error_code BitcodeReader::ResolveGlobalAndAliasInits() {
1077 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
1078 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
1079 std::vector<std::pair<Function*, unsigned> > FunctionPrefixWorklist;
1081 GlobalInitWorklist.swap(GlobalInits);
1082 AliasInitWorklist.swap(AliasInits);
1083 FunctionPrefixWorklist.swap(FunctionPrefixes);
1085 while (!GlobalInitWorklist.empty()) {
1086 unsigned ValID = GlobalInitWorklist.back().second;
1087 if (ValID >= ValueList.size()) {
1088 // Not ready to resolve this yet, it requires something later in the file.
1089 GlobalInits.push_back(GlobalInitWorklist.back());
1091 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
1092 GlobalInitWorklist.back().first->setInitializer(C);
1094 return Error(ExpectedConstant);
1096 GlobalInitWorklist.pop_back();
1099 while (!AliasInitWorklist.empty()) {
1100 unsigned ValID = AliasInitWorklist.back().second;
1101 if (ValID >= ValueList.size()) {
1102 AliasInits.push_back(AliasInitWorklist.back());
1104 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
1105 AliasInitWorklist.back().first->setAliasee(C);
1107 return Error(ExpectedConstant);
1109 AliasInitWorklist.pop_back();
1112 while (!FunctionPrefixWorklist.empty()) {
1113 unsigned ValID = FunctionPrefixWorklist.back().second;
1114 if (ValID >= ValueList.size()) {
1115 FunctionPrefixes.push_back(FunctionPrefixWorklist.back());
1117 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
1118 FunctionPrefixWorklist.back().first->setPrefixData(C);
1120 return Error(ExpectedConstant);
1122 FunctionPrefixWorklist.pop_back();
1125 return error_code::success();
1128 static APInt ReadWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
1129 SmallVector<uint64_t, 8> Words(Vals.size());
1130 std::transform(Vals.begin(), Vals.end(), Words.begin(),
1131 BitcodeReader::decodeSignRotatedValue);
1133 return APInt(TypeBits, Words);
1136 error_code BitcodeReader::ParseConstants() {
1137 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
1138 return Error(InvalidRecord);
1140 SmallVector<uint64_t, 64> Record;
1142 // Read all the records for this value table.
1143 Type *CurTy = Type::getInt32Ty(Context);
1144 unsigned NextCstNo = ValueList.size();
1146 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1148 switch (Entry.Kind) {
1149 case BitstreamEntry::SubBlock: // Handled for us already.
1150 case BitstreamEntry::Error:
1151 return Error(MalformedBlock);
1152 case BitstreamEntry::EndBlock:
1153 if (NextCstNo != ValueList.size())
1154 return Error(InvalidConstantReference);
1156 // Once all the constants have been read, go through and resolve forward
1158 ValueList.ResolveConstantForwardRefs();
1159 return error_code::success();
1160 case BitstreamEntry::Record:
1161 // The interesting case.
1168 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
1170 default: // Default behavior: unknown constant
1171 case bitc::CST_CODE_UNDEF: // UNDEF
1172 V = UndefValue::get(CurTy);
1174 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
1176 return Error(InvalidRecord);
1177 if (Record[0] >= TypeList.size())
1178 return Error(InvalidRecord);
1179 CurTy = TypeList[Record[0]];
1180 continue; // Skip the ValueList manipulation.
1181 case bitc::CST_CODE_NULL: // NULL
1182 V = Constant::getNullValue(CurTy);
1184 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
1185 if (!CurTy->isIntegerTy() || Record.empty())
1186 return Error(InvalidRecord);
1187 V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
1189 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
1190 if (!CurTy->isIntegerTy() || Record.empty())
1191 return Error(InvalidRecord);
1193 APInt VInt = ReadWideAPInt(Record,
1194 cast<IntegerType>(CurTy)->getBitWidth());
1195 V = ConstantInt::get(Context, VInt);
1199 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
1201 return Error(InvalidRecord);
1202 if (CurTy->isHalfTy())
1203 V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf,
1204 APInt(16, (uint16_t)Record[0])));
1205 else if (CurTy->isFloatTy())
1206 V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle,
1207 APInt(32, (uint32_t)Record[0])));
1208 else if (CurTy->isDoubleTy())
1209 V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble,
1210 APInt(64, Record[0])));
1211 else if (CurTy->isX86_FP80Ty()) {
1212 // Bits are not stored the same way as a normal i80 APInt, compensate.
1213 uint64_t Rearrange[2];
1214 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
1215 Rearrange[1] = Record[0] >> 48;
1216 V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended,
1217 APInt(80, Rearrange)));
1218 } else if (CurTy->isFP128Ty())
1219 V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad,
1220 APInt(128, Record)));
1221 else if (CurTy->isPPC_FP128Ty())
1222 V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble,
1223 APInt(128, Record)));
1225 V = UndefValue::get(CurTy);
1229 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
1231 return Error(InvalidRecord);
1233 unsigned Size = Record.size();
1234 SmallVector<Constant*, 16> Elts;
1236 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
1237 for (unsigned i = 0; i != Size; ++i)
1238 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
1239 STy->getElementType(i)));
1240 V = ConstantStruct::get(STy, Elts);
1241 } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
1242 Type *EltTy = ATy->getElementType();
1243 for (unsigned i = 0; i != Size; ++i)
1244 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
1245 V = ConstantArray::get(ATy, Elts);
1246 } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
1247 Type *EltTy = VTy->getElementType();
1248 for (unsigned i = 0; i != Size; ++i)
1249 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
1250 V = ConstantVector::get(Elts);
1252 V = UndefValue::get(CurTy);
1256 case bitc::CST_CODE_STRING: // STRING: [values]
1257 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
1259 return Error(InvalidRecord);
1261 SmallString<16> Elts(Record.begin(), Record.end());
1262 V = ConstantDataArray::getString(Context, Elts,
1263 BitCode == bitc::CST_CODE_CSTRING);
1266 case bitc::CST_CODE_DATA: {// DATA: [n x value]
1268 return Error(InvalidRecord);
1270 Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
1271 unsigned Size = Record.size();
1273 if (EltTy->isIntegerTy(8)) {
1274 SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
1275 if (isa<VectorType>(CurTy))
1276 V = ConstantDataVector::get(Context, Elts);
1278 V = ConstantDataArray::get(Context, Elts);
1279 } else if (EltTy->isIntegerTy(16)) {
1280 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
1281 if (isa<VectorType>(CurTy))
1282 V = ConstantDataVector::get(Context, Elts);
1284 V = ConstantDataArray::get(Context, Elts);
1285 } else if (EltTy->isIntegerTy(32)) {
1286 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
1287 if (isa<VectorType>(CurTy))
1288 V = ConstantDataVector::get(Context, Elts);
1290 V = ConstantDataArray::get(Context, Elts);
1291 } else if (EltTy->isIntegerTy(64)) {
1292 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
1293 if (isa<VectorType>(CurTy))
1294 V = ConstantDataVector::get(Context, Elts);
1296 V = ConstantDataArray::get(Context, Elts);
1297 } else if (EltTy->isFloatTy()) {
1298 SmallVector<float, 16> Elts(Size);
1299 std::transform(Record.begin(), Record.end(), Elts.begin(), BitsToFloat);
1300 if (isa<VectorType>(CurTy))
1301 V = ConstantDataVector::get(Context, Elts);
1303 V = ConstantDataArray::get(Context, Elts);
1304 } else if (EltTy->isDoubleTy()) {
1305 SmallVector<double, 16> Elts(Size);
1306 std::transform(Record.begin(), Record.end(), Elts.begin(),
1308 if (isa<VectorType>(CurTy))
1309 V = ConstantDataVector::get(Context, Elts);
1311 V = ConstantDataArray::get(Context, Elts);
1313 return Error(InvalidTypeForValue);
1318 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
1319 if (Record.size() < 3)
1320 return Error(InvalidRecord);
1321 int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
1323 V = UndefValue::get(CurTy); // Unknown binop.
1325 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
1326 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
1328 if (Record.size() >= 4) {
1329 if (Opc == Instruction::Add ||
1330 Opc == Instruction::Sub ||
1331 Opc == Instruction::Mul ||
1332 Opc == Instruction::Shl) {
1333 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
1334 Flags |= OverflowingBinaryOperator::NoSignedWrap;
1335 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
1336 Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
1337 } else if (Opc == Instruction::SDiv ||
1338 Opc == Instruction::UDiv ||
1339 Opc == Instruction::LShr ||
1340 Opc == Instruction::AShr) {
1341 if (Record[3] & (1 << bitc::PEO_EXACT))
1342 Flags |= SDivOperator::IsExact;
1345 V = ConstantExpr::get(Opc, LHS, RHS, Flags);
1349 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
1350 if (Record.size() < 3)
1351 return Error(InvalidRecord);
1352 int Opc = GetDecodedCastOpcode(Record[0]);
1354 V = UndefValue::get(CurTy); // Unknown cast.
1356 Type *OpTy = getTypeByID(Record[1]);
1358 return Error(InvalidRecord);
1359 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
1360 V = UpgradeBitCastExpr(Opc, Op, CurTy);
1361 if (!V) V = ConstantExpr::getCast(Opc, Op, CurTy);
1365 case bitc::CST_CODE_CE_INBOUNDS_GEP:
1366 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
1367 if (Record.size() & 1)
1368 return Error(InvalidRecord);
1369 SmallVector<Constant*, 16> Elts;
1370 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
1371 Type *ElTy = getTypeByID(Record[i]);
1373 return Error(InvalidRecord);
1374 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
1376 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
1377 V = ConstantExpr::getGetElementPtr(Elts[0], Indices,
1379 bitc::CST_CODE_CE_INBOUNDS_GEP);
1382 case bitc::CST_CODE_CE_SELECT: { // CE_SELECT: [opval#, opval#, opval#]
1383 if (Record.size() < 3)
1384 return Error(InvalidRecord);
1386 Type *SelectorTy = Type::getInt1Ty(Context);
1388 // If CurTy is a vector of length n, then Record[0] must be a <n x i1>
1389 // vector. Otherwise, it must be a single bit.
1390 if (VectorType *VTy = dyn_cast<VectorType>(CurTy))
1391 SelectorTy = VectorType::get(Type::getInt1Ty(Context),
1392 VTy->getNumElements());
1394 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
1396 ValueList.getConstantFwdRef(Record[1],CurTy),
1397 ValueList.getConstantFwdRef(Record[2],CurTy));
1400 case bitc::CST_CODE_CE_EXTRACTELT: { // CE_EXTRACTELT: [opty, opval, opval]
1401 if (Record.size() < 3)
1402 return Error(InvalidRecord);
1404 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1406 return Error(InvalidRecord);
1407 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1408 Constant *Op1 = ValueList.getConstantFwdRef(Record[2],
1409 Type::getInt32Ty(Context));
1410 V = ConstantExpr::getExtractElement(Op0, Op1);
1413 case bitc::CST_CODE_CE_INSERTELT: { // CE_INSERTELT: [opval, opval, opval]
1414 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
1415 if (Record.size() < 3 || OpTy == 0)
1416 return Error(InvalidRecord);
1417 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1418 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
1419 OpTy->getElementType());
1420 Constant *Op2 = ValueList.getConstantFwdRef(Record[2],
1421 Type::getInt32Ty(Context));
1422 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
1425 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
1426 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
1427 if (Record.size() < 3 || OpTy == 0)
1428 return Error(InvalidRecord);
1429 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1430 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
1431 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
1432 OpTy->getNumElements());
1433 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
1434 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
1437 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
1438 VectorType *RTy = dyn_cast<VectorType>(CurTy);
1440 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1441 if (Record.size() < 4 || RTy == 0 || OpTy == 0)
1442 return Error(InvalidRecord);
1443 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1444 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1445 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
1446 RTy->getNumElements());
1447 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
1448 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
1451 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
1452 if (Record.size() < 4)
1453 return Error(InvalidRecord);
1454 Type *OpTy = getTypeByID(Record[0]);
1456 return Error(InvalidRecord);
1457 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1458 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1460 if (OpTy->isFPOrFPVectorTy())
1461 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
1463 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
1466 // This maintains backward compatibility, pre-asm dialect keywords.
1467 // FIXME: Remove with the 4.0 release.
1468 case bitc::CST_CODE_INLINEASM_OLD: {
1469 if (Record.size() < 2)
1470 return Error(InvalidRecord);
1471 std::string AsmStr, ConstrStr;
1472 bool HasSideEffects = Record[0] & 1;
1473 bool IsAlignStack = Record[0] >> 1;
1474 unsigned AsmStrSize = Record[1];
1475 if (2+AsmStrSize >= Record.size())
1476 return Error(InvalidRecord);
1477 unsigned ConstStrSize = Record[2+AsmStrSize];
1478 if (3+AsmStrSize+ConstStrSize > Record.size())
1479 return Error(InvalidRecord);
1481 for (unsigned i = 0; i != AsmStrSize; ++i)
1482 AsmStr += (char)Record[2+i];
1483 for (unsigned i = 0; i != ConstStrSize; ++i)
1484 ConstrStr += (char)Record[3+AsmStrSize+i];
1485 PointerType *PTy = cast<PointerType>(CurTy);
1486 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
1487 AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
1490 // This version adds support for the asm dialect keywords (e.g.,
1492 case bitc::CST_CODE_INLINEASM: {
1493 if (Record.size() < 2)
1494 return Error(InvalidRecord);
1495 std::string AsmStr, ConstrStr;
1496 bool HasSideEffects = Record[0] & 1;
1497 bool IsAlignStack = (Record[0] >> 1) & 1;
1498 unsigned AsmDialect = Record[0] >> 2;
1499 unsigned AsmStrSize = Record[1];
1500 if (2+AsmStrSize >= Record.size())
1501 return Error(InvalidRecord);
1502 unsigned ConstStrSize = Record[2+AsmStrSize];
1503 if (3+AsmStrSize+ConstStrSize > Record.size())
1504 return Error(InvalidRecord);
1506 for (unsigned i = 0; i != AsmStrSize; ++i)
1507 AsmStr += (char)Record[2+i];
1508 for (unsigned i = 0; i != ConstStrSize; ++i)
1509 ConstrStr += (char)Record[3+AsmStrSize+i];
1510 PointerType *PTy = cast<PointerType>(CurTy);
1511 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
1512 AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
1513 InlineAsm::AsmDialect(AsmDialect));
1516 case bitc::CST_CODE_BLOCKADDRESS:{
1517 if (Record.size() < 3)
1518 return Error(InvalidRecord);
1519 Type *FnTy = getTypeByID(Record[0]);
1521 return Error(InvalidRecord);
1523 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
1525 return Error(InvalidRecord);
1527 // If the function is already parsed we can insert the block address right
1530 Function::iterator BBI = Fn->begin(), BBE = Fn->end();
1531 for (size_t I = 0, E = Record[2]; I != E; ++I) {
1533 return Error(InvalidID);
1536 V = BlockAddress::get(Fn, BBI);
1538 // Otherwise insert a placeholder and remember it so it can be inserted
1539 // when the function is parsed.
1540 GlobalVariable *FwdRef = new GlobalVariable(*Fn->getParent(),
1541 Type::getInt8Ty(Context),
1542 false, GlobalValue::InternalLinkage,
1544 BlockAddrFwdRefs[Fn].push_back(std::make_pair(Record[2], FwdRef));
1551 ValueList.AssignValue(V, NextCstNo);
1556 error_code BitcodeReader::ParseUseLists() {
1557 if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
1558 return Error(InvalidRecord);
1560 SmallVector<uint64_t, 64> Record;
1562 // Read all the records.
1564 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1566 switch (Entry.Kind) {
1567 case BitstreamEntry::SubBlock: // Handled for us already.
1568 case BitstreamEntry::Error:
1569 return Error(MalformedBlock);
1570 case BitstreamEntry::EndBlock:
1571 return error_code::success();
1572 case BitstreamEntry::Record:
1573 // The interesting case.
1577 // Read a use list record.
1579 switch (Stream.readRecord(Entry.ID, Record)) {
1580 default: // Default behavior: unknown type.
1582 case bitc::USELIST_CODE_ENTRY: { // USELIST_CODE_ENTRY: TBD.
1583 unsigned RecordLength = Record.size();
1584 if (RecordLength < 1)
1585 return Error(InvalidRecord);
1586 UseListRecords.push_back(Record);
1593 /// RememberAndSkipFunctionBody - When we see the block for a function body,
1594 /// remember where it is and then skip it. This lets us lazily deserialize the
1596 error_code BitcodeReader::RememberAndSkipFunctionBody() {
1597 // Get the function we are talking about.
1598 if (FunctionsWithBodies.empty())
1599 return Error(InsufficientFunctionProtos);
1601 Function *Fn = FunctionsWithBodies.back();
1602 FunctionsWithBodies.pop_back();
1604 // Save the current stream state.
1605 uint64_t CurBit = Stream.GetCurrentBitNo();
1606 DeferredFunctionInfo[Fn] = CurBit;
1608 // Skip over the function block for now.
1609 if (Stream.SkipBlock())
1610 return Error(InvalidRecord);
1611 return error_code::success();
1614 error_code BitcodeReader::GlobalCleanup() {
1615 // Patch the initializers for globals and aliases up.
1616 ResolveGlobalAndAliasInits();
1617 if (!GlobalInits.empty() || !AliasInits.empty())
1618 return Error(MalformedGlobalInitializerSet);
1620 // Look for intrinsic functions which need to be upgraded at some point
1621 for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
1624 if (UpgradeIntrinsicFunction(FI, NewFn))
1625 UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
1628 // Look for global variables which need to be renamed.
1629 for (Module::global_iterator
1630 GI = TheModule->global_begin(), GE = TheModule->global_end();
1632 UpgradeGlobalVariable(GI);
1633 // Force deallocation of memory for these vectors to favor the client that
1634 // want lazy deserialization.
1635 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
1636 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
1637 return error_code::success();
1640 error_code BitcodeReader::ParseModule(bool Resume) {
1642 Stream.JumpToBit(NextUnreadBit);
1643 else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
1644 return Error(InvalidRecord);
1646 SmallVector<uint64_t, 64> Record;
1647 std::vector<std::string> SectionTable;
1648 std::vector<std::string> GCTable;
1650 // Read all the records for this module.
1652 BitstreamEntry Entry = Stream.advance();
1654 switch (Entry.Kind) {
1655 case BitstreamEntry::Error:
1656 return Error(MalformedBlock);
1657 case BitstreamEntry::EndBlock:
1658 return GlobalCleanup();
1660 case BitstreamEntry::SubBlock:
1662 default: // Skip unknown content.
1663 if (Stream.SkipBlock())
1664 return Error(InvalidRecord);
1666 case bitc::BLOCKINFO_BLOCK_ID:
1667 if (Stream.ReadBlockInfoBlock())
1668 return Error(MalformedBlock);
1670 case bitc::PARAMATTR_BLOCK_ID:
1671 if (error_code EC = ParseAttributeBlock())
1674 case bitc::PARAMATTR_GROUP_BLOCK_ID:
1675 if (error_code EC = ParseAttributeGroupBlock())
1678 case bitc::TYPE_BLOCK_ID_NEW:
1679 if (error_code EC = ParseTypeTable())
1682 case bitc::VALUE_SYMTAB_BLOCK_ID:
1683 if (error_code EC = ParseValueSymbolTable())
1685 SeenValueSymbolTable = true;
1687 case bitc::CONSTANTS_BLOCK_ID:
1688 if (error_code EC = ParseConstants())
1690 if (error_code EC = ResolveGlobalAndAliasInits())
1693 case bitc::METADATA_BLOCK_ID:
1694 if (error_code EC = ParseMetadata())
1697 case bitc::FUNCTION_BLOCK_ID:
1698 // If this is the first function body we've seen, reverse the
1699 // FunctionsWithBodies list.
1700 if (!SeenFirstFunctionBody) {
1701 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
1702 if (error_code EC = GlobalCleanup())
1704 SeenFirstFunctionBody = true;
1707 if (error_code EC = RememberAndSkipFunctionBody())
1709 // For streaming bitcode, suspend parsing when we reach the function
1710 // bodies. Subsequent materialization calls will resume it when
1711 // necessary. For streaming, the function bodies must be at the end of
1712 // the bitcode. If the bitcode file is old, the symbol table will be
1713 // at the end instead and will not have been seen yet. In this case,
1714 // just finish the parse now.
1715 if (LazyStreamer && SeenValueSymbolTable) {
1716 NextUnreadBit = Stream.GetCurrentBitNo();
1717 return error_code::success();
1720 case bitc::USELIST_BLOCK_ID:
1721 if (error_code EC = ParseUseLists())
1727 case BitstreamEntry::Record:
1728 // The interesting case.
1734 switch (Stream.readRecord(Entry.ID, Record)) {
1735 default: break; // Default behavior, ignore unknown content.
1736 case bitc::MODULE_CODE_VERSION: { // VERSION: [version#]
1737 if (Record.size() < 1)
1738 return Error(InvalidRecord);
1739 // Only version #0 and #1 are supported so far.
1740 unsigned module_version = Record[0];
1741 switch (module_version) {
1743 return Error(InvalidValue);
1745 UseRelativeIDs = false;
1748 UseRelativeIDs = true;
1753 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
1755 if (ConvertToString(Record, 0, S))
1756 return Error(InvalidRecord);
1757 TheModule->setTargetTriple(S);
1760 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
1762 if (ConvertToString(Record, 0, S))
1763 return Error(InvalidRecord);
1764 TheModule->setDataLayout(S);
1767 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
1769 if (ConvertToString(Record, 0, S))
1770 return Error(InvalidRecord);
1771 TheModule->setModuleInlineAsm(S);
1774 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
1775 // FIXME: Remove in 4.0.
1777 if (ConvertToString(Record, 0, S))
1778 return Error(InvalidRecord);
1782 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
1784 if (ConvertToString(Record, 0, S))
1785 return Error(InvalidRecord);
1786 SectionTable.push_back(S);
1789 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
1791 if (ConvertToString(Record, 0, S))
1792 return Error(InvalidRecord);
1793 GCTable.push_back(S);
1796 // GLOBALVAR: [pointer type, isconst, initid,
1797 // linkage, alignment, section, visibility, threadlocal,
1799 case bitc::MODULE_CODE_GLOBALVAR: {
1800 if (Record.size() < 6)
1801 return Error(InvalidRecord);
1802 Type *Ty = getTypeByID(Record[0]);
1804 return Error(InvalidRecord);
1805 if (!Ty->isPointerTy())
1806 return Error(InvalidTypeForValue);
1807 unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
1808 Ty = cast<PointerType>(Ty)->getElementType();
1810 bool isConstant = Record[1];
1811 GlobalValue::LinkageTypes Linkage = GetDecodedLinkage(Record[3]);
1812 unsigned Alignment = (1 << Record[4]) >> 1;
1813 std::string Section;
1815 if (Record[5]-1 >= SectionTable.size())
1816 return Error(InvalidID);
1817 Section = SectionTable[Record[5]-1];
1819 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
1820 if (Record.size() > 6)
1821 Visibility = GetDecodedVisibility(Record[6]);
1823 GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
1824 if (Record.size() > 7)
1825 TLM = GetDecodedThreadLocalMode(Record[7]);
1827 bool UnnamedAddr = false;
1828 if (Record.size() > 8)
1829 UnnamedAddr = Record[8];
1831 bool ExternallyInitialized = false;
1832 if (Record.size() > 9)
1833 ExternallyInitialized = Record[9];
1835 GlobalVariable *NewGV =
1836 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, 0, "", 0,
1837 TLM, AddressSpace, ExternallyInitialized);
1838 NewGV->setAlignment(Alignment);
1839 if (!Section.empty())
1840 NewGV->setSection(Section);
1841 NewGV->setVisibility(Visibility);
1842 NewGV->setUnnamedAddr(UnnamedAddr);
1844 ValueList.push_back(NewGV);
1846 // Remember which value to use for the global initializer.
1847 if (unsigned InitID = Record[2])
1848 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
1851 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
1852 // alignment, section, visibility, gc, unnamed_addr]
1853 case bitc::MODULE_CODE_FUNCTION: {
1854 if (Record.size() < 8)
1855 return Error(InvalidRecord);
1856 Type *Ty = getTypeByID(Record[0]);
1858 return Error(InvalidRecord);
1859 if (!Ty->isPointerTy())
1860 return Error(InvalidTypeForValue);
1862 dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
1864 return Error(InvalidTypeForValue);
1866 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
1869 Func->setCallingConv(static_cast<CallingConv::ID>(Record[1]));
1870 bool isProto = Record[2];
1871 Func->setLinkage(GetDecodedLinkage(Record[3]));
1872 Func->setAttributes(getAttributes(Record[4]));
1874 Func->setAlignment((1 << Record[5]) >> 1);
1876 if (Record[6]-1 >= SectionTable.size())
1877 return Error(InvalidID);
1878 Func->setSection(SectionTable[Record[6]-1]);
1880 Func->setVisibility(GetDecodedVisibility(Record[7]));
1881 if (Record.size() > 8 && Record[8]) {
1882 if (Record[8]-1 > GCTable.size())
1883 return Error(InvalidID);
1884 Func->setGC(GCTable[Record[8]-1].c_str());
1886 bool UnnamedAddr = false;
1887 if (Record.size() > 9)
1888 UnnamedAddr = Record[9];
1889 Func->setUnnamedAddr(UnnamedAddr);
1890 if (Record.size() > 10 && Record[10] != 0)
1891 FunctionPrefixes.push_back(std::make_pair(Func, Record[10]-1));
1892 ValueList.push_back(Func);
1894 // If this is a function with a body, remember the prototype we are
1895 // creating now, so that we can match up the body with them later.
1897 FunctionsWithBodies.push_back(Func);
1898 if (LazyStreamer) DeferredFunctionInfo[Func] = 0;
1902 // ALIAS: [alias type, aliasee val#, linkage]
1903 // ALIAS: [alias type, aliasee val#, linkage, visibility]
1904 case bitc::MODULE_CODE_ALIAS: {
1905 if (Record.size() < 3)
1906 return Error(InvalidRecord);
1907 Type *Ty = getTypeByID(Record[0]);
1909 return Error(InvalidRecord);
1910 if (!Ty->isPointerTy())
1911 return Error(InvalidTypeForValue);
1913 GlobalAlias *NewGA = new GlobalAlias(Ty, GetDecodedLinkage(Record[2]),
1915 // Old bitcode files didn't have visibility field.
1916 if (Record.size() > 3)
1917 NewGA->setVisibility(GetDecodedVisibility(Record[3]));
1918 ValueList.push_back(NewGA);
1919 AliasInits.push_back(std::make_pair(NewGA, Record[1]));
1922 /// MODULE_CODE_PURGEVALS: [numvals]
1923 case bitc::MODULE_CODE_PURGEVALS:
1924 // Trim down the value list to the specified size.
1925 if (Record.size() < 1 || Record[0] > ValueList.size())
1926 return Error(InvalidRecord);
1927 ValueList.shrinkTo(Record[0]);
1934 error_code BitcodeReader::ParseBitcodeInto(Module *M) {
1937 if (error_code EC = InitStream())
1940 // Sniff for the signature.
1941 if (Stream.Read(8) != 'B' ||
1942 Stream.Read(8) != 'C' ||
1943 Stream.Read(4) != 0x0 ||
1944 Stream.Read(4) != 0xC ||
1945 Stream.Read(4) != 0xE ||
1946 Stream.Read(4) != 0xD)
1947 return Error(InvalidBitcodeSignature);
1949 // We expect a number of well-defined blocks, though we don't necessarily
1950 // need to understand them all.
1952 if (Stream.AtEndOfStream())
1953 return error_code::success();
1955 BitstreamEntry Entry =
1956 Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
1958 switch (Entry.Kind) {
1959 case BitstreamEntry::Error:
1960 return Error(MalformedBlock);
1961 case BitstreamEntry::EndBlock:
1962 return error_code::success();
1964 case BitstreamEntry::SubBlock:
1966 case bitc::BLOCKINFO_BLOCK_ID:
1967 if (Stream.ReadBlockInfoBlock())
1968 return Error(MalformedBlock);
1970 case bitc::MODULE_BLOCK_ID:
1971 // Reject multiple MODULE_BLOCK's in a single bitstream.
1973 return Error(InvalidMultipleBlocks);
1975 if (error_code EC = ParseModule(false))
1978 return error_code::success();
1981 if (Stream.SkipBlock())
1982 return Error(InvalidRecord);
1986 case BitstreamEntry::Record:
1987 // There should be no records in the top-level of blocks.
1989 // The ranlib in Xcode 4 will align archive members by appending newlines
1990 // to the end of them. If this file size is a multiple of 4 but not 8, we
1991 // have to read and ignore these final 4 bytes :-(
1992 if (Stream.getAbbrevIDWidth() == 2 && Entry.ID == 2 &&
1993 Stream.Read(6) == 2 && Stream.Read(24) == 0xa0a0a &&
1994 Stream.AtEndOfStream())
1995 return error_code::success();
1997 return Error(InvalidRecord);
2002 error_code BitcodeReader::ParseModuleTriple(std::string &Triple) {
2003 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
2004 return Error(InvalidRecord);
2006 SmallVector<uint64_t, 64> Record;
2008 // Read all the records for this module.
2010 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2012 switch (Entry.Kind) {
2013 case BitstreamEntry::SubBlock: // Handled for us already.
2014 case BitstreamEntry::Error:
2015 return Error(MalformedBlock);
2016 case BitstreamEntry::EndBlock:
2017 return error_code::success();
2018 case BitstreamEntry::Record:
2019 // The interesting case.
2024 switch (Stream.readRecord(Entry.ID, Record)) {
2025 default: break; // Default behavior, ignore unknown content.
2026 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
2028 if (ConvertToString(Record, 0, S))
2029 return Error(InvalidRecord);
2038 error_code BitcodeReader::ParseTriple(std::string &Triple) {
2039 if (error_code EC = InitStream())
2042 // Sniff for the signature.
2043 if (Stream.Read(8) != 'B' ||
2044 Stream.Read(8) != 'C' ||
2045 Stream.Read(4) != 0x0 ||
2046 Stream.Read(4) != 0xC ||
2047 Stream.Read(4) != 0xE ||
2048 Stream.Read(4) != 0xD)
2049 return Error(InvalidBitcodeSignature);
2051 // We expect a number of well-defined blocks, though we don't necessarily
2052 // need to understand them all.
2054 BitstreamEntry Entry = Stream.advance();
2056 switch (Entry.Kind) {
2057 case BitstreamEntry::Error:
2058 return Error(MalformedBlock);
2059 case BitstreamEntry::EndBlock:
2060 return error_code::success();
2062 case BitstreamEntry::SubBlock:
2063 if (Entry.ID == bitc::MODULE_BLOCK_ID)
2064 return ParseModuleTriple(Triple);
2066 // Ignore other sub-blocks.
2067 if (Stream.SkipBlock())
2068 return Error(MalformedBlock);
2071 case BitstreamEntry::Record:
2072 Stream.skipRecord(Entry.ID);
2078 /// ParseMetadataAttachment - Parse metadata attachments.
2079 error_code BitcodeReader::ParseMetadataAttachment() {
2080 if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
2081 return Error(InvalidRecord);
2083 SmallVector<uint64_t, 64> Record;
2085 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2087 switch (Entry.Kind) {
2088 case BitstreamEntry::SubBlock: // Handled for us already.
2089 case BitstreamEntry::Error:
2090 return Error(MalformedBlock);
2091 case BitstreamEntry::EndBlock:
2092 return error_code::success();
2093 case BitstreamEntry::Record:
2094 // The interesting case.
2098 // Read a metadata attachment record.
2100 switch (Stream.readRecord(Entry.ID, Record)) {
2101 default: // Default behavior: ignore.
2103 case bitc::METADATA_ATTACHMENT: {
2104 unsigned RecordLength = Record.size();
2105 if (Record.empty() || (RecordLength - 1) % 2 == 1)
2106 return Error(InvalidRecord);
2107 Instruction *Inst = InstructionList[Record[0]];
2108 for (unsigned i = 1; i != RecordLength; i = i+2) {
2109 unsigned Kind = Record[i];
2110 DenseMap<unsigned, unsigned>::iterator I =
2111 MDKindMap.find(Kind);
2112 if (I == MDKindMap.end())
2113 return Error(InvalidID);
2114 Value *Node = MDValueList.getValueFwdRef(Record[i+1]);
2115 Inst->setMetadata(I->second, cast<MDNode>(Node));
2116 if (I->second == LLVMContext::MD_tbaa)
2117 InstsWithTBAATag.push_back(Inst);
2125 /// ParseFunctionBody - Lazily parse the specified function body block.
2126 error_code BitcodeReader::ParseFunctionBody(Function *F) {
2127 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
2128 return Error(InvalidRecord);
2130 InstructionList.clear();
2131 unsigned ModuleValueListSize = ValueList.size();
2132 unsigned ModuleMDValueListSize = MDValueList.size();
2134 // Add all the function arguments to the value table.
2135 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
2136 ValueList.push_back(I);
2138 unsigned NextValueNo = ValueList.size();
2139 BasicBlock *CurBB = 0;
2140 unsigned CurBBNo = 0;
2144 // Read all the records.
2145 SmallVector<uint64_t, 64> Record;
2147 BitstreamEntry Entry = Stream.advance();
2149 switch (Entry.Kind) {
2150 case BitstreamEntry::Error:
2151 return Error(MalformedBlock);
2152 case BitstreamEntry::EndBlock:
2153 goto OutOfRecordLoop;
2155 case BitstreamEntry::SubBlock:
2157 default: // Skip unknown content.
2158 if (Stream.SkipBlock())
2159 return Error(InvalidRecord);
2161 case bitc::CONSTANTS_BLOCK_ID:
2162 if (error_code EC = ParseConstants())
2164 NextValueNo = ValueList.size();
2166 case bitc::VALUE_SYMTAB_BLOCK_ID:
2167 if (error_code EC = ParseValueSymbolTable())
2170 case bitc::METADATA_ATTACHMENT_ID:
2171 if (error_code EC = ParseMetadataAttachment())
2174 case bitc::METADATA_BLOCK_ID:
2175 if (error_code EC = ParseMetadata())
2181 case BitstreamEntry::Record:
2182 // The interesting case.
2189 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
2191 default: // Default behavior: reject
2192 return Error(InvalidValue);
2193 case bitc::FUNC_CODE_DECLAREBLOCKS: // DECLAREBLOCKS: [nblocks]
2194 if (Record.size() < 1 || Record[0] == 0)
2195 return Error(InvalidRecord);
2196 // Create all the basic blocks for the function.
2197 FunctionBBs.resize(Record[0]);
2198 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
2199 FunctionBBs[i] = BasicBlock::Create(Context, "", F);
2200 CurBB = FunctionBBs[0];
2203 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN
2204 // This record indicates that the last instruction is at the same
2205 // location as the previous instruction with a location.
2208 // Get the last instruction emitted.
2209 if (CurBB && !CurBB->empty())
2211 else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
2212 !FunctionBBs[CurBBNo-1]->empty())
2213 I = &FunctionBBs[CurBBNo-1]->back();
2216 return Error(InvalidRecord);
2217 I->setDebugLoc(LastLoc);
2221 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia]
2222 I = 0; // Get the last instruction emitted.
2223 if (CurBB && !CurBB->empty())
2225 else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
2226 !FunctionBBs[CurBBNo-1]->empty())
2227 I = &FunctionBBs[CurBBNo-1]->back();
2228 if (I == 0 || Record.size() < 4)
2229 return Error(InvalidRecord);
2231 unsigned Line = Record[0], Col = Record[1];
2232 unsigned ScopeID = Record[2], IAID = Record[3];
2234 MDNode *Scope = 0, *IA = 0;
2235 if (ScopeID) Scope = cast<MDNode>(MDValueList.getValueFwdRef(ScopeID-1));
2236 if (IAID) IA = cast<MDNode>(MDValueList.getValueFwdRef(IAID-1));
2237 LastLoc = DebugLoc::get(Line, Col, Scope, IA);
2238 I->setDebugLoc(LastLoc);
2243 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
2246 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
2247 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
2248 OpNum+1 > Record.size())
2249 return Error(InvalidRecord);
2251 int Opc = GetDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
2253 return Error(InvalidRecord);
2254 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
2255 InstructionList.push_back(I);
2256 if (OpNum < Record.size()) {
2257 if (Opc == Instruction::Add ||
2258 Opc == Instruction::Sub ||
2259 Opc == Instruction::Mul ||
2260 Opc == Instruction::Shl) {
2261 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
2262 cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
2263 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
2264 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
2265 } else if (Opc == Instruction::SDiv ||
2266 Opc == Instruction::UDiv ||
2267 Opc == Instruction::LShr ||
2268 Opc == Instruction::AShr) {
2269 if (Record[OpNum] & (1 << bitc::PEO_EXACT))
2270 cast<BinaryOperator>(I)->setIsExact(true);
2271 } else if (isa<FPMathOperator>(I)) {
2273 if (0 != (Record[OpNum] & FastMathFlags::UnsafeAlgebra))
2274 FMF.setUnsafeAlgebra();
2275 if (0 != (Record[OpNum] & FastMathFlags::NoNaNs))
2277 if (0 != (Record[OpNum] & FastMathFlags::NoInfs))
2279 if (0 != (Record[OpNum] & FastMathFlags::NoSignedZeros))
2280 FMF.setNoSignedZeros();
2281 if (0 != (Record[OpNum] & FastMathFlags::AllowReciprocal))
2282 FMF.setAllowReciprocal();
2284 I->setFastMathFlags(FMF);
2290 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
2293 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2294 OpNum+2 != Record.size())
2295 return Error(InvalidRecord);
2297 Type *ResTy = getTypeByID(Record[OpNum]);
2298 int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
2299 if (Opc == -1 || ResTy == 0)
2300 return Error(InvalidRecord);
2301 Instruction *Temp = 0;
2302 if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) {
2304 InstructionList.push_back(Temp);
2305 CurBB->getInstList().push_back(Temp);
2308 I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
2310 InstructionList.push_back(I);
2313 case bitc::FUNC_CODE_INST_INBOUNDS_GEP:
2314 case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands]
2317 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
2318 return Error(InvalidRecord);
2320 SmallVector<Value*, 16> GEPIdx;
2321 while (OpNum != Record.size()) {
2323 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2324 return Error(InvalidRecord);
2325 GEPIdx.push_back(Op);
2328 I = GetElementPtrInst::Create(BasePtr, GEPIdx);
2329 InstructionList.push_back(I);
2330 if (BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP)
2331 cast<GetElementPtrInst>(I)->setIsInBounds(true);
2335 case bitc::FUNC_CODE_INST_EXTRACTVAL: {
2336 // EXTRACTVAL: [opty, opval, n x indices]
2339 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2340 return Error(InvalidRecord);
2342 SmallVector<unsigned, 4> EXTRACTVALIdx;
2343 for (unsigned RecSize = Record.size();
2344 OpNum != RecSize; ++OpNum) {
2345 uint64_t Index = Record[OpNum];
2346 if ((unsigned)Index != Index)
2347 return Error(InvalidValue);
2348 EXTRACTVALIdx.push_back((unsigned)Index);
2351 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
2352 InstructionList.push_back(I);
2356 case bitc::FUNC_CODE_INST_INSERTVAL: {
2357 // INSERTVAL: [opty, opval, opty, opval, n x indices]
2360 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2361 return Error(InvalidRecord);
2363 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
2364 return Error(InvalidRecord);
2366 SmallVector<unsigned, 4> INSERTVALIdx;
2367 for (unsigned RecSize = Record.size();
2368 OpNum != RecSize; ++OpNum) {
2369 uint64_t Index = Record[OpNum];
2370 if ((unsigned)Index != Index)
2371 return Error(InvalidValue);
2372 INSERTVALIdx.push_back((unsigned)Index);
2375 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
2376 InstructionList.push_back(I);
2380 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
2381 // obsolete form of select
2382 // handles select i1 ... in old bitcode
2384 Value *TrueVal, *FalseVal, *Cond;
2385 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
2386 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
2387 popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond))
2388 return Error(InvalidRecord);
2390 I = SelectInst::Create(Cond, TrueVal, FalseVal);
2391 InstructionList.push_back(I);
2395 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
2396 // new form of select
2397 // handles select i1 or select [N x i1]
2399 Value *TrueVal, *FalseVal, *Cond;
2400 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
2401 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
2402 getValueTypePair(Record, OpNum, NextValueNo, Cond))
2403 return Error(InvalidRecord);
2405 // select condition can be either i1 or [N x i1]
2406 if (VectorType* vector_type =
2407 dyn_cast<VectorType>(Cond->getType())) {
2409 if (vector_type->getElementType() != Type::getInt1Ty(Context))
2410 return Error(InvalidTypeForValue);
2413 if (Cond->getType() != Type::getInt1Ty(Context))
2414 return Error(InvalidTypeForValue);
2417 I = SelectInst::Create(Cond, TrueVal, FalseVal);
2418 InstructionList.push_back(I);
2422 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
2425 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
2426 popValue(Record, OpNum, NextValueNo, Type::getInt32Ty(Context), Idx))
2427 return Error(InvalidRecord);
2428 I = ExtractElementInst::Create(Vec, Idx);
2429 InstructionList.push_back(I);
2433 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
2435 Value *Vec, *Elt, *Idx;
2436 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
2437 popValue(Record, OpNum, NextValueNo,
2438 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
2439 popValue(Record, OpNum, NextValueNo, Type::getInt32Ty(Context), Idx))
2440 return Error(InvalidRecord);
2441 I = InsertElementInst::Create(Vec, Elt, Idx);
2442 InstructionList.push_back(I);
2446 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
2448 Value *Vec1, *Vec2, *Mask;
2449 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
2450 popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2))
2451 return Error(InvalidRecord);
2453 if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
2454 return Error(InvalidRecord);
2455 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
2456 InstructionList.push_back(I);
2460 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
2461 // Old form of ICmp/FCmp returning bool
2462 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
2463 // both legal on vectors but had different behaviour.
2464 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
2465 // FCmp/ICmp returning bool or vector of bool
2469 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
2470 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
2471 OpNum+1 != Record.size())
2472 return Error(InvalidRecord);
2474 if (LHS->getType()->isFPOrFPVectorTy())
2475 I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
2477 I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
2478 InstructionList.push_back(I);
2482 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
2484 unsigned Size = Record.size();
2486 I = ReturnInst::Create(Context);
2487 InstructionList.push_back(I);
2493 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2494 return Error(InvalidRecord);
2495 if (OpNum != Record.size())
2496 return Error(InvalidRecord);
2498 I = ReturnInst::Create(Context, Op);
2499 InstructionList.push_back(I);
2502 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
2503 if (Record.size() != 1 && Record.size() != 3)
2504 return Error(InvalidRecord);
2505 BasicBlock *TrueDest = getBasicBlock(Record[0]);
2507 return Error(InvalidRecord);
2509 if (Record.size() == 1) {
2510 I = BranchInst::Create(TrueDest);
2511 InstructionList.push_back(I);
2514 BasicBlock *FalseDest = getBasicBlock(Record[1]);
2515 Value *Cond = getValue(Record, 2, NextValueNo,
2516 Type::getInt1Ty(Context));
2517 if (FalseDest == 0 || Cond == 0)
2518 return Error(InvalidRecord);
2519 I = BranchInst::Create(TrueDest, FalseDest, Cond);
2520 InstructionList.push_back(I);
2524 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
2526 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
2527 // "New" SwitchInst format with case ranges. The changes to write this
2528 // format were reverted but we still recognize bitcode that uses it.
2529 // Hopefully someday we will have support for case ranges and can use
2530 // this format again.
2532 Type *OpTy = getTypeByID(Record[1]);
2533 unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
2535 Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
2536 BasicBlock *Default = getBasicBlock(Record[3]);
2537 if (OpTy == 0 || Cond == 0 || Default == 0)
2538 return Error(InvalidRecord);
2540 unsigned NumCases = Record[4];
2542 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
2543 InstructionList.push_back(SI);
2545 unsigned CurIdx = 5;
2546 for (unsigned i = 0; i != NumCases; ++i) {
2547 SmallVector<ConstantInt*, 1> CaseVals;
2548 unsigned NumItems = Record[CurIdx++];
2549 for (unsigned ci = 0; ci != NumItems; ++ci) {
2550 bool isSingleNumber = Record[CurIdx++];
2553 unsigned ActiveWords = 1;
2554 if (ValueBitWidth > 64)
2555 ActiveWords = Record[CurIdx++];
2556 Low = ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
2558 CurIdx += ActiveWords;
2560 if (!isSingleNumber) {
2562 if (ValueBitWidth > 64)
2563 ActiveWords = Record[CurIdx++];
2565 ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
2567 CurIdx += ActiveWords;
2569 // FIXME: It is not clear whether values in the range should be
2570 // compared as signed or unsigned values. The partially
2571 // implemented changes that used this format in the past used
2572 // unsigned comparisons.
2573 for ( ; Low.ule(High); ++Low)
2574 CaseVals.push_back(ConstantInt::get(Context, Low));
2576 CaseVals.push_back(ConstantInt::get(Context, Low));
2578 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
2579 for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(),
2580 cve = CaseVals.end(); cvi != cve; ++cvi)
2581 SI->addCase(*cvi, DestBB);
2587 // Old SwitchInst format without case ranges.
2589 if (Record.size() < 3 || (Record.size() & 1) == 0)
2590 return Error(InvalidRecord);
2591 Type *OpTy = getTypeByID(Record[0]);
2592 Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
2593 BasicBlock *Default = getBasicBlock(Record[2]);
2594 if (OpTy == 0 || Cond == 0 || Default == 0)
2595 return Error(InvalidRecord);
2596 unsigned NumCases = (Record.size()-3)/2;
2597 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
2598 InstructionList.push_back(SI);
2599 for (unsigned i = 0, e = NumCases; i != e; ++i) {
2600 ConstantInt *CaseVal =
2601 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
2602 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
2603 if (CaseVal == 0 || DestBB == 0) {
2605 return Error(InvalidRecord);
2607 SI->addCase(CaseVal, DestBB);
2612 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
2613 if (Record.size() < 2)
2614 return Error(InvalidRecord);
2615 Type *OpTy = getTypeByID(Record[0]);
2616 Value *Address = getValue(Record, 1, NextValueNo, OpTy);
2617 if (OpTy == 0 || Address == 0)
2618 return Error(InvalidRecord);
2619 unsigned NumDests = Record.size()-2;
2620 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
2621 InstructionList.push_back(IBI);
2622 for (unsigned i = 0, e = NumDests; i != e; ++i) {
2623 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
2624 IBI->addDestination(DestBB);
2627 return Error(InvalidRecord);
2634 case bitc::FUNC_CODE_INST_INVOKE: {
2635 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
2636 if (Record.size() < 4)
2637 return Error(InvalidRecord);
2638 AttributeSet PAL = getAttributes(Record[0]);
2639 unsigned CCInfo = Record[1];
2640 BasicBlock *NormalBB = getBasicBlock(Record[2]);
2641 BasicBlock *UnwindBB = getBasicBlock(Record[3]);
2645 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
2646 return Error(InvalidRecord);
2648 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
2649 FunctionType *FTy = !CalleeTy ? 0 :
2650 dyn_cast<FunctionType>(CalleeTy->getElementType());
2652 // Check that the right number of fixed parameters are here.
2653 if (FTy == 0 || NormalBB == 0 || UnwindBB == 0 ||
2654 Record.size() < OpNum+FTy->getNumParams())
2655 return Error(InvalidRecord);
2657 SmallVector<Value*, 16> Ops;
2658 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
2659 Ops.push_back(getValue(Record, OpNum, NextValueNo,
2660 FTy->getParamType(i)));
2661 if (Ops.back() == 0)
2662 return Error(InvalidRecord);
2665 if (!FTy->isVarArg()) {
2666 if (Record.size() != OpNum)
2667 return Error(InvalidRecord);
2669 // Read type/value pairs for varargs params.
2670 while (OpNum != Record.size()) {
2672 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2673 return Error(InvalidRecord);
2678 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops);
2679 InstructionList.push_back(I);
2680 cast<InvokeInst>(I)->setCallingConv(
2681 static_cast<CallingConv::ID>(CCInfo));
2682 cast<InvokeInst>(I)->setAttributes(PAL);
2685 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
2688 if (getValueTypePair(Record, Idx, NextValueNo, Val))
2689 return Error(InvalidRecord);
2690 I = ResumeInst::Create(Val);
2691 InstructionList.push_back(I);
2694 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
2695 I = new UnreachableInst(Context);
2696 InstructionList.push_back(I);
2698 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
2699 if (Record.size() < 1 || ((Record.size()-1)&1))
2700 return Error(InvalidRecord);
2701 Type *Ty = getTypeByID(Record[0]);
2703 return Error(InvalidRecord);
2705 PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
2706 InstructionList.push_back(PN);
2708 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
2710 // With the new function encoding, it is possible that operands have
2711 // negative IDs (for forward references). Use a signed VBR
2712 // representation to keep the encoding small.
2714 V = getValueSigned(Record, 1+i, NextValueNo, Ty);
2716 V = getValue(Record, 1+i, NextValueNo, Ty);
2717 BasicBlock *BB = getBasicBlock(Record[2+i]);
2719 return Error(InvalidRecord);
2720 PN->addIncoming(V, BB);
2726 case bitc::FUNC_CODE_INST_LANDINGPAD: {
2727 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
2729 if (Record.size() < 4)
2730 return Error(InvalidRecord);
2731 Type *Ty = getTypeByID(Record[Idx++]);
2733 return Error(InvalidRecord);
2735 if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
2736 return Error(InvalidRecord);
2738 bool IsCleanup = !!Record[Idx++];
2739 unsigned NumClauses = Record[Idx++];
2740 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, NumClauses);
2741 LP->setCleanup(IsCleanup);
2742 for (unsigned J = 0; J != NumClauses; ++J) {
2743 LandingPadInst::ClauseType CT =
2744 LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
2747 if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
2749 return Error(InvalidRecord);
2752 assert((CT != LandingPadInst::Catch ||
2753 !isa<ArrayType>(Val->getType())) &&
2754 "Catch clause has a invalid type!");
2755 assert((CT != LandingPadInst::Filter ||
2756 isa<ArrayType>(Val->getType())) &&
2757 "Filter clause has invalid type!");
2762 InstructionList.push_back(I);
2766 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
2767 if (Record.size() != 4)
2768 return Error(InvalidRecord);
2770 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
2771 Type *OpTy = getTypeByID(Record[1]);
2772 Value *Size = getFnValueByID(Record[2], OpTy);
2773 unsigned Align = Record[3];
2775 return Error(InvalidRecord);
2776 I = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
2777 InstructionList.push_back(I);
2780 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
2783 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2784 OpNum+2 != Record.size())
2785 return Error(InvalidRecord);
2787 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1);
2788 InstructionList.push_back(I);
2791 case bitc::FUNC_CODE_INST_LOADATOMIC: {
2792 // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
2795 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2796 OpNum+4 != Record.size())
2797 return Error(InvalidRecord);
2800 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
2801 if (Ordering == NotAtomic || Ordering == Release ||
2802 Ordering == AcquireRelease)
2803 return Error(InvalidRecord);
2804 if (Ordering != NotAtomic && Record[OpNum] == 0)
2805 return Error(InvalidRecord);
2806 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2808 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1,
2809 Ordering, SynchScope);
2810 InstructionList.push_back(I);
2813 case bitc::FUNC_CODE_INST_STORE: { // STORE2:[ptrty, ptr, val, align, vol]
2816 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2817 popValue(Record, OpNum, NextValueNo,
2818 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2819 OpNum+2 != Record.size())
2820 return Error(InvalidRecord);
2822 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
2823 InstructionList.push_back(I);
2826 case bitc::FUNC_CODE_INST_STOREATOMIC: {
2827 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
2830 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2831 popValue(Record, OpNum, NextValueNo,
2832 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2833 OpNum+4 != Record.size())
2834 return Error(InvalidRecord);
2836 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
2837 if (Ordering == NotAtomic || Ordering == Acquire ||
2838 Ordering == AcquireRelease)
2839 return Error(InvalidRecord);
2840 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2841 if (Ordering != NotAtomic && Record[OpNum] == 0)
2842 return Error(InvalidRecord);
2844 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1,
2845 Ordering, SynchScope);
2846 InstructionList.push_back(I);
2849 case bitc::FUNC_CODE_INST_CMPXCHG: {
2850 // CMPXCHG:[ptrty, ptr, cmp, new, vol, ordering, synchscope]
2852 Value *Ptr, *Cmp, *New;
2853 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2854 popValue(Record, OpNum, NextValueNo,
2855 cast<PointerType>(Ptr->getType())->getElementType(), Cmp) ||
2856 popValue(Record, OpNum, NextValueNo,
2857 cast<PointerType>(Ptr->getType())->getElementType(), New) ||
2858 OpNum+3 != Record.size())
2859 return Error(InvalidRecord);
2860 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+1]);
2861 if (Ordering == NotAtomic || Ordering == Unordered)
2862 return Error(InvalidRecord);
2863 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+2]);
2864 I = new AtomicCmpXchgInst(Ptr, Cmp, New, Ordering, SynchScope);
2865 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
2866 InstructionList.push_back(I);
2869 case bitc::FUNC_CODE_INST_ATOMICRMW: {
2870 // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
2873 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2874 popValue(Record, OpNum, NextValueNo,
2875 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2876 OpNum+4 != Record.size())
2877 return Error(InvalidRecord);
2878 AtomicRMWInst::BinOp Operation = GetDecodedRMWOperation(Record[OpNum]);
2879 if (Operation < AtomicRMWInst::FIRST_BINOP ||
2880 Operation > AtomicRMWInst::LAST_BINOP)
2881 return Error(InvalidRecord);
2882 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
2883 if (Ordering == NotAtomic || Ordering == Unordered)
2884 return Error(InvalidRecord);
2885 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2886 I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
2887 cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
2888 InstructionList.push_back(I);
2891 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
2892 if (2 != Record.size())
2893 return Error(InvalidRecord);
2894 AtomicOrdering Ordering = GetDecodedOrdering(Record[0]);
2895 if (Ordering == NotAtomic || Ordering == Unordered ||
2896 Ordering == Monotonic)
2897 return Error(InvalidRecord);
2898 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[1]);
2899 I = new FenceInst(Context, Ordering, SynchScope);
2900 InstructionList.push_back(I);
2903 case bitc::FUNC_CODE_INST_CALL: {
2904 // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
2905 if (Record.size() < 3)
2906 return Error(InvalidRecord);
2908 AttributeSet PAL = getAttributes(Record[0]);
2909 unsigned CCInfo = Record[1];
2913 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
2914 return Error(InvalidRecord);
2916 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
2917 FunctionType *FTy = 0;
2918 if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
2919 if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
2920 return Error(InvalidRecord);
2922 SmallVector<Value*, 16> Args;
2923 // Read the fixed params.
2924 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
2925 if (FTy->getParamType(i)->isLabelTy())
2926 Args.push_back(getBasicBlock(Record[OpNum]));
2928 Args.push_back(getValue(Record, OpNum, NextValueNo,
2929 FTy->getParamType(i)));
2930 if (Args.back() == 0)
2931 return Error(InvalidRecord);
2934 // Read type/value pairs for varargs params.
2935 if (!FTy->isVarArg()) {
2936 if (OpNum != Record.size())
2937 return Error(InvalidRecord);
2939 while (OpNum != Record.size()) {
2941 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2942 return Error(InvalidRecord);
2947 I = CallInst::Create(Callee, Args);
2948 InstructionList.push_back(I);
2949 cast<CallInst>(I)->setCallingConv(
2950 static_cast<CallingConv::ID>(CCInfo>>1));
2951 cast<CallInst>(I)->setTailCall(CCInfo & 1);
2952 cast<CallInst>(I)->setAttributes(PAL);
2955 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
2956 if (Record.size() < 3)
2957 return Error(InvalidRecord);
2958 Type *OpTy = getTypeByID(Record[0]);
2959 Value *Op = getValue(Record, 1, NextValueNo, OpTy);
2960 Type *ResTy = getTypeByID(Record[2]);
2961 if (!OpTy || !Op || !ResTy)
2962 return Error(InvalidRecord);
2963 I = new VAArgInst(Op, ResTy);
2964 InstructionList.push_back(I);
2969 // Add instruction to end of current BB. If there is no current BB, reject
2973 return Error(InvalidInstructionWithNoBB);
2975 CurBB->getInstList().push_back(I);
2977 // If this was a terminator instruction, move to the next block.
2978 if (isa<TerminatorInst>(I)) {
2980 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : 0;
2983 // Non-void values get registered in the value table for future use.
2984 if (I && !I->getType()->isVoidTy())
2985 ValueList.AssignValue(I, NextValueNo++);
2990 // Check the function list for unresolved values.
2991 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
2992 if (A->getParent() == 0) {
2993 // We found at least one unresolved value. Nuke them all to avoid leaks.
2994 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
2995 if ((A = dyn_cast<Argument>(ValueList[i])) && A->getParent() == 0) {
2996 A->replaceAllUsesWith(UndefValue::get(A->getType()));
3000 return Error(NeverResolvedValueFoundInFunction);
3004 // FIXME: Check for unresolved forward-declared metadata references
3005 // and clean up leaks.
3007 // See if anything took the address of blocks in this function. If so,
3008 // resolve them now.
3009 DenseMap<Function*, std::vector<BlockAddrRefTy> >::iterator BAFRI =
3010 BlockAddrFwdRefs.find(F);
3011 if (BAFRI != BlockAddrFwdRefs.end()) {
3012 std::vector<BlockAddrRefTy> &RefList = BAFRI->second;
3013 for (unsigned i = 0, e = RefList.size(); i != e; ++i) {
3014 unsigned BlockIdx = RefList[i].first;
3015 if (BlockIdx >= FunctionBBs.size())
3016 return Error(InvalidID);
3018 GlobalVariable *FwdRef = RefList[i].second;
3019 FwdRef->replaceAllUsesWith(BlockAddress::get(F, FunctionBBs[BlockIdx]));
3020 FwdRef->eraseFromParent();
3023 BlockAddrFwdRefs.erase(BAFRI);
3026 // Trim the value list down to the size it was before we parsed this function.
3027 ValueList.shrinkTo(ModuleValueListSize);
3028 MDValueList.shrinkTo(ModuleMDValueListSize);
3029 std::vector<BasicBlock*>().swap(FunctionBBs);
3030 return error_code::success();
3033 /// Find the function body in the bitcode stream
3034 error_code BitcodeReader::FindFunctionInStream(Function *F,
3035 DenseMap<Function*, uint64_t>::iterator DeferredFunctionInfoIterator) {
3036 while (DeferredFunctionInfoIterator->second == 0) {
3037 if (Stream.AtEndOfStream())
3038 return Error(CouldNotFindFunctionInStream);
3039 // ParseModule will parse the next body in the stream and set its
3040 // position in the DeferredFunctionInfo map.
3041 if (error_code EC = ParseModule(true))
3044 return error_code::success();
3047 //===----------------------------------------------------------------------===//
3048 // GVMaterializer implementation
3049 //===----------------------------------------------------------------------===//
3052 bool BitcodeReader::isMaterializable(const GlobalValue *GV) const {
3053 if (const Function *F = dyn_cast<Function>(GV)) {
3054 return F->isDeclaration() &&
3055 DeferredFunctionInfo.count(const_cast<Function*>(F));
3060 error_code BitcodeReader::Materialize(GlobalValue *GV) {
3061 Function *F = dyn_cast<Function>(GV);
3062 // If it's not a function or is already material, ignore the request.
3063 if (!F || !F->isMaterializable())
3064 return error_code::success();
3066 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
3067 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
3068 // If its position is recorded as 0, its body is somewhere in the stream
3069 // but we haven't seen it yet.
3070 if (DFII->second == 0 && LazyStreamer)
3071 if (error_code EC = FindFunctionInStream(F, DFII))
3074 // Move the bit stream to the saved position of the deferred function body.
3075 Stream.JumpToBit(DFII->second);
3077 if (error_code EC = ParseFunctionBody(F))
3080 // Upgrade any old intrinsic calls in the function.
3081 for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
3082 E = UpgradedIntrinsics.end(); I != E; ++I) {
3083 if (I->first != I->second) {
3084 for (Value::use_iterator UI = I->first->use_begin(),
3085 UE = I->first->use_end(); UI != UE; ) {
3086 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
3087 UpgradeIntrinsicCall(CI, I->second);
3092 return error_code::success();
3095 bool BitcodeReader::isDematerializable(const GlobalValue *GV) const {
3096 const Function *F = dyn_cast<Function>(GV);
3097 if (!F || F->isDeclaration())
3099 return DeferredFunctionInfo.count(const_cast<Function*>(F));
3102 void BitcodeReader::Dematerialize(GlobalValue *GV) {
3103 Function *F = dyn_cast<Function>(GV);
3104 // If this function isn't dematerializable, this is a noop.
3105 if (!F || !isDematerializable(F))
3108 assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
3110 // Just forget the function body, we can remat it later.
3115 error_code BitcodeReader::MaterializeModule(Module *M) {
3116 assert(M == TheModule &&
3117 "Can only Materialize the Module this BitcodeReader is attached to.");
3118 // Iterate over the module, deserializing any functions that are still on
3120 for (Module::iterator F = TheModule->begin(), E = TheModule->end();
3122 if (F->isMaterializable()) {
3123 if (error_code EC = Materialize(F))
3127 // At this point, if there are any function bodies, the current bit is
3128 // pointing to the END_BLOCK record after them. Now make sure the rest
3129 // of the bits in the module have been read.
3133 // Upgrade any intrinsic calls that slipped through (should not happen!) and
3134 // delete the old functions to clean up. We can't do this unless the entire
3135 // module is materialized because there could always be another function body
3136 // with calls to the old function.
3137 for (std::vector<std::pair<Function*, Function*> >::iterator I =
3138 UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
3139 if (I->first != I->second) {
3140 for (Value::use_iterator UI = I->first->use_begin(),
3141 UE = I->first->use_end(); UI != UE; ) {
3142 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
3143 UpgradeIntrinsicCall(CI, I->second);
3145 if (!I->first->use_empty())
3146 I->first->replaceAllUsesWith(I->second);
3147 I->first->eraseFromParent();
3150 std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
3152 for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
3153 UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
3155 return error_code::success();
3158 error_code BitcodeReader::InitStream() {
3160 return InitLazyStream();
3161 return InitStreamFromBuffer();
3164 error_code BitcodeReader::InitStreamFromBuffer() {
3165 const unsigned char *BufPtr = (const unsigned char*)Buffer->getBufferStart();
3166 const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
3168 if (Buffer->getBufferSize() & 3) {
3169 if (!isRawBitcode(BufPtr, BufEnd) && !isBitcodeWrapper(BufPtr, BufEnd))
3170 return Error(InvalidBitcodeSignature);
3172 return Error(BitcodeStreamInvalidSize);
3175 // If we have a wrapper header, parse it and ignore the non-bc file contents.
3176 // The magic number is 0x0B17C0DE stored in little endian.
3177 if (isBitcodeWrapper(BufPtr, BufEnd))
3178 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
3179 return Error(InvalidBitcodeWrapperHeader);
3181 StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
3182 Stream.init(*StreamFile);
3184 return error_code::success();
3187 error_code BitcodeReader::InitLazyStream() {
3188 // Check and strip off the bitcode wrapper; BitstreamReader expects never to
3190 StreamingMemoryObject *Bytes = new StreamingMemoryObject(LazyStreamer);
3191 StreamFile.reset(new BitstreamReader(Bytes));
3192 Stream.init(*StreamFile);
3194 unsigned char buf[16];
3195 if (Bytes->readBytes(0, 16, buf) == -1)
3196 return Error(BitcodeStreamInvalidSize);
3198 if (!isBitcode(buf, buf + 16))
3199 return Error(InvalidBitcodeSignature);
3201 if (isBitcodeWrapper(buf, buf + 4)) {
3202 const unsigned char *bitcodeStart = buf;
3203 const unsigned char *bitcodeEnd = buf + 16;
3204 SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
3205 Bytes->dropLeadingBytes(bitcodeStart - buf);
3206 Bytes->setKnownObjectSize(bitcodeEnd - bitcodeStart);
3208 return error_code::success();
3212 class BitcodeErrorCategoryType : public _do_message {
3213 const char *name() const LLVM_OVERRIDE {
3214 return "llvm.bitcode";
3216 std::string message(int IE) const LLVM_OVERRIDE {
3217 BitcodeReader::ErrorType E = static_cast<BitcodeReader::ErrorType>(IE);
3219 case BitcodeReader::BitcodeStreamInvalidSize:
3220 return "Bitcode stream length should be >= 16 bytes and a multiple of 4";
3221 case BitcodeReader::ConflictingMETADATA_KINDRecords:
3222 return "Conflicting METADATA_KIND records";
3223 case BitcodeReader::CouldNotFindFunctionInStream:
3224 return "Could not find function in stream";
3225 case BitcodeReader::ExpectedConstant:
3226 return "Expected a constant";
3227 case BitcodeReader::InsufficientFunctionProtos:
3228 return "Insufficient function protos";
3229 case BitcodeReader::InvalidBitcodeSignature:
3230 return "Invalid bitcode signature";
3231 case BitcodeReader::InvalidBitcodeWrapperHeader:
3232 return "Invalid bitcode wrapper header";
3233 case BitcodeReader::InvalidConstantReference:
3234 return "Invalid ronstant reference";
3235 case BitcodeReader::InvalidID:
3236 return "Invalid ID";
3237 case BitcodeReader::InvalidInstructionWithNoBB:
3238 return "Invalid instruction with no BB";
3239 case BitcodeReader::InvalidRecord:
3240 return "Invalid record";
3241 case BitcodeReader::InvalidTypeForValue:
3242 return "Invalid type for value";
3243 case BitcodeReader::InvalidTYPETable:
3244 return "Invalid TYPE table";
3245 case BitcodeReader::InvalidType:
3246 return "Invalid type";
3247 case BitcodeReader::MalformedBlock:
3248 return "Malformed block";
3249 case BitcodeReader::MalformedGlobalInitializerSet:
3250 return "Malformed global initializer set";
3251 case BitcodeReader::InvalidMultipleBlocks:
3252 return "Invalid multiple blocks";
3253 case BitcodeReader::NeverResolvedValueFoundInFunction:
3254 return "Never resolved value found in function";
3255 case BitcodeReader::InvalidValue:
3256 return "Invalid value";
3258 llvm_unreachable("Unknown error type!");
3263 const error_category &BitcodeReader::BitcodeErrorCategory() {
3264 static BitcodeErrorCategoryType O;
3268 //===----------------------------------------------------------------------===//
3269 // External interface
3270 //===----------------------------------------------------------------------===//
3272 /// getLazyBitcodeModule - lazy function-at-a-time loading from a file.
3274 Module *llvm::getLazyBitcodeModule(MemoryBuffer *Buffer,
3275 LLVMContext& Context,
3276 std::string *ErrMsg) {
3277 Module *M = new Module(Buffer->getBufferIdentifier(), Context);
3278 BitcodeReader *R = new BitcodeReader(Buffer, Context);
3279 M->setMaterializer(R);
3280 if (error_code EC = R->ParseBitcodeInto(M)) {
3282 *ErrMsg = EC.message();
3284 delete M; // Also deletes R.
3287 // Have the BitcodeReader dtor delete 'Buffer'.
3288 R->setBufferOwned(true);
3290 R->materializeForwardReferencedFunctions();
3296 Module *llvm::getStreamedBitcodeModule(const std::string &name,
3297 DataStreamer *streamer,
3298 LLVMContext &Context,
3299 std::string *ErrMsg) {
3300 Module *M = new Module(name, Context);
3301 BitcodeReader *R = new BitcodeReader(streamer, Context);
3302 M->setMaterializer(R);
3303 if (error_code EC = R->ParseBitcodeInto(M)) {
3305 *ErrMsg = EC.message();
3306 delete M; // Also deletes R.
3309 R->setBufferOwned(false); // no buffer to delete
3313 /// ParseBitcodeFile - Read the specified bitcode file, returning the module.
3314 /// If an error occurs, return null and fill in *ErrMsg if non-null.
3315 Module *llvm::ParseBitcodeFile(MemoryBuffer *Buffer, LLVMContext& Context,
3316 std::string *ErrMsg){
3317 Module *M = getLazyBitcodeModule(Buffer, Context, ErrMsg);
3320 // Don't let the BitcodeReader dtor delete 'Buffer', regardless of whether
3321 // there was an error.
3322 static_cast<BitcodeReader*>(M->getMaterializer())->setBufferOwned(false);
3324 // Read in the entire module, and destroy the BitcodeReader.
3325 if (M->MaterializeAllPermanently(ErrMsg)) {
3330 // TODO: Restore the use-lists to the in-memory state when the bitcode was
3331 // written. We must defer until the Module has been fully materialized.
3336 std::string llvm::getBitcodeTargetTriple(MemoryBuffer *Buffer,
3337 LLVMContext& Context,
3338 std::string *ErrMsg) {
3339 BitcodeReader *R = new BitcodeReader(Buffer, Context);
3340 // Don't let the BitcodeReader dtor delete 'Buffer'.
3341 R->setBufferOwned(false);
3343 std::string Triple("");
3344 if (error_code EC = R->ParseTriple(Triple))
3346 *ErrMsg = EC.message();