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/SymbolTable.h"
27 #include "llvm/TypeSymbolTable.h"
28 #include "llvm/Bytecode/Format.h"
29 #include "llvm/Config/alloca.h"
30 #include "llvm/Support/GetElementPtrTypeIterator.h"
31 #include "llvm/Support/Compressor.h"
32 #include "llvm/Support/MathExtras.h"
33 #include "llvm/ADT/StringExtras.h"
39 /// @brief A class for maintaining the slot number definition
40 /// as a placeholder for the actual definition for forward constants defs.
41 class ConstantPlaceHolder : public ConstantExpr {
42 ConstantPlaceHolder(); // DO NOT IMPLEMENT
43 void operator=(const ConstantPlaceHolder &); // DO NOT IMPLEMENT
46 ConstantPlaceHolder(const Type *Ty)
47 : ConstantExpr(Ty, Instruction::UserOp1, &Op, 1),
48 Op(UndefValue::get(Type::Int32Ty), this) {
53 // Provide some details on error
54 inline void BytecodeReader::error(const std::string& err) {
55 ErrorMsg = err + " (Vers=" + itostr(RevisionNum) + ", Pos="
56 + itostr(At-MemStart) + ")";
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() {
92 error("Ran out of data reading vbr_uint!");
93 Result |= (unsigned)((*At++) & 0x7F) << Shift;
95 } while (At[-1] & 0x80);
96 if (Handler) Handler->handleVBR32(At-Save);
100 /// Read a variable-bit-rate encoded unsigned 64-bit integer.
101 inline uint64_t BytecodeReader::read_vbr_uint64() {
108 error("Ran out of data reading vbr_uint64!");
109 Result |= (uint64_t)((*At++) & 0x7F) << Shift;
111 } while (At[-1] & 0x80);
112 if (Handler) Handler->handleVBR64(At-Save);
116 /// Read a variable-bit-rate encoded signed 64-bit integer.
117 inline int64_t BytecodeReader::read_vbr_int64() {
118 uint64_t R = read_vbr_uint64();
121 return -(int64_t)(R >> 1);
122 else // There is no such thing as -0 with integers. "-0" really means
123 // 0x8000000000000000.
126 return (int64_t)(R >> 1);
129 /// Read a pascal-style string (length followed by text)
130 inline std::string BytecodeReader::read_str() {
131 unsigned Size = read_vbr_uint();
132 const unsigned char *OldAt = At;
134 if (At > BlockEnd) // Size invalid?
135 error("Ran out of data reading a string!");
136 return std::string((char*)OldAt, Size);
139 /// Read an arbitrary block of data
140 inline void BytecodeReader::read_data(void *Ptr, void *End) {
141 unsigned char *Start = (unsigned char *)Ptr;
142 unsigned Amount = (unsigned char *)End - Start;
143 if (At+Amount > BlockEnd)
144 error("Ran out of data!");
145 std::copy(At, At+Amount, Start);
149 /// Read a float value in little-endian order
150 inline void BytecodeReader::read_float(float& FloatVal) {
151 /// FIXME: This isn't optimal, it has size problems on some platforms
152 /// where FP is not IEEE.
153 FloatVal = BitsToFloat(At[0] | (At[1] << 8) | (At[2] << 16) | (At[3] << 24));
154 At+=sizeof(uint32_t);
157 /// Read a double value in little-endian order
158 inline void BytecodeReader::read_double(double& DoubleVal) {
159 /// FIXME: This isn't optimal, it has size problems on some platforms
160 /// where FP is not IEEE.
161 DoubleVal = BitsToDouble((uint64_t(At[0]) << 0) | (uint64_t(At[1]) << 8) |
162 (uint64_t(At[2]) << 16) | (uint64_t(At[3]) << 24) |
163 (uint64_t(At[4]) << 32) | (uint64_t(At[5]) << 40) |
164 (uint64_t(At[6]) << 48) | (uint64_t(At[7]) << 56));
165 At+=sizeof(uint64_t);
168 /// Read a block header and obtain its type and size
169 inline void BytecodeReader::read_block(unsigned &Type, unsigned &Size) {
170 Size = read_uint(); // Read the header
171 Type = Size & 0x1F; // mask low order five bits to get type
172 Size >>= 5; // high order 27 bits is the size
174 if (At + Size > BlockEnd)
175 error("Attempt to size a block past end of memory");
176 BlockEnd = At + Size;
177 if (Handler) Handler->handleBlock(Type, BlockStart, Size);
180 //===----------------------------------------------------------------------===//
182 //===----------------------------------------------------------------------===//
184 /// Determine if a type id has an implicit null value
185 inline bool BytecodeReader::hasImplicitNull(unsigned TyID) {
186 return TyID != Type::LabelTyID && TyID != Type::VoidTyID;
189 /// Obtain a type given a typeid and account for things like compaction tables,
190 /// function level vs module level, and the offsetting for the primitive types.
191 const Type *BytecodeReader::getType(unsigned ID) {
192 if (ID < Type::FirstDerivedTyID)
193 if (const Type *T = Type::getPrimitiveType((Type::TypeID)ID))
194 return T; // Asked for a primitive type...
196 // Otherwise, derived types need offset...
197 ID -= Type::FirstDerivedTyID;
199 if (!CompactionTypes.empty()) {
200 if (ID >= CompactionTypes.size())
201 error("Type ID out of range for compaction table!");
202 return CompactionTypes[ID].first;
205 // Is it a module-level type?
206 if (ID < ModuleTypes.size())
207 return ModuleTypes[ID].get();
209 // Nope, is it a function-level type?
210 ID -= ModuleTypes.size();
211 if (ID < FunctionTypes.size())
212 return FunctionTypes[ID].get();
214 error("Illegal type reference!");
218 /// This method just saves some coding. It uses read_vbr_uint to read in a
219 /// type id, errors that its not the type type, and then calls getType to
220 /// return the type value.
221 inline const Type* BytecodeReader::readType() {
222 return getType(read_vbr_uint());
225 /// Get the slot number associated with a type accounting for primitive
226 /// types, compaction tables, and function level vs module level.
227 unsigned BytecodeReader::getTypeSlot(const Type *Ty) {
228 if (Ty->isPrimitiveType())
229 return Ty->getTypeID();
231 // Scan the compaction table for the type if needed.
232 if (!CompactionTypes.empty()) {
233 for (unsigned i = 0, e = CompactionTypes.size(); i != e; ++i)
234 if (CompactionTypes[i].first == Ty)
235 return Type::FirstDerivedTyID + i;
237 error("Couldn't find type specified in compaction table!");
240 // Check the function level types first...
241 TypeListTy::iterator I = std::find(FunctionTypes.begin(),
242 FunctionTypes.end(), Ty);
244 if (I != FunctionTypes.end())
245 return Type::FirstDerivedTyID + ModuleTypes.size() +
246 (&*I - &FunctionTypes[0]);
248 // If we don't have our cache yet, build it now.
249 if (ModuleTypeIDCache.empty()) {
251 ModuleTypeIDCache.reserve(ModuleTypes.size());
252 for (TypeListTy::iterator I = ModuleTypes.begin(), E = ModuleTypes.end();
254 ModuleTypeIDCache.push_back(std::make_pair(*I, N));
256 std::sort(ModuleTypeIDCache.begin(), ModuleTypeIDCache.end());
259 // Binary search the cache for the entry.
260 std::vector<std::pair<const Type*, unsigned> >::iterator IT =
261 std::lower_bound(ModuleTypeIDCache.begin(), ModuleTypeIDCache.end(),
262 std::make_pair(Ty, 0U));
263 if (IT == ModuleTypeIDCache.end() || IT->first != Ty)
264 error("Didn't find type in ModuleTypes.");
266 return Type::FirstDerivedTyID + IT->second;
269 /// This is just like getType, but when a compaction table is in use, it is
270 /// ignored. It also ignores function level types.
272 const Type *BytecodeReader::getGlobalTableType(unsigned Slot) {
273 if (Slot < Type::FirstDerivedTyID) {
274 const Type *Ty = Type::getPrimitiveType((Type::TypeID)Slot);
276 error("Not a primitive type ID?");
279 Slot -= Type::FirstDerivedTyID;
280 if (Slot >= ModuleTypes.size())
281 error("Illegal compaction table type reference!");
282 return ModuleTypes[Slot];
285 /// This is just like getTypeSlot, but when a compaction table is in use, it
286 /// is ignored. It also ignores function level types.
287 unsigned BytecodeReader::getGlobalTableTypeSlot(const Type *Ty) {
288 if (Ty->isPrimitiveType())
289 return Ty->getTypeID();
291 // If we don't have our cache yet, build it now.
292 if (ModuleTypeIDCache.empty()) {
294 ModuleTypeIDCache.reserve(ModuleTypes.size());
295 for (TypeListTy::iterator I = ModuleTypes.begin(), E = ModuleTypes.end();
297 ModuleTypeIDCache.push_back(std::make_pair(*I, N));
299 std::sort(ModuleTypeIDCache.begin(), ModuleTypeIDCache.end());
302 // Binary search the cache for the entry.
303 std::vector<std::pair<const Type*, unsigned> >::iterator IT =
304 std::lower_bound(ModuleTypeIDCache.begin(), ModuleTypeIDCache.end(),
305 std::make_pair(Ty, 0U));
306 if (IT == ModuleTypeIDCache.end() || IT->first != Ty)
307 error("Didn't find type in ModuleTypes.");
309 return Type::FirstDerivedTyID + IT->second;
312 /// Retrieve a value of a given type and slot number, possibly creating
313 /// it if it doesn't already exist.
314 Value * BytecodeReader::getValue(unsigned type, unsigned oNum, bool Create) {
315 assert(type != Type::LabelTyID && "getValue() cannot get blocks!");
318 // If there is a compaction table active, it defines the low-level numbers.
319 // If not, the module values define the low-level numbers.
320 if (CompactionValues.size() > type && !CompactionValues[type].empty()) {
321 if (Num < CompactionValues[type].size())
322 return CompactionValues[type][Num];
323 Num -= CompactionValues[type].size();
325 // By default, the global type id is the type id passed in
326 unsigned GlobalTyID = type;
328 // If the type plane was compactified, figure out the global type ID by
329 // adding the derived type ids and the distance.
330 if (!CompactionTypes.empty() && type >= Type::FirstDerivedTyID)
331 GlobalTyID = CompactionTypes[type-Type::FirstDerivedTyID].second;
333 if (hasImplicitNull(GlobalTyID)) {
334 const Type *Ty = getType(type);
335 if (!isa<OpaqueType>(Ty)) {
337 return Constant::getNullValue(Ty);
342 if (GlobalTyID < ModuleValues.size() && ModuleValues[GlobalTyID]) {
343 if (Num < ModuleValues[GlobalTyID]->size())
344 return ModuleValues[GlobalTyID]->getOperand(Num);
345 Num -= ModuleValues[GlobalTyID]->size();
349 if (FunctionValues.size() > type &&
350 FunctionValues[type] &&
351 Num < FunctionValues[type]->size())
352 return FunctionValues[type]->getOperand(Num);
354 if (!Create) return 0; // Do not create a placeholder?
356 // Did we already create a place holder?
357 std::pair<unsigned,unsigned> KeyValue(type, oNum);
358 ForwardReferenceMap::iterator I = ForwardReferences.lower_bound(KeyValue);
359 if (I != ForwardReferences.end() && I->first == KeyValue)
360 return I->second; // We have already created this placeholder
362 // If the type exists (it should)
363 if (const Type* Ty = getType(type)) {
364 // Create the place holder
365 Value *Val = new Argument(Ty);
366 ForwardReferences.insert(I, std::make_pair(KeyValue, Val));
369 error("Can't create placeholder for value of type slot #" + utostr(type));
370 return 0; // just silence warning, error calls longjmp
373 /// This is just like getValue, but when a compaction table is in use, it
374 /// is ignored. Also, no forward references or other fancy features are
376 Value* BytecodeReader::getGlobalTableValue(unsigned TyID, unsigned SlotNo) {
378 return Constant::getNullValue(getType(TyID));
380 if (!CompactionTypes.empty() && TyID >= Type::FirstDerivedTyID) {
381 TyID -= Type::FirstDerivedTyID;
382 if (TyID >= CompactionTypes.size())
383 error("Type ID out of range for compaction table!");
384 TyID = CompactionTypes[TyID].second;
389 if (TyID >= ModuleValues.size() || ModuleValues[TyID] == 0 ||
390 SlotNo >= ModuleValues[TyID]->size()) {
391 if (TyID >= ModuleValues.size() || ModuleValues[TyID] == 0)
392 error("Corrupt compaction table entry!"
393 + utostr(TyID) + ", " + utostr(SlotNo) + ": "
394 + utostr(ModuleValues.size()));
396 error("Corrupt compaction table entry!"
397 + utostr(TyID) + ", " + utostr(SlotNo) + ": "
398 + utostr(ModuleValues.size()) + ", "
399 + utohexstr(reinterpret_cast<uint64_t>(((void*)ModuleValues[TyID])))
401 + utostr(ModuleValues[TyID]->size()));
403 return ModuleValues[TyID]->getOperand(SlotNo);
406 /// Just like getValue, except that it returns a null pointer
407 /// only on error. It always returns a constant (meaning that if the value is
408 /// defined, but is not a constant, that is an error). If the specified
409 /// constant hasn't been parsed yet, a placeholder is defined and used.
410 /// Later, after the real value is parsed, the placeholder is eliminated.
411 Constant* BytecodeReader::getConstantValue(unsigned TypeSlot, unsigned Slot) {
412 if (Value *V = getValue(TypeSlot, Slot, false))
413 if (Constant *C = dyn_cast<Constant>(V))
414 return C; // If we already have the value parsed, just return it
416 error("Value for slot " + utostr(Slot) +
417 " is expected to be a constant!");
419 std::pair<unsigned, unsigned> Key(TypeSlot, Slot);
420 ConstantRefsType::iterator I = ConstantFwdRefs.lower_bound(Key);
422 if (I != ConstantFwdRefs.end() && I->first == Key) {
425 // Create a placeholder for the constant reference and
426 // keep track of the fact that we have a forward ref to recycle it
427 Constant *C = new ConstantPlaceHolder(getType(TypeSlot));
429 // Keep track of the fact that we have a forward ref to recycle it
430 ConstantFwdRefs.insert(I, std::make_pair(Key, C));
435 //===----------------------------------------------------------------------===//
436 // IR Construction Methods
437 //===----------------------------------------------------------------------===//
439 /// As values are created, they are inserted into the appropriate place
440 /// with this method. The ValueTable argument must be one of ModuleValues
441 /// or FunctionValues data members of this class.
442 unsigned BytecodeReader::insertValue(Value *Val, unsigned type,
443 ValueTable &ValueTab) {
444 if (ValueTab.size() <= type)
445 ValueTab.resize(type+1);
447 if (!ValueTab[type]) ValueTab[type] = new ValueList();
449 ValueTab[type]->push_back(Val);
451 bool HasOffset = hasImplicitNull(type) && !isa<OpaqueType>(Val->getType());
452 return ValueTab[type]->size()-1 + HasOffset;
455 /// Insert the arguments of a function as new values in the reader.
456 void BytecodeReader::insertArguments(Function* F) {
457 const FunctionType *FT = F->getFunctionType();
458 Function::arg_iterator AI = F->arg_begin();
459 for (FunctionType::param_iterator It = FT->param_begin();
460 It != FT->param_end(); ++It, ++AI)
461 insertValue(AI, getTypeSlot(AI->getType()), FunctionValues);
464 //===----------------------------------------------------------------------===//
465 // Bytecode Parsing Methods
466 //===----------------------------------------------------------------------===//
468 /// This method parses a single instruction. The instruction is
469 /// inserted at the end of the \p BB provided. The arguments of
470 /// the instruction are provided in the \p Oprnds vector.
471 void BytecodeReader::ParseInstruction(std::vector<unsigned> &Oprnds,
475 // Clear instruction data
479 unsigned Op = read_uint();
481 // bits Instruction format: Common to all formats
482 // --------------------------
483 // 01-00: Opcode type, fixed to 1.
485 Opcode = (Op >> 2) & 63;
486 Oprnds.resize((Op >> 0) & 03);
488 // Extract the operands
489 switch (Oprnds.size()) {
491 // bits Instruction format:
492 // --------------------------
493 // 19-08: Resulting type plane
494 // 31-20: Operand #1 (if set to (2^12-1), then zero operands)
496 iType = (Op >> 8) & 4095;
497 Oprnds[0] = (Op >> 20) & 4095;
498 if (Oprnds[0] == 4095) // Handle special encoding for 0 operands...
502 // bits Instruction format:
503 // --------------------------
504 // 15-08: Resulting type plane
508 iType = (Op >> 8) & 255;
509 Oprnds[0] = (Op >> 16) & 255;
510 Oprnds[1] = (Op >> 24) & 255;
513 // bits Instruction format:
514 // --------------------------
515 // 13-08: Resulting type plane
520 iType = (Op >> 8) & 63;
521 Oprnds[0] = (Op >> 14) & 63;
522 Oprnds[1] = (Op >> 20) & 63;
523 Oprnds[2] = (Op >> 26) & 63;
526 At -= 4; // Hrm, try this again...
527 Opcode = read_vbr_uint();
529 iType = read_vbr_uint();
531 unsigned NumOprnds = read_vbr_uint();
532 Oprnds.resize(NumOprnds);
535 error("Zero-argument instruction found; this is invalid.");
537 for (unsigned i = 0; i != NumOprnds; ++i)
538 Oprnds[i] = read_vbr_uint();
542 const Type *InstTy = getType(iType);
544 // Make the necessary adjustments for dealing with backwards compatibility
546 Instruction* Result = 0;
548 // We have enough info to inform the handler now.
550 Handler->handleInstruction(Opcode, InstTy, Oprnds, At-SaveAt);
552 // First, handle the easy binary operators case
553 if (Opcode >= Instruction::BinaryOpsBegin &&
554 Opcode < Instruction::BinaryOpsEnd && Oprnds.size() == 2) {
555 Result = BinaryOperator::create(Instruction::BinaryOps(Opcode),
556 getValue(iType, Oprnds[0]),
557 getValue(iType, Oprnds[1]));
559 // Indicate that we don't think this is a call instruction (yet).
560 // Process based on the Opcode read
562 default: // There was an error, this shouldn't happen.
564 error("Illegal instruction read!");
566 case Instruction::VAArg:
567 if (Oprnds.size() != 2)
568 error("Invalid VAArg instruction!");
569 Result = new VAArgInst(getValue(iType, Oprnds[0]),
572 case Instruction::ExtractElement: {
573 if (Oprnds.size() != 2)
574 error("Invalid extractelement instruction!");
575 Value *V1 = getValue(iType, Oprnds[0]);
576 Value *V2 = getValue(Type::Int32TyID, Oprnds[1]);
578 if (!ExtractElementInst::isValidOperands(V1, V2))
579 error("Invalid extractelement instruction!");
581 Result = new ExtractElementInst(V1, V2);
584 case Instruction::InsertElement: {
585 const PackedType *PackedTy = dyn_cast<PackedType>(InstTy);
586 if (!PackedTy || Oprnds.size() != 3)
587 error("Invalid insertelement instruction!");
589 Value *V1 = getValue(iType, Oprnds[0]);
590 Value *V2 = getValue(getTypeSlot(PackedTy->getElementType()),Oprnds[1]);
591 Value *V3 = getValue(Type::Int32TyID, Oprnds[2]);
593 if (!InsertElementInst::isValidOperands(V1, V2, V3))
594 error("Invalid insertelement instruction!");
595 Result = new InsertElementInst(V1, V2, V3);
598 case Instruction::ShuffleVector: {
599 const PackedType *PackedTy = dyn_cast<PackedType>(InstTy);
600 if (!PackedTy || Oprnds.size() != 3)
601 error("Invalid shufflevector instruction!");
602 Value *V1 = getValue(iType, Oprnds[0]);
603 Value *V2 = getValue(iType, Oprnds[1]);
604 const PackedType *EltTy =
605 PackedType::get(Type::Int32Ty, PackedTy->getNumElements());
606 Value *V3 = getValue(getTypeSlot(EltTy), Oprnds[2]);
607 if (!ShuffleVectorInst::isValidOperands(V1, V2, V3))
608 error("Invalid shufflevector instruction!");
609 Result = new ShuffleVectorInst(V1, V2, V3);
612 case Instruction::Trunc:
613 if (Oprnds.size() != 2)
614 error("Invalid cast instruction!");
615 Result = new TruncInst(getValue(iType, Oprnds[0]),
618 case Instruction::ZExt:
619 if (Oprnds.size() != 2)
620 error("Invalid cast instruction!");
621 Result = new ZExtInst(getValue(iType, Oprnds[0]),
624 case Instruction::SExt:
625 if (Oprnds.size() != 2)
626 error("Invalid Cast instruction!");
627 Result = new SExtInst(getValue(iType, Oprnds[0]),
630 case Instruction::FPTrunc:
631 if (Oprnds.size() != 2)
632 error("Invalid cast instruction!");
633 Result = new FPTruncInst(getValue(iType, Oprnds[0]),
636 case Instruction::FPExt:
637 if (Oprnds.size() != 2)
638 error("Invalid cast instruction!");
639 Result = new FPExtInst(getValue(iType, Oprnds[0]),
642 case Instruction::UIToFP:
643 if (Oprnds.size() != 2)
644 error("Invalid cast instruction!");
645 Result = new UIToFPInst(getValue(iType, Oprnds[0]),
648 case Instruction::SIToFP:
649 if (Oprnds.size() != 2)
650 error("Invalid cast instruction!");
651 Result = new SIToFPInst(getValue(iType, Oprnds[0]),
654 case Instruction::FPToUI:
655 if (Oprnds.size() != 2)
656 error("Invalid cast instruction!");
657 Result = new FPToUIInst(getValue(iType, Oprnds[0]),
660 case Instruction::FPToSI:
661 if (Oprnds.size() != 2)
662 error("Invalid cast instruction!");
663 Result = new FPToSIInst(getValue(iType, Oprnds[0]),
666 case Instruction::IntToPtr:
667 if (Oprnds.size() != 2)
668 error("Invalid cast instruction!");
669 Result = new IntToPtrInst(getValue(iType, Oprnds[0]),
672 case Instruction::PtrToInt:
673 if (Oprnds.size() != 2)
674 error("Invalid cast instruction!");
675 Result = new PtrToIntInst(getValue(iType, Oprnds[0]),
678 case Instruction::BitCast:
679 if (Oprnds.size() != 2)
680 error("Invalid cast instruction!");
681 Result = new BitCastInst(getValue(iType, Oprnds[0]),
684 case Instruction::Select:
685 if (Oprnds.size() != 3)
686 error("Invalid Select instruction!");
687 Result = new SelectInst(getValue(Type::Int1TyID, Oprnds[0]),
688 getValue(iType, Oprnds[1]),
689 getValue(iType, Oprnds[2]));
691 case Instruction::PHI: {
692 if (Oprnds.size() == 0 || (Oprnds.size() & 1))
693 error("Invalid phi node encountered!");
695 PHINode *PN = new PHINode(InstTy);
696 PN->reserveOperandSpace(Oprnds.size());
697 for (unsigned i = 0, e = Oprnds.size(); i != e; i += 2)
699 getValue(iType, Oprnds[i]), getBasicBlock(Oprnds[i+1]));
703 case Instruction::ICmp:
704 case Instruction::FCmp:
705 if (Oprnds.size() != 3)
706 error("Cmp instructions requires 3 operands");
707 // These instructions encode the comparison predicate as the 3rd operand.
708 Result = CmpInst::create(Instruction::OtherOps(Opcode),
709 static_cast<unsigned short>(Oprnds[2]),
710 getValue(iType, Oprnds[0]), getValue(iType, Oprnds[1]));
712 case Instruction::Shl:
713 case Instruction::LShr:
714 case Instruction::AShr:
715 Result = new ShiftInst(Instruction::OtherOps(Opcode),
716 getValue(iType, Oprnds[0]),
717 getValue(Type::Int8TyID, Oprnds[1]));
719 case Instruction::Ret:
720 if (Oprnds.size() == 0)
721 Result = new ReturnInst();
722 else if (Oprnds.size() == 1)
723 Result = new ReturnInst(getValue(iType, Oprnds[0]));
725 error("Unrecognized instruction!");
728 case Instruction::Br:
729 if (Oprnds.size() == 1)
730 Result = new BranchInst(getBasicBlock(Oprnds[0]));
731 else if (Oprnds.size() == 3)
732 Result = new BranchInst(getBasicBlock(Oprnds[0]),
733 getBasicBlock(Oprnds[1]), getValue(Type::Int1TyID , Oprnds[2]));
735 error("Invalid number of operands for a 'br' instruction!");
737 case Instruction::Switch: {
738 if (Oprnds.size() & 1)
739 error("Switch statement with odd number of arguments!");
741 SwitchInst *I = new SwitchInst(getValue(iType, Oprnds[0]),
742 getBasicBlock(Oprnds[1]),
744 for (unsigned i = 2, e = Oprnds.size(); i != e; i += 2)
745 I->addCase(cast<ConstantInt>(getValue(iType, Oprnds[i])),
746 getBasicBlock(Oprnds[i+1]));
750 case 58: // Call with extra operand for calling conv
751 case 59: // tail call, Fast CC
752 case 60: // normal call, Fast CC
753 case 61: // tail call, C Calling Conv
754 case Instruction::Call: { // Normal Call, C Calling Convention
755 if (Oprnds.size() == 0)
756 error("Invalid call instruction encountered!");
757 Value *F = getValue(iType, Oprnds[0]);
759 unsigned CallingConv = CallingConv::C;
760 bool isTailCall = false;
762 if (Opcode == 61 || Opcode == 59)
766 isTailCall = Oprnds.back() & 1;
767 CallingConv = Oprnds.back() >> 1;
769 } else if (Opcode == 59 || Opcode == 60) {
770 CallingConv = CallingConv::Fast;
773 // Check to make sure we have a pointer to function type
774 const PointerType *PTy = dyn_cast<PointerType>(F->getType());
775 if (PTy == 0) error("Call to non function pointer value!");
776 const FunctionType *FTy = dyn_cast<FunctionType>(PTy->getElementType());
777 if (FTy == 0) error("Call to non function pointer value!");
779 std::vector<Value *> Params;
780 if (!FTy->isVarArg()) {
781 FunctionType::param_iterator It = FTy->param_begin();
783 for (unsigned i = 1, e = Oprnds.size(); i != e; ++i) {
784 if (It == FTy->param_end())
785 error("Invalid call instruction!");
786 Params.push_back(getValue(getTypeSlot(*It++), Oprnds[i]));
788 if (It != FTy->param_end())
789 error("Invalid call instruction!");
791 Oprnds.erase(Oprnds.begin(), Oprnds.begin()+1);
793 unsigned FirstVariableOperand;
794 if (Oprnds.size() < FTy->getNumParams())
795 error("Call instruction missing operands!");
797 // Read all of the fixed arguments
798 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
800 getValue(getTypeSlot(FTy->getParamType(i)),Oprnds[i]));
802 FirstVariableOperand = FTy->getNumParams();
804 if ((Oprnds.size()-FirstVariableOperand) & 1)
805 error("Invalid call instruction!"); // Must be pairs of type/value
807 for (unsigned i = FirstVariableOperand, e = Oprnds.size();
809 Params.push_back(getValue(Oprnds[i], Oprnds[i+1]));
812 Result = new CallInst(F, Params);
813 if (isTailCall) cast<CallInst>(Result)->setTailCall();
814 if (CallingConv) cast<CallInst>(Result)->setCallingConv(CallingConv);
817 case Instruction::Invoke: { // Invoke C CC
818 if (Oprnds.size() < 3)
819 error("Invalid invoke instruction!");
820 Value *F = getValue(iType, Oprnds[0]);
822 // Check to make sure we have a pointer to function type
823 const PointerType *PTy = dyn_cast<PointerType>(F->getType());
825 error("Invoke to non function pointer value!");
826 const FunctionType *FTy = dyn_cast<FunctionType>(PTy->getElementType());
828 error("Invoke to non function pointer value!");
830 std::vector<Value *> Params;
831 BasicBlock *Normal, *Except;
832 unsigned CallingConv = Oprnds.back();
835 if (!FTy->isVarArg()) {
836 Normal = getBasicBlock(Oprnds[1]);
837 Except = getBasicBlock(Oprnds[2]);
839 FunctionType::param_iterator It = FTy->param_begin();
840 for (unsigned i = 3, e = Oprnds.size(); i != e; ++i) {
841 if (It == FTy->param_end())
842 error("Invalid invoke instruction!");
843 Params.push_back(getValue(getTypeSlot(*It++), Oprnds[i]));
845 if (It != FTy->param_end())
846 error("Invalid invoke instruction!");
848 Oprnds.erase(Oprnds.begin(), Oprnds.begin()+1);
850 Normal = getBasicBlock(Oprnds[0]);
851 Except = getBasicBlock(Oprnds[1]);
853 unsigned FirstVariableArgument = FTy->getNumParams()+2;
854 for (unsigned i = 2; i != FirstVariableArgument; ++i)
855 Params.push_back(getValue(getTypeSlot(FTy->getParamType(i-2)),
858 // Must be type/value pairs. If not, error out.
859 if (Oprnds.size()-FirstVariableArgument & 1)
860 error("Invalid invoke instruction!");
862 for (unsigned i = FirstVariableArgument; i < Oprnds.size(); i += 2)
863 Params.push_back(getValue(Oprnds[i], Oprnds[i+1]));
866 Result = new InvokeInst(F, Normal, Except, Params);
867 if (CallingConv) cast<InvokeInst>(Result)->setCallingConv(CallingConv);
870 case Instruction::Malloc: {
872 if (Oprnds.size() == 2)
873 Align = (1 << Oprnds[1]) >> 1;
874 else if (Oprnds.size() > 2)
875 error("Invalid malloc instruction!");
876 if (!isa<PointerType>(InstTy))
877 error("Invalid malloc instruction!");
879 Result = new MallocInst(cast<PointerType>(InstTy)->getElementType(),
880 getValue(Type::Int32TyID, Oprnds[0]), Align);
883 case Instruction::Alloca: {
885 if (Oprnds.size() == 2)
886 Align = (1 << Oprnds[1]) >> 1;
887 else if (Oprnds.size() > 2)
888 error("Invalid alloca instruction!");
889 if (!isa<PointerType>(InstTy))
890 error("Invalid alloca instruction!");
892 Result = new AllocaInst(cast<PointerType>(InstTy)->getElementType(),
893 getValue(Type::Int32TyID, Oprnds[0]), Align);
896 case Instruction::Free:
897 if (!isa<PointerType>(InstTy))
898 error("Invalid free instruction!");
899 Result = new FreeInst(getValue(iType, Oprnds[0]));
901 case Instruction::GetElementPtr: {
902 if (Oprnds.size() == 0 || !isa<PointerType>(InstTy))
903 error("Invalid getelementptr instruction!");
905 std::vector<Value*> Idx;
907 const Type *NextTy = InstTy;
908 for (unsigned i = 1, e = Oprnds.size(); i != e; ++i) {
909 const CompositeType *TopTy = dyn_cast_or_null<CompositeType>(NextTy);
911 error("Invalid getelementptr instruction!");
913 unsigned ValIdx = Oprnds[i];
915 // Struct indices are always uints, sequential type indices can be
916 // any of the 32 or 64-bit integer types. The actual choice of
917 // type is encoded in the low bit of the slot number.
918 if (isa<StructType>(TopTy))
919 IdxTy = Type::Int32TyID;
921 switch (ValIdx & 1) {
923 case 0: IdxTy = Type::Int32TyID; break;
924 case 1: IdxTy = Type::Int64TyID; break;
928 Idx.push_back(getValue(IdxTy, ValIdx));
929 NextTy = GetElementPtrInst::getIndexedType(InstTy, Idx, true);
932 Result = new GetElementPtrInst(getValue(iType, Oprnds[0]), Idx);
935 case 62: // volatile load
936 case Instruction::Load:
937 if (Oprnds.size() != 1 || !isa<PointerType>(InstTy))
938 error("Invalid load instruction!");
939 Result = new LoadInst(getValue(iType, Oprnds[0]), "", Opcode == 62);
941 case 63: // volatile store
942 case Instruction::Store: {
943 if (!isa<PointerType>(InstTy) || Oprnds.size() != 2)
944 error("Invalid store instruction!");
946 Value *Ptr = getValue(iType, Oprnds[1]);
947 const Type *ValTy = cast<PointerType>(Ptr->getType())->getElementType();
948 Result = new StoreInst(getValue(getTypeSlot(ValTy), Oprnds[0]), Ptr,
952 case Instruction::Unwind:
953 if (Oprnds.size() != 0) error("Invalid unwind instruction!");
954 Result = new UnwindInst();
956 case Instruction::Unreachable:
957 if (Oprnds.size() != 0) error("Invalid unreachable instruction!");
958 Result = new UnreachableInst();
960 } // end switch(Opcode)
963 BB->getInstList().push_back(Result);
966 if (Result->getType() == InstTy)
969 TypeSlot = getTypeSlot(Result->getType());
971 insertValue(Result, TypeSlot, FunctionValues);
974 /// Get a particular numbered basic block, which might be a forward reference.
975 /// This works together with ParseInstructionList to handle these forward
976 /// references in a clean manner. This function is used when constructing
977 /// phi, br, switch, and other instructions that reference basic blocks.
978 /// Blocks are numbered sequentially as they appear in the function.
979 BasicBlock *BytecodeReader::getBasicBlock(unsigned ID) {
980 // Make sure there is room in the table...
981 if (ParsedBasicBlocks.size() <= ID) ParsedBasicBlocks.resize(ID+1);
983 // First check to see if this is a backwards reference, i.e. this block
984 // has already been created, or if the forward reference has already
986 if (ParsedBasicBlocks[ID])
987 return ParsedBasicBlocks[ID];
989 // Otherwise, the basic block has not yet been created. Do so and add it to
990 // the ParsedBasicBlocks list.
991 return ParsedBasicBlocks[ID] = new BasicBlock();
994 /// Parse all of the BasicBlock's & Instruction's in the body of a function.
995 /// In post 1.0 bytecode files, we no longer emit basic block individually,
996 /// in order to avoid per-basic-block overhead.
997 /// @returns the number of basic blocks encountered.
998 unsigned BytecodeReader::ParseInstructionList(Function* F) {
999 unsigned BlockNo = 0;
1000 std::vector<unsigned> Args;
1002 while (moreInBlock()) {
1003 if (Handler) Handler->handleBasicBlockBegin(BlockNo);
1005 if (ParsedBasicBlocks.size() == BlockNo)
1006 ParsedBasicBlocks.push_back(BB = new BasicBlock());
1007 else if (ParsedBasicBlocks[BlockNo] == 0)
1008 BB = ParsedBasicBlocks[BlockNo] = new BasicBlock();
1010 BB = ParsedBasicBlocks[BlockNo];
1012 F->getBasicBlockList().push_back(BB);
1014 // Read instructions into this basic block until we get to a terminator
1015 while (moreInBlock() && !BB->getTerminator())
1016 ParseInstruction(Args, BB);
1018 if (!BB->getTerminator())
1019 error("Non-terminated basic block found!");
1021 if (Handler) Handler->handleBasicBlockEnd(BlockNo-1);
1027 /// Parse a type symbol table.
1028 void BytecodeReader::ParseTypeSymbolTable(TypeSymbolTable *TST) {
1029 // Type Symtab block header: [num entries]
1030 unsigned NumEntries = read_vbr_uint();
1031 for (unsigned i = 0; i < NumEntries; ++i) {
1032 // Symtab entry: [type slot #][name]
1033 unsigned slot = read_vbr_uint();
1034 std::string Name = read_str();
1035 const Type* T = getType(slot);
1036 TST->insert(Name, T);
1040 /// Parse a value symbol table. This works for both module level and function
1041 /// level symbol tables. For function level symbol tables, the CurrentFunction
1042 /// parameter must be non-zero and the ST parameter must correspond to
1043 /// CurrentFunction's symbol table. For Module level symbol tables, the
1044 /// CurrentFunction argument must be zero.
1045 void BytecodeReader::ParseValueSymbolTable(Function *CurrentFunction,
1048 if (Handler) Handler->handleSymbolTableBegin(CurrentFunction,ST);
1050 // Allow efficient basic block lookup by number.
1051 std::vector<BasicBlock*> BBMap;
1052 if (CurrentFunction)
1053 for (Function::iterator I = CurrentFunction->begin(),
1054 E = CurrentFunction->end(); I != E; ++I)
1057 while (moreInBlock()) {
1058 // Symtab block header: [num entries][type id number]
1059 unsigned NumEntries = read_vbr_uint();
1060 unsigned Typ = read_vbr_uint();
1062 for (unsigned i = 0; i != NumEntries; ++i) {
1063 // Symtab entry: [def slot #][name]
1064 unsigned slot = read_vbr_uint();
1065 std::string Name = read_str();
1067 if (Typ == Type::LabelTyID) {
1068 if (slot < BBMap.size())
1071 V = getValue(Typ, slot, false); // Find mapping...
1074 error("Failed value look-up for name '" + Name + "'");
1078 checkPastBlockEnd("Symbol Table");
1079 if (Handler) Handler->handleSymbolTableEnd();
1082 /// Read in the types portion of a compaction table.
1083 void BytecodeReader::ParseCompactionTypes(unsigned NumEntries) {
1084 for (unsigned i = 0; i != NumEntries; ++i) {
1085 unsigned TypeSlot = read_vbr_uint();
1086 const Type *Typ = getGlobalTableType(TypeSlot);
1087 CompactionTypes.push_back(std::make_pair(Typ, TypeSlot));
1088 if (Handler) Handler->handleCompactionTableType(i, TypeSlot, Typ);
1092 /// Parse a compaction table.
1093 void BytecodeReader::ParseCompactionTable() {
1095 // Notify handler that we're beginning a compaction table.
1096 if (Handler) Handler->handleCompactionTableBegin();
1098 // Get the types for the compaction table.
1099 unsigned NumEntries = read_vbr_uint();
1100 ParseCompactionTypes(NumEntries);
1102 // Compaction tables live in separate blocks so we have to loop
1103 // until we've read the whole thing.
1104 while (moreInBlock()) {
1105 // Read the number of Value* entries in the compaction table
1106 unsigned NumEntries = read_vbr_uint();
1109 // Decode the type from value read in. Most compaction table
1110 // planes will have one or two entries in them. If that's the
1111 // case then the length is encoded in the bottom two bits and
1112 // the higher bits encode the type. This saves another VBR value.
1113 if ((NumEntries & 3) == 3) {
1114 // In this case, both low-order bits are set (value 3). This
1115 // is a signal that the typeid follows.
1117 Ty = read_vbr_uint();
1119 // In this case, the low-order bits specify the number of entries
1120 // and the high order bits specify the type.
1121 Ty = NumEntries >> 2;
1125 // Make sure we have enough room for the plane.
1126 if (Ty >= CompactionValues.size())
1127 CompactionValues.resize(Ty+1);
1129 // Make sure the plane is empty or we have some kind of error.
1130 if (!CompactionValues[Ty].empty())
1131 error("Compaction table plane contains multiple entries!");
1133 // Notify handler about the plane.
1134 if (Handler) Handler->handleCompactionTablePlane(Ty, NumEntries);
1136 // Push the implicit zero.
1137 CompactionValues[Ty].push_back(Constant::getNullValue(getType(Ty)));
1139 // Read in each of the entries, put them in the compaction table
1140 // and notify the handler that we have a new compaction table value.
1141 for (unsigned i = 0; i != NumEntries; ++i) {
1142 unsigned ValSlot = read_vbr_uint();
1143 Value *V = getGlobalTableValue(Ty, ValSlot);
1144 CompactionValues[Ty].push_back(V);
1145 if (Handler) Handler->handleCompactionTableValue(i, Ty, ValSlot);
1148 // Notify handler that the compaction table is done.
1149 if (Handler) Handler->handleCompactionTableEnd();
1152 // Parse a single type. The typeid is read in first. If its a primitive type
1153 // then nothing else needs to be read, we know how to instantiate it. If its
1154 // a derived type, then additional data is read to fill out the type
1156 const Type *BytecodeReader::ParseType() {
1157 unsigned PrimType = read_vbr_uint();
1158 const Type *Result = 0;
1159 if ((Result = Type::getPrimitiveType((Type::TypeID)PrimType)))
1163 case Type::FunctionTyID: {
1164 const Type *RetType = readType();
1165 unsigned RetAttr = read_vbr_uint();
1167 unsigned NumParams = read_vbr_uint();
1169 std::vector<const Type*> Params;
1170 std::vector<FunctionType::ParameterAttributes> Attrs;
1171 Attrs.push_back(FunctionType::ParameterAttributes(RetAttr));
1172 while (NumParams--) {
1173 Params.push_back(readType());
1174 if (Params.back() != Type::VoidTy)
1175 Attrs.push_back(FunctionType::ParameterAttributes(read_vbr_uint()));
1178 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1179 if (isVarArg) Params.pop_back();
1181 Result = FunctionType::get(RetType, Params, isVarArg, Attrs);
1184 case Type::ArrayTyID: {
1185 const Type *ElementType = readType();
1186 unsigned NumElements = read_vbr_uint();
1187 Result = ArrayType::get(ElementType, NumElements);
1190 case Type::PackedTyID: {
1191 const Type *ElementType = readType();
1192 unsigned NumElements = read_vbr_uint();
1193 Result = PackedType::get(ElementType, NumElements);
1196 case Type::StructTyID: {
1197 std::vector<const Type*> Elements;
1198 unsigned Typ = read_vbr_uint();
1199 while (Typ) { // List is terminated by void/0 typeid
1200 Elements.push_back(getType(Typ));
1201 Typ = read_vbr_uint();
1204 Result = StructType::get(Elements, false);
1207 case Type::BC_ONLY_PackedStructTyID: {
1208 std::vector<const Type*> Elements;
1209 unsigned Typ = read_vbr_uint();
1210 while (Typ) { // List is terminated by void/0 typeid
1211 Elements.push_back(getType(Typ));
1212 Typ = read_vbr_uint();
1215 Result = StructType::get(Elements, true);
1218 case Type::PointerTyID: {
1219 Result = PointerType::get(readType());
1223 case Type::OpaqueTyID: {
1224 Result = OpaqueType::get();
1229 error("Don't know how to deserialize primitive type " + utostr(PrimType));
1232 if (Handler) Handler->handleType(Result);
1236 // ParseTypes - We have to use this weird code to handle recursive
1237 // types. We know that recursive types will only reference the current slab of
1238 // values in the type plane, but they can forward reference types before they
1239 // have been read. For example, Type #0 might be '{ Ty#1 }' and Type #1 might
1240 // be 'Ty#0*'. When reading Type #0, type number one doesn't exist. To fix
1241 // this ugly problem, we pessimistically insert an opaque type for each type we
1242 // are about to read. This means that forward references will resolve to
1243 // something and when we reread the type later, we can replace the opaque type
1244 // with a new resolved concrete type.
1246 void BytecodeReader::ParseTypes(TypeListTy &Tab, unsigned NumEntries){
1247 assert(Tab.size() == 0 && "should not have read type constants in before!");
1249 // Insert a bunch of opaque types to be resolved later...
1250 Tab.reserve(NumEntries);
1251 for (unsigned i = 0; i != NumEntries; ++i)
1252 Tab.push_back(OpaqueType::get());
1255 Handler->handleTypeList(NumEntries);
1257 // If we are about to resolve types, make sure the type cache is clear.
1259 ModuleTypeIDCache.clear();
1261 // Loop through reading all of the types. Forward types will make use of the
1262 // opaque types just inserted.
1264 for (unsigned i = 0; i != NumEntries; ++i) {
1265 const Type* NewTy = ParseType();
1266 const Type* OldTy = Tab[i].get();
1268 error("Couldn't parse type!");
1270 // Don't directly push the new type on the Tab. Instead we want to replace
1271 // the opaque type we previously inserted with the new concrete value. This
1272 // approach helps with forward references to types. The refinement from the
1273 // abstract (opaque) type to the new type causes all uses of the abstract
1274 // type to use the concrete type (NewTy). This will also cause the opaque
1275 // type to be deleted.
1276 cast<DerivedType>(const_cast<Type*>(OldTy))->refineAbstractTypeTo(NewTy);
1278 // This should have replaced the old opaque type with the new type in the
1279 // value table... or with a preexisting type that was already in the system.
1280 // Let's just make sure it did.
1281 assert(Tab[i] != OldTy && "refineAbstractType didn't work!");
1285 /// Parse a single constant value
1286 Value *BytecodeReader::ParseConstantPoolValue(unsigned TypeID) {
1287 // We must check for a ConstantExpr before switching by type because
1288 // a ConstantExpr can be of any type, and has no explicit value.
1290 // 0 if not expr; numArgs if is expr
1291 unsigned isExprNumArgs = read_vbr_uint();
1293 if (isExprNumArgs) {
1294 // 'undef' is encoded with 'exprnumargs' == 1.
1295 if (isExprNumArgs == 1)
1296 return UndefValue::get(getType(TypeID));
1298 // Inline asm is encoded with exprnumargs == ~0U.
1299 if (isExprNumArgs == ~0U) {
1300 std::string AsmStr = read_str();
1301 std::string ConstraintStr = read_str();
1302 unsigned Flags = read_vbr_uint();
1304 const PointerType *PTy = dyn_cast<PointerType>(getType(TypeID));
1305 const FunctionType *FTy =
1306 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
1308 if (!FTy || !InlineAsm::Verify(FTy, ConstraintStr))
1309 error("Invalid constraints for inline asm");
1311 error("Invalid flags for inline asm");
1312 bool HasSideEffects = Flags & 1;
1313 return InlineAsm::get(FTy, AsmStr, ConstraintStr, HasSideEffects);
1318 // FIXME: Encoding of constant exprs could be much more compact!
1319 std::vector<Constant*> ArgVec;
1320 ArgVec.reserve(isExprNumArgs);
1321 unsigned Opcode = read_vbr_uint();
1323 // Read the slot number and types of each of the arguments
1324 for (unsigned i = 0; i != isExprNumArgs; ++i) {
1325 unsigned ArgValSlot = read_vbr_uint();
1326 unsigned ArgTypeSlot = read_vbr_uint();
1328 // Get the arg value from its slot if it exists, otherwise a placeholder
1329 ArgVec.push_back(getConstantValue(ArgTypeSlot, ArgValSlot));
1332 // Construct a ConstantExpr of the appropriate kind
1333 if (isExprNumArgs == 1) { // All one-operand expressions
1334 if (!Instruction::isCast(Opcode))
1335 error("Only cast instruction has one argument for ConstantExpr");
1337 Constant *Result = ConstantExpr::getCast(Opcode, ArgVec[0],
1339 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
1341 } else if (Opcode == Instruction::GetElementPtr) { // GetElementPtr
1342 std::vector<Constant*> IdxList(ArgVec.begin()+1, ArgVec.end());
1343 Constant *Result = ConstantExpr::getGetElementPtr(ArgVec[0], IdxList);
1344 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
1346 } else if (Opcode == Instruction::Select) {
1347 if (ArgVec.size() != 3)
1348 error("Select instruction must have three arguments.");
1349 Constant* Result = ConstantExpr::getSelect(ArgVec[0], ArgVec[1],
1351 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
1353 } else if (Opcode == Instruction::ExtractElement) {
1354 if (ArgVec.size() != 2 ||
1355 !ExtractElementInst::isValidOperands(ArgVec[0], ArgVec[1]))
1356 error("Invalid extractelement constand expr arguments");
1357 Constant* Result = ConstantExpr::getExtractElement(ArgVec[0], ArgVec[1]);
1358 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
1360 } else if (Opcode == Instruction::InsertElement) {
1361 if (ArgVec.size() != 3 ||
1362 !InsertElementInst::isValidOperands(ArgVec[0], ArgVec[1], ArgVec[2]))
1363 error("Invalid insertelement constand expr arguments");
1366 ConstantExpr::getInsertElement(ArgVec[0], ArgVec[1], ArgVec[2]);
1367 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
1369 } else if (Opcode == Instruction::ShuffleVector) {
1370 if (ArgVec.size() != 3 ||
1371 !ShuffleVectorInst::isValidOperands(ArgVec[0], ArgVec[1], ArgVec[2]))
1372 error("Invalid shufflevector constant expr arguments.");
1374 ConstantExpr::getShuffleVector(ArgVec[0], ArgVec[1], ArgVec[2]);
1375 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
1377 } else if (Opcode == Instruction::ICmp) {
1378 if (ArgVec.size() != 2)
1379 error("Invalid ICmp constant expr arguments.");
1380 unsigned predicate = read_vbr_uint();
1381 Constant *Result = ConstantExpr::getICmp(predicate, ArgVec[0], ArgVec[1]);
1382 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
1384 } else if (Opcode == Instruction::FCmp) {
1385 if (ArgVec.size() != 2)
1386 error("Invalid FCmp constant expr arguments.");
1387 unsigned predicate = read_vbr_uint();
1388 Constant *Result = ConstantExpr::getFCmp(predicate, ArgVec[0], ArgVec[1]);
1389 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
1391 } else { // All other 2-operand expressions
1392 Constant* Result = ConstantExpr::get(Opcode, ArgVec[0], ArgVec[1]);
1393 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
1398 // Ok, not an ConstantExpr. We now know how to read the given type...
1399 const Type *Ty = getType(TypeID);
1400 Constant *Result = 0;
1401 switch (Ty->getTypeID()) {
1402 case Type::Int1TyID: {
1403 unsigned Val = read_vbr_uint();
1404 if (Val != 0 && Val != 1)
1405 error("Invalid boolean value read.");
1406 Result = ConstantInt::get(Val == 1);
1407 if (Handler) Handler->handleConstantValue(Result);
1411 case Type::Int8TyID: // Unsigned integer types...
1412 case Type::Int16TyID:
1413 case Type::Int32TyID: {
1414 unsigned Val = read_vbr_uint();
1415 if (!ConstantInt::isValueValidForType(Ty, uint64_t(Val)))
1416 error("Invalid unsigned byte/short/int read.");
1417 Result = ConstantInt::get(Ty, Val);
1418 if (Handler) Handler->handleConstantValue(Result);
1422 case Type::Int64TyID: {
1423 uint64_t Val = read_vbr_uint64();
1424 if (!ConstantInt::isValueValidForType(Ty, Val))
1425 error("Invalid constant integer read.");
1426 Result = ConstantInt::get(Ty, Val);
1427 if (Handler) Handler->handleConstantValue(Result);
1430 case Type::FloatTyID: {
1433 Result = ConstantFP::get(Ty, Val);
1434 if (Handler) Handler->handleConstantValue(Result);
1438 case Type::DoubleTyID: {
1441 Result = ConstantFP::get(Ty, Val);
1442 if (Handler) Handler->handleConstantValue(Result);
1446 case Type::ArrayTyID: {
1447 const ArrayType *AT = cast<ArrayType>(Ty);
1448 unsigned NumElements = AT->getNumElements();
1449 unsigned TypeSlot = getTypeSlot(AT->getElementType());
1450 std::vector<Constant*> Elements;
1451 Elements.reserve(NumElements);
1452 while (NumElements--) // Read all of the elements of the constant.
1453 Elements.push_back(getConstantValue(TypeSlot,
1455 Result = ConstantArray::get(AT, Elements);
1456 if (Handler) Handler->handleConstantArray(AT, Elements, TypeSlot, Result);
1460 case Type::StructTyID: {
1461 const StructType *ST = cast<StructType>(Ty);
1463 std::vector<Constant *> Elements;
1464 Elements.reserve(ST->getNumElements());
1465 for (unsigned i = 0; i != ST->getNumElements(); ++i)
1466 Elements.push_back(getConstantValue(ST->getElementType(i),
1469 Result = ConstantStruct::get(ST, Elements);
1470 if (Handler) Handler->handleConstantStruct(ST, Elements, Result);
1474 case Type::PackedTyID: {
1475 const PackedType *PT = cast<PackedType>(Ty);
1476 unsigned NumElements = PT->getNumElements();
1477 unsigned TypeSlot = getTypeSlot(PT->getElementType());
1478 std::vector<Constant*> Elements;
1479 Elements.reserve(NumElements);
1480 while (NumElements--) // Read all of the elements of the constant.
1481 Elements.push_back(getConstantValue(TypeSlot,
1483 Result = ConstantPacked::get(PT, Elements);
1484 if (Handler) Handler->handleConstantPacked(PT, Elements, TypeSlot, Result);
1488 case Type::PointerTyID: { // ConstantPointerRef value (backwards compat).
1489 const PointerType *PT = cast<PointerType>(Ty);
1490 unsigned Slot = read_vbr_uint();
1492 // Check to see if we have already read this global variable...
1493 Value *Val = getValue(TypeID, Slot, false);
1495 GlobalValue *GV = dyn_cast<GlobalValue>(Val);
1496 if (!GV) error("GlobalValue not in ValueTable!");
1497 if (Handler) Handler->handleConstantPointer(PT, Slot, GV);
1500 error("Forward references are not allowed here.");
1505 error("Don't know how to deserialize constant value of type '" +
1506 Ty->getDescription());
1510 // Check that we didn't read a null constant if they are implicit for this
1511 // type plane. Do not do this check for constantexprs, as they may be folded
1512 // to a null value in a way that isn't predicted when a .bc file is initially
1514 assert((!isa<Constant>(Result) || !cast<Constant>(Result)->isNullValue()) ||
1515 !hasImplicitNull(TypeID) &&
1516 "Cannot read null values from bytecode!");
1520 /// Resolve references for constants. This function resolves the forward
1521 /// referenced constants in the ConstantFwdRefs map. It uses the
1522 /// replaceAllUsesWith method of Value class to substitute the placeholder
1523 /// instance with the actual instance.
1524 void BytecodeReader::ResolveReferencesToConstant(Constant *NewV, unsigned Typ,
1526 ConstantRefsType::iterator I =
1527 ConstantFwdRefs.find(std::make_pair(Typ, Slot));
1528 if (I == ConstantFwdRefs.end()) return; // Never forward referenced?
1530 Value *PH = I->second; // Get the placeholder...
1531 PH->replaceAllUsesWith(NewV);
1532 delete PH; // Delete the old placeholder
1533 ConstantFwdRefs.erase(I); // Remove the map entry for it
1536 /// Parse the constant strings section.
1537 void BytecodeReader::ParseStringConstants(unsigned NumEntries, ValueTable &Tab){
1538 for (; NumEntries; --NumEntries) {
1539 unsigned Typ = read_vbr_uint();
1540 const Type *Ty = getType(Typ);
1541 if (!isa<ArrayType>(Ty))
1542 error("String constant data invalid!");
1544 const ArrayType *ATy = cast<ArrayType>(Ty);
1545 if (ATy->getElementType() != Type::Int8Ty &&
1546 ATy->getElementType() != Type::Int8Ty)
1547 error("String constant data invalid!");
1549 // Read character data. The type tells us how long the string is.
1550 char *Data = reinterpret_cast<char *>(alloca(ATy->getNumElements()));
1551 read_data(Data, Data+ATy->getNumElements());
1553 std::vector<Constant*> Elements(ATy->getNumElements());
1554 const Type* ElemType = ATy->getElementType();
1555 for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
1556 Elements[i] = ConstantInt::get(ElemType, (unsigned char)Data[i]);
1558 // Create the constant, inserting it as needed.
1559 Constant *C = ConstantArray::get(ATy, Elements);
1560 unsigned Slot = insertValue(C, Typ, Tab);
1561 ResolveReferencesToConstant(C, Typ, Slot);
1562 if (Handler) Handler->handleConstantString(cast<ConstantArray>(C));
1566 /// Parse the constant pool.
1567 void BytecodeReader::ParseConstantPool(ValueTable &Tab,
1568 TypeListTy &TypeTab,
1570 if (Handler) Handler->handleGlobalConstantsBegin();
1572 /// In LLVM 1.3 Type does not derive from Value so the types
1573 /// do not occupy a plane. Consequently, we read the types
1574 /// first in the constant pool.
1576 unsigned NumEntries = read_vbr_uint();
1577 ParseTypes(TypeTab, NumEntries);
1580 while (moreInBlock()) {
1581 unsigned NumEntries = read_vbr_uint();
1582 unsigned Typ = read_vbr_uint();
1584 if (Typ == Type::VoidTyID) {
1585 /// Use of Type::VoidTyID is a misnomer. It actually means
1586 /// that the following plane is constant strings
1587 assert(&Tab == &ModuleValues && "Cannot read strings in functions!");
1588 ParseStringConstants(NumEntries, Tab);
1590 for (unsigned i = 0; i < NumEntries; ++i) {
1591 Value *V = ParseConstantPoolValue(Typ);
1592 assert(V && "ParseConstantPoolValue returned NULL!");
1593 unsigned Slot = insertValue(V, Typ, Tab);
1595 // If we are reading a function constant table, make sure that we adjust
1596 // the slot number to be the real global constant number.
1598 if (&Tab != &ModuleValues && Typ < ModuleValues.size() &&
1600 Slot += ModuleValues[Typ]->size();
1601 if (Constant *C = dyn_cast<Constant>(V))
1602 ResolveReferencesToConstant(C, Typ, Slot);
1607 // After we have finished parsing the constant pool, we had better not have
1608 // any dangling references left.
1609 if (!ConstantFwdRefs.empty()) {
1610 ConstantRefsType::const_iterator I = ConstantFwdRefs.begin();
1611 Constant* missingConst = I->second;
1612 error(utostr(ConstantFwdRefs.size()) +
1613 " unresolved constant reference exist. First one is '" +
1614 missingConst->getName() + "' of type '" +
1615 missingConst->getType()->getDescription() + "'.");
1618 checkPastBlockEnd("Constant Pool");
1619 if (Handler) Handler->handleGlobalConstantsEnd();
1622 /// Parse the contents of a function. Note that this function can be
1623 /// called lazily by materializeFunction
1624 /// @see materializeFunction
1625 void BytecodeReader::ParseFunctionBody(Function* F) {
1627 unsigned FuncSize = BlockEnd - At;
1628 GlobalValue::LinkageTypes Linkage = GlobalValue::ExternalLinkage;
1630 unsigned LinkageType = read_vbr_uint();
1631 switch (LinkageType) {
1632 case 0: Linkage = GlobalValue::ExternalLinkage; break;
1633 case 1: Linkage = GlobalValue::WeakLinkage; break;
1634 case 2: Linkage = GlobalValue::AppendingLinkage; break;
1635 case 3: Linkage = GlobalValue::InternalLinkage; break;
1636 case 4: Linkage = GlobalValue::LinkOnceLinkage; break;
1637 case 5: Linkage = GlobalValue::DLLImportLinkage; break;
1638 case 6: Linkage = GlobalValue::DLLExportLinkage; break;
1639 case 7: Linkage = GlobalValue::ExternalWeakLinkage; break;
1641 error("Invalid linkage type for Function.");
1642 Linkage = GlobalValue::InternalLinkage;
1646 F->setLinkage(Linkage);
1647 if (Handler) Handler->handleFunctionBegin(F,FuncSize);
1649 // Keep track of how many basic blocks we have read in...
1650 unsigned BlockNum = 0;
1651 bool InsertedArguments = false;
1653 BufPtr MyEnd = BlockEnd;
1654 while (At < MyEnd) {
1655 unsigned Type, Size;
1657 read_block(Type, Size);
1660 case BytecodeFormat::ConstantPoolBlockID:
1661 if (!InsertedArguments) {
1662 // Insert arguments into the value table before we parse the first basic
1663 // block in the function, but after we potentially read in the
1664 // compaction table.
1666 InsertedArguments = true;
1669 ParseConstantPool(FunctionValues, FunctionTypes, true);
1672 case BytecodeFormat::CompactionTableBlockID:
1673 ParseCompactionTable();
1676 case BytecodeFormat::InstructionListBlockID: {
1677 // Insert arguments into the value table before we parse the instruction
1678 // list for the function, but after we potentially read in the compaction
1680 if (!InsertedArguments) {
1682 InsertedArguments = true;
1686 error("Already parsed basic blocks!");
1687 BlockNum = ParseInstructionList(F);
1691 case BytecodeFormat::ValueSymbolTableBlockID:
1692 ParseValueSymbolTable(F, &F->getValueSymbolTable());
1695 case BytecodeFormat::TypeSymbolTableBlockID:
1696 error("Functions don't have type symbol tables");
1702 error("Wrapped around reading bytecode.");
1708 // Make sure there were no references to non-existant basic blocks.
1709 if (BlockNum != ParsedBasicBlocks.size())
1710 error("Illegal basic block operand reference");
1712 ParsedBasicBlocks.clear();
1714 // Resolve forward references. Replace any uses of a forward reference value
1715 // with the real value.
1716 while (!ForwardReferences.empty()) {
1717 std::map<std::pair<unsigned,unsigned>, Value*>::iterator
1718 I = ForwardReferences.begin();
1719 Value *V = getValue(I->first.first, I->first.second, false);
1720 Value *PlaceHolder = I->second;
1721 PlaceHolder->replaceAllUsesWith(V);
1722 ForwardReferences.erase(I);
1726 // Clear out function-level types...
1727 FunctionTypes.clear();
1728 CompactionTypes.clear();
1729 CompactionValues.clear();
1730 freeTable(FunctionValues);
1732 if (Handler) Handler->handleFunctionEnd(F);
1735 /// This function parses LLVM functions lazily. It obtains the type of the
1736 /// function and records where the body of the function is in the bytecode
1737 /// buffer. The caller can then use the ParseNextFunction and
1738 /// ParseAllFunctionBodies to get handler events for the functions.
1739 void BytecodeReader::ParseFunctionLazily() {
1740 if (FunctionSignatureList.empty())
1741 error("FunctionSignatureList empty!");
1743 Function *Func = FunctionSignatureList.back();
1744 FunctionSignatureList.pop_back();
1746 // Save the information for future reading of the function
1747 LazyFunctionLoadMap[Func] = LazyFunctionInfo(BlockStart, BlockEnd);
1749 // This function has a body but it's not loaded so it appears `External'.
1750 // Mark it as a `Ghost' instead to notify the users that it has a body.
1751 Func->setLinkage(GlobalValue::GhostLinkage);
1753 // Pretend we've `parsed' this function
1757 /// The ParserFunction method lazily parses one function. Use this method to
1758 /// casue the parser to parse a specific function in the module. Note that
1759 /// this will remove the function from what is to be included by
1760 /// ParseAllFunctionBodies.
1761 /// @see ParseAllFunctionBodies
1762 /// @see ParseBytecode
1763 bool BytecodeReader::ParseFunction(Function* Func, std::string* ErrMsg) {
1765 if (setjmp(context)) {
1766 // Set caller's error message, if requested
1769 // Indicate an error occurred
1773 // Find {start, end} pointers and slot in the map. If not there, we're done.
1774 LazyFunctionMap::iterator Fi = LazyFunctionLoadMap.find(Func);
1776 // Make sure we found it
1777 if (Fi == LazyFunctionLoadMap.end()) {
1778 error("Unrecognized function of type " + Func->getType()->getDescription());
1782 BlockStart = At = Fi->second.Buf;
1783 BlockEnd = Fi->second.EndBuf;
1784 assert(Fi->first == Func && "Found wrong function?");
1786 LazyFunctionLoadMap.erase(Fi);
1788 this->ParseFunctionBody(Func);
1792 /// The ParseAllFunctionBodies method parses through all the previously
1793 /// unparsed functions in the bytecode file. If you want to completely parse
1794 /// a bytecode file, this method should be called after Parsebytecode because
1795 /// Parsebytecode only records the locations in the bytecode file of where
1796 /// the function definitions are located. This function uses that information
1797 /// to materialize the functions.
1798 /// @see ParseBytecode
1799 bool BytecodeReader::ParseAllFunctionBodies(std::string* ErrMsg) {
1800 if (setjmp(context)) {
1801 // Set caller's error message, if requested
1804 // Indicate an error occurred
1808 LazyFunctionMap::iterator Fi = LazyFunctionLoadMap.begin();
1809 LazyFunctionMap::iterator Fe = LazyFunctionLoadMap.end();
1812 Function* Func = Fi->first;
1813 BlockStart = At = Fi->second.Buf;
1814 BlockEnd = Fi->second.EndBuf;
1815 ParseFunctionBody(Func);
1818 LazyFunctionLoadMap.clear();
1822 /// Parse the global type list
1823 void BytecodeReader::ParseGlobalTypes() {
1824 // Read the number of types
1825 unsigned NumEntries = read_vbr_uint();
1826 ParseTypes(ModuleTypes, NumEntries);
1829 /// Parse the Global info (types, global vars, constants)
1830 void BytecodeReader::ParseModuleGlobalInfo() {
1832 if (Handler) Handler->handleModuleGlobalsBegin();
1834 // SectionID - If a global has an explicit section specified, this map
1835 // remembers the ID until we can translate it into a string.
1836 std::map<GlobalValue*, unsigned> SectionID;
1838 // Read global variables...
1839 unsigned VarType = read_vbr_uint();
1840 while (VarType != Type::VoidTyID) { // List is terminated by Void
1841 // VarType Fields: bit0 = isConstant, bit1 = hasInitializer, bit2,3,4 =
1842 // Linkage, bit4+ = slot#
1843 unsigned SlotNo = VarType >> 5;
1844 unsigned LinkageID = (VarType >> 2) & 7;
1845 bool isConstant = VarType & 1;
1846 bool hasInitializer = (VarType & 2) != 0;
1847 unsigned Alignment = 0;
1848 unsigned GlobalSectionID = 0;
1850 // An extension word is present when linkage = 3 (internal) and hasinit = 0.
1851 if (LinkageID == 3 && !hasInitializer) {
1852 unsigned ExtWord = read_vbr_uint();
1853 // The extension word has this format: bit 0 = has initializer, bit 1-3 =
1854 // linkage, bit 4-8 = alignment (log2), bits 10+ = future use.
1855 hasInitializer = ExtWord & 1;
1856 LinkageID = (ExtWord >> 1) & 7;
1857 Alignment = (1 << ((ExtWord >> 4) & 31)) >> 1;
1859 if (ExtWord & (1 << 9)) // Has a section ID.
1860 GlobalSectionID = read_vbr_uint();
1863 GlobalValue::LinkageTypes Linkage;
1864 switch (LinkageID) {
1865 case 0: Linkage = GlobalValue::ExternalLinkage; break;
1866 case 1: Linkage = GlobalValue::WeakLinkage; break;
1867 case 2: Linkage = GlobalValue::AppendingLinkage; break;
1868 case 3: Linkage = GlobalValue::InternalLinkage; break;
1869 case 4: Linkage = GlobalValue::LinkOnceLinkage; break;
1870 case 5: Linkage = GlobalValue::DLLImportLinkage; break;
1871 case 6: Linkage = GlobalValue::DLLExportLinkage; break;
1872 case 7: Linkage = GlobalValue::ExternalWeakLinkage; break;
1874 error("Unknown linkage type: " + utostr(LinkageID));
1875 Linkage = GlobalValue::InternalLinkage;
1879 const Type *Ty = getType(SlotNo);
1881 error("Global has no type! SlotNo=" + utostr(SlotNo));
1883 if (!isa<PointerType>(Ty))
1884 error("Global not a pointer type! Ty= " + Ty->getDescription());
1886 const Type *ElTy = cast<PointerType>(Ty)->getElementType();
1888 // Create the global variable...
1889 GlobalVariable *GV = new GlobalVariable(ElTy, isConstant, Linkage,
1891 GV->setAlignment(Alignment);
1892 insertValue(GV, SlotNo, ModuleValues);
1894 if (GlobalSectionID != 0)
1895 SectionID[GV] = GlobalSectionID;
1897 unsigned initSlot = 0;
1898 if (hasInitializer) {
1899 initSlot = read_vbr_uint();
1900 GlobalInits.push_back(std::make_pair(GV, initSlot));
1903 // Notify handler about the global value.
1905 Handler->handleGlobalVariable(ElTy, isConstant, Linkage, SlotNo,initSlot);
1908 VarType = read_vbr_uint();
1911 // Read the function objects for all of the functions that are coming
1912 unsigned FnSignature = read_vbr_uint();
1914 // List is terminated by VoidTy.
1915 while (((FnSignature & (~0U >> 1)) >> 5) != Type::VoidTyID) {
1916 const Type *Ty = getType((FnSignature & (~0U >> 1)) >> 5);
1917 if (!isa<PointerType>(Ty) ||
1918 !isa<FunctionType>(cast<PointerType>(Ty)->getElementType())) {
1919 error("Function not a pointer to function type! Ty = " +
1920 Ty->getDescription());
1923 // We create functions by passing the underlying FunctionType to create...
1924 const FunctionType* FTy =
1925 cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
1927 // Insert the place holder.
1928 Function *Func = new Function(FTy, GlobalValue::ExternalLinkage,
1931 insertValue(Func, (FnSignature & (~0U >> 1)) >> 5, ModuleValues);
1933 // Flags are not used yet.
1934 unsigned Flags = FnSignature & 31;
1936 // Save this for later so we know type of lazily instantiated functions.
1937 // Note that known-external functions do not have FunctionInfo blocks, so we
1938 // do not add them to the FunctionSignatureList.
1939 if ((Flags & (1 << 4)) == 0)
1940 FunctionSignatureList.push_back(Func);
1942 // Get the calling convention from the low bits.
1943 unsigned CC = Flags & 15;
1944 unsigned Alignment = 0;
1945 if (FnSignature & (1 << 31)) { // Has extension word?
1946 unsigned ExtWord = read_vbr_uint();
1947 Alignment = (1 << (ExtWord & 31)) >> 1;
1948 CC |= ((ExtWord >> 5) & 15) << 4;
1950 if (ExtWord & (1 << 10)) // Has a section ID.
1951 SectionID[Func] = read_vbr_uint();
1953 // Parse external declaration linkage
1954 switch ((ExtWord >> 11) & 3) {
1956 case 1: Func->setLinkage(Function::DLLImportLinkage); break;
1957 case 2: Func->setLinkage(Function::ExternalWeakLinkage); break;
1958 default: assert(0 && "Unsupported external linkage");
1962 Func->setCallingConv(CC-1);
1963 Func->setAlignment(Alignment);
1965 if (Handler) Handler->handleFunctionDeclaration(Func);
1967 // Get the next function signature.
1968 FnSignature = read_vbr_uint();
1971 // Now that the function signature list is set up, reverse it so that we can
1972 // remove elements efficiently from the back of the vector.
1973 std::reverse(FunctionSignatureList.begin(), FunctionSignatureList.end());
1975 /// SectionNames - This contains the list of section names encoded in the
1976 /// moduleinfoblock. Functions and globals with an explicit section index
1977 /// into this to get their section name.
1978 std::vector<std::string> SectionNames;
1980 // Read in the dependent library information.
1981 unsigned num_dep_libs = read_vbr_uint();
1982 std::string dep_lib;
1983 while (num_dep_libs--) {
1984 dep_lib = read_str();
1985 TheModule->addLibrary(dep_lib);
1987 Handler->handleDependentLibrary(dep_lib);
1990 // Read target triple and place into the module.
1991 std::string triple = read_str();
1992 TheModule->setTargetTriple(triple);
1994 Handler->handleTargetTriple(triple);
1996 if (At != BlockEnd) {
1997 // If the file has section info in it, read the section names now.
1998 unsigned NumSections = read_vbr_uint();
1999 while (NumSections--)
2000 SectionNames.push_back(read_str());
2003 // If the file has module-level inline asm, read it now.
2005 TheModule->setModuleInlineAsm(read_str());
2007 // If any globals are in specified sections, assign them now.
2008 for (std::map<GlobalValue*, unsigned>::iterator I = SectionID.begin(), E =
2009 SectionID.end(); I != E; ++I)
2011 if (I->second > SectionID.size())
2012 error("SectionID out of range for global!");
2013 I->first->setSection(SectionNames[I->second-1]);
2016 // This is for future proofing... in the future extra fields may be added that
2017 // we don't understand, so we transparently ignore them.
2021 if (Handler) Handler->handleModuleGlobalsEnd();
2024 /// Parse the version information and decode it by setting flags on the
2025 /// Reader that enable backward compatibility of the reader.
2026 void BytecodeReader::ParseVersionInfo() {
2027 unsigned Version = read_vbr_uint();
2029 // Unpack version number: low four bits are for flags, top bits = version
2030 Module::Endianness Endianness;
2031 Module::PointerSize PointerSize;
2032 Endianness = (Version & 1) ? Module::BigEndian : Module::LittleEndian;
2033 PointerSize = (Version & 2) ? Module::Pointer64 : Module::Pointer32;
2035 bool hasNoEndianness = Version & 4;
2036 bool hasNoPointerSize = Version & 8;
2038 RevisionNum = Version >> 4;
2040 // We don't provide backwards compatibility in the Reader any more. To
2041 // upgrade, the user should use llvm-upgrade.
2042 if (RevisionNum < 7)
2043 error("Bytecode formats < 7 are no longer supported. Use llvm-upgrade.");
2045 if (hasNoEndianness) Endianness = Module::AnyEndianness;
2046 if (hasNoPointerSize) PointerSize = Module::AnyPointerSize;
2048 TheModule->setEndianness(Endianness);
2049 TheModule->setPointerSize(PointerSize);
2051 if (Handler) Handler->handleVersionInfo(RevisionNum, Endianness, PointerSize);
2054 /// Parse a whole module.
2055 void BytecodeReader::ParseModule() {
2056 unsigned Type, Size;
2058 FunctionSignatureList.clear(); // Just in case...
2060 // Read into instance variables...
2063 bool SeenModuleGlobalInfo = false;
2064 bool SeenGlobalTypePlane = false;
2065 BufPtr MyEnd = BlockEnd;
2066 while (At < MyEnd) {
2068 read_block(Type, Size);
2072 case BytecodeFormat::GlobalTypePlaneBlockID:
2073 if (SeenGlobalTypePlane)
2074 error("Two GlobalTypePlane Blocks Encountered!");
2078 SeenGlobalTypePlane = true;
2081 case BytecodeFormat::ModuleGlobalInfoBlockID:
2082 if (SeenModuleGlobalInfo)
2083 error("Two ModuleGlobalInfo Blocks Encountered!");
2084 ParseModuleGlobalInfo();
2085 SeenModuleGlobalInfo = true;
2088 case BytecodeFormat::ConstantPoolBlockID:
2089 ParseConstantPool(ModuleValues, ModuleTypes,false);
2092 case BytecodeFormat::FunctionBlockID:
2093 ParseFunctionLazily();
2096 case BytecodeFormat::ValueSymbolTableBlockID:
2097 ParseValueSymbolTable(0, &TheModule->getValueSymbolTable());
2100 case BytecodeFormat::TypeSymbolTableBlockID:
2101 ParseTypeSymbolTable(&TheModule->getTypeSymbolTable());
2107 error("Unexpected Block of Type #" + utostr(Type) + " encountered!");
2114 // After the module constant pool has been read, we can safely initialize
2115 // global variables...
2116 while (!GlobalInits.empty()) {
2117 GlobalVariable *GV = GlobalInits.back().first;
2118 unsigned Slot = GlobalInits.back().second;
2119 GlobalInits.pop_back();
2121 // Look up the initializer value...
2122 // FIXME: Preserve this type ID!
2124 const llvm::PointerType* GVType = GV->getType();
2125 unsigned TypeSlot = getTypeSlot(GVType->getElementType());
2126 if (Constant *CV = getConstantValue(TypeSlot, Slot)) {
2127 if (GV->hasInitializer())
2128 error("Global *already* has an initializer?!");
2129 if (Handler) Handler->handleGlobalInitializer(GV,CV);
2130 GV->setInitializer(CV);
2132 error("Cannot find initializer value.");
2135 if (!ConstantFwdRefs.empty())
2136 error("Use of undefined constants in a module");
2138 /// Make sure we pulled them all out. If we didn't then there's a declaration
2139 /// but a missing body. That's not allowed.
2140 if (!FunctionSignatureList.empty())
2141 error("Function declared, but bytecode stream ended before definition");
2144 /// This function completely parses a bytecode buffer given by the \p Buf
2145 /// and \p Length parameters.
2146 bool BytecodeReader::ParseBytecode(volatile BufPtr Buf, unsigned Length,
2147 const std::string &ModuleID,
2148 std::string* ErrMsg) {
2150 /// We handle errors by
2151 if (setjmp(context)) {
2152 // Cleanup after error
2153 if (Handler) Handler->handleError(ErrorMsg);
2157 if (decompressedBlock != 0 ) {
2158 ::free(decompressedBlock);
2159 decompressedBlock = 0;
2161 // Set caller's error message, if requested
2164 // Indicate an error occurred
2169 At = MemStart = BlockStart = Buf;
2170 MemEnd = BlockEnd = Buf + Length;
2172 // Create the module
2173 TheModule = new Module(ModuleID);
2175 if (Handler) Handler->handleStart(TheModule, Length);
2177 // Read the four bytes of the signature.
2178 unsigned Sig = read_uint();
2180 // If this is a compressed file
2181 if (Sig == ('l' | ('l' << 8) | ('v' << 16) | ('c' << 24))) {
2183 // Invoke the decompression of the bytecode. Note that we have to skip the
2184 // file's magic number which is not part of the compressed block. Hence,
2185 // the Buf+4 and Length-4. The result goes into decompressedBlock, a data
2186 // member for retention until BytecodeReader is destructed.
2187 unsigned decompressedLength = Compressor::decompressToNewBuffer(
2188 (char*)Buf+4,Length-4,decompressedBlock);
2190 // We must adjust the buffer pointers used by the bytecode reader to point
2191 // into the new decompressed block. After decompression, the
2192 // decompressedBlock will point to a contiguous memory area that has
2193 // the decompressed data.
2194 At = MemStart = BlockStart = Buf = (BufPtr) decompressedBlock;
2195 MemEnd = BlockEnd = Buf + decompressedLength;
2197 // else if this isn't a regular (uncompressed) bytecode file, then its
2198 // and error, generate that now.
2199 } else if (Sig != ('l' | ('l' << 8) | ('v' << 16) | ('m' << 24))) {
2200 error("Invalid bytecode signature: " + utohexstr(Sig));
2203 // Tell the handler we're starting a module
2204 if (Handler) Handler->handleModuleBegin(ModuleID);
2206 // Get the module block and size and verify. This is handled specially
2207 // because the module block/size is always written in long format. Other
2208 // blocks are written in short format so the read_block method is used.
2209 unsigned Type, Size;
2212 if (Type != BytecodeFormat::ModuleBlockID) {
2213 error("Expected Module Block! Type:" + utostr(Type) + ", Size:"
2217 // It looks like the darwin ranlib program is broken, and adds trailing
2218 // garbage to the end of some bytecode files. This hack allows the bc
2219 // reader to ignore trailing garbage on bytecode files.
2220 if (At + Size < MemEnd)
2221 MemEnd = BlockEnd = At+Size;
2223 if (At + Size != MemEnd)
2224 error("Invalid Top Level Block Length! Type:" + utostr(Type)
2225 + ", Size:" + utostr(Size));
2227 // Parse the module contents
2228 this->ParseModule();
2230 // Check for missing functions
2232 error("Function expected, but bytecode stream ended!");
2234 // Tell the handler we're done with the module
2236 Handler->handleModuleEnd(ModuleID);
2238 // Tell the handler we're finished the parse
2239 if (Handler) Handler->handleFinish();
2245 //===----------------------------------------------------------------------===//
2246 //=== Default Implementations of Handler Methods
2247 //===----------------------------------------------------------------------===//
2249 BytecodeHandler::~BytecodeHandler() {}