1 //===- Reader.cpp - Code to read bytecode files ---------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This library implements the functionality defined in llvm/Bytecode/Reader.h
12 // Note that this library should be as fast as possible, reentrant, and
15 // TODO: Allow passing in an option to ignore the symbol table
17 //===----------------------------------------------------------------------===//
20 #include "llvm/Bytecode/BytecodeHandler.h"
21 #include "llvm/BasicBlock.h"
22 #include "llvm/CallingConv.h"
23 #include "llvm/Constants.h"
24 #include "llvm/InlineAsm.h"
25 #include "llvm/Instructions.h"
26 #include "llvm/TypeSymbolTable.h"
27 #include "llvm/Bytecode/Format.h"
28 #include "llvm/Config/alloca.h"
29 #include "llvm/Support/GetElementPtrTypeIterator.h"
30 #include "llvm/Support/MathExtras.h"
31 #include "llvm/ADT/SmallVector.h"
32 #include "llvm/ADT/StringExtras.h"
38 /// @brief A class for maintaining the slot number definition
39 /// as a placeholder for the actual definition for forward constants defs.
40 class ConstantPlaceHolder : public ConstantExpr {
41 ConstantPlaceHolder(); // DO NOT IMPLEMENT
42 void operator=(const ConstantPlaceHolder &); // DO NOT IMPLEMENT
45 ConstantPlaceHolder(const Type *Ty)
46 : ConstantExpr(Ty, Instruction::UserOp1, &Op, 1),
47 Op(UndefValue::get(Type::Int32Ty), this) {
52 // Provide some details on error
53 inline void BytecodeReader::error(const std::string& err) {
54 ErrorMsg = err + " (Vers=" + itostr(RevisionNum) + ", Pos="
55 + itostr(At-MemStart) + ")";
56 if (Handler) Handler->handleError(ErrorMsg);
60 //===----------------------------------------------------------------------===//
61 // Bytecode Reading Methods
62 //===----------------------------------------------------------------------===//
64 /// Determine if the current block being read contains any more data.
65 inline bool BytecodeReader::moreInBlock() {
69 /// Throw an error if we've read past the end of the current block
70 inline void BytecodeReader::checkPastBlockEnd(const char * block_name) {
72 error(std::string("Attempt to read past the end of ") + block_name +
76 /// Read a whole unsigned integer
77 inline unsigned BytecodeReader::read_uint() {
79 error("Ran out of data reading uint!");
81 return At[-4] | (At[-3] << 8) | (At[-2] << 16) | (At[-1] << 24);
84 /// Read a variable-bit-rate encoded unsigned integer
85 inline unsigned BytecodeReader::read_vbr_uint() {
91 error("Ran out of data reading vbr_uint!");
92 Result |= (unsigned)((*At++) & 0x7F) << Shift;
94 } while (At[-1] & 0x80);
98 /// Read a variable-bit-rate encoded unsigned 64-bit integer.
99 inline uint64_t BytecodeReader::read_vbr_uint64() {
105 error("Ran out of data reading vbr_uint64!");
106 Result |= (uint64_t)((*At++) & 0x7F) << Shift;
108 } while (At[-1] & 0x80);
112 /// Read a variable-bit-rate encoded signed 64-bit integer.
113 inline int64_t BytecodeReader::read_vbr_int64() {
114 uint64_t R = read_vbr_uint64();
117 return -(int64_t)(R >> 1);
118 else // There is no such thing as -0 with integers. "-0" really means
119 // 0x8000000000000000.
122 return (int64_t)(R >> 1);
125 /// Read a pascal-style string (length followed by text)
126 inline std::string BytecodeReader::read_str() {
127 unsigned Size = read_vbr_uint();
128 const unsigned char *OldAt = At;
130 if (At > BlockEnd) // Size invalid?
131 error("Ran out of data reading a string!");
132 return std::string((char*)OldAt, Size);
135 /// Read an arbitrary block of data
136 inline void BytecodeReader::read_data(void *Ptr, void *End) {
137 unsigned char *Start = (unsigned char *)Ptr;
138 unsigned Amount = (unsigned char *)End - Start;
139 if (At+Amount > BlockEnd)
140 error("Ran out of data!");
141 std::copy(At, At+Amount, Start);
145 /// Read a float value in little-endian order
146 inline void BytecodeReader::read_float(float& FloatVal) {
147 /// FIXME: This isn't optimal, it has size problems on some platforms
148 /// where FP is not IEEE.
149 FloatVal = BitsToFloat(At[0] | (At[1] << 8) | (At[2] << 16) | (At[3] << 24));
150 At+=sizeof(uint32_t);
153 /// Read a double value in little-endian order
154 inline void BytecodeReader::read_double(double& DoubleVal) {
155 /// FIXME: This isn't optimal, it has size problems on some platforms
156 /// where FP is not IEEE.
157 DoubleVal = BitsToDouble((uint64_t(At[0]) << 0) | (uint64_t(At[1]) << 8) |
158 (uint64_t(At[2]) << 16) | (uint64_t(At[3]) << 24) |
159 (uint64_t(At[4]) << 32) | (uint64_t(At[5]) << 40) |
160 (uint64_t(At[6]) << 48) | (uint64_t(At[7]) << 56));
161 At+=sizeof(uint64_t);
164 /// Read a block header and obtain its type and size
165 inline void BytecodeReader::read_block(unsigned &Type, unsigned &Size) {
166 Size = read_uint(); // Read the header
167 Type = Size & 0x1F; // mask low order five bits to get type
168 Size >>= 5; // high order 27 bits is the size
170 if (At + Size > BlockEnd)
171 error("Attempt to size a block past end of memory");
172 BlockEnd = At + Size;
173 if (Handler) Handler->handleBlock(Type, BlockStart, Size);
176 //===----------------------------------------------------------------------===//
178 //===----------------------------------------------------------------------===//
180 /// Determine if a type id has an implicit null value
181 inline bool BytecodeReader::hasImplicitNull(unsigned TyID) {
182 return TyID != Type::LabelTyID && TyID != Type::VoidTyID;
185 /// Obtain a type given a typeid and account for things like function level vs
186 /// module level, and the offsetting for the primitive types.
187 const Type *BytecodeReader::getType(unsigned ID) {
188 if (ID <= Type::LastPrimitiveTyID)
189 if (const Type *T = Type::getPrimitiveType((Type::TypeID)ID))
190 return T; // Asked for a primitive type...
192 // Otherwise, derived types need offset...
193 ID -= Type::FirstDerivedTyID;
195 // Is it a module-level type?
196 if (ID < ModuleTypes.size())
197 return ModuleTypes[ID].get();
199 // Nope, is it a function-level type?
200 ID -= ModuleTypes.size();
201 if (ID < FunctionTypes.size())
202 return FunctionTypes[ID].get();
204 error("Illegal type reference!");
208 /// This method just saves some coding. It uses read_vbr_uint to read in a
209 /// type id, errors that its not the type type, and then calls getType to
210 /// return the type value.
211 inline const Type* BytecodeReader::readType() {
212 return getType(read_vbr_uint());
215 /// Get the slot number associated with a type accounting for primitive
216 /// types and function level vs module level.
217 unsigned BytecodeReader::getTypeSlot(const Type *Ty) {
218 if (Ty->isPrimitiveType())
219 return Ty->getTypeID();
221 // Check the function level types first...
222 TypeListTy::iterator I = std::find(FunctionTypes.begin(),
223 FunctionTypes.end(), Ty);
225 if (I != FunctionTypes.end())
226 return Type::FirstDerivedTyID + ModuleTypes.size() +
227 (&*I - &FunctionTypes[0]);
229 // If we don't have our cache yet, build it now.
230 if (ModuleTypeIDCache.empty()) {
232 ModuleTypeIDCache.reserve(ModuleTypes.size());
233 for (TypeListTy::iterator I = ModuleTypes.begin(), E = ModuleTypes.end();
235 ModuleTypeIDCache.push_back(std::make_pair(*I, N));
237 std::sort(ModuleTypeIDCache.begin(), ModuleTypeIDCache.end());
240 // Binary search the cache for the entry.
241 std::vector<std::pair<const Type*, unsigned> >::iterator IT =
242 std::lower_bound(ModuleTypeIDCache.begin(), ModuleTypeIDCache.end(),
243 std::make_pair(Ty, 0U));
244 if (IT == ModuleTypeIDCache.end() || IT->first != Ty)
245 error("Didn't find type in ModuleTypes.");
247 return Type::FirstDerivedTyID + IT->second;
250 /// Retrieve a value of a given type and slot number, possibly creating
251 /// it if it doesn't already exist.
252 Value * BytecodeReader::getValue(unsigned type, unsigned oNum, bool Create) {
253 assert(type != Type::LabelTyID && "getValue() cannot get blocks!");
256 // By default, the global type id is the type id passed in
257 unsigned GlobalTyID = type;
259 if (hasImplicitNull(GlobalTyID)) {
260 const Type *Ty = getType(type);
261 if (!isa<OpaqueType>(Ty)) {
263 return Constant::getNullValue(Ty);
268 if (GlobalTyID < ModuleValues.size() && ModuleValues[GlobalTyID]) {
269 if (Num < ModuleValues[GlobalTyID]->size())
270 return ModuleValues[GlobalTyID]->getOperand(Num);
271 Num -= ModuleValues[GlobalTyID]->size();
274 if (FunctionValues.size() > type &&
275 FunctionValues[type] &&
276 Num < FunctionValues[type]->size())
277 return FunctionValues[type]->getOperand(Num);
279 if (!Create) return 0; // Do not create a placeholder?
281 // Did we already create a place holder?
282 std::pair<unsigned,unsigned> KeyValue(type, oNum);
283 ForwardReferenceMap::iterator I = ForwardReferences.lower_bound(KeyValue);
284 if (I != ForwardReferences.end() && I->first == KeyValue)
285 return I->second; // We have already created this placeholder
287 // If the type exists (it should)
288 if (const Type* Ty = getType(type)) {
289 // Create the place holder
290 Value *Val = new Argument(Ty);
291 ForwardReferences.insert(I, std::make_pair(KeyValue, Val));
294 error("Can't create placeholder for value of type slot #" + utostr(type));
295 return 0; // just silence warning, error calls longjmp
299 /// Just like getValue, except that it returns a null pointer
300 /// only on error. It always returns a constant (meaning that if the value is
301 /// defined, but is not a constant, that is an error). If the specified
302 /// constant hasn't been parsed yet, a placeholder is defined and used.
303 /// Later, after the real value is parsed, the placeholder is eliminated.
304 Constant* BytecodeReader::getConstantValue(unsigned TypeSlot, unsigned Slot) {
305 if (Value *V = getValue(TypeSlot, Slot, false))
306 if (Constant *C = dyn_cast<Constant>(V))
307 return C; // If we already have the value parsed, just return it
309 error("Value for slot " + utostr(Slot) +
310 " is expected to be a constant!");
312 std::pair<unsigned, unsigned> Key(TypeSlot, Slot);
313 ConstantRefsType::iterator I = ConstantFwdRefs.lower_bound(Key);
315 if (I != ConstantFwdRefs.end() && I->first == Key) {
318 // Create a placeholder for the constant reference and
319 // keep track of the fact that we have a forward ref to recycle it
320 Constant *C = new ConstantPlaceHolder(getType(TypeSlot));
322 // Keep track of the fact that we have a forward ref to recycle it
323 ConstantFwdRefs.insert(I, std::make_pair(Key, C));
328 //===----------------------------------------------------------------------===//
329 // IR Construction Methods
330 //===----------------------------------------------------------------------===//
332 /// As values are created, they are inserted into the appropriate place
333 /// with this method. The ValueTable argument must be one of ModuleValues
334 /// or FunctionValues data members of this class.
335 unsigned BytecodeReader::insertValue(Value *Val, unsigned type,
336 ValueTable &ValueTab) {
337 if (ValueTab.size() <= type)
338 ValueTab.resize(type+1);
340 if (!ValueTab[type]) ValueTab[type] = new ValueList();
342 ValueTab[type]->push_back(Val);
344 bool HasOffset = hasImplicitNull(type) && !isa<OpaqueType>(Val->getType());
345 return ValueTab[type]->size()-1 + HasOffset;
348 /// Insert the arguments of a function as new values in the reader.
349 void BytecodeReader::insertArguments(Function* F) {
350 const FunctionType *FT = F->getFunctionType();
351 Function::arg_iterator AI = F->arg_begin();
352 for (FunctionType::param_iterator It = FT->param_begin();
353 It != FT->param_end(); ++It, ++AI)
354 insertValue(AI, getTypeSlot(AI->getType()), FunctionValues);
357 //===----------------------------------------------------------------------===//
358 // Bytecode Parsing Methods
359 //===----------------------------------------------------------------------===//
361 /// This method parses a single instruction. The instruction is
362 /// inserted at the end of the \p BB provided. The arguments of
363 /// the instruction are provided in the \p Oprnds vector.
364 void BytecodeReader::ParseInstruction(SmallVector<unsigned, 8> &Oprnds,
368 // Clear instruction data
372 unsigned Op = read_uint();
374 // bits Instruction format: Common to all formats
375 // --------------------------
376 // 01-00: Opcode type, fixed to 1.
378 Opcode = (Op >> 2) & 63;
379 Oprnds.resize((Op >> 0) & 03);
381 // Extract the operands
382 switch (Oprnds.size()) {
384 // bits Instruction format:
385 // --------------------------
386 // 19-08: Resulting type plane
387 // 31-20: Operand #1 (if set to (2^12-1), then zero operands)
389 iType = (Op >> 8) & 4095;
390 Oprnds[0] = (Op >> 20) & 4095;
391 if (Oprnds[0] == 4095) // Handle special encoding for 0 operands...
395 // bits Instruction format:
396 // --------------------------
397 // 15-08: Resulting type plane
401 iType = (Op >> 8) & 255;
402 Oprnds[0] = (Op >> 16) & 255;
403 Oprnds[1] = (Op >> 24) & 255;
406 // bits Instruction format:
407 // --------------------------
408 // 13-08: Resulting type plane
413 iType = (Op >> 8) & 63;
414 Oprnds[0] = (Op >> 14) & 63;
415 Oprnds[1] = (Op >> 20) & 63;
416 Oprnds[2] = (Op >> 26) & 63;
419 At -= 4; // Hrm, try this again...
420 Opcode = read_vbr_uint();
422 iType = read_vbr_uint();
424 unsigned NumOprnds = read_vbr_uint();
425 Oprnds.resize(NumOprnds);
428 error("Zero-argument instruction found; this is invalid.");
430 for (unsigned i = 0; i != NumOprnds; ++i)
431 Oprnds[i] = read_vbr_uint();
435 const Type *InstTy = getType(iType);
437 // Make the necessary adjustments for dealing with backwards compatibility
439 Instruction* Result = 0;
441 // First, handle the easy binary operators case
442 if (Opcode >= Instruction::BinaryOpsBegin &&
443 Opcode < Instruction::BinaryOpsEnd && Oprnds.size() == 2) {
444 Result = BinaryOperator::create(Instruction::BinaryOps(Opcode),
445 getValue(iType, Oprnds[0]),
446 getValue(iType, Oprnds[1]));
448 // Indicate that we don't think this is a call instruction (yet).
449 // Process based on the Opcode read
451 default: // There was an error, this shouldn't happen.
453 error("Illegal instruction read!");
455 case Instruction::VAArg:
456 if (Oprnds.size() != 2)
457 error("Invalid VAArg instruction!");
458 Result = new VAArgInst(getValue(iType, Oprnds[0]),
461 case Instruction::ExtractElement: {
462 if (Oprnds.size() != 2)
463 error("Invalid extractelement instruction!");
464 Value *V1 = getValue(iType, Oprnds[0]);
465 Value *V2 = getValue(Int32TySlot, Oprnds[1]);
467 if (!ExtractElementInst::isValidOperands(V1, V2))
468 error("Invalid extractelement instruction!");
470 Result = new ExtractElementInst(V1, V2);
473 case Instruction::InsertElement: {
474 const PackedType *PackedTy = dyn_cast<PackedType>(InstTy);
475 if (!PackedTy || Oprnds.size() != 3)
476 error("Invalid insertelement instruction!");
478 Value *V1 = getValue(iType, Oprnds[0]);
479 Value *V2 = getValue(getTypeSlot(PackedTy->getElementType()),Oprnds[1]);
480 Value *V3 = getValue(Int32TySlot, Oprnds[2]);
482 if (!InsertElementInst::isValidOperands(V1, V2, V3))
483 error("Invalid insertelement instruction!");
484 Result = new InsertElementInst(V1, V2, V3);
487 case Instruction::ShuffleVector: {
488 const PackedType *PackedTy = dyn_cast<PackedType>(InstTy);
489 if (!PackedTy || Oprnds.size() != 3)
490 error("Invalid shufflevector instruction!");
491 Value *V1 = getValue(iType, Oprnds[0]);
492 Value *V2 = getValue(iType, Oprnds[1]);
493 const PackedType *EltTy =
494 PackedType::get(Type::Int32Ty, PackedTy->getNumElements());
495 Value *V3 = getValue(getTypeSlot(EltTy), Oprnds[2]);
496 if (!ShuffleVectorInst::isValidOperands(V1, V2, V3))
497 error("Invalid shufflevector instruction!");
498 Result = new ShuffleVectorInst(V1, V2, V3);
501 case Instruction::Trunc:
502 if (Oprnds.size() != 2)
503 error("Invalid cast instruction!");
504 Result = new TruncInst(getValue(iType, Oprnds[0]),
507 case Instruction::ZExt:
508 if (Oprnds.size() != 2)
509 error("Invalid cast instruction!");
510 Result = new ZExtInst(getValue(iType, Oprnds[0]),
513 case Instruction::SExt:
514 if (Oprnds.size() != 2)
515 error("Invalid Cast instruction!");
516 Result = new SExtInst(getValue(iType, Oprnds[0]),
519 case Instruction::FPTrunc:
520 if (Oprnds.size() != 2)
521 error("Invalid cast instruction!");
522 Result = new FPTruncInst(getValue(iType, Oprnds[0]),
525 case Instruction::FPExt:
526 if (Oprnds.size() != 2)
527 error("Invalid cast instruction!");
528 Result = new FPExtInst(getValue(iType, Oprnds[0]),
531 case Instruction::UIToFP:
532 if (Oprnds.size() != 2)
533 error("Invalid cast instruction!");
534 Result = new UIToFPInst(getValue(iType, Oprnds[0]),
537 case Instruction::SIToFP:
538 if (Oprnds.size() != 2)
539 error("Invalid cast instruction!");
540 Result = new SIToFPInst(getValue(iType, Oprnds[0]),
543 case Instruction::FPToUI:
544 if (Oprnds.size() != 2)
545 error("Invalid cast instruction!");
546 Result = new FPToUIInst(getValue(iType, Oprnds[0]),
549 case Instruction::FPToSI:
550 if (Oprnds.size() != 2)
551 error("Invalid cast instruction!");
552 Result = new FPToSIInst(getValue(iType, Oprnds[0]),
555 case Instruction::IntToPtr:
556 if (Oprnds.size() != 2)
557 error("Invalid cast instruction!");
558 Result = new IntToPtrInst(getValue(iType, Oprnds[0]),
561 case Instruction::PtrToInt:
562 if (Oprnds.size() != 2)
563 error("Invalid cast instruction!");
564 Result = new PtrToIntInst(getValue(iType, Oprnds[0]),
567 case Instruction::BitCast:
568 if (Oprnds.size() != 2)
569 error("Invalid cast instruction!");
570 Result = new BitCastInst(getValue(iType, Oprnds[0]),
573 case Instruction::Select:
574 if (Oprnds.size() != 3)
575 error("Invalid Select instruction!");
576 Result = new SelectInst(getValue(BoolTySlot, Oprnds[0]),
577 getValue(iType, Oprnds[1]),
578 getValue(iType, Oprnds[2]));
580 case Instruction::PHI: {
581 if (Oprnds.size() == 0 || (Oprnds.size() & 1))
582 error("Invalid phi node encountered!");
584 PHINode *PN = new PHINode(InstTy);
585 PN->reserveOperandSpace(Oprnds.size());
586 for (unsigned i = 0, e = Oprnds.size(); i != e; i += 2)
588 getValue(iType, Oprnds[i]), getBasicBlock(Oprnds[i+1]));
592 case Instruction::ICmp:
593 case Instruction::FCmp:
594 if (Oprnds.size() != 3)
595 error("Cmp instructions requires 3 operands");
596 // These instructions encode the comparison predicate as the 3rd operand.
597 Result = CmpInst::create(Instruction::OtherOps(Opcode),
598 static_cast<unsigned short>(Oprnds[2]),
599 getValue(iType, Oprnds[0]), getValue(iType, Oprnds[1]));
601 case Instruction::Ret:
602 if (Oprnds.size() == 0)
603 Result = new ReturnInst();
604 else if (Oprnds.size() == 1)
605 Result = new ReturnInst(getValue(iType, Oprnds[0]));
607 error("Unrecognized instruction!");
610 case Instruction::Br:
611 if (Oprnds.size() == 1)
612 Result = new BranchInst(getBasicBlock(Oprnds[0]));
613 else if (Oprnds.size() == 3)
614 Result = new BranchInst(getBasicBlock(Oprnds[0]),
615 getBasicBlock(Oprnds[1]), getValue(BoolTySlot, Oprnds[2]));
617 error("Invalid number of operands for a 'br' instruction!");
619 case Instruction::Switch: {
620 if (Oprnds.size() & 1)
621 error("Switch statement with odd number of arguments!");
623 SwitchInst *I = new SwitchInst(getValue(iType, Oprnds[0]),
624 getBasicBlock(Oprnds[1]),
626 for (unsigned i = 2, e = Oprnds.size(); i != e; i += 2)
627 I->addCase(cast<ConstantInt>(getValue(iType, Oprnds[i])),
628 getBasicBlock(Oprnds[i+1]));
632 case 58: // Call with extra operand for calling conv
633 case 59: // tail call, Fast CC
634 case 60: // normal call, Fast CC
635 case 61: // tail call, C Calling Conv
636 case Instruction::Call: { // Normal Call, C Calling Convention
637 if (Oprnds.size() == 0)
638 error("Invalid call instruction encountered!");
639 Value *F = getValue(iType, Oprnds[0]);
641 unsigned CallingConv = CallingConv::C;
642 bool isTailCall = false;
644 if (Opcode == 61 || Opcode == 59)
648 isTailCall = Oprnds.back() & 1;
649 CallingConv = Oprnds.back() >> 1;
651 } else if (Opcode == 59 || Opcode == 60) {
652 CallingConv = CallingConv::Fast;
655 // Check to make sure we have a pointer to function type
656 const PointerType *PTy = dyn_cast<PointerType>(F->getType());
657 if (PTy == 0) error("Call to non function pointer value!");
658 const FunctionType *FTy = dyn_cast<FunctionType>(PTy->getElementType());
659 if (FTy == 0) error("Call to non function pointer value!");
661 std::vector<Value *> Params;
662 if (!FTy->isVarArg()) {
663 FunctionType::param_iterator It = FTy->param_begin();
665 for (unsigned i = 1, e = Oprnds.size(); i != e; ++i) {
666 if (It == FTy->param_end())
667 error("Invalid call instruction!");
668 Params.push_back(getValue(getTypeSlot(*It++), Oprnds[i]));
670 if (It != FTy->param_end())
671 error("Invalid call instruction!");
673 Oprnds.erase(Oprnds.begin(), Oprnds.begin()+1);
675 unsigned FirstVariableOperand;
676 if (Oprnds.size() < FTy->getNumParams())
677 error("Call instruction missing operands!");
679 // Read all of the fixed arguments
680 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
682 getValue(getTypeSlot(FTy->getParamType(i)),Oprnds[i]));
684 FirstVariableOperand = FTy->getNumParams();
686 if ((Oprnds.size()-FirstVariableOperand) & 1)
687 error("Invalid call instruction!"); // Must be pairs of type/value
689 for (unsigned i = FirstVariableOperand, e = Oprnds.size();
691 Params.push_back(getValue(Oprnds[i], Oprnds[i+1]));
694 Result = new CallInst(F, Params);
695 if (isTailCall) cast<CallInst>(Result)->setTailCall();
696 if (CallingConv) cast<CallInst>(Result)->setCallingConv(CallingConv);
699 case Instruction::Invoke: { // Invoke C CC
700 if (Oprnds.size() < 3)
701 error("Invalid invoke instruction!");
702 Value *F = getValue(iType, Oprnds[0]);
704 // Check to make sure we have a pointer to function type
705 const PointerType *PTy = dyn_cast<PointerType>(F->getType());
707 error("Invoke to non function pointer value!");
708 const FunctionType *FTy = dyn_cast<FunctionType>(PTy->getElementType());
710 error("Invoke to non function pointer value!");
712 std::vector<Value *> Params;
713 BasicBlock *Normal, *Except;
714 unsigned CallingConv = Oprnds.back();
717 if (!FTy->isVarArg()) {
718 Normal = getBasicBlock(Oprnds[1]);
719 Except = getBasicBlock(Oprnds[2]);
721 FunctionType::param_iterator It = FTy->param_begin();
722 for (unsigned i = 3, e = Oprnds.size(); i != e; ++i) {
723 if (It == FTy->param_end())
724 error("Invalid invoke instruction!");
725 Params.push_back(getValue(getTypeSlot(*It++), Oprnds[i]));
727 if (It != FTy->param_end())
728 error("Invalid invoke instruction!");
730 Oprnds.erase(Oprnds.begin(), Oprnds.begin()+1);
732 Normal = getBasicBlock(Oprnds[0]);
733 Except = getBasicBlock(Oprnds[1]);
735 unsigned FirstVariableArgument = FTy->getNumParams()+2;
736 for (unsigned i = 2; i != FirstVariableArgument; ++i)
737 Params.push_back(getValue(getTypeSlot(FTy->getParamType(i-2)),
740 // Must be type/value pairs. If not, error out.
741 if (Oprnds.size()-FirstVariableArgument & 1)
742 error("Invalid invoke instruction!");
744 for (unsigned i = FirstVariableArgument; i < Oprnds.size(); i += 2)
745 Params.push_back(getValue(Oprnds[i], Oprnds[i+1]));
748 Result = new InvokeInst(F, Normal, Except, Params);
749 if (CallingConv) cast<InvokeInst>(Result)->setCallingConv(CallingConv);
752 case Instruction::Malloc: {
754 if (Oprnds.size() == 2)
755 Align = (1 << Oprnds[1]) >> 1;
756 else if (Oprnds.size() > 2)
757 error("Invalid malloc instruction!");
758 if (!isa<PointerType>(InstTy))
759 error("Invalid malloc instruction!");
761 Result = new MallocInst(cast<PointerType>(InstTy)->getElementType(),
762 getValue(Int32TySlot, Oprnds[0]), Align);
765 case Instruction::Alloca: {
767 if (Oprnds.size() == 2)
768 Align = (1 << Oprnds[1]) >> 1;
769 else if (Oprnds.size() > 2)
770 error("Invalid alloca instruction!");
771 if (!isa<PointerType>(InstTy))
772 error("Invalid alloca instruction!");
774 Result = new AllocaInst(cast<PointerType>(InstTy)->getElementType(),
775 getValue(Int32TySlot, Oprnds[0]), Align);
778 case Instruction::Free:
779 if (!isa<PointerType>(InstTy))
780 error("Invalid free instruction!");
781 Result = new FreeInst(getValue(iType, Oprnds[0]));
783 case Instruction::GetElementPtr: {
784 if (Oprnds.size() == 0 || !isa<PointerType>(InstTy))
785 error("Invalid getelementptr instruction!");
787 SmallVector<Value*, 8> Idx;
789 const Type *NextTy = InstTy;
790 for (unsigned i = 1, e = Oprnds.size(); i != e; ++i) {
791 const CompositeType *TopTy = dyn_cast_or_null<CompositeType>(NextTy);
793 error("Invalid getelementptr instruction!");
795 unsigned ValIdx = Oprnds[i];
797 // Struct indices are always uints, sequential type indices can be
798 // any of the 32 or 64-bit integer types. The actual choice of
799 // type is encoded in the low bit of the slot number.
800 if (isa<StructType>(TopTy))
803 switch (ValIdx & 1) {
805 case 0: IdxTy = Int32TySlot; break;
806 case 1: IdxTy = Int64TySlot; break;
810 Idx.push_back(getValue(IdxTy, ValIdx));
811 NextTy = GetElementPtrInst::getIndexedType(InstTy, &Idx[0], Idx.size(),
815 Result = new GetElementPtrInst(getValue(iType, Oprnds[0]),
816 &Idx[0], Idx.size());
819 case 62: // volatile load
820 case Instruction::Load:
821 if (Oprnds.size() != 1 || !isa<PointerType>(InstTy))
822 error("Invalid load instruction!");
823 Result = new LoadInst(getValue(iType, Oprnds[0]), "", Opcode == 62);
825 case 63: // volatile store
826 case Instruction::Store: {
827 if (!isa<PointerType>(InstTy) || Oprnds.size() != 2)
828 error("Invalid store instruction!");
830 Value *Ptr = getValue(iType, Oprnds[1]);
831 const Type *ValTy = cast<PointerType>(Ptr->getType())->getElementType();
832 Result = new StoreInst(getValue(getTypeSlot(ValTy), Oprnds[0]), Ptr,
836 case Instruction::Unwind:
837 if (Oprnds.size() != 0) error("Invalid unwind instruction!");
838 Result = new UnwindInst();
840 case Instruction::Unreachable:
841 if (Oprnds.size() != 0) error("Invalid unreachable instruction!");
842 Result = new UnreachableInst();
844 } // end switch(Opcode)
847 BB->getInstList().push_back(Result);
850 if (Result->getType() == InstTy)
853 TypeSlot = getTypeSlot(Result->getType());
855 // We have enough info to inform the handler now.
857 Handler->handleInstruction(Opcode, InstTy, &Oprnds[0], Oprnds.size(),
860 insertValue(Result, TypeSlot, FunctionValues);
863 /// Get a particular numbered basic block, which might be a forward reference.
864 /// This works together with ParseInstructionList to handle these forward
865 /// references in a clean manner. This function is used when constructing
866 /// phi, br, switch, and other instructions that reference basic blocks.
867 /// Blocks are numbered sequentially as they appear in the function.
868 BasicBlock *BytecodeReader::getBasicBlock(unsigned ID) {
869 // Make sure there is room in the table...
870 if (ParsedBasicBlocks.size() <= ID) ParsedBasicBlocks.resize(ID+1);
872 // First check to see if this is a backwards reference, i.e. this block
873 // has already been created, or if the forward reference has already
875 if (ParsedBasicBlocks[ID])
876 return ParsedBasicBlocks[ID];
878 // Otherwise, the basic block has not yet been created. Do so and add it to
879 // the ParsedBasicBlocks list.
880 return ParsedBasicBlocks[ID] = new BasicBlock();
883 /// Parse all of the BasicBlock's & Instruction's in the body of a function.
884 /// In post 1.0 bytecode files, we no longer emit basic block individually,
885 /// in order to avoid per-basic-block overhead.
886 /// @returns the number of basic blocks encountered.
887 unsigned BytecodeReader::ParseInstructionList(Function* F) {
888 unsigned BlockNo = 0;
889 SmallVector<unsigned, 8> Args;
891 while (moreInBlock()) {
892 if (Handler) Handler->handleBasicBlockBegin(BlockNo);
894 if (ParsedBasicBlocks.size() == BlockNo)
895 ParsedBasicBlocks.push_back(BB = new BasicBlock());
896 else if (ParsedBasicBlocks[BlockNo] == 0)
897 BB = ParsedBasicBlocks[BlockNo] = new BasicBlock();
899 BB = ParsedBasicBlocks[BlockNo];
901 F->getBasicBlockList().push_back(BB);
903 // Read instructions into this basic block until we get to a terminator
904 while (moreInBlock() && !BB->getTerminator())
905 ParseInstruction(Args, BB);
907 if (!BB->getTerminator())
908 error("Non-terminated basic block found!");
910 if (Handler) Handler->handleBasicBlockEnd(BlockNo-1);
916 /// Parse a type symbol table.
917 void BytecodeReader::ParseTypeSymbolTable(TypeSymbolTable *TST) {
918 // Type Symtab block header: [num entries]
919 unsigned NumEntries = read_vbr_uint();
920 for (unsigned i = 0; i < NumEntries; ++i) {
921 // Symtab entry: [type slot #][name]
922 unsigned slot = read_vbr_uint();
923 std::string Name = read_str();
924 const Type* T = getType(slot);
925 TST->insert(Name, T);
929 /// Parse a value symbol table. This works for both module level and function
930 /// level symbol tables. For function level symbol tables, the CurrentFunction
931 /// parameter must be non-zero and the ST parameter must correspond to
932 /// CurrentFunction's symbol table. For Module level symbol tables, the
933 /// CurrentFunction argument must be zero.
934 void BytecodeReader::ParseValueSymbolTable(Function *CurrentFunction,
935 ValueSymbolTable *VST) {
937 if (Handler) Handler->handleValueSymbolTableBegin(CurrentFunction,VST);
939 // Allow efficient basic block lookup by number.
940 SmallVector<BasicBlock*, 32> BBMap;
942 for (Function::iterator I = CurrentFunction->begin(),
943 E = CurrentFunction->end(); I != E; ++I)
946 while (moreInBlock()) {
947 // Symtab block header: [num entries][type id number]
948 unsigned NumEntries = read_vbr_uint();
949 unsigned Typ = read_vbr_uint();
951 for (unsigned i = 0; i != NumEntries; ++i) {
952 // Symtab entry: [def slot #][name]
953 unsigned slot = read_vbr_uint();
954 std::string Name = read_str();
956 if (Typ == LabelTySlot) {
957 if (slot < BBMap.size())
960 V = getValue(Typ, slot, false); // Find mapping...
962 if (Handler) Handler->handleSymbolTableValue(Typ, slot, Name);
964 error("Failed value look-up for name '" + Name + "', type #" +
965 utostr(Typ) + " slot #" + utostr(slot));
969 checkPastBlockEnd("Symbol Table");
970 if (Handler) Handler->handleValueSymbolTableEnd();
973 // Parse a single type. The typeid is read in first. If its a primitive type
974 // then nothing else needs to be read, we know how to instantiate it. If its
975 // a derived type, then additional data is read to fill out the type
977 const Type *BytecodeReader::ParseType() {
978 unsigned PrimType = read_vbr_uint();
979 const Type *Result = 0;
980 if ((Result = Type::getPrimitiveType((Type::TypeID)PrimType)))
984 case Type::IntegerTyID: {
985 unsigned NumBits = read_vbr_uint();
986 Result = IntegerType::get(NumBits);
989 case Type::FunctionTyID: {
990 const Type *RetType = readType();
991 unsigned RetAttr = read_vbr_uint();
993 unsigned NumParams = read_vbr_uint();
995 std::vector<const Type*> Params;
996 std::vector<FunctionType::ParameterAttributes> Attrs;
997 Attrs.push_back(FunctionType::ParameterAttributes(RetAttr));
998 while (NumParams--) {
999 Params.push_back(readType());
1000 if (Params.back() != Type::VoidTy)
1001 Attrs.push_back(FunctionType::ParameterAttributes(read_vbr_uint()));
1004 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1005 if (isVarArg) Params.pop_back();
1007 Result = FunctionType::get(RetType, Params, isVarArg, Attrs);
1010 case Type::ArrayTyID: {
1011 const Type *ElementType = readType();
1012 unsigned NumElements = read_vbr_uint();
1013 Result = ArrayType::get(ElementType, NumElements);
1016 case Type::PackedTyID: {
1017 const Type *ElementType = readType();
1018 unsigned NumElements = read_vbr_uint();
1019 Result = PackedType::get(ElementType, NumElements);
1022 case Type::StructTyID: {
1023 std::vector<const Type*> Elements;
1024 unsigned Typ = read_vbr_uint();
1025 while (Typ) { // List is terminated by void/0 typeid
1026 Elements.push_back(getType(Typ));
1027 Typ = read_vbr_uint();
1030 Result = StructType::get(Elements, false);
1033 case Type::PackedStructTyID: {
1034 std::vector<const Type*> Elements;
1035 unsigned Typ = read_vbr_uint();
1036 while (Typ) { // List is terminated by void/0 typeid
1037 Elements.push_back(getType(Typ));
1038 Typ = read_vbr_uint();
1041 Result = StructType::get(Elements, true);
1044 case Type::PointerTyID: {
1045 Result = PointerType::get(readType());
1049 case Type::OpaqueTyID: {
1050 Result = OpaqueType::get();
1055 error("Don't know how to deserialize primitive type " + utostr(PrimType));
1058 if (Handler) Handler->handleType(Result);
1062 // ParseTypes - We have to use this weird code to handle recursive
1063 // types. We know that recursive types will only reference the current slab of
1064 // values in the type plane, but they can forward reference types before they
1065 // have been read. For example, Type #0 might be '{ Ty#1 }' and Type #1 might
1066 // be 'Ty#0*'. When reading Type #0, type number one doesn't exist. To fix
1067 // this ugly problem, we pessimistically insert an opaque type for each type we
1068 // are about to read. This means that forward references will resolve to
1069 // something and when we reread the type later, we can replace the opaque type
1070 // with a new resolved concrete type.
1072 void BytecodeReader::ParseTypes(TypeListTy &Tab, unsigned NumEntries){
1073 assert(Tab.size() == 0 && "should not have read type constants in before!");
1075 // Insert a bunch of opaque types to be resolved later...
1076 Tab.reserve(NumEntries);
1077 for (unsigned i = 0; i != NumEntries; ++i)
1078 Tab.push_back(OpaqueType::get());
1081 Handler->handleTypeList(NumEntries);
1083 // If we are about to resolve types, make sure the type cache is clear.
1085 ModuleTypeIDCache.clear();
1087 // Loop through reading all of the types. Forward types will make use of the
1088 // opaque types just inserted.
1090 for (unsigned i = 0; i != NumEntries; ++i) {
1091 const Type* NewTy = ParseType();
1092 const Type* OldTy = Tab[i].get();
1094 error("Couldn't parse type!");
1096 // Don't directly push the new type on the Tab. Instead we want to replace
1097 // the opaque type we previously inserted with the new concrete value. This
1098 // approach helps with forward references to types. The refinement from the
1099 // abstract (opaque) type to the new type causes all uses of the abstract
1100 // type to use the concrete type (NewTy). This will also cause the opaque
1101 // type to be deleted.
1102 cast<DerivedType>(const_cast<Type*>(OldTy))->refineAbstractTypeTo(NewTy);
1104 // This should have replaced the old opaque type with the new type in the
1105 // value table... or with a preexisting type that was already in the system.
1106 // Let's just make sure it did.
1107 assert(Tab[i] != OldTy && "refineAbstractType didn't work!");
1111 /// Parse a single constant value
1112 Value *BytecodeReader::ParseConstantPoolValue(unsigned TypeID) {
1113 // We must check for a ConstantExpr before switching by type because
1114 // a ConstantExpr can be of any type, and has no explicit value.
1116 // 0 if not expr; numArgs if is expr
1117 unsigned isExprNumArgs = read_vbr_uint();
1119 if (isExprNumArgs) {
1120 // 'undef' is encoded with 'exprnumargs' == 1.
1121 if (isExprNumArgs == 1)
1122 return UndefValue::get(getType(TypeID));
1124 // Inline asm is encoded with exprnumargs == ~0U.
1125 if (isExprNumArgs == ~0U) {
1126 std::string AsmStr = read_str();
1127 std::string ConstraintStr = read_str();
1128 unsigned Flags = read_vbr_uint();
1130 const PointerType *PTy = dyn_cast<PointerType>(getType(TypeID));
1131 const FunctionType *FTy =
1132 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
1134 if (!FTy || !InlineAsm::Verify(FTy, ConstraintStr))
1135 error("Invalid constraints for inline asm");
1137 error("Invalid flags for inline asm");
1138 bool HasSideEffects = Flags & 1;
1139 return InlineAsm::get(FTy, AsmStr, ConstraintStr, HasSideEffects);
1144 // FIXME: Encoding of constant exprs could be much more compact!
1145 SmallVector<Constant*, 8> ArgVec;
1146 ArgVec.reserve(isExprNumArgs);
1147 unsigned Opcode = read_vbr_uint();
1149 // Read the slot number and types of each of the arguments
1150 for (unsigned i = 0; i != isExprNumArgs; ++i) {
1151 unsigned ArgValSlot = read_vbr_uint();
1152 unsigned ArgTypeSlot = read_vbr_uint();
1154 // Get the arg value from its slot if it exists, otherwise a placeholder
1155 ArgVec.push_back(getConstantValue(ArgTypeSlot, ArgValSlot));
1158 // Construct a ConstantExpr of the appropriate kind
1159 if (isExprNumArgs == 1) { // All one-operand expressions
1160 if (!Instruction::isCast(Opcode))
1161 error("Only cast instruction has one argument for ConstantExpr");
1163 Constant *Result = ConstantExpr::getCast(Opcode, ArgVec[0],
1165 if (Handler) Handler->handleConstantExpression(Opcode, &ArgVec[0],
1166 ArgVec.size(), Result);
1168 } else if (Opcode == Instruction::GetElementPtr) { // GetElementPtr
1169 Constant *Result = ConstantExpr::getGetElementPtr(ArgVec[0], &ArgVec[1],
1171 if (Handler) Handler->handleConstantExpression(Opcode, &ArgVec[0],
1172 ArgVec.size(), Result);
1174 } else if (Opcode == Instruction::Select) {
1175 if (ArgVec.size() != 3)
1176 error("Select instruction must have three arguments.");
1177 Constant* Result = ConstantExpr::getSelect(ArgVec[0], ArgVec[1],
1179 if (Handler) Handler->handleConstantExpression(Opcode, &ArgVec[0],
1180 ArgVec.size(), Result);
1182 } else if (Opcode == Instruction::ExtractElement) {
1183 if (ArgVec.size() != 2 ||
1184 !ExtractElementInst::isValidOperands(ArgVec[0], ArgVec[1]))
1185 error("Invalid extractelement constand expr arguments");
1186 Constant* Result = ConstantExpr::getExtractElement(ArgVec[0], ArgVec[1]);
1187 if (Handler) Handler->handleConstantExpression(Opcode, &ArgVec[0],
1188 ArgVec.size(), Result);
1190 } else if (Opcode == Instruction::InsertElement) {
1191 if (ArgVec.size() != 3 ||
1192 !InsertElementInst::isValidOperands(ArgVec[0], ArgVec[1], ArgVec[2]))
1193 error("Invalid insertelement constand expr arguments");
1196 ConstantExpr::getInsertElement(ArgVec[0], ArgVec[1], ArgVec[2]);
1197 if (Handler) Handler->handleConstantExpression(Opcode, &ArgVec[0],
1198 ArgVec.size(), Result);
1200 } else if (Opcode == Instruction::ShuffleVector) {
1201 if (ArgVec.size() != 3 ||
1202 !ShuffleVectorInst::isValidOperands(ArgVec[0], ArgVec[1], ArgVec[2]))
1203 error("Invalid shufflevector constant expr arguments.");
1205 ConstantExpr::getShuffleVector(ArgVec[0], ArgVec[1], ArgVec[2]);
1206 if (Handler) Handler->handleConstantExpression(Opcode, &ArgVec[0],
1207 ArgVec.size(), Result);
1209 } else if (Opcode == Instruction::ICmp) {
1210 if (ArgVec.size() != 2)
1211 error("Invalid ICmp constant expr arguments.");
1212 unsigned predicate = read_vbr_uint();
1213 Constant *Result = ConstantExpr::getICmp(predicate, ArgVec[0], ArgVec[1]);
1214 if (Handler) Handler->handleConstantExpression(Opcode, &ArgVec[0],
1215 ArgVec.size(), Result);
1217 } else if (Opcode == Instruction::FCmp) {
1218 if (ArgVec.size() != 2)
1219 error("Invalid FCmp constant expr arguments.");
1220 unsigned predicate = read_vbr_uint();
1221 Constant *Result = ConstantExpr::getFCmp(predicate, ArgVec[0], ArgVec[1]);
1222 if (Handler) Handler->handleConstantExpression(Opcode, &ArgVec[0],
1223 ArgVec.size(), Result);
1225 } else { // All other 2-operand expressions
1226 Constant* Result = ConstantExpr::get(Opcode, ArgVec[0], ArgVec[1]);
1227 if (Handler) Handler->handleConstantExpression(Opcode, &ArgVec[0],
1228 ArgVec.size(), Result);
1233 // Ok, not an ConstantExpr. We now know how to read the given type...
1234 const Type *Ty = getType(TypeID);
1235 Constant *Result = 0;
1236 switch (Ty->getTypeID()) {
1237 case Type::IntegerTyID: {
1238 const IntegerType *IT = cast<IntegerType>(Ty);
1239 if (IT->getBitWidth() <= 32) {
1240 uint32_t Val = read_vbr_uint();
1241 if (!ConstantInt::isValueValidForType(Ty, uint64_t(Val)))
1242 error("Integer value read is invalid for type.");
1243 Result = ConstantInt::get(IT, Val);
1244 if (Handler) Handler->handleConstantValue(Result);
1245 } else if (IT->getBitWidth() <= 64) {
1246 uint64_t Val = read_vbr_uint64();
1247 if (!ConstantInt::isValueValidForType(Ty, Val))
1248 error("Invalid constant integer read.");
1249 Result = ConstantInt::get(IT, Val);
1250 if (Handler) Handler->handleConstantValue(Result);
1252 assert("Integer types > 64 bits not supported");
1255 case Type::FloatTyID: {
1258 Result = ConstantFP::get(Ty, Val);
1259 if (Handler) Handler->handleConstantValue(Result);
1263 case Type::DoubleTyID: {
1266 Result = ConstantFP::get(Ty, Val);
1267 if (Handler) Handler->handleConstantValue(Result);
1271 case Type::ArrayTyID: {
1272 const ArrayType *AT = cast<ArrayType>(Ty);
1273 unsigned NumElements = AT->getNumElements();
1274 unsigned TypeSlot = getTypeSlot(AT->getElementType());
1275 std::vector<Constant*> Elements;
1276 Elements.reserve(NumElements);
1277 while (NumElements--) // Read all of the elements of the constant.
1278 Elements.push_back(getConstantValue(TypeSlot,
1280 Result = ConstantArray::get(AT, Elements);
1281 if (Handler) Handler->handleConstantArray(AT, &Elements[0], Elements.size(),
1286 case Type::StructTyID: {
1287 const StructType *ST = cast<StructType>(Ty);
1289 std::vector<Constant *> Elements;
1290 Elements.reserve(ST->getNumElements());
1291 for (unsigned i = 0; i != ST->getNumElements(); ++i)
1292 Elements.push_back(getConstantValue(ST->getElementType(i),
1295 Result = ConstantStruct::get(ST, Elements);
1296 if (Handler) Handler->handleConstantStruct(ST, &Elements[0],Elements.size(),
1301 case Type::PackedTyID: {
1302 const PackedType *PT = cast<PackedType>(Ty);
1303 unsigned NumElements = PT->getNumElements();
1304 unsigned TypeSlot = getTypeSlot(PT->getElementType());
1305 std::vector<Constant*> Elements;
1306 Elements.reserve(NumElements);
1307 while (NumElements--) // Read all of the elements of the constant.
1308 Elements.push_back(getConstantValue(TypeSlot,
1310 Result = ConstantPacked::get(PT, Elements);
1311 if (Handler) Handler->handleConstantPacked(PT, &Elements[0],Elements.size(),
1316 case Type::PointerTyID: { // ConstantPointerRef value (backwards compat).
1317 const PointerType *PT = cast<PointerType>(Ty);
1318 unsigned Slot = read_vbr_uint();
1320 // Check to see if we have already read this global variable...
1321 Value *Val = getValue(TypeID, Slot, false);
1323 GlobalValue *GV = dyn_cast<GlobalValue>(Val);
1324 if (!GV) error("GlobalValue not in ValueTable!");
1325 if (Handler) Handler->handleConstantPointer(PT, Slot, GV);
1328 error("Forward references are not allowed here.");
1333 error("Don't know how to deserialize constant value of type '" +
1334 Ty->getDescription());
1338 // Check that we didn't read a null constant if they are implicit for this
1339 // type plane. Do not do this check for constantexprs, as they may be folded
1340 // to a null value in a way that isn't predicted when a .bc file is initially
1342 assert((!isa<Constant>(Result) || !cast<Constant>(Result)->isNullValue()) ||
1343 !hasImplicitNull(TypeID) &&
1344 "Cannot read null values from bytecode!");
1348 /// Resolve references for constants. This function resolves the forward
1349 /// referenced constants in the ConstantFwdRefs map. It uses the
1350 /// replaceAllUsesWith method of Value class to substitute the placeholder
1351 /// instance with the actual instance.
1352 void BytecodeReader::ResolveReferencesToConstant(Constant *NewV, unsigned Typ,
1354 ConstantRefsType::iterator I =
1355 ConstantFwdRefs.find(std::make_pair(Typ, Slot));
1356 if (I == ConstantFwdRefs.end()) return; // Never forward referenced?
1358 Value *PH = I->second; // Get the placeholder...
1359 PH->replaceAllUsesWith(NewV);
1360 delete PH; // Delete the old placeholder
1361 ConstantFwdRefs.erase(I); // Remove the map entry for it
1364 /// Parse the constant strings section.
1365 void BytecodeReader::ParseStringConstants(unsigned NumEntries, ValueTable &Tab){
1366 for (; NumEntries; --NumEntries) {
1367 unsigned Typ = read_vbr_uint();
1368 const Type *Ty = getType(Typ);
1369 if (!isa<ArrayType>(Ty))
1370 error("String constant data invalid!");
1372 const ArrayType *ATy = cast<ArrayType>(Ty);
1373 if (ATy->getElementType() != Type::Int8Ty &&
1374 ATy->getElementType() != Type::Int8Ty)
1375 error("String constant data invalid!");
1377 // Read character data. The type tells us how long the string is.
1378 char *Data = reinterpret_cast<char *>(alloca(ATy->getNumElements()));
1379 read_data(Data, Data+ATy->getNumElements());
1381 std::vector<Constant*> Elements(ATy->getNumElements());
1382 const Type* ElemType = ATy->getElementType();
1383 for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
1384 Elements[i] = ConstantInt::get(ElemType, (unsigned char)Data[i]);
1386 // Create the constant, inserting it as needed.
1387 Constant *C = ConstantArray::get(ATy, Elements);
1388 unsigned Slot = insertValue(C, Typ, Tab);
1389 ResolveReferencesToConstant(C, Typ, Slot);
1390 if (Handler) Handler->handleConstantString(cast<ConstantArray>(C));
1394 /// Parse the constant pool.
1395 void BytecodeReader::ParseConstantPool(ValueTable &Tab,
1396 TypeListTy &TypeTab,
1398 if (Handler) Handler->handleGlobalConstantsBegin();
1400 /// In LLVM 1.3 Type does not derive from Value so the types
1401 /// do not occupy a plane. Consequently, we read the types
1402 /// first in the constant pool.
1404 unsigned NumEntries = read_vbr_uint();
1405 ParseTypes(TypeTab, NumEntries);
1408 while (moreInBlock()) {
1409 unsigned NumEntries = read_vbr_uint();
1410 unsigned Typ = read_vbr_uint();
1412 if (Typ == Type::VoidTyID) {
1413 /// Use of Type::VoidTyID is a misnomer. It actually means
1414 /// that the following plane is constant strings
1415 assert(&Tab == &ModuleValues && "Cannot read strings in functions!");
1416 ParseStringConstants(NumEntries, Tab);
1418 for (unsigned i = 0; i < NumEntries; ++i) {
1419 Value *V = ParseConstantPoolValue(Typ);
1420 assert(V && "ParseConstantPoolValue returned NULL!");
1421 unsigned Slot = insertValue(V, Typ, Tab);
1423 // If we are reading a function constant table, make sure that we adjust
1424 // the slot number to be the real global constant number.
1426 if (&Tab != &ModuleValues && Typ < ModuleValues.size() &&
1428 Slot += ModuleValues[Typ]->size();
1429 if (Constant *C = dyn_cast<Constant>(V))
1430 ResolveReferencesToConstant(C, Typ, Slot);
1435 // After we have finished parsing the constant pool, we had better not have
1436 // any dangling references left.
1437 if (!ConstantFwdRefs.empty()) {
1438 ConstantRefsType::const_iterator I = ConstantFwdRefs.begin();
1439 Constant* missingConst = I->second;
1440 error(utostr(ConstantFwdRefs.size()) +
1441 " unresolved constant reference exist. First one is '" +
1442 missingConst->getName() + "' of type '" +
1443 missingConst->getType()->getDescription() + "'.");
1446 checkPastBlockEnd("Constant Pool");
1447 if (Handler) Handler->handleGlobalConstantsEnd();
1450 /// Parse the contents of a function. Note that this function can be
1451 /// called lazily by materializeFunction
1452 /// @see materializeFunction
1453 void BytecodeReader::ParseFunctionBody(Function* F) {
1455 unsigned FuncSize = BlockEnd - At;
1456 GlobalValue::LinkageTypes Linkage = GlobalValue::ExternalLinkage;
1457 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
1459 unsigned rWord = read_vbr_uint();
1460 unsigned LinkageID = rWord & 65535;
1461 unsigned VisibilityID = rWord >> 16;
1462 switch (LinkageID) {
1463 case 0: Linkage = GlobalValue::ExternalLinkage; break;
1464 case 1: Linkage = GlobalValue::WeakLinkage; break;
1465 case 2: Linkage = GlobalValue::AppendingLinkage; break;
1466 case 3: Linkage = GlobalValue::InternalLinkage; break;
1467 case 4: Linkage = GlobalValue::LinkOnceLinkage; break;
1468 case 5: Linkage = GlobalValue::DLLImportLinkage; break;
1469 case 6: Linkage = GlobalValue::DLLExportLinkage; break;
1470 case 7: Linkage = GlobalValue::ExternalWeakLinkage; break;
1472 error("Invalid linkage type for Function.");
1473 Linkage = GlobalValue::InternalLinkage;
1476 switch (VisibilityID) {
1477 case 0: Visibility = GlobalValue::DefaultVisibility; break;
1478 case 1: Visibility = GlobalValue::HiddenVisibility; break;
1480 error("Unknown visibility type: " + utostr(VisibilityID));
1481 Visibility = GlobalValue::DefaultVisibility;
1485 F->setLinkage(Linkage);
1486 F->setVisibility(Visibility);
1487 if (Handler) Handler->handleFunctionBegin(F,FuncSize);
1489 // Keep track of how many basic blocks we have read in...
1490 unsigned BlockNum = 0;
1491 bool InsertedArguments = false;
1493 BufPtr MyEnd = BlockEnd;
1494 while (At < MyEnd) {
1495 unsigned Type, Size;
1497 read_block(Type, Size);
1500 case BytecodeFormat::ConstantPoolBlockID:
1501 if (!InsertedArguments) {
1502 // Insert arguments into the value table before we parse the first basic
1503 // block in the function
1505 InsertedArguments = true;
1508 ParseConstantPool(FunctionValues, FunctionTypes, true);
1511 case BytecodeFormat::InstructionListBlockID: {
1512 // Insert arguments into the value table before we parse the instruction
1513 // list for the function
1514 if (!InsertedArguments) {
1516 InsertedArguments = true;
1520 error("Already parsed basic blocks!");
1521 BlockNum = ParseInstructionList(F);
1525 case BytecodeFormat::ValueSymbolTableBlockID:
1526 ParseValueSymbolTable(F, &F->getValueSymbolTable());
1529 case BytecodeFormat::TypeSymbolTableBlockID:
1530 error("Functions don't have type symbol tables");
1536 error("Wrapped around reading bytecode.");
1542 // Make sure there were no references to non-existant basic blocks.
1543 if (BlockNum != ParsedBasicBlocks.size())
1544 error("Illegal basic block operand reference");
1546 ParsedBasicBlocks.clear();
1548 // Resolve forward references. Replace any uses of a forward reference value
1549 // with the real value.
1550 while (!ForwardReferences.empty()) {
1551 std::map<std::pair<unsigned,unsigned>, Value*>::iterator
1552 I = ForwardReferences.begin();
1553 Value *V = getValue(I->first.first, I->first.second, false);
1554 Value *PlaceHolder = I->second;
1555 PlaceHolder->replaceAllUsesWith(V);
1556 ForwardReferences.erase(I);
1560 // Clear out function-level types...
1561 FunctionTypes.clear();
1562 freeTable(FunctionValues);
1564 if (Handler) Handler->handleFunctionEnd(F);
1567 /// This function parses LLVM functions lazily. It obtains the type of the
1568 /// function and records where the body of the function is in the bytecode
1569 /// buffer. The caller can then use the ParseNextFunction and
1570 /// ParseAllFunctionBodies to get handler events for the functions.
1571 void BytecodeReader::ParseFunctionLazily() {
1572 if (FunctionSignatureList.empty())
1573 error("FunctionSignatureList empty!");
1575 Function *Func = FunctionSignatureList.back();
1576 FunctionSignatureList.pop_back();
1578 // Save the information for future reading of the function
1579 LazyFunctionLoadMap[Func] = LazyFunctionInfo(BlockStart, BlockEnd);
1581 // This function has a body but it's not loaded so it appears `External'.
1582 // Mark it as a `Ghost' instead to notify the users that it has a body.
1583 Func->setLinkage(GlobalValue::GhostLinkage);
1585 // Pretend we've `parsed' this function
1589 /// The ParserFunction method lazily parses one function. Use this method to
1590 /// casue the parser to parse a specific function in the module. Note that
1591 /// this will remove the function from what is to be included by
1592 /// ParseAllFunctionBodies.
1593 /// @see ParseAllFunctionBodies
1594 /// @see ParseBytecode
1595 bool BytecodeReader::ParseFunction(Function* Func, std::string* ErrMsg) {
1597 if (setjmp(context)) {
1598 // Set caller's error message, if requested
1601 // Indicate an error occurred
1605 // Find {start, end} pointers and slot in the map. If not there, we're done.
1606 LazyFunctionMap::iterator Fi = LazyFunctionLoadMap.find(Func);
1608 // Make sure we found it
1609 if (Fi == LazyFunctionLoadMap.end()) {
1610 error("Unrecognized function of type " + Func->getType()->getDescription());
1614 BlockStart = At = Fi->second.Buf;
1615 BlockEnd = Fi->second.EndBuf;
1616 assert(Fi->first == Func && "Found wrong function?");
1618 LazyFunctionLoadMap.erase(Fi);
1620 this->ParseFunctionBody(Func);
1624 /// The ParseAllFunctionBodies method parses through all the previously
1625 /// unparsed functions in the bytecode file. If you want to completely parse
1626 /// a bytecode file, this method should be called after Parsebytecode because
1627 /// Parsebytecode only records the locations in the bytecode file of where
1628 /// the function definitions are located. This function uses that information
1629 /// to materialize the functions.
1630 /// @see ParseBytecode
1631 bool BytecodeReader::ParseAllFunctionBodies(std::string* ErrMsg) {
1632 if (setjmp(context)) {
1633 // Set caller's error message, if requested
1636 // Indicate an error occurred
1640 LazyFunctionMap::iterator Fi = LazyFunctionLoadMap.begin();
1641 LazyFunctionMap::iterator Fe = LazyFunctionLoadMap.end();
1644 Function* Func = Fi->first;
1645 BlockStart = At = Fi->second.Buf;
1646 BlockEnd = Fi->second.EndBuf;
1647 ParseFunctionBody(Func);
1650 LazyFunctionLoadMap.clear();
1654 /// Parse the global type list
1655 void BytecodeReader::ParseGlobalTypes() {
1656 // Read the number of types
1657 unsigned NumEntries = read_vbr_uint();
1658 ParseTypes(ModuleTypes, NumEntries);
1661 /// Parse the Global info (types, global vars, constants)
1662 void BytecodeReader::ParseModuleGlobalInfo() {
1664 if (Handler) Handler->handleModuleGlobalsBegin();
1666 // SectionID - If a global has an explicit section specified, this map
1667 // remembers the ID until we can translate it into a string.
1668 std::map<GlobalValue*, unsigned> SectionID;
1670 // Read global variables...
1671 unsigned VarType = read_vbr_uint();
1672 while (VarType != Type::VoidTyID) { // List is terminated by Void
1673 // VarType Fields: bit0 = isConstant, bit1 = hasInitializer, bit2,3,4 =
1674 // Linkage, bit4+ = slot#
1675 unsigned SlotNo = VarType >> 5;
1676 unsigned LinkageID = (VarType >> 2) & 7;
1677 unsigned VisibilityID = 0;
1678 bool isConstant = VarType & 1;
1679 bool hasInitializer = (VarType & 2) != 0;
1680 unsigned Alignment = 0;
1681 unsigned GlobalSectionID = 0;
1683 // An extension word is present when linkage = 3 (internal) and hasinit = 0.
1684 if (LinkageID == 3 && !hasInitializer) {
1685 unsigned ExtWord = read_vbr_uint();
1686 // The extension word has this format: bit 0 = has initializer, bit 1-3 =
1687 // linkage, bit 4-8 = alignment (log2), bit 9 = has section,
1688 // bits 10-12 = visibility, bits 13+ = future use.
1689 hasInitializer = ExtWord & 1;
1690 LinkageID = (ExtWord >> 1) & 7;
1691 Alignment = (1 << ((ExtWord >> 4) & 31)) >> 1;
1692 VisibilityID = (ExtWord >> 10) & 7;
1694 if (ExtWord & (1 << 9)) // Has a section ID.
1695 GlobalSectionID = read_vbr_uint();
1698 GlobalValue::LinkageTypes Linkage;
1699 switch (LinkageID) {
1700 case 0: Linkage = GlobalValue::ExternalLinkage; break;
1701 case 1: Linkage = GlobalValue::WeakLinkage; break;
1702 case 2: Linkage = GlobalValue::AppendingLinkage; break;
1703 case 3: Linkage = GlobalValue::InternalLinkage; break;
1704 case 4: Linkage = GlobalValue::LinkOnceLinkage; break;
1705 case 5: Linkage = GlobalValue::DLLImportLinkage; break;
1706 case 6: Linkage = GlobalValue::DLLExportLinkage; break;
1707 case 7: Linkage = GlobalValue::ExternalWeakLinkage; break;
1709 error("Unknown linkage type: " + utostr(LinkageID));
1710 Linkage = GlobalValue::InternalLinkage;
1713 GlobalValue::VisibilityTypes Visibility;
1714 switch (VisibilityID) {
1715 case 0: Visibility = GlobalValue::DefaultVisibility; break;
1716 case 1: Visibility = GlobalValue::HiddenVisibility; break;
1718 error("Unknown visibility type: " + utostr(VisibilityID));
1719 Visibility = GlobalValue::DefaultVisibility;
1723 const Type *Ty = getType(SlotNo);
1725 error("Global has no type! SlotNo=" + utostr(SlotNo));
1727 if (!isa<PointerType>(Ty))
1728 error("Global not a pointer type! Ty= " + Ty->getDescription());
1730 const Type *ElTy = cast<PointerType>(Ty)->getElementType();
1732 // Create the global variable...
1733 GlobalVariable *GV = new GlobalVariable(ElTy, isConstant, Linkage,
1735 GV->setAlignment(Alignment);
1736 GV->setVisibility(Visibility);
1737 insertValue(GV, SlotNo, ModuleValues);
1739 if (GlobalSectionID != 0)
1740 SectionID[GV] = GlobalSectionID;
1742 unsigned initSlot = 0;
1743 if (hasInitializer) {
1744 initSlot = read_vbr_uint();
1745 GlobalInits.push_back(std::make_pair(GV, initSlot));
1748 // Notify handler about the global value.
1750 Handler->handleGlobalVariable(ElTy, isConstant, Linkage, Visibility,
1754 VarType = read_vbr_uint();
1757 // Read the function objects for all of the functions that are coming
1758 unsigned FnSignature = read_vbr_uint();
1760 // List is terminated by VoidTy.
1761 while (((FnSignature & (~0U >> 1)) >> 5) != Type::VoidTyID) {
1762 const Type *Ty = getType((FnSignature & (~0U >> 1)) >> 5);
1763 if (!isa<PointerType>(Ty) ||
1764 !isa<FunctionType>(cast<PointerType>(Ty)->getElementType())) {
1765 error("Function not a pointer to function type! Ty = " +
1766 Ty->getDescription());
1769 // We create functions by passing the underlying FunctionType to create...
1770 const FunctionType* FTy =
1771 cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
1773 // Insert the place holder.
1774 Function *Func = new Function(FTy, GlobalValue::ExternalLinkage,
1777 insertValue(Func, (FnSignature & (~0U >> 1)) >> 5, ModuleValues);
1779 // Flags are not used yet.
1780 unsigned Flags = FnSignature & 31;
1782 // Save this for later so we know type of lazily instantiated functions.
1783 // Note that known-external functions do not have FunctionInfo blocks, so we
1784 // do not add them to the FunctionSignatureList.
1785 if ((Flags & (1 << 4)) == 0)
1786 FunctionSignatureList.push_back(Func);
1788 // Get the calling convention from the low bits.
1789 unsigned CC = Flags & 15;
1790 unsigned Alignment = 0;
1791 if (FnSignature & (1 << 31)) { // Has extension word?
1792 unsigned ExtWord = read_vbr_uint();
1793 Alignment = (1 << (ExtWord & 31)) >> 1;
1794 CC |= ((ExtWord >> 5) & 15) << 4;
1796 if (ExtWord & (1 << 10)) // Has a section ID.
1797 SectionID[Func] = read_vbr_uint();
1799 // Parse external declaration linkage
1800 switch ((ExtWord >> 11) & 3) {
1802 case 1: Func->setLinkage(Function::DLLImportLinkage); break;
1803 case 2: Func->setLinkage(Function::ExternalWeakLinkage); break;
1804 default: assert(0 && "Unsupported external linkage");
1808 Func->setCallingConv(CC-1);
1809 Func->setAlignment(Alignment);
1811 if (Handler) Handler->handleFunctionDeclaration(Func);
1813 // Get the next function signature.
1814 FnSignature = read_vbr_uint();
1817 // Now that the function signature list is set up, reverse it so that we can
1818 // remove elements efficiently from the back of the vector.
1819 std::reverse(FunctionSignatureList.begin(), FunctionSignatureList.end());
1821 /// SectionNames - This contains the list of section names encoded in the
1822 /// moduleinfoblock. Functions and globals with an explicit section index
1823 /// into this to get their section name.
1824 std::vector<std::string> SectionNames;
1826 // Read in the dependent library information.
1827 unsigned num_dep_libs = read_vbr_uint();
1828 std::string dep_lib;
1829 while (num_dep_libs--) {
1830 dep_lib = read_str();
1831 TheModule->addLibrary(dep_lib);
1833 Handler->handleDependentLibrary(dep_lib);
1836 // Read target triple and place into the module.
1837 std::string triple = read_str();
1838 TheModule->setTargetTriple(triple);
1840 Handler->handleTargetTriple(triple);
1842 // Read the data layout string and place into the module.
1843 std::string datalayout = read_str();
1844 TheModule->setDataLayout(datalayout);
1847 // Handler->handleDataLayout(datalayout);
1849 if (At != BlockEnd) {
1850 // If the file has section info in it, read the section names now.
1851 unsigned NumSections = read_vbr_uint();
1852 while (NumSections--)
1853 SectionNames.push_back(read_str());
1856 // If the file has module-level inline asm, read it now.
1858 TheModule->setModuleInlineAsm(read_str());
1860 // If any globals are in specified sections, assign them now.
1861 for (std::map<GlobalValue*, unsigned>::iterator I = SectionID.begin(), E =
1862 SectionID.end(); I != E; ++I)
1864 if (I->second > SectionID.size())
1865 error("SectionID out of range for global!");
1866 I->first->setSection(SectionNames[I->second-1]);
1869 // This is for future proofing... in the future extra fields may be added that
1870 // we don't understand, so we transparently ignore them.
1874 if (Handler) Handler->handleModuleGlobalsEnd();
1877 /// Parse the version information and decode it by setting flags on the
1878 /// Reader that enable backward compatibility of the reader.
1879 void BytecodeReader::ParseVersionInfo() {
1880 unsigned RevisionNum = read_vbr_uint();
1882 // We don't provide backwards compatibility in the Reader any more. To
1883 // upgrade, the user should use llvm-upgrade.
1884 if (RevisionNum < 7)
1885 error("Bytecode formats < 7 are no longer supported. Use llvm-upgrade.");
1887 if (Handler) Handler->handleVersionInfo(RevisionNum);
1890 /// Parse a whole module.
1891 void BytecodeReader::ParseModule() {
1892 unsigned Type, Size;
1894 FunctionSignatureList.clear(); // Just in case...
1896 // Read into instance variables...
1899 bool SeenModuleGlobalInfo = false;
1900 bool SeenGlobalTypePlane = false;
1901 BufPtr MyEnd = BlockEnd;
1902 while (At < MyEnd) {
1904 read_block(Type, Size);
1908 case BytecodeFormat::GlobalTypePlaneBlockID:
1909 if (SeenGlobalTypePlane)
1910 error("Two GlobalTypePlane Blocks Encountered!");
1914 SeenGlobalTypePlane = true;
1917 case BytecodeFormat::ModuleGlobalInfoBlockID:
1918 if (SeenModuleGlobalInfo)
1919 error("Two ModuleGlobalInfo Blocks Encountered!");
1920 ParseModuleGlobalInfo();
1921 SeenModuleGlobalInfo = true;
1924 case BytecodeFormat::ConstantPoolBlockID:
1925 ParseConstantPool(ModuleValues, ModuleTypes,false);
1928 case BytecodeFormat::FunctionBlockID:
1929 ParseFunctionLazily();
1932 case BytecodeFormat::ValueSymbolTableBlockID:
1933 ParseValueSymbolTable(0, &TheModule->getValueSymbolTable());
1936 case BytecodeFormat::TypeSymbolTableBlockID:
1937 ParseTypeSymbolTable(&TheModule->getTypeSymbolTable());
1943 error("Unexpected Block of Type #" + utostr(Type) + " encountered!");
1950 // After the module constant pool has been read, we can safely initialize
1951 // global variables...
1952 while (!GlobalInits.empty()) {
1953 GlobalVariable *GV = GlobalInits.back().first;
1954 unsigned Slot = GlobalInits.back().second;
1955 GlobalInits.pop_back();
1957 // Look up the initializer value...
1958 // FIXME: Preserve this type ID!
1960 const llvm::PointerType* GVType = GV->getType();
1961 unsigned TypeSlot = getTypeSlot(GVType->getElementType());
1962 if (Constant *CV = getConstantValue(TypeSlot, Slot)) {
1963 if (GV->hasInitializer())
1964 error("Global *already* has an initializer?!");
1965 if (Handler) Handler->handleGlobalInitializer(GV,CV);
1966 GV->setInitializer(CV);
1968 error("Cannot find initializer value.");
1971 if (!ConstantFwdRefs.empty())
1972 error("Use of undefined constants in a module");
1974 /// Make sure we pulled them all out. If we didn't then there's a declaration
1975 /// but a missing body. That's not allowed.
1976 if (!FunctionSignatureList.empty())
1977 error("Function declared, but bytecode stream ended before definition");
1980 /// This function completely parses a bytecode buffer given by the \p Buf
1981 /// and \p Length parameters.
1982 bool BytecodeReader::ParseBytecode(volatile BufPtr Buf, unsigned Length,
1983 const std::string &ModuleID,
1984 Decompressor_t *Decompressor,
1985 std::string* ErrMsg) {
1987 /// We handle errors by
1988 if (setjmp(context)) {
1989 // Cleanup after error
1990 if (Handler) Handler->handleError(ErrorMsg);
1994 if (decompressedBlock != 0 ) {
1995 ::free(decompressedBlock);
1996 decompressedBlock = 0;
1998 // Set caller's error message, if requested
2001 // Indicate an error occurred
2006 At = MemStart = BlockStart = Buf;
2007 MemEnd = BlockEnd = Buf + Length;
2009 // Create the module
2010 TheModule = new Module(ModuleID);
2012 if (Handler) Handler->handleStart(TheModule, Length);
2014 // Read the four bytes of the signature.
2015 unsigned Sig = read_uint();
2017 // If this is a compressed file
2018 if (Sig == ('l' | ('l' << 8) | ('v' << 16) | ('c' << 24))) {
2020 // Invoke the decompression of the bytecode. Note that we have to skip the
2021 // file's magic number which is not part of the compressed block. Hence,
2022 // the Buf+4 and Length-4. The result goes into decompressedBlock, a data
2023 // member for retention until BytecodeReader is destructed.
2024 unsigned decompressedLength =
2025 Decompressor((char*)Buf+4,Length-4,decompressedBlock, 0);
2027 // We must adjust the buffer pointers used by the bytecode reader to point
2028 // into the new decompressed block. After decompression, the
2029 // decompressedBlock will point to a contiguous memory area that has
2030 // the decompressed data.
2031 At = MemStart = BlockStart = Buf = (BufPtr) decompressedBlock;
2032 MemEnd = BlockEnd = Buf + decompressedLength;
2034 // else if this isn't a regular (uncompressed) bytecode file, then its
2035 // and error, generate that now.
2036 } else if (Sig != ('l' | ('l' << 8) | ('v' << 16) | ('m' << 24))) {
2037 error("Invalid bytecode signature: " + utohexstr(Sig));
2040 // Tell the handler we're starting a module
2041 if (Handler) Handler->handleModuleBegin(ModuleID);
2043 // Get the module block and size and verify. This is handled specially
2044 // because the module block/size is always written in long format. Other
2045 // blocks are written in short format so the read_block method is used.
2046 unsigned Type, Size;
2049 if (Type != BytecodeFormat::ModuleBlockID) {
2050 error("Expected Module Block! Type:" + utostr(Type) + ", Size:"
2054 // It looks like the darwin ranlib program is broken, and adds trailing
2055 // garbage to the end of some bytecode files. This hack allows the bc
2056 // reader to ignore trailing garbage on bytecode files.
2057 if (At + Size < MemEnd)
2058 MemEnd = BlockEnd = At+Size;
2060 if (At + Size != MemEnd)
2061 error("Invalid Top Level Block Length! Type:" + utostr(Type)
2062 + ", Size:" + utostr(Size));
2064 // Parse the module contents
2065 this->ParseModule();
2067 // Check for missing functions
2069 error("Function expected, but bytecode stream ended!");
2071 // Tell the handler we're done with the module
2073 Handler->handleModuleEnd(ModuleID);
2075 // Tell the handler we're finished the parse
2076 if (Handler) Handler->handleFinish();
2082 //===----------------------------------------------------------------------===//
2083 //=== Default Implementations of Handler Methods
2084 //===----------------------------------------------------------------------===//
2086 BytecodeHandler::~BytecodeHandler() {}