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/Instructions.h"
25 #include "llvm/SymbolTable.h"
26 #include "llvm/Bytecode/Format.h"
27 #include "llvm/Config/alloca.h"
28 #include "llvm/Support/GetElementPtrTypeIterator.h"
29 #include "llvm/Support/Compressor.h"
30 #include "llvm/Support/MathExtras.h"
31 #include "llvm/ADT/StringExtras.h"
37 /// @brief A class for maintaining the slot number definition
38 /// as a placeholder for the actual definition for forward constants defs.
39 class ConstantPlaceHolder : public ConstantExpr {
40 ConstantPlaceHolder(); // DO NOT IMPLEMENT
41 void operator=(const ConstantPlaceHolder &); // DO NOT IMPLEMENT
44 ConstantPlaceHolder(const Type *Ty)
45 : ConstantExpr(Ty, Instruction::UserOp1, &Op, 1),
46 Op(UndefValue::get(Type::IntTy), this) {
51 // Provide some details on error
52 inline void BytecodeReader::error(std::string err) {
54 err += itostr(RevisionNum) ;
56 err += itostr(At-MemStart);
61 //===----------------------------------------------------------------------===//
62 // Bytecode Reading Methods
63 //===----------------------------------------------------------------------===//
65 /// Determine if the current block being read contains any more data.
66 inline bool BytecodeReader::moreInBlock() {
70 /// Throw an error if we've read past the end of the current block
71 inline void BytecodeReader::checkPastBlockEnd(const char * block_name) {
73 error(std::string("Attempt to read past the end of ") + block_name +
77 /// Align the buffer position to a 32 bit boundary
78 inline void BytecodeReader::align32() {
81 At = (const unsigned char *)((unsigned long)(At+3) & (~3UL));
83 if (Handler) Handler->handleAlignment(At - Save);
85 error("Ran out of data while aligning!");
89 /// Read a whole unsigned integer
90 inline unsigned BytecodeReader::read_uint() {
92 error("Ran out of data reading uint!");
94 return At[-4] | (At[-3] << 8) | (At[-2] << 16) | (At[-1] << 24);
97 /// Read a variable-bit-rate encoded unsigned integer
98 inline unsigned BytecodeReader::read_vbr_uint() {
105 error("Ran out of data reading vbr_uint!");
106 Result |= (unsigned)((*At++) & 0x7F) << Shift;
108 } while (At[-1] & 0x80);
109 if (Handler) Handler->handleVBR32(At-Save);
113 /// Read a variable-bit-rate encoded unsigned 64-bit integer.
114 inline uint64_t BytecodeReader::read_vbr_uint64() {
121 error("Ran out of data reading vbr_uint64!");
122 Result |= (uint64_t)((*At++) & 0x7F) << Shift;
124 } while (At[-1] & 0x80);
125 if (Handler) Handler->handleVBR64(At-Save);
129 /// Read a variable-bit-rate encoded signed 64-bit integer.
130 inline int64_t BytecodeReader::read_vbr_int64() {
131 uint64_t R = read_vbr_uint64();
134 return -(int64_t)(R >> 1);
135 else // There is no such thing as -0 with integers. "-0" really means
136 // 0x8000000000000000.
139 return (int64_t)(R >> 1);
142 /// Read a pascal-style string (length followed by text)
143 inline std::string BytecodeReader::read_str() {
144 unsigned Size = read_vbr_uint();
145 const unsigned char *OldAt = At;
147 if (At > BlockEnd) // Size invalid?
148 error("Ran out of data reading a string!");
149 return std::string((char*)OldAt, Size);
152 /// Read an arbitrary block of data
153 inline void BytecodeReader::read_data(void *Ptr, void *End) {
154 unsigned char *Start = (unsigned char *)Ptr;
155 unsigned Amount = (unsigned char *)End - Start;
156 if (At+Amount > BlockEnd)
157 error("Ran out of data!");
158 std::copy(At, At+Amount, Start);
162 /// Read a float value in little-endian order
163 inline void BytecodeReader::read_float(float& FloatVal) {
164 /// FIXME: This isn't optimal, it has size problems on some platforms
165 /// where FP is not IEEE.
166 FloatVal = BitsToFloat(At[0] | (At[1] << 8) | (At[2] << 16) | (At[3] << 24));
167 At+=sizeof(uint32_t);
170 /// Read a double value in little-endian order
171 inline void BytecodeReader::read_double(double& DoubleVal) {
172 /// FIXME: This isn't optimal, it has size problems on some platforms
173 /// where FP is not IEEE.
174 DoubleVal = BitsToDouble((uint64_t(At[0]) << 0) | (uint64_t(At[1]) << 8) |
175 (uint64_t(At[2]) << 16) | (uint64_t(At[3]) << 24) |
176 (uint64_t(At[4]) << 32) | (uint64_t(At[5]) << 40) |
177 (uint64_t(At[6]) << 48) | (uint64_t(At[7]) << 56));
178 At+=sizeof(uint64_t);
181 /// Read a block header and obtain its type and size
182 inline void BytecodeReader::read_block(unsigned &Type, unsigned &Size) {
183 if ( hasLongBlockHeaders ) {
187 case BytecodeFormat::Reserved_DoNotUse :
188 error("Reserved_DoNotUse used as Module Type?");
189 Type = BytecodeFormat::ModuleBlockID; break;
190 case BytecodeFormat::Module:
191 Type = BytecodeFormat::ModuleBlockID; break;
192 case BytecodeFormat::Function:
193 Type = BytecodeFormat::FunctionBlockID; break;
194 case BytecodeFormat::ConstantPool:
195 Type = BytecodeFormat::ConstantPoolBlockID; break;
196 case BytecodeFormat::SymbolTable:
197 Type = BytecodeFormat::SymbolTableBlockID; break;
198 case BytecodeFormat::ModuleGlobalInfo:
199 Type = BytecodeFormat::ModuleGlobalInfoBlockID; break;
200 case BytecodeFormat::GlobalTypePlane:
201 Type = BytecodeFormat::GlobalTypePlaneBlockID; break;
202 case BytecodeFormat::InstructionList:
203 Type = BytecodeFormat::InstructionListBlockID; break;
204 case BytecodeFormat::CompactionTable:
205 Type = BytecodeFormat::CompactionTableBlockID; break;
206 case BytecodeFormat::BasicBlock:
207 /// This block type isn't used after version 1.1. However, we have to
208 /// still allow the value in case this is an old bc format file.
209 /// We just let its value creep thru.
212 error("Invalid block id found: " + utostr(Type));
217 Type = Size & 0x1F; // mask low order five bits
218 Size >>= 5; // get rid of five low order bits, leaving high 27
221 if (At + Size > BlockEnd)
222 error("Attempt to size a block past end of memory");
223 BlockEnd = At + Size;
224 if (Handler) Handler->handleBlock(Type, BlockStart, Size);
228 /// In LLVM 1.2 and before, Types were derived from Value and so they were
229 /// written as part of the type planes along with any other Value. In LLVM
230 /// 1.3 this changed so that Type does not derive from Value. Consequently,
231 /// the BytecodeReader's containers for Values can't contain Types because
232 /// there's no inheritance relationship. This means that the "Type Type"
233 /// plane is defunct along with the Type::TypeTyID TypeID. In LLVM 1.3
234 /// whenever a bytecode construct must have both types and values together,
235 /// the types are always read/written first and then the Values. Furthermore
236 /// since Type::TypeTyID no longer exists, its value (12) now corresponds to
237 /// Type::LabelTyID. In order to overcome this we must "sanitize" all the
238 /// type TypeIDs we encounter. For LLVM 1.3 bytecode files, there's no change.
239 /// For LLVM 1.2 and before, this function will decrement the type id by
240 /// one to account for the missing Type::TypeTyID enumerator if the value is
241 /// larger than 12 (Type::LabelTyID). If the value is exactly 12, then this
242 /// function returns true, otherwise false. This helps detect situations
243 /// where the pre 1.3 bytecode is indicating that what follows is a type.
244 /// @returns true iff type id corresponds to pre 1.3 "type type"
245 inline bool BytecodeReader::sanitizeTypeId(unsigned &TypeId) {
246 if (hasTypeDerivedFromValue) { /// do nothing if 1.3 or later
247 if (TypeId == Type::LabelTyID) {
248 TypeId = Type::VoidTyID; // sanitize it
249 return true; // indicate we got TypeTyID in pre 1.3 bytecode
250 } else if (TypeId > Type::LabelTyID)
251 --TypeId; // shift all planes down because type type plane is missing
256 /// Reads a vbr uint to read in a type id and does the necessary
257 /// conversion on it by calling sanitizeTypeId.
258 /// @returns true iff \p TypeId read corresponds to a pre 1.3 "type type"
259 /// @see sanitizeTypeId
260 inline bool BytecodeReader::read_typeid(unsigned &TypeId) {
261 TypeId = read_vbr_uint();
262 if ( !has32BitTypes )
263 if ( TypeId == 0x00FFFFFF )
264 TypeId = read_vbr_uint();
265 return sanitizeTypeId(TypeId);
268 //===----------------------------------------------------------------------===//
270 //===----------------------------------------------------------------------===//
272 /// Determine if a type id has an implicit null value
273 inline bool BytecodeReader::hasImplicitNull(unsigned TyID) {
274 if (!hasExplicitPrimitiveZeros)
275 return TyID != Type::LabelTyID && TyID != Type::VoidTyID;
276 return TyID >= Type::FirstDerivedTyID;
279 /// Obtain a type given a typeid and account for things like compaction tables,
280 /// function level vs module level, and the offsetting for the primitive types.
281 const Type *BytecodeReader::getType(unsigned ID) {
282 if (ID < Type::FirstDerivedTyID)
283 if (const Type *T = Type::getPrimitiveType((Type::TypeID)ID))
284 return T; // Asked for a primitive type...
286 // Otherwise, derived types need offset...
287 ID -= Type::FirstDerivedTyID;
289 if (!CompactionTypes.empty()) {
290 if (ID >= CompactionTypes.size())
291 error("Type ID out of range for compaction table!");
292 return CompactionTypes[ID].first;
295 // Is it a module-level type?
296 if (ID < ModuleTypes.size())
297 return ModuleTypes[ID].get();
299 // Nope, is it a function-level type?
300 ID -= ModuleTypes.size();
301 if (ID < FunctionTypes.size())
302 return FunctionTypes[ID].get();
304 error("Illegal type reference!");
308 /// Get a sanitized type id. This just makes sure that the \p ID
309 /// is both sanitized and not the "type type" of pre-1.3 bytecode.
310 /// @see sanitizeTypeId
311 inline const Type* BytecodeReader::getSanitizedType(unsigned& ID) {
312 if (sanitizeTypeId(ID))
313 error("Invalid type id encountered");
317 /// This method just saves some coding. It uses read_typeid to read
318 /// in a sanitized type id, errors that its not the type type, and
319 /// then calls getType to return the type value.
320 inline const Type* BytecodeReader::readSanitizedType() {
323 error("Invalid type id encountered");
327 /// Get the slot number associated with a type accounting for primitive
328 /// types, compaction tables, and function level vs module level.
329 unsigned BytecodeReader::getTypeSlot(const Type *Ty) {
330 if (Ty->isPrimitiveType())
331 return Ty->getTypeID();
333 // Scan the compaction table for the type if needed.
334 if (!CompactionTypes.empty()) {
335 for (unsigned i = 0, e = CompactionTypes.size(); i != e; ++i)
336 if (CompactionTypes[i].first == Ty)
337 return Type::FirstDerivedTyID + i;
339 error("Couldn't find type specified in compaction table!");
342 // Check the function level types first...
343 TypeListTy::iterator I = std::find(FunctionTypes.begin(),
344 FunctionTypes.end(), Ty);
346 if (I != FunctionTypes.end())
347 return Type::FirstDerivedTyID + ModuleTypes.size() +
348 (&*I - &FunctionTypes[0]);
350 // If we don't have our cache yet, build it now.
351 if (ModuleTypeIDCache.empty()) {
353 ModuleTypeIDCache.reserve(ModuleTypes.size());
354 for (TypeListTy::iterator I = ModuleTypes.begin(), E = ModuleTypes.end();
356 ModuleTypeIDCache.push_back(std::make_pair(*I, N));
358 std::sort(ModuleTypeIDCache.begin(), ModuleTypeIDCache.end());
361 // Binary search the cache for the entry.
362 std::vector<std::pair<const Type*, unsigned> >::iterator IT =
363 std::lower_bound(ModuleTypeIDCache.begin(), ModuleTypeIDCache.end(),
364 std::make_pair(Ty, 0U));
365 if (IT == ModuleTypeIDCache.end() || IT->first != Ty)
366 error("Didn't find type in ModuleTypes.");
368 return Type::FirstDerivedTyID + IT->second;
371 /// This is just like getType, but when a compaction table is in use, it is
372 /// ignored. It also ignores function level types.
374 const Type *BytecodeReader::getGlobalTableType(unsigned Slot) {
375 if (Slot < Type::FirstDerivedTyID) {
376 const Type *Ty = Type::getPrimitiveType((Type::TypeID)Slot);
378 error("Not a primitive type ID?");
381 Slot -= Type::FirstDerivedTyID;
382 if (Slot >= ModuleTypes.size())
383 error("Illegal compaction table type reference!");
384 return ModuleTypes[Slot];
387 /// This is just like getTypeSlot, but when a compaction table is in use, it
388 /// is ignored. It also ignores function level types.
389 unsigned BytecodeReader::getGlobalTableTypeSlot(const Type *Ty) {
390 if (Ty->isPrimitiveType())
391 return Ty->getTypeID();
393 // If we don't have our cache yet, build it now.
394 if (ModuleTypeIDCache.empty()) {
396 ModuleTypeIDCache.reserve(ModuleTypes.size());
397 for (TypeListTy::iterator I = ModuleTypes.begin(), E = ModuleTypes.end();
399 ModuleTypeIDCache.push_back(std::make_pair(*I, N));
401 std::sort(ModuleTypeIDCache.begin(), ModuleTypeIDCache.end());
404 // Binary search the cache for the entry.
405 std::vector<std::pair<const Type*, unsigned> >::iterator IT =
406 std::lower_bound(ModuleTypeIDCache.begin(), ModuleTypeIDCache.end(),
407 std::make_pair(Ty, 0U));
408 if (IT == ModuleTypeIDCache.end() || IT->first != Ty)
409 error("Didn't find type in ModuleTypes.");
411 return Type::FirstDerivedTyID + IT->second;
414 /// Retrieve a value of a given type and slot number, possibly creating
415 /// it if it doesn't already exist.
416 Value * BytecodeReader::getValue(unsigned type, unsigned oNum, bool Create) {
417 assert(type != Type::LabelTyID && "getValue() cannot get blocks!");
420 // If there is a compaction table active, it defines the low-level numbers.
421 // If not, the module values define the low-level numbers.
422 if (CompactionValues.size() > type && !CompactionValues[type].empty()) {
423 if (Num < CompactionValues[type].size())
424 return CompactionValues[type][Num];
425 Num -= CompactionValues[type].size();
427 // By default, the global type id is the type id passed in
428 unsigned GlobalTyID = type;
430 // If the type plane was compactified, figure out the global type ID by
431 // adding the derived type ids and the distance.
432 if (!CompactionTypes.empty() && type >= Type::FirstDerivedTyID)
433 GlobalTyID = CompactionTypes[type-Type::FirstDerivedTyID].second;
435 if (hasImplicitNull(GlobalTyID)) {
436 const Type *Ty = getType(type);
437 if (!isa<OpaqueType>(Ty)) {
439 return Constant::getNullValue(Ty);
444 if (GlobalTyID < ModuleValues.size() && ModuleValues[GlobalTyID]) {
445 if (Num < ModuleValues[GlobalTyID]->size())
446 return ModuleValues[GlobalTyID]->getOperand(Num);
447 Num -= ModuleValues[GlobalTyID]->size();
451 if (FunctionValues.size() > type &&
452 FunctionValues[type] &&
453 Num < FunctionValues[type]->size())
454 return FunctionValues[type]->getOperand(Num);
456 if (!Create) return 0; // Do not create a placeholder?
458 // Did we already create a place holder?
459 std::pair<unsigned,unsigned> KeyValue(type, oNum);
460 ForwardReferenceMap::iterator I = ForwardReferences.lower_bound(KeyValue);
461 if (I != ForwardReferences.end() && I->first == KeyValue)
462 return I->second; // We have already created this placeholder
464 // If the type exists (it should)
465 if (const Type* Ty = getType(type)) {
466 // Create the place holder
467 Value *Val = new Argument(Ty);
468 ForwardReferences.insert(I, std::make_pair(KeyValue, Val));
471 throw "Can't create placeholder for value of type slot #" + utostr(type);
474 /// This is just like getValue, but when a compaction table is in use, it
475 /// is ignored. Also, no forward references or other fancy features are
477 Value* BytecodeReader::getGlobalTableValue(unsigned TyID, unsigned SlotNo) {
479 return Constant::getNullValue(getType(TyID));
481 if (!CompactionTypes.empty() && TyID >= Type::FirstDerivedTyID) {
482 TyID -= Type::FirstDerivedTyID;
483 if (TyID >= CompactionTypes.size())
484 error("Type ID out of range for compaction table!");
485 TyID = CompactionTypes[TyID].second;
490 if (TyID >= ModuleValues.size() || ModuleValues[TyID] == 0 ||
491 SlotNo >= ModuleValues[TyID]->size()) {
492 if (TyID >= ModuleValues.size() || ModuleValues[TyID] == 0)
493 error("Corrupt compaction table entry!"
494 + utostr(TyID) + ", " + utostr(SlotNo) + ": "
495 + utostr(ModuleValues.size()));
497 error("Corrupt compaction table entry!"
498 + utostr(TyID) + ", " + utostr(SlotNo) + ": "
499 + utostr(ModuleValues.size()) + ", "
500 + utohexstr(reinterpret_cast<uint64_t>(((void*)ModuleValues[TyID])))
502 + utostr(ModuleValues[TyID]->size()));
504 return ModuleValues[TyID]->getOperand(SlotNo);
507 /// Just like getValue, except that it returns a null pointer
508 /// only on error. It always returns a constant (meaning that if the value is
509 /// defined, but is not a constant, that is an error). If the specified
510 /// constant hasn't been parsed yet, a placeholder is defined and used.
511 /// Later, after the real value is parsed, the placeholder is eliminated.
512 Constant* BytecodeReader::getConstantValue(unsigned TypeSlot, unsigned Slot) {
513 if (Value *V = getValue(TypeSlot, Slot, false))
514 if (Constant *C = dyn_cast<Constant>(V))
515 return C; // If we already have the value parsed, just return it
517 error("Value for slot " + utostr(Slot) +
518 " is expected to be a constant!");
520 std::pair<unsigned, unsigned> Key(TypeSlot, Slot);
521 ConstantRefsType::iterator I = ConstantFwdRefs.lower_bound(Key);
523 if (I != ConstantFwdRefs.end() && I->first == Key) {
526 // Create a placeholder for the constant reference and
527 // keep track of the fact that we have a forward ref to recycle it
528 Constant *C = new ConstantPlaceHolder(getType(TypeSlot));
530 // Keep track of the fact that we have a forward ref to recycle it
531 ConstantFwdRefs.insert(I, std::make_pair(Key, C));
536 //===----------------------------------------------------------------------===//
537 // IR Construction Methods
538 //===----------------------------------------------------------------------===//
540 /// As values are created, they are inserted into the appropriate place
541 /// with this method. The ValueTable argument must be one of ModuleValues
542 /// or FunctionValues data members of this class.
543 unsigned BytecodeReader::insertValue(Value *Val, unsigned type,
544 ValueTable &ValueTab) {
545 assert((!isa<Constant>(Val) || !cast<Constant>(Val)->isNullValue()) ||
546 !hasImplicitNull(type) &&
547 "Cannot read null values from bytecode!");
549 if (ValueTab.size() <= type)
550 ValueTab.resize(type+1);
552 if (!ValueTab[type]) ValueTab[type] = new ValueList();
554 ValueTab[type]->push_back(Val);
556 bool HasOffset = hasImplicitNull(type) && !isa<OpaqueType>(Val->getType());
557 return ValueTab[type]->size()-1 + HasOffset;
560 /// Insert the arguments of a function as new values in the reader.
561 void BytecodeReader::insertArguments(Function* F) {
562 const FunctionType *FT = F->getFunctionType();
563 Function::arg_iterator AI = F->arg_begin();
564 for (FunctionType::param_iterator It = FT->param_begin();
565 It != FT->param_end(); ++It, ++AI)
566 insertValue(AI, getTypeSlot(AI->getType()), FunctionValues);
569 //===----------------------------------------------------------------------===//
570 // Bytecode Parsing Methods
571 //===----------------------------------------------------------------------===//
573 /// This method parses a single instruction. The instruction is
574 /// inserted at the end of the \p BB provided. The arguments of
575 /// the instruction are provided in the \p Oprnds vector.
576 void BytecodeReader::ParseInstruction(std::vector<unsigned> &Oprnds,
580 // Clear instruction data
584 unsigned Op = read_uint();
586 // bits Instruction format: Common to all formats
587 // --------------------------
588 // 01-00: Opcode type, fixed to 1.
590 Opcode = (Op >> 2) & 63;
591 Oprnds.resize((Op >> 0) & 03);
593 // Extract the operands
594 switch (Oprnds.size()) {
596 // bits Instruction format:
597 // --------------------------
598 // 19-08: Resulting type plane
599 // 31-20: Operand #1 (if set to (2^12-1), then zero operands)
601 iType = (Op >> 8) & 4095;
602 Oprnds[0] = (Op >> 20) & 4095;
603 if (Oprnds[0] == 4095) // Handle special encoding for 0 operands...
607 // bits Instruction format:
608 // --------------------------
609 // 15-08: Resulting type plane
613 iType = (Op >> 8) & 255;
614 Oprnds[0] = (Op >> 16) & 255;
615 Oprnds[1] = (Op >> 24) & 255;
618 // bits Instruction format:
619 // --------------------------
620 // 13-08: Resulting type plane
625 iType = (Op >> 8) & 63;
626 Oprnds[0] = (Op >> 14) & 63;
627 Oprnds[1] = (Op >> 20) & 63;
628 Oprnds[2] = (Op >> 26) & 63;
631 At -= 4; // Hrm, try this again...
632 Opcode = read_vbr_uint();
634 iType = read_vbr_uint();
636 unsigned NumOprnds = read_vbr_uint();
637 Oprnds.resize(NumOprnds);
640 error("Zero-argument instruction found; this is invalid.");
642 for (unsigned i = 0; i != NumOprnds; ++i)
643 Oprnds[i] = read_vbr_uint();
648 const Type *InstTy = getSanitizedType(iType);
650 // We have enough info to inform the handler now.
651 if (Handler) Handler->handleInstruction(Opcode, InstTy, Oprnds, At-SaveAt);
653 // Declare the resulting instruction we'll build.
654 Instruction *Result = 0;
656 // If this is a bytecode format that did not include the unreachable
657 // instruction, bump up all opcodes numbers to make space.
658 if (hasNoUnreachableInst) {
659 if (Opcode >= Instruction::Unreachable &&
665 // Handle binary operators
666 if (Opcode >= Instruction::BinaryOpsBegin &&
667 Opcode < Instruction::BinaryOpsEnd && Oprnds.size() == 2)
668 Result = BinaryOperator::create((Instruction::BinaryOps)Opcode,
669 getValue(iType, Oprnds[0]),
670 getValue(iType, Oprnds[1]));
675 error("Illegal instruction read!");
677 case Instruction::VAArg:
678 Result = new VAArgInst(getValue(iType, Oprnds[0]),
679 getSanitizedType(Oprnds[1]));
681 case 32: { //VANext_old
682 const Type* ArgTy = getValue(iType, Oprnds[0])->getType();
683 Function* NF = TheModule->getOrInsertFunction("llvm.va_copy", ArgTy, ArgTy,
687 //foo = alloca 1 of t
692 AllocaInst* foo = new AllocaInst(ArgTy, 0, "vanext.fix");
693 BB->getInstList().push_back(foo);
694 CallInst* bar = new CallInst(NF, getValue(iType, Oprnds[0]));
695 BB->getInstList().push_back(bar);
696 BB->getInstList().push_back(new StoreInst(bar, foo));
697 Instruction* tmp = new VAArgInst(foo, getSanitizedType(Oprnds[1]));
698 BB->getInstList().push_back(tmp);
699 Result = new LoadInst(foo);
702 case 33: { //VAArg_old
703 const Type* ArgTy = getValue(iType, Oprnds[0])->getType();
704 Function* NF = TheModule->getOrInsertFunction("llvm.va_copy", ArgTy, ArgTy,
708 //foo = alloca 1 of t
712 AllocaInst* foo = new AllocaInst(ArgTy, 0, "vaarg.fix");
713 BB->getInstList().push_back(foo);
714 CallInst* bar = new CallInst(NF, getValue(iType, Oprnds[0]));
715 BB->getInstList().push_back(bar);
716 BB->getInstList().push_back(new StoreInst(bar, foo));
717 Result = new VAArgInst(foo, getSanitizedType(Oprnds[1]));
720 case Instruction::Cast:
721 Result = new CastInst(getValue(iType, Oprnds[0]),
722 getSanitizedType(Oprnds[1]));
724 case Instruction::Select:
725 Result = new SelectInst(getValue(Type::BoolTyID, Oprnds[0]),
726 getValue(iType, Oprnds[1]),
727 getValue(iType, Oprnds[2]));
729 case Instruction::PHI: {
730 if (Oprnds.size() == 0 || (Oprnds.size() & 1))
731 error("Invalid phi node encountered!");
733 PHINode *PN = new PHINode(InstTy);
734 PN->reserveOperandSpace(Oprnds.size());
735 for (unsigned i = 0, e = Oprnds.size(); i != e; i += 2)
736 PN->addIncoming(getValue(iType, Oprnds[i]), getBasicBlock(Oprnds[i+1]));
741 case Instruction::Shl:
742 case Instruction::Shr:
743 Result = new ShiftInst((Instruction::OtherOps)Opcode,
744 getValue(iType, Oprnds[0]),
745 getValue(Type::UByteTyID, Oprnds[1]));
747 case Instruction::Ret:
748 if (Oprnds.size() == 0)
749 Result = new ReturnInst();
750 else if (Oprnds.size() == 1)
751 Result = new ReturnInst(getValue(iType, Oprnds[0]));
753 error("Unrecognized instruction!");
756 case Instruction::Br:
757 if (Oprnds.size() == 1)
758 Result = new BranchInst(getBasicBlock(Oprnds[0]));
759 else if (Oprnds.size() == 3)
760 Result = new BranchInst(getBasicBlock(Oprnds[0]),
761 getBasicBlock(Oprnds[1]), getValue(Type::BoolTyID , Oprnds[2]));
763 error("Invalid number of operands for a 'br' instruction!");
765 case Instruction::Switch: {
766 if (Oprnds.size() & 1)
767 error("Switch statement with odd number of arguments!");
769 SwitchInst *I = new SwitchInst(getValue(iType, Oprnds[0]),
770 getBasicBlock(Oprnds[1]),
772 for (unsigned i = 2, e = Oprnds.size(); i != e; i += 2)
773 I->addCase(cast<ConstantInt>(getValue(iType, Oprnds[i])),
774 getBasicBlock(Oprnds[i+1]));
779 case 58: // Call with extra operand for calling conv
780 case 59: // tail call, Fast CC
781 case 60: // normal call, Fast CC
782 case 61: // tail call, C Calling Conv
783 case Instruction::Call: { // Normal Call, C Calling Convention
784 if (Oprnds.size() == 0)
785 error("Invalid call instruction encountered!");
787 Value *F = getValue(iType, Oprnds[0]);
789 unsigned CallingConv = CallingConv::C;
790 bool isTailCall = false;
792 if (Opcode == 61 || Opcode == 59)
795 // Check to make sure we have a pointer to function type
796 const PointerType *PTy = dyn_cast<PointerType>(F->getType());
797 if (PTy == 0) error("Call to non function pointer value!");
798 const FunctionType *FTy = dyn_cast<FunctionType>(PTy->getElementType());
799 if (FTy == 0) error("Call to non function pointer value!");
801 std::vector<Value *> Params;
802 if (!FTy->isVarArg()) {
803 FunctionType::param_iterator It = FTy->param_begin();
806 isTailCall = Oprnds.back() & 1;
807 CallingConv = Oprnds.back() >> 1;
809 } else if (Opcode == 59 || Opcode == 60)
810 CallingConv = CallingConv::Fast;
812 for (unsigned i = 1, e = Oprnds.size(); i != e; ++i) {
813 if (It == FTy->param_end())
814 error("Invalid call instruction!");
815 Params.push_back(getValue(getTypeSlot(*It++), Oprnds[i]));
817 if (It != FTy->param_end())
818 error("Invalid call instruction!");
820 Oprnds.erase(Oprnds.begin(), Oprnds.begin()+1);
822 unsigned FirstVariableOperand;
823 if (Oprnds.size() < FTy->getNumParams())
824 error("Call instruction missing operands!");
826 // Read all of the fixed arguments
827 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
828 Params.push_back(getValue(getTypeSlot(FTy->getParamType(i)),Oprnds[i]));
830 FirstVariableOperand = FTy->getNumParams();
832 if ((Oprnds.size()-FirstVariableOperand) & 1)
833 error("Invalid call instruction!"); // Must be pairs of type/value
835 for (unsigned i = FirstVariableOperand, e = Oprnds.size();
837 Params.push_back(getValue(Oprnds[i], Oprnds[i+1]));
840 Result = new CallInst(F, Params);
841 if (isTailCall) cast<CallInst>(Result)->setTailCall();
842 if (CallingConv) cast<CallInst>(Result)->setCallingConv(CallingConv);
845 case 56: // Invoke with encoded CC
846 case 57: // Invoke Fast CC
847 case Instruction::Invoke: { // Invoke C CC
848 if (Oprnds.size() < 3)
849 error("Invalid invoke instruction!");
850 Value *F = getValue(iType, Oprnds[0]);
852 // Check to make sure we have a pointer to function type
853 const PointerType *PTy = dyn_cast<PointerType>(F->getType());
855 error("Invoke to non function pointer value!");
856 const FunctionType *FTy = dyn_cast<FunctionType>(PTy->getElementType());
858 error("Invoke to non function pointer value!");
860 std::vector<Value *> Params;
861 BasicBlock *Normal, *Except;
862 unsigned CallingConv = CallingConv::C;
865 CallingConv = CallingConv::Fast;
866 else if (Opcode == 56) {
867 CallingConv = Oprnds.back();
871 if (!FTy->isVarArg()) {
872 Normal = getBasicBlock(Oprnds[1]);
873 Except = getBasicBlock(Oprnds[2]);
875 FunctionType::param_iterator It = FTy->param_begin();
876 for (unsigned i = 3, e = Oprnds.size(); i != e; ++i) {
877 if (It == FTy->param_end())
878 error("Invalid invoke instruction!");
879 Params.push_back(getValue(getTypeSlot(*It++), Oprnds[i]));
881 if (It != FTy->param_end())
882 error("Invalid invoke instruction!");
884 Oprnds.erase(Oprnds.begin(), Oprnds.begin()+1);
886 Normal = getBasicBlock(Oprnds[0]);
887 Except = getBasicBlock(Oprnds[1]);
889 unsigned FirstVariableArgument = FTy->getNumParams()+2;
890 for (unsigned i = 2; i != FirstVariableArgument; ++i)
891 Params.push_back(getValue(getTypeSlot(FTy->getParamType(i-2)),
894 if (Oprnds.size()-FirstVariableArgument & 1) // Must be type/value pairs
895 error("Invalid invoke instruction!");
897 for (unsigned i = FirstVariableArgument; i < Oprnds.size(); i += 2)
898 Params.push_back(getValue(Oprnds[i], Oprnds[i+1]));
901 Result = new InvokeInst(F, Normal, Except, Params);
902 if (CallingConv) cast<InvokeInst>(Result)->setCallingConv(CallingConv);
905 case Instruction::Malloc: {
907 if (Oprnds.size() == 2)
908 Align = (1 << Oprnds[1]) >> 1;
909 else if (Oprnds.size() > 2)
910 error("Invalid malloc instruction!");
911 if (!isa<PointerType>(InstTy))
912 error("Invalid malloc instruction!");
914 Result = new MallocInst(cast<PointerType>(InstTy)->getElementType(),
915 getValue(Type::UIntTyID, Oprnds[0]), Align);
919 case Instruction::Alloca: {
921 if (Oprnds.size() == 2)
922 Align = (1 << Oprnds[1]) >> 1;
923 else if (Oprnds.size() > 2)
924 error("Invalid alloca instruction!");
925 if (!isa<PointerType>(InstTy))
926 error("Invalid alloca instruction!");
928 Result = new AllocaInst(cast<PointerType>(InstTy)->getElementType(),
929 getValue(Type::UIntTyID, Oprnds[0]), Align);
932 case Instruction::Free:
933 if (!isa<PointerType>(InstTy))
934 error("Invalid free instruction!");
935 Result = new FreeInst(getValue(iType, Oprnds[0]));
937 case Instruction::GetElementPtr: {
938 if (Oprnds.size() == 0 || !isa<PointerType>(InstTy))
939 error("Invalid getelementptr instruction!");
941 std::vector<Value*> Idx;
943 const Type *NextTy = InstTy;
944 for (unsigned i = 1, e = Oprnds.size(); i != e; ++i) {
945 const CompositeType *TopTy = dyn_cast_or_null<CompositeType>(NextTy);
947 error("Invalid getelementptr instruction!");
949 unsigned ValIdx = Oprnds[i];
951 if (!hasRestrictedGEPTypes) {
952 // Struct indices are always uints, sequential type indices can be any
953 // of the 32 or 64-bit integer types. The actual choice of type is
954 // encoded in the low two bits of the slot number.
955 if (isa<StructType>(TopTy))
956 IdxTy = Type::UIntTyID;
958 switch (ValIdx & 3) {
960 case 0: IdxTy = Type::UIntTyID; break;
961 case 1: IdxTy = Type::IntTyID; break;
962 case 2: IdxTy = Type::ULongTyID; break;
963 case 3: IdxTy = Type::LongTyID; break;
968 IdxTy = isa<StructType>(TopTy) ? Type::UByteTyID : Type::LongTyID;
971 Idx.push_back(getValue(IdxTy, ValIdx));
973 // Convert ubyte struct indices into uint struct indices.
974 if (isa<StructType>(TopTy) && hasRestrictedGEPTypes)
975 if (ConstantUInt *C = dyn_cast<ConstantUInt>(Idx.back()))
976 Idx[Idx.size()-1] = ConstantExpr::getCast(C, Type::UIntTy);
978 NextTy = GetElementPtrInst::getIndexedType(InstTy, Idx, true);
981 Result = new GetElementPtrInst(getValue(iType, Oprnds[0]), Idx);
985 case 62: // volatile load
986 case Instruction::Load:
987 if (Oprnds.size() != 1 || !isa<PointerType>(InstTy))
988 error("Invalid load instruction!");
989 Result = new LoadInst(getValue(iType, Oprnds[0]), "", Opcode == 62);
992 case 63: // volatile store
993 case Instruction::Store: {
994 if (!isa<PointerType>(InstTy) || Oprnds.size() != 2)
995 error("Invalid store instruction!");
997 Value *Ptr = getValue(iType, Oprnds[1]);
998 const Type *ValTy = cast<PointerType>(Ptr->getType())->getElementType();
999 Result = new StoreInst(getValue(getTypeSlot(ValTy), Oprnds[0]), Ptr,
1003 case Instruction::Unwind:
1004 if (Oprnds.size() != 0) error("Invalid unwind instruction!");
1005 Result = new UnwindInst();
1007 case Instruction::Unreachable:
1008 if (Oprnds.size() != 0) error("Invalid unreachable instruction!");
1009 Result = new UnreachableInst();
1011 } // end switch(Opcode)
1014 if (Result->getType() == InstTy)
1017 TypeSlot = getTypeSlot(Result->getType());
1019 insertValue(Result, TypeSlot, FunctionValues);
1020 BB->getInstList().push_back(Result);
1023 /// Get a particular numbered basic block, which might be a forward reference.
1024 /// This works together with ParseBasicBlock to handle these forward references
1025 /// in a clean manner. This function is used when constructing phi, br, switch,
1026 /// and other instructions that reference basic blocks. Blocks are numbered
1027 /// sequentially as they appear in the function.
1028 BasicBlock *BytecodeReader::getBasicBlock(unsigned ID) {
1029 // Make sure there is room in the table...
1030 if (ParsedBasicBlocks.size() <= ID) ParsedBasicBlocks.resize(ID+1);
1032 // First check to see if this is a backwards reference, i.e., ParseBasicBlock
1033 // has already created this block, or if the forward reference has already
1035 if (ParsedBasicBlocks[ID])
1036 return ParsedBasicBlocks[ID];
1038 // Otherwise, the basic block has not yet been created. Do so and add it to
1039 // the ParsedBasicBlocks list.
1040 return ParsedBasicBlocks[ID] = new BasicBlock();
1043 /// In LLVM 1.0 bytecode files, we used to output one basicblock at a time.
1044 /// This method reads in one of the basicblock packets. This method is not used
1045 /// for bytecode files after LLVM 1.0
1046 /// @returns The basic block constructed.
1047 BasicBlock *BytecodeReader::ParseBasicBlock(unsigned BlockNo) {
1048 if (Handler) Handler->handleBasicBlockBegin(BlockNo);
1052 if (ParsedBasicBlocks.size() == BlockNo)
1053 ParsedBasicBlocks.push_back(BB = new BasicBlock());
1054 else if (ParsedBasicBlocks[BlockNo] == 0)
1055 BB = ParsedBasicBlocks[BlockNo] = new BasicBlock();
1057 BB = ParsedBasicBlocks[BlockNo];
1059 std::vector<unsigned> Operands;
1060 while (moreInBlock())
1061 ParseInstruction(Operands, BB);
1063 if (Handler) Handler->handleBasicBlockEnd(BlockNo);
1067 /// Parse all of the BasicBlock's & Instruction's in the body of a function.
1068 /// In post 1.0 bytecode files, we no longer emit basic block individually,
1069 /// in order to avoid per-basic-block overhead.
1070 /// @returns Rhe number of basic blocks encountered.
1071 unsigned BytecodeReader::ParseInstructionList(Function* F) {
1072 unsigned BlockNo = 0;
1073 std::vector<unsigned> Args;
1075 while (moreInBlock()) {
1076 if (Handler) Handler->handleBasicBlockBegin(BlockNo);
1078 if (ParsedBasicBlocks.size() == BlockNo)
1079 ParsedBasicBlocks.push_back(BB = new BasicBlock());
1080 else if (ParsedBasicBlocks[BlockNo] == 0)
1081 BB = ParsedBasicBlocks[BlockNo] = new BasicBlock();
1083 BB = ParsedBasicBlocks[BlockNo];
1085 F->getBasicBlockList().push_back(BB);
1087 // Read instructions into this basic block until we get to a terminator
1088 while (moreInBlock() && !BB->getTerminator())
1089 ParseInstruction(Args, BB);
1091 if (!BB->getTerminator())
1092 error("Non-terminated basic block found!");
1094 if (Handler) Handler->handleBasicBlockEnd(BlockNo-1);
1100 /// Parse a symbol table. This works for both module level and function
1101 /// level symbol tables. For function level symbol tables, the CurrentFunction
1102 /// parameter must be non-zero and the ST parameter must correspond to
1103 /// CurrentFunction's symbol table. For Module level symbol tables, the
1104 /// CurrentFunction argument must be zero.
1105 void BytecodeReader::ParseSymbolTable(Function *CurrentFunction,
1107 if (Handler) Handler->handleSymbolTableBegin(CurrentFunction,ST);
1109 // Allow efficient basic block lookup by number.
1110 std::vector<BasicBlock*> BBMap;
1111 if (CurrentFunction)
1112 for (Function::iterator I = CurrentFunction->begin(),
1113 E = CurrentFunction->end(); I != E; ++I)
1116 /// In LLVM 1.3 we write types separately from values so
1117 /// The types are always first in the symbol table. This is
1118 /// because Type no longer derives from Value.
1119 if (!hasTypeDerivedFromValue) {
1120 // Symtab block header: [num entries]
1121 unsigned NumEntries = read_vbr_uint();
1122 for (unsigned i = 0; i < NumEntries; ++i) {
1123 // Symtab entry: [def slot #][name]
1124 unsigned slot = read_vbr_uint();
1125 std::string Name = read_str();
1126 const Type* T = getType(slot);
1127 ST->insert(Name, T);
1131 while (moreInBlock()) {
1132 // Symtab block header: [num entries][type id number]
1133 unsigned NumEntries = read_vbr_uint();
1135 bool isTypeType = read_typeid(Typ);
1136 const Type *Ty = getType(Typ);
1138 for (unsigned i = 0; i != NumEntries; ++i) {
1139 // Symtab entry: [def slot #][name]
1140 unsigned slot = read_vbr_uint();
1141 std::string Name = read_str();
1143 // if we're reading a pre 1.3 bytecode file and the type plane
1144 // is the "type type", handle it here
1146 const Type* T = getType(slot);
1148 error("Failed type look-up for name '" + Name + "'");
1149 ST->insert(Name, T);
1150 continue; // code below must be short circuited
1153 if (Typ == Type::LabelTyID) {
1154 if (slot < BBMap.size())
1157 V = getValue(Typ, slot, false); // Find mapping...
1160 error("Failed value look-up for name '" + Name + "'");
1165 checkPastBlockEnd("Symbol Table");
1166 if (Handler) Handler->handleSymbolTableEnd();
1169 /// Read in the types portion of a compaction table.
1170 void BytecodeReader::ParseCompactionTypes(unsigned NumEntries) {
1171 for (unsigned i = 0; i != NumEntries; ++i) {
1172 unsigned TypeSlot = 0;
1173 if (read_typeid(TypeSlot))
1174 error("Invalid type in compaction table: type type");
1175 const Type *Typ = getGlobalTableType(TypeSlot);
1176 CompactionTypes.push_back(std::make_pair(Typ, TypeSlot));
1177 if (Handler) Handler->handleCompactionTableType(i, TypeSlot, Typ);
1181 /// Parse a compaction table.
1182 void BytecodeReader::ParseCompactionTable() {
1184 // Notify handler that we're beginning a compaction table.
1185 if (Handler) Handler->handleCompactionTableBegin();
1187 // In LLVM 1.3 Type no longer derives from Value. So,
1188 // we always write them first in the compaction table
1189 // because they can't occupy a "type plane" where the
1191 if (! hasTypeDerivedFromValue) {
1192 unsigned NumEntries = read_vbr_uint();
1193 ParseCompactionTypes(NumEntries);
1196 // Compaction tables live in separate blocks so we have to loop
1197 // until we've read the whole thing.
1198 while (moreInBlock()) {
1199 // Read the number of Value* entries in the compaction table
1200 unsigned NumEntries = read_vbr_uint();
1202 unsigned isTypeType = false;
1204 // Decode the type from value read in. Most compaction table
1205 // planes will have one or two entries in them. If that's the
1206 // case then the length is encoded in the bottom two bits and
1207 // the higher bits encode the type. This saves another VBR value.
1208 if ((NumEntries & 3) == 3) {
1209 // In this case, both low-order bits are set (value 3). This
1210 // is a signal that the typeid follows.
1212 isTypeType = read_typeid(Ty);
1214 // In this case, the low-order bits specify the number of entries
1215 // and the high order bits specify the type.
1216 Ty = NumEntries >> 2;
1217 isTypeType = sanitizeTypeId(Ty);
1221 // if we're reading a pre 1.3 bytecode file and the type plane
1222 // is the "type type", handle it here
1224 ParseCompactionTypes(NumEntries);
1226 // Make sure we have enough room for the plane.
1227 if (Ty >= CompactionValues.size())
1228 CompactionValues.resize(Ty+1);
1230 // Make sure the plane is empty or we have some kind of error.
1231 if (!CompactionValues[Ty].empty())
1232 error("Compaction table plane contains multiple entries!");
1234 // Notify handler about the plane.
1235 if (Handler) Handler->handleCompactionTablePlane(Ty, NumEntries);
1237 // Push the implicit zero.
1238 CompactionValues[Ty].push_back(Constant::getNullValue(getType(Ty)));
1240 // Read in each of the entries, put them in the compaction table
1241 // and notify the handler that we have a new compaction table value.
1242 for (unsigned i = 0; i != NumEntries; ++i) {
1243 unsigned ValSlot = read_vbr_uint();
1244 Value *V = getGlobalTableValue(Ty, ValSlot);
1245 CompactionValues[Ty].push_back(V);
1246 if (Handler) Handler->handleCompactionTableValue(i, Ty, ValSlot);
1250 // Notify handler that the compaction table is done.
1251 if (Handler) Handler->handleCompactionTableEnd();
1254 // Parse a single type. The typeid is read in first. If its a primitive type
1255 // then nothing else needs to be read, we know how to instantiate it. If its
1256 // a derived type, then additional data is read to fill out the type
1258 const Type *BytecodeReader::ParseType() {
1259 unsigned PrimType = 0;
1260 if (read_typeid(PrimType))
1261 error("Invalid type (type type) in type constants!");
1263 const Type *Result = 0;
1264 if ((Result = Type::getPrimitiveType((Type::TypeID)PrimType)))
1268 case Type::FunctionTyID: {
1269 const Type *RetType = readSanitizedType();
1271 unsigned NumParams = read_vbr_uint();
1273 std::vector<const Type*> Params;
1275 Params.push_back(readSanitizedType());
1277 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1278 if (isVarArg) Params.pop_back();
1280 Result = FunctionType::get(RetType, Params, isVarArg);
1283 case Type::ArrayTyID: {
1284 const Type *ElementType = readSanitizedType();
1285 unsigned NumElements = read_vbr_uint();
1286 Result = ArrayType::get(ElementType, NumElements);
1289 case Type::PackedTyID: {
1290 const Type *ElementType = readSanitizedType();
1291 unsigned NumElements = read_vbr_uint();
1292 Result = PackedType::get(ElementType, NumElements);
1295 case Type::StructTyID: {
1296 std::vector<const Type*> Elements;
1298 if (read_typeid(Typ))
1299 error("Invalid element type (type type) for structure!");
1301 while (Typ) { // List is terminated by void/0 typeid
1302 Elements.push_back(getType(Typ));
1303 if (read_typeid(Typ))
1304 error("Invalid element type (type type) for structure!");
1307 Result = StructType::get(Elements);
1310 case Type::PointerTyID: {
1311 Result = PointerType::get(readSanitizedType());
1315 case Type::OpaqueTyID: {
1316 Result = OpaqueType::get();
1321 error("Don't know how to deserialize primitive type " + utostr(PrimType));
1324 if (Handler) Handler->handleType(Result);
1328 // ParseTypes - We have to use this weird code to handle recursive
1329 // types. We know that recursive types will only reference the current slab of
1330 // values in the type plane, but they can forward reference types before they
1331 // have been read. For example, Type #0 might be '{ Ty#1 }' and Type #1 might
1332 // be 'Ty#0*'. When reading Type #0, type number one doesn't exist. To fix
1333 // this ugly problem, we pessimistically insert an opaque type for each type we
1334 // are about to read. This means that forward references will resolve to
1335 // something and when we reread the type later, we can replace the opaque type
1336 // with a new resolved concrete type.
1338 void BytecodeReader::ParseTypes(TypeListTy &Tab, unsigned NumEntries){
1339 assert(Tab.size() == 0 && "should not have read type constants in before!");
1341 // Insert a bunch of opaque types to be resolved later...
1342 Tab.reserve(NumEntries);
1343 for (unsigned i = 0; i != NumEntries; ++i)
1344 Tab.push_back(OpaqueType::get());
1347 Handler->handleTypeList(NumEntries);
1349 // If we are about to resolve types, make sure the type cache is clear.
1351 ModuleTypeIDCache.clear();
1353 // Loop through reading all of the types. Forward types will make use of the
1354 // opaque types just inserted.
1356 for (unsigned i = 0; i != NumEntries; ++i) {
1357 const Type* NewTy = ParseType();
1358 const Type* OldTy = Tab[i].get();
1360 error("Couldn't parse type!");
1362 // Don't directly push the new type on the Tab. Instead we want to replace
1363 // the opaque type we previously inserted with the new concrete value. This
1364 // approach helps with forward references to types. The refinement from the
1365 // abstract (opaque) type to the new type causes all uses of the abstract
1366 // type to use the concrete type (NewTy). This will also cause the opaque
1367 // type to be deleted.
1368 cast<DerivedType>(const_cast<Type*>(OldTy))->refineAbstractTypeTo(NewTy);
1370 // This should have replaced the old opaque type with the new type in the
1371 // value table... or with a preexisting type that was already in the system.
1372 // Let's just make sure it did.
1373 assert(Tab[i] != OldTy && "refineAbstractType didn't work!");
1377 /// Parse a single constant value
1378 Constant *BytecodeReader::ParseConstantValue(unsigned TypeID) {
1379 // We must check for a ConstantExpr before switching by type because
1380 // a ConstantExpr can be of any type, and has no explicit value.
1382 // 0 if not expr; numArgs if is expr
1383 unsigned isExprNumArgs = read_vbr_uint();
1385 if (isExprNumArgs) {
1386 // 'undef' is encoded with 'exprnumargs' == 1.
1387 if (!hasNoUndefValue)
1388 if (--isExprNumArgs == 0)
1389 return UndefValue::get(getType(TypeID));
1391 // FIXME: Encoding of constant exprs could be much more compact!
1392 std::vector<Constant*> ArgVec;
1393 ArgVec.reserve(isExprNumArgs);
1394 unsigned Opcode = read_vbr_uint();
1396 // Bytecode files before LLVM 1.4 need have a missing terminator inst.
1397 if (hasNoUnreachableInst) Opcode++;
1399 // Read the slot number and types of each of the arguments
1400 for (unsigned i = 0; i != isExprNumArgs; ++i) {
1401 unsigned ArgValSlot = read_vbr_uint();
1402 unsigned ArgTypeSlot = 0;
1403 if (read_typeid(ArgTypeSlot))
1404 error("Invalid argument type (type type) for constant value");
1406 // Get the arg value from its slot if it exists, otherwise a placeholder
1407 ArgVec.push_back(getConstantValue(ArgTypeSlot, ArgValSlot));
1410 // Construct a ConstantExpr of the appropriate kind
1411 if (isExprNumArgs == 1) { // All one-operand expressions
1412 if (Opcode != Instruction::Cast)
1413 error("Only cast instruction has one argument for ConstantExpr");
1415 Constant* Result = ConstantExpr::getCast(ArgVec[0], getType(TypeID));
1416 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
1418 } else if (Opcode == Instruction::GetElementPtr) { // GetElementPtr
1419 std::vector<Constant*> IdxList(ArgVec.begin()+1, ArgVec.end());
1421 if (hasRestrictedGEPTypes) {
1422 const Type *BaseTy = ArgVec[0]->getType();
1423 generic_gep_type_iterator<std::vector<Constant*>::iterator>
1424 GTI = gep_type_begin(BaseTy, IdxList.begin(), IdxList.end()),
1425 E = gep_type_end(BaseTy, IdxList.begin(), IdxList.end());
1426 for (unsigned i = 0; GTI != E; ++GTI, ++i)
1427 if (isa<StructType>(*GTI)) {
1428 if (IdxList[i]->getType() != Type::UByteTy)
1429 error("Invalid index for getelementptr!");
1430 IdxList[i] = ConstantExpr::getCast(IdxList[i], Type::UIntTy);
1434 Constant* Result = ConstantExpr::getGetElementPtr(ArgVec[0], IdxList);
1435 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
1437 } else if (Opcode == Instruction::Select) {
1438 if (ArgVec.size() != 3)
1439 error("Select instruction must have three arguments.");
1440 Constant* Result = ConstantExpr::getSelect(ArgVec[0], ArgVec[1],
1442 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
1444 } else { // All other 2-operand expressions
1445 Constant* Result = ConstantExpr::get(Opcode, ArgVec[0], ArgVec[1]);
1446 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
1451 // Ok, not an ConstantExpr. We now know how to read the given type...
1452 const Type *Ty = getType(TypeID);
1453 switch (Ty->getTypeID()) {
1454 case Type::BoolTyID: {
1455 unsigned Val = read_vbr_uint();
1456 if (Val != 0 && Val != 1)
1457 error("Invalid boolean value read.");
1458 Constant* Result = ConstantBool::get(Val == 1);
1459 if (Handler) Handler->handleConstantValue(Result);
1463 case Type::UByteTyID: // Unsigned integer types...
1464 case Type::UShortTyID:
1465 case Type::UIntTyID: {
1466 unsigned Val = read_vbr_uint();
1467 if (!ConstantUInt::isValueValidForType(Ty, Val))
1468 error("Invalid unsigned byte/short/int read.");
1469 Constant* Result = ConstantUInt::get(Ty, Val);
1470 if (Handler) Handler->handleConstantValue(Result);
1474 case Type::ULongTyID: {
1475 Constant* Result = ConstantUInt::get(Ty, read_vbr_uint64());
1476 if (Handler) Handler->handleConstantValue(Result);
1480 case Type::SByteTyID: // Signed integer types...
1481 case Type::ShortTyID:
1482 case Type::IntTyID: {
1483 case Type::LongTyID:
1484 int64_t Val = read_vbr_int64();
1485 if (!ConstantSInt::isValueValidForType(Ty, Val))
1486 error("Invalid signed byte/short/int/long read.");
1487 Constant* Result = ConstantSInt::get(Ty, Val);
1488 if (Handler) Handler->handleConstantValue(Result);
1492 case Type::FloatTyID: {
1495 Constant* Result = ConstantFP::get(Ty, Val);
1496 if (Handler) Handler->handleConstantValue(Result);
1500 case Type::DoubleTyID: {
1503 Constant* Result = ConstantFP::get(Ty, Val);
1504 if (Handler) Handler->handleConstantValue(Result);
1508 case Type::ArrayTyID: {
1509 const ArrayType *AT = cast<ArrayType>(Ty);
1510 unsigned NumElements = AT->getNumElements();
1511 unsigned TypeSlot = getTypeSlot(AT->getElementType());
1512 std::vector<Constant*> Elements;
1513 Elements.reserve(NumElements);
1514 while (NumElements--) // Read all of the elements of the constant.
1515 Elements.push_back(getConstantValue(TypeSlot,
1517 Constant* Result = ConstantArray::get(AT, Elements);
1518 if (Handler) Handler->handleConstantArray(AT, Elements, TypeSlot, Result);
1522 case Type::StructTyID: {
1523 const StructType *ST = cast<StructType>(Ty);
1525 std::vector<Constant *> Elements;
1526 Elements.reserve(ST->getNumElements());
1527 for (unsigned i = 0; i != ST->getNumElements(); ++i)
1528 Elements.push_back(getConstantValue(ST->getElementType(i),
1531 Constant* Result = ConstantStruct::get(ST, Elements);
1532 if (Handler) Handler->handleConstantStruct(ST, Elements, Result);
1536 case Type::PackedTyID: {
1537 const PackedType *PT = cast<PackedType>(Ty);
1538 unsigned NumElements = PT->getNumElements();
1539 unsigned TypeSlot = getTypeSlot(PT->getElementType());
1540 std::vector<Constant*> Elements;
1541 Elements.reserve(NumElements);
1542 while (NumElements--) // Read all of the elements of the constant.
1543 Elements.push_back(getConstantValue(TypeSlot,
1545 Constant* Result = ConstantPacked::get(PT, Elements);
1546 if (Handler) Handler->handleConstantPacked(PT, Elements, TypeSlot, Result);
1550 case Type::PointerTyID: { // ConstantPointerRef value (backwards compat).
1551 const PointerType *PT = cast<PointerType>(Ty);
1552 unsigned Slot = read_vbr_uint();
1554 // Check to see if we have already read this global variable...
1555 Value *Val = getValue(TypeID, Slot, false);
1557 GlobalValue *GV = dyn_cast<GlobalValue>(Val);
1558 if (!GV) error("GlobalValue not in ValueTable!");
1559 if (Handler) Handler->handleConstantPointer(PT, Slot, GV);
1562 error("Forward references are not allowed here.");
1567 error("Don't know how to deserialize constant value of type '" +
1568 Ty->getDescription());
1574 /// Resolve references for constants. This function resolves the forward
1575 /// referenced constants in the ConstantFwdRefs map. It uses the
1576 /// replaceAllUsesWith method of Value class to substitute the placeholder
1577 /// instance with the actual instance.
1578 void BytecodeReader::ResolveReferencesToConstant(Constant *NewV, unsigned Typ,
1580 ConstantRefsType::iterator I =
1581 ConstantFwdRefs.find(std::make_pair(Typ, Slot));
1582 if (I == ConstantFwdRefs.end()) return; // Never forward referenced?
1584 Value *PH = I->second; // Get the placeholder...
1585 PH->replaceAllUsesWith(NewV);
1586 delete PH; // Delete the old placeholder
1587 ConstantFwdRefs.erase(I); // Remove the map entry for it
1590 /// Parse the constant strings section.
1591 void BytecodeReader::ParseStringConstants(unsigned NumEntries, ValueTable &Tab){
1592 for (; NumEntries; --NumEntries) {
1594 if (read_typeid(Typ))
1595 error("Invalid type (type type) for string constant");
1596 const Type *Ty = getType(Typ);
1597 if (!isa<ArrayType>(Ty))
1598 error("String constant data invalid!");
1600 const ArrayType *ATy = cast<ArrayType>(Ty);
1601 if (ATy->getElementType() != Type::SByteTy &&
1602 ATy->getElementType() != Type::UByteTy)
1603 error("String constant data invalid!");
1605 // Read character data. The type tells us how long the string is.
1606 char *Data = reinterpret_cast<char *>(alloca(ATy->getNumElements()));
1607 read_data(Data, Data+ATy->getNumElements());
1609 std::vector<Constant*> Elements(ATy->getNumElements());
1610 if (ATy->getElementType() == Type::SByteTy)
1611 for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
1612 Elements[i] = ConstantSInt::get(Type::SByteTy, (signed char)Data[i]);
1614 for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
1615 Elements[i] = ConstantUInt::get(Type::UByteTy, (unsigned char)Data[i]);
1617 // Create the constant, inserting it as needed.
1618 Constant *C = ConstantArray::get(ATy, Elements);
1619 unsigned Slot = insertValue(C, Typ, Tab);
1620 ResolveReferencesToConstant(C, Typ, Slot);
1621 if (Handler) Handler->handleConstantString(cast<ConstantArray>(C));
1625 /// Parse the constant pool.
1626 void BytecodeReader::ParseConstantPool(ValueTable &Tab,
1627 TypeListTy &TypeTab,
1629 if (Handler) Handler->handleGlobalConstantsBegin();
1631 /// In LLVM 1.3 Type does not derive from Value so the types
1632 /// do not occupy a plane. Consequently, we read the types
1633 /// first in the constant pool.
1634 if (isFunction && !hasTypeDerivedFromValue) {
1635 unsigned NumEntries = read_vbr_uint();
1636 ParseTypes(TypeTab, NumEntries);
1639 while (moreInBlock()) {
1640 unsigned NumEntries = read_vbr_uint();
1642 bool isTypeType = read_typeid(Typ);
1644 /// In LLVM 1.2 and before, Types were written to the
1645 /// bytecode file in the "Type Type" plane (#12).
1646 /// In 1.3 plane 12 is now the label plane. Handle this here.
1648 ParseTypes(TypeTab, NumEntries);
1649 } else if (Typ == Type::VoidTyID) {
1650 /// Use of Type::VoidTyID is a misnomer. It actually means
1651 /// that the following plane is constant strings
1652 assert(&Tab == &ModuleValues && "Cannot read strings in functions!");
1653 ParseStringConstants(NumEntries, Tab);
1655 for (unsigned i = 0; i < NumEntries; ++i) {
1656 Constant *C = ParseConstantValue(Typ);
1657 assert(C && "ParseConstantValue returned NULL!");
1658 unsigned Slot = insertValue(C, Typ, Tab);
1660 // If we are reading a function constant table, make sure that we adjust
1661 // the slot number to be the real global constant number.
1663 if (&Tab != &ModuleValues && Typ < ModuleValues.size() &&
1665 Slot += ModuleValues[Typ]->size();
1666 ResolveReferencesToConstant(C, Typ, Slot);
1671 // After we have finished parsing the constant pool, we had better not have
1672 // any dangling references left.
1673 if (!ConstantFwdRefs.empty()) {
1674 ConstantRefsType::const_iterator I = ConstantFwdRefs.begin();
1675 Constant* missingConst = I->second;
1676 error(utostr(ConstantFwdRefs.size()) +
1677 " unresolved constant reference exist. First one is '" +
1678 missingConst->getName() + "' of type '" +
1679 missingConst->getType()->getDescription() + "'.");
1682 checkPastBlockEnd("Constant Pool");
1683 if (Handler) Handler->handleGlobalConstantsEnd();
1686 /// Parse the contents of a function. Note that this function can be
1687 /// called lazily by materializeFunction
1688 /// @see materializeFunction
1689 void BytecodeReader::ParseFunctionBody(Function* F) {
1691 unsigned FuncSize = BlockEnd - At;
1692 GlobalValue::LinkageTypes Linkage = GlobalValue::ExternalLinkage;
1694 unsigned LinkageType = read_vbr_uint();
1695 switch (LinkageType) {
1696 case 0: Linkage = GlobalValue::ExternalLinkage; break;
1697 case 1: Linkage = GlobalValue::WeakLinkage; break;
1698 case 2: Linkage = GlobalValue::AppendingLinkage; break;
1699 case 3: Linkage = GlobalValue::InternalLinkage; break;
1700 case 4: Linkage = GlobalValue::LinkOnceLinkage; break;
1702 error("Invalid linkage type for Function.");
1703 Linkage = GlobalValue::InternalLinkage;
1707 F->setLinkage(Linkage);
1708 if (Handler) Handler->handleFunctionBegin(F,FuncSize);
1710 // Keep track of how many basic blocks we have read in...
1711 unsigned BlockNum = 0;
1712 bool InsertedArguments = false;
1714 BufPtr MyEnd = BlockEnd;
1715 while (At < MyEnd) {
1716 unsigned Type, Size;
1718 read_block(Type, Size);
1721 case BytecodeFormat::ConstantPoolBlockID:
1722 if (!InsertedArguments) {
1723 // Insert arguments into the value table before we parse the first basic
1724 // block in the function, but after we potentially read in the
1725 // compaction table.
1727 InsertedArguments = true;
1730 ParseConstantPool(FunctionValues, FunctionTypes, true);
1733 case BytecodeFormat::CompactionTableBlockID:
1734 ParseCompactionTable();
1737 case BytecodeFormat::BasicBlock: {
1738 if (!InsertedArguments) {
1739 // Insert arguments into the value table before we parse the first basic
1740 // block in the function, but after we potentially read in the
1741 // compaction table.
1743 InsertedArguments = true;
1746 BasicBlock *BB = ParseBasicBlock(BlockNum++);
1747 F->getBasicBlockList().push_back(BB);
1751 case BytecodeFormat::InstructionListBlockID: {
1752 // Insert arguments into the value table before we parse the instruction
1753 // list for the function, but after we potentially read in the compaction
1755 if (!InsertedArguments) {
1757 InsertedArguments = true;
1761 error("Already parsed basic blocks!");
1762 BlockNum = ParseInstructionList(F);
1766 case BytecodeFormat::SymbolTableBlockID:
1767 ParseSymbolTable(F, &F->getSymbolTable());
1773 error("Wrapped around reading bytecode.");
1778 // Malformed bc file if read past end of block.
1782 // Make sure there were no references to non-existant basic blocks.
1783 if (BlockNum != ParsedBasicBlocks.size())
1784 error("Illegal basic block operand reference");
1786 ParsedBasicBlocks.clear();
1788 // Resolve forward references. Replace any uses of a forward reference value
1789 // with the real value.
1790 while (!ForwardReferences.empty()) {
1791 std::map<std::pair<unsigned,unsigned>, Value*>::iterator
1792 I = ForwardReferences.begin();
1793 Value *V = getValue(I->first.first, I->first.second, false);
1794 Value *PlaceHolder = I->second;
1795 PlaceHolder->replaceAllUsesWith(V);
1796 ForwardReferences.erase(I);
1800 // Clear out function-level types...
1801 FunctionTypes.clear();
1802 CompactionTypes.clear();
1803 CompactionValues.clear();
1804 freeTable(FunctionValues);
1806 if (Handler) Handler->handleFunctionEnd(F);
1809 /// This function parses LLVM functions lazily. It obtains the type of the
1810 /// function and records where the body of the function is in the bytecode
1811 /// buffer. The caller can then use the ParseNextFunction and
1812 /// ParseAllFunctionBodies to get handler events for the functions.
1813 void BytecodeReader::ParseFunctionLazily() {
1814 if (FunctionSignatureList.empty())
1815 error("FunctionSignatureList empty!");
1817 Function *Func = FunctionSignatureList.back();
1818 FunctionSignatureList.pop_back();
1820 // Save the information for future reading of the function
1821 LazyFunctionLoadMap[Func] = LazyFunctionInfo(BlockStart, BlockEnd);
1823 // This function has a body but it's not loaded so it appears `External'.
1824 // Mark it as a `Ghost' instead to notify the users that it has a body.
1825 Func->setLinkage(GlobalValue::GhostLinkage);
1827 // Pretend we've `parsed' this function
1831 /// The ParserFunction method lazily parses one function. Use this method to
1832 /// casue the parser to parse a specific function in the module. Note that
1833 /// this will remove the function from what is to be included by
1834 /// ParseAllFunctionBodies.
1835 /// @see ParseAllFunctionBodies
1836 /// @see ParseBytecode
1837 void BytecodeReader::ParseFunction(Function* Func) {
1838 // Find {start, end} pointers and slot in the map. If not there, we're done.
1839 LazyFunctionMap::iterator Fi = LazyFunctionLoadMap.find(Func);
1841 // Make sure we found it
1842 if (Fi == LazyFunctionLoadMap.end()) {
1843 error("Unrecognized function of type " + Func->getType()->getDescription());
1847 BlockStart = At = Fi->second.Buf;
1848 BlockEnd = Fi->second.EndBuf;
1849 assert(Fi->first == Func && "Found wrong function?");
1851 LazyFunctionLoadMap.erase(Fi);
1853 this->ParseFunctionBody(Func);
1856 /// The ParseAllFunctionBodies method parses through all the previously
1857 /// unparsed functions in the bytecode file. If you want to completely parse
1858 /// a bytecode file, this method should be called after Parsebytecode because
1859 /// Parsebytecode only records the locations in the bytecode file of where
1860 /// the function definitions are located. This function uses that information
1861 /// to materialize the functions.
1862 /// @see ParseBytecode
1863 void BytecodeReader::ParseAllFunctionBodies() {
1864 LazyFunctionMap::iterator Fi = LazyFunctionLoadMap.begin();
1865 LazyFunctionMap::iterator Fe = LazyFunctionLoadMap.end();
1868 Function* Func = Fi->first;
1869 BlockStart = At = Fi->second.Buf;
1870 BlockEnd = Fi->second.EndBuf;
1871 ParseFunctionBody(Func);
1874 LazyFunctionLoadMap.clear();
1877 /// Parse the global type list
1878 void BytecodeReader::ParseGlobalTypes() {
1879 // Read the number of types
1880 unsigned NumEntries = read_vbr_uint();
1882 // Ignore the type plane identifier for types if the bc file is pre 1.3
1883 if (hasTypeDerivedFromValue)
1886 ParseTypes(ModuleTypes, NumEntries);
1889 /// Parse the Global info (types, global vars, constants)
1890 void BytecodeReader::ParseModuleGlobalInfo() {
1892 if (Handler) Handler->handleModuleGlobalsBegin();
1894 // Read global variables...
1895 unsigned VarType = read_vbr_uint();
1896 while (VarType != Type::VoidTyID) { // List is terminated by Void
1897 // VarType Fields: bit0 = isConstant, bit1 = hasInitializer, bit2,3,4 =
1898 // Linkage, bit4+ = slot#
1899 unsigned SlotNo = VarType >> 5;
1900 if (sanitizeTypeId(SlotNo))
1901 error("Invalid type (type type) for global var!");
1902 unsigned LinkageID = (VarType >> 2) & 7;
1903 bool isConstant = VarType & 1;
1904 bool hasInitializer = (VarType & 2) != 0;
1905 unsigned Alignment = 0;
1907 // An extension word is present when linkage = 3 (internal) and hasinit = 0.
1908 if (LinkageID == 3 && !hasInitializer) {
1909 unsigned ExtWord = read_vbr_uint();
1910 // The extension word has this format: bit 0 = has initializer, bit 1-3 =
1911 // linkage, bit 4-8 = alignment (log2), bits 10+ = future use.
1912 hasInitializer = ExtWord & 1;
1913 LinkageID = (ExtWord >> 1) & 7;
1914 Alignment = (1 << ((ExtWord >> 4) & 31)) >> 1;
1917 GlobalValue::LinkageTypes Linkage;
1918 switch (LinkageID) {
1919 case 0: Linkage = GlobalValue::ExternalLinkage; break;
1920 case 1: Linkage = GlobalValue::WeakLinkage; break;
1921 case 2: Linkage = GlobalValue::AppendingLinkage; break;
1922 case 3: Linkage = GlobalValue::InternalLinkage; break;
1923 case 4: Linkage = GlobalValue::LinkOnceLinkage; break;
1925 error("Unknown linkage type: " + utostr(LinkageID));
1926 Linkage = GlobalValue::InternalLinkage;
1930 const Type *Ty = getType(SlotNo);
1932 error("Global has no type! SlotNo=" + utostr(SlotNo));
1934 if (!isa<PointerType>(Ty))
1935 error("Global not a pointer type! Ty= " + Ty->getDescription());
1937 const Type *ElTy = cast<PointerType>(Ty)->getElementType();
1939 // Create the global variable...
1940 GlobalVariable *GV = new GlobalVariable(ElTy, isConstant, Linkage,
1942 GV->setAlignment(Alignment);
1943 insertValue(GV, SlotNo, ModuleValues);
1945 unsigned initSlot = 0;
1946 if (hasInitializer) {
1947 initSlot = read_vbr_uint();
1948 GlobalInits.push_back(std::make_pair(GV, initSlot));
1951 // Notify handler about the global value.
1953 Handler->handleGlobalVariable(ElTy, isConstant, Linkage, SlotNo,initSlot);
1956 VarType = read_vbr_uint();
1959 // Read the function objects for all of the functions that are coming
1960 unsigned FnSignature = read_vbr_uint();
1962 if (hasNoFlagsForFunctions)
1963 FnSignature = (FnSignature << 5) + 1;
1965 // List is terminated by VoidTy.
1966 while (((FnSignature & (~0U >> 1)) >> 5) != Type::VoidTyID) {
1967 const Type *Ty = getType((FnSignature & (~0U >> 1)) >> 5);
1968 if (!isa<PointerType>(Ty) ||
1969 !isa<FunctionType>(cast<PointerType>(Ty)->getElementType())) {
1970 error("Function not a pointer to function type! Ty = " +
1971 Ty->getDescription());
1974 // We create functions by passing the underlying FunctionType to create...
1975 const FunctionType* FTy =
1976 cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
1979 // Insert the place holder.
1980 Function* Func = new Function(FTy, GlobalValue::ExternalLinkage,
1982 insertValue(Func, (FnSignature & (~0U >> 1)) >> 5, ModuleValues);
1984 // Flags are not used yet.
1985 unsigned Flags = FnSignature & 31;
1987 // Save this for later so we know type of lazily instantiated functions.
1988 // Note that known-external functions do not have FunctionInfo blocks, so we
1989 // do not add them to the FunctionSignatureList.
1990 if ((Flags & (1 << 4)) == 0)
1991 FunctionSignatureList.push_back(Func);
1993 // Get the calling convention from the low bits.
1994 unsigned CC = Flags & 15;
1995 unsigned Alignment = 0;
1996 if (FnSignature & (1 << 31)) { // Has extension word?
1997 unsigned ExtWord = read_vbr_uint();
1998 Alignment = (1 << (ExtWord & 31)) >> 1;
1999 CC |= ((ExtWord >> 5) & 15) << 4;
2002 Func->setCallingConv(CC-1);
2003 Func->setAlignment(Alignment);
2005 if (Handler) Handler->handleFunctionDeclaration(Func);
2007 // Get the next function signature.
2008 FnSignature = read_vbr_uint();
2009 if (hasNoFlagsForFunctions)
2010 FnSignature = (FnSignature << 5) + 1;
2013 // Now that the function signature list is set up, reverse it so that we can
2014 // remove elements efficiently from the back of the vector.
2015 std::reverse(FunctionSignatureList.begin(), FunctionSignatureList.end());
2017 // If this bytecode format has dependent library information in it ..
2018 if (!hasNoDependentLibraries) {
2019 // Read in the number of dependent library items that follow
2020 unsigned num_dep_libs = read_vbr_uint();
2021 std::string dep_lib;
2022 while( num_dep_libs-- ) {
2023 dep_lib = read_str();
2024 TheModule->addLibrary(dep_lib);
2026 Handler->handleDependentLibrary(dep_lib);
2030 // Read target triple and place into the module
2031 std::string triple = read_str();
2032 TheModule->setTargetTriple(triple);
2034 Handler->handleTargetTriple(triple);
2037 if (hasInconsistentModuleGlobalInfo)
2040 // This is for future proofing... in the future extra fields may be added that
2041 // we don't understand, so we transparently ignore them.
2045 if (Handler) Handler->handleModuleGlobalsEnd();
2048 /// Parse the version information and decode it by setting flags on the
2049 /// Reader that enable backward compatibility of the reader.
2050 void BytecodeReader::ParseVersionInfo() {
2051 unsigned Version = read_vbr_uint();
2053 // Unpack version number: low four bits are for flags, top bits = version
2054 Module::Endianness Endianness;
2055 Module::PointerSize PointerSize;
2056 Endianness = (Version & 1) ? Module::BigEndian : Module::LittleEndian;
2057 PointerSize = (Version & 2) ? Module::Pointer64 : Module::Pointer32;
2059 bool hasNoEndianness = Version & 4;
2060 bool hasNoPointerSize = Version & 8;
2062 RevisionNum = Version >> 4;
2064 // Default values for the current bytecode version
2065 hasInconsistentModuleGlobalInfo = false;
2066 hasExplicitPrimitiveZeros = false;
2067 hasRestrictedGEPTypes = false;
2068 hasTypeDerivedFromValue = false;
2069 hasLongBlockHeaders = false;
2070 has32BitTypes = false;
2071 hasNoDependentLibraries = false;
2072 hasAlignment = false;
2073 hasNoUndefValue = false;
2074 hasNoFlagsForFunctions = false;
2075 hasNoUnreachableInst = false;
2077 switch (RevisionNum) {
2078 case 0: // LLVM 1.0, 1.1 (Released)
2079 // Base LLVM 1.0 bytecode format.
2080 hasInconsistentModuleGlobalInfo = true;
2081 hasExplicitPrimitiveZeros = true;
2085 case 1: // LLVM 1.2 (Released)
2086 // LLVM 1.2 added explicit support for emitting strings efficiently.
2088 // Also, it fixed the problem where the size of the ModuleGlobalInfo block
2089 // included the size for the alignment at the end, where the rest of the
2092 // LLVM 1.2 and before required that GEP indices be ubyte constants for
2093 // structures and longs for sequential types.
2094 hasRestrictedGEPTypes = true;
2096 // LLVM 1.2 and before had the Type class derive from Value class. This
2097 // changed in release 1.3 and consequently LLVM 1.3 bytecode files are
2098 // written differently because Types can no longer be part of the
2099 // type planes for Values.
2100 hasTypeDerivedFromValue = true;
2104 case 2: // 1.2.5 (Not Released)
2106 // LLVM 1.2 and earlier had two-word block headers. This is a bit wasteful,
2107 // especially for small files where the 8 bytes per block is a large
2108 // fraction of the total block size. In LLVM 1.3, the block type and length
2109 // are compressed into a single 32-bit unsigned integer. 27 bits for length,
2110 // 5 bits for block type.
2111 hasLongBlockHeaders = true;
2113 // LLVM 1.2 and earlier wrote type slot numbers as vbr_uint32. In LLVM 1.3
2114 // this has been reduced to vbr_uint24. It shouldn't make much difference
2115 // since we haven't run into a module with > 24 million types, but for
2116 // safety the 24-bit restriction has been enforced in 1.3 to free some bits
2117 // in various places and to ensure consistency.
2118 has32BitTypes = true;
2120 // LLVM 1.2 and earlier did not provide a target triple nor a list of
2121 // libraries on which the bytecode is dependent. LLVM 1.3 provides these
2122 // features, for use in future versions of LLVM.
2123 hasNoDependentLibraries = true;
2127 case 3: // LLVM 1.3 (Released)
2128 // LLVM 1.3 and earlier caused alignment bytes to be written on some block
2129 // boundaries and at the end of some strings. In extreme cases (e.g. lots
2130 // of GEP references to a constant array), this can increase the file size
2131 // by 30% or more. In version 1.4 alignment is done away with completely.
2132 hasAlignment = true;
2136 case 4: // 1.3.1 (Not Released)
2137 // In version 4, we did not support the 'undef' constant.
2138 hasNoUndefValue = true;
2140 // In version 4 and above, we did not include space for flags for functions
2141 // in the module info block.
2142 hasNoFlagsForFunctions = true;
2144 // In version 4 and above, we did not include the 'unreachable' instruction
2145 // in the opcode numbering in the bytecode file.
2146 hasNoUnreachableInst = true;
2151 case 5: // 1.4 (Released)
2155 error("Unknown bytecode version number: " + itostr(RevisionNum));
2158 if (hasNoEndianness) Endianness = Module::AnyEndianness;
2159 if (hasNoPointerSize) PointerSize = Module::AnyPointerSize;
2161 TheModule->setEndianness(Endianness);
2162 TheModule->setPointerSize(PointerSize);
2164 if (Handler) Handler->handleVersionInfo(RevisionNum, Endianness, PointerSize);
2167 /// Parse a whole module.
2168 void BytecodeReader::ParseModule() {
2169 unsigned Type, Size;
2171 FunctionSignatureList.clear(); // Just in case...
2173 // Read into instance variables...
2177 bool SeenModuleGlobalInfo = false;
2178 bool SeenGlobalTypePlane = false;
2179 BufPtr MyEnd = BlockEnd;
2180 while (At < MyEnd) {
2182 read_block(Type, Size);
2186 case BytecodeFormat::GlobalTypePlaneBlockID:
2187 if (SeenGlobalTypePlane)
2188 error("Two GlobalTypePlane Blocks Encountered!");
2192 SeenGlobalTypePlane = true;
2195 case BytecodeFormat::ModuleGlobalInfoBlockID:
2196 if (SeenModuleGlobalInfo)
2197 error("Two ModuleGlobalInfo Blocks Encountered!");
2198 ParseModuleGlobalInfo();
2199 SeenModuleGlobalInfo = true;
2202 case BytecodeFormat::ConstantPoolBlockID:
2203 ParseConstantPool(ModuleValues, ModuleTypes,false);
2206 case BytecodeFormat::FunctionBlockID:
2207 ParseFunctionLazily();
2210 case BytecodeFormat::SymbolTableBlockID:
2211 ParseSymbolTable(0, &TheModule->getSymbolTable());
2217 error("Unexpected Block of Type #" + utostr(Type) + " encountered!");
2225 // After the module constant pool has been read, we can safely initialize
2226 // global variables...
2227 while (!GlobalInits.empty()) {
2228 GlobalVariable *GV = GlobalInits.back().first;
2229 unsigned Slot = GlobalInits.back().second;
2230 GlobalInits.pop_back();
2232 // Look up the initializer value...
2233 // FIXME: Preserve this type ID!
2235 const llvm::PointerType* GVType = GV->getType();
2236 unsigned TypeSlot = getTypeSlot(GVType->getElementType());
2237 if (Constant *CV = getConstantValue(TypeSlot, Slot)) {
2238 if (GV->hasInitializer())
2239 error("Global *already* has an initializer?!");
2240 if (Handler) Handler->handleGlobalInitializer(GV,CV);
2241 GV->setInitializer(CV);
2243 error("Cannot find initializer value.");
2246 if (!ConstantFwdRefs.empty())
2247 error("Use of undefined constants in a module");
2249 /// Make sure we pulled them all out. If we didn't then there's a declaration
2250 /// but a missing body. That's not allowed.
2251 if (!FunctionSignatureList.empty())
2252 error("Function declared, but bytecode stream ended before definition");
2255 /// This function completely parses a bytecode buffer given by the \p Buf
2256 /// and \p Length parameters.
2257 void BytecodeReader::ParseBytecode(BufPtr Buf, unsigned Length,
2258 const std::string &ModuleID) {
2262 At = MemStart = BlockStart = Buf;
2263 MemEnd = BlockEnd = Buf + Length;
2265 // Create the module
2266 TheModule = new Module(ModuleID);
2268 if (Handler) Handler->handleStart(TheModule, Length);
2270 // Read the four bytes of the signature.
2271 unsigned Sig = read_uint();
2273 // If this is a compressed file
2274 if (Sig == ('l' | ('l' << 8) | ('v' << 16) | ('c' << 24))) {
2276 // Invoke the decompression of the bytecode. Note that we have to skip the
2277 // file's magic number which is not part of the compressed block. Hence,
2278 // the Buf+4 and Length-4. The result goes into decompressedBlock, a data
2279 // member for retention until BytecodeReader is destructed.
2280 unsigned decompressedLength = Compressor::decompressToNewBuffer(
2281 (char*)Buf+4,Length-4,decompressedBlock);
2283 // We must adjust the buffer pointers used by the bytecode reader to point
2284 // into the new decompressed block. After decompression, the
2285 // decompressedBlock will point to a contiguous memory area that has
2286 // the decompressed data.
2287 At = MemStart = BlockStart = Buf = (BufPtr) decompressedBlock;
2288 MemEnd = BlockEnd = Buf + decompressedLength;
2290 // else if this isn't a regular (uncompressed) bytecode file, then its
2291 // and error, generate that now.
2292 } else if (Sig != ('l' | ('l' << 8) | ('v' << 16) | ('m' << 24))) {
2293 error("Invalid bytecode signature: " + utohexstr(Sig));
2296 // Tell the handler we're starting a module
2297 if (Handler) Handler->handleModuleBegin(ModuleID);
2299 // Get the module block and size and verify. This is handled specially
2300 // because the module block/size is always written in long format. Other
2301 // blocks are written in short format so the read_block method is used.
2302 unsigned Type, Size;
2305 if (Type != BytecodeFormat::ModuleBlockID) {
2306 error("Expected Module Block! Type:" + utostr(Type) + ", Size:"
2310 // It looks like the darwin ranlib program is broken, and adds trailing
2311 // garbage to the end of some bytecode files. This hack allows the bc
2312 // reader to ignore trailing garbage on bytecode files.
2313 if (At + Size < MemEnd)
2314 MemEnd = BlockEnd = At+Size;
2316 if (At + Size != MemEnd)
2317 error("Invalid Top Level Block Length! Type:" + utostr(Type)
2318 + ", Size:" + utostr(Size));
2320 // Parse the module contents
2321 this->ParseModule();
2323 // Check for missing functions
2325 error("Function expected, but bytecode stream ended!");
2327 // Tell the handler we're done with the module
2329 Handler->handleModuleEnd(ModuleID);
2331 // Tell the handler we're finished the parse
2332 if (Handler) Handler->handleFinish();
2334 } catch (std::string& errstr) {
2335 if (Handler) Handler->handleError(errstr);
2339 if (decompressedBlock != 0 ) {
2340 ::free(decompressedBlock);
2341 decompressedBlock = 0;
2345 std::string msg("Unknown Exception Occurred");
2346 if (Handler) Handler->handleError(msg);
2350 if (decompressedBlock != 0) {
2351 ::free(decompressedBlock);
2352 decompressedBlock = 0;
2358 //===----------------------------------------------------------------------===//
2359 //=== Default Implementations of Handler Methods
2360 //===----------------------------------------------------------------------===//
2362 BytecodeHandler::~BytecodeHandler() {}