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/Constants.h"
23 #include "llvm/Instructions.h"
24 #include "llvm/SymbolTable.h"
25 #include "llvm/Bytecode/Format.h"
26 #include "llvm/Support/GetElementPtrTypeIterator.h"
27 #include "llvm/Support/Compressor.h"
28 #include "llvm/ADT/StringExtras.h"
33 #include "llvm/Support/Timer.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 {
41 ConstantPlaceHolder(); // DO NOT IMPLEMENT
42 void operator=(const ConstantPlaceHolder &); // DO NOT IMPLEMENT
44 ConstantPlaceHolder(const Type *Ty, unsigned id)
45 : ConstantExpr(Instruction::UserOp1, Constant::getNullValue(Ty), Ty),
47 unsigned getID() { return ID; }
52 // Provide some details on error
53 inline void BytecodeReader::error(std::string err) {
55 err += itostr(RevisionNum) ;
57 err += itostr(At-MemStart);
62 //===----------------------------------------------------------------------===//
63 // Bytecode Reading Methods
64 //===----------------------------------------------------------------------===//
66 /// Determine if the current block being read contains any more data.
67 inline bool BytecodeReader::moreInBlock() {
71 /// Throw an error if we've read past the end of the current block
72 inline void BytecodeReader::checkPastBlockEnd(const char * block_name) {
74 error(std::string("Attempt to read past the end of ") + block_name +
78 /// Align the buffer position to a 32 bit boundary
79 inline void BytecodeReader::align32() {
82 At = (const unsigned char *)((unsigned long)(At+3) & (~3UL));
84 if (Handler) Handler->handleAlignment(At - Save);
86 error("Ran out of data while aligning!");
90 /// Read a whole unsigned integer
91 inline unsigned BytecodeReader::read_uint() {
93 error("Ran out of data reading uint!");
95 return At[-4] | (At[-3] << 8) | (At[-2] << 16) | (At[-1] << 24);
98 /// Read a variable-bit-rate encoded unsigned integer
99 inline unsigned BytecodeReader::read_vbr_uint() {
106 error("Ran out of data reading vbr_uint!");
107 Result |= (unsigned)((*At++) & 0x7F) << Shift;
109 } while (At[-1] & 0x80);
110 if (Handler) Handler->handleVBR32(At-Save);
114 /// Read a variable-bit-rate encoded unsigned 64-bit integer.
115 inline uint64_t BytecodeReader::read_vbr_uint64() {
122 error("Ran out of data reading vbr_uint64!");
123 Result |= (uint64_t)((*At++) & 0x7F) << Shift;
125 } while (At[-1] & 0x80);
126 if (Handler) Handler->handleVBR64(At-Save);
130 /// Read a variable-bit-rate encoded signed 64-bit integer.
131 inline int64_t BytecodeReader::read_vbr_int64() {
132 uint64_t R = read_vbr_uint64();
135 return -(int64_t)(R >> 1);
136 else // There is no such thing as -0 with integers. "-0" really means
137 // 0x8000000000000000.
140 return (int64_t)(R >> 1);
143 /// Read a pascal-style string (length followed by text)
144 inline std::string BytecodeReader::read_str() {
145 unsigned Size = read_vbr_uint();
146 const unsigned char *OldAt = At;
148 if (At > BlockEnd) // Size invalid?
149 error("Ran out of data reading a string!");
150 return std::string((char*)OldAt, Size);
153 /// Read an arbitrary block of data
154 inline void BytecodeReader::read_data(void *Ptr, void *End) {
155 unsigned char *Start = (unsigned char *)Ptr;
156 unsigned Amount = (unsigned char *)End - Start;
157 if (At+Amount > BlockEnd)
158 error("Ran out of data!");
159 std::copy(At, At+Amount, Start);
163 /// Read a float value in little-endian order
164 inline void BytecodeReader::read_float(float& FloatVal) {
165 /// FIXME: This isn't optimal, it has size problems on some platforms
166 /// where FP is not IEEE.
171 FloatUnion.i = At[0] | (At[1] << 8) | (At[2] << 16) | (At[3] << 24);
172 At+=sizeof(uint32_t);
173 FloatVal = FloatUnion.f;
176 /// Read a double value in little-endian order
177 inline void BytecodeReader::read_double(double& DoubleVal) {
178 /// FIXME: This isn't optimal, it has size problems on some platforms
179 /// where FP is not IEEE.
184 DoubleUnion.i = (uint64_t(At[0]) << 0) | (uint64_t(At[1]) << 8) |
185 (uint64_t(At[2]) << 16) | (uint64_t(At[3]) << 24) |
186 (uint64_t(At[4]) << 32) | (uint64_t(At[5]) << 40) |
187 (uint64_t(At[6]) << 48) | (uint64_t(At[7]) << 56);
188 At+=sizeof(uint64_t);
189 DoubleVal = DoubleUnion.d;
192 /// Read a block header and obtain its type and size
193 inline void BytecodeReader::read_block(unsigned &Type, unsigned &Size) {
194 if ( hasLongBlockHeaders ) {
198 case BytecodeFormat::Reserved_DoNotUse :
199 error("Reserved_DoNotUse used as Module Type?");
200 Type = BytecodeFormat::ModuleBlockID; break;
201 case BytecodeFormat::Module:
202 Type = BytecodeFormat::ModuleBlockID; break;
203 case BytecodeFormat::Function:
204 Type = BytecodeFormat::FunctionBlockID; break;
205 case BytecodeFormat::ConstantPool:
206 Type = BytecodeFormat::ConstantPoolBlockID; break;
207 case BytecodeFormat::SymbolTable:
208 Type = BytecodeFormat::SymbolTableBlockID; break;
209 case BytecodeFormat::ModuleGlobalInfo:
210 Type = BytecodeFormat::ModuleGlobalInfoBlockID; break;
211 case BytecodeFormat::GlobalTypePlane:
212 Type = BytecodeFormat::GlobalTypePlaneBlockID; break;
213 case BytecodeFormat::InstructionList:
214 Type = BytecodeFormat::InstructionListBlockID; break;
215 case BytecodeFormat::CompactionTable:
216 Type = BytecodeFormat::CompactionTableBlockID; break;
217 case BytecodeFormat::BasicBlock:
218 /// This block type isn't used after version 1.1. However, we have to
219 /// still allow the value in case this is an old bc format file.
220 /// We just let its value creep thru.
223 error("Invalid block id found: " + utostr(Type));
228 Type = Size & 0x1F; // mask low order five bits
229 Size >>= 5; // get rid of five low order bits, leaving high 27
232 if (At + Size > BlockEnd)
233 error("Attempt to size a block past end of memory");
234 BlockEnd = At + Size;
235 if (Handler) Handler->handleBlock(Type, BlockStart, Size);
239 /// In LLVM 1.2 and before, Types were derived from Value and so they were
240 /// written as part of the type planes along with any other Value. In LLVM
241 /// 1.3 this changed so that Type does not derive from Value. Consequently,
242 /// the BytecodeReader's containers for Values can't contain Types because
243 /// there's no inheritance relationship. This means that the "Type Type"
244 /// plane is defunct along with the Type::TypeTyID TypeID. In LLVM 1.3
245 /// whenever a bytecode construct must have both types and values together,
246 /// the types are always read/written first and then the Values. Furthermore
247 /// since Type::TypeTyID no longer exists, its value (12) now corresponds to
248 /// Type::LabelTyID. In order to overcome this we must "sanitize" all the
249 /// type TypeIDs we encounter. For LLVM 1.3 bytecode files, there's no change.
250 /// For LLVM 1.2 and before, this function will decrement the type id by
251 /// one to account for the missing Type::TypeTyID enumerator if the value is
252 /// larger than 12 (Type::LabelTyID). If the value is exactly 12, then this
253 /// function returns true, otherwise false. This helps detect situations
254 /// where the pre 1.3 bytecode is indicating that what follows is a type.
255 /// @returns true iff type id corresponds to pre 1.3 "type type"
256 inline bool BytecodeReader::sanitizeTypeId(unsigned &TypeId) {
257 if (hasTypeDerivedFromValue) { /// do nothing if 1.3 or later
258 if (TypeId == Type::LabelTyID) {
259 TypeId = Type::VoidTyID; // sanitize it
260 return true; // indicate we got TypeTyID in pre 1.3 bytecode
261 } else if (TypeId > Type::LabelTyID)
262 --TypeId; // shift all planes down because type type plane is missing
267 /// Reads a vbr uint to read in a type id and does the necessary
268 /// conversion on it by calling sanitizeTypeId.
269 /// @returns true iff \p TypeId read corresponds to a pre 1.3 "type type"
270 /// @see sanitizeTypeId
271 inline bool BytecodeReader::read_typeid(unsigned &TypeId) {
272 TypeId = read_vbr_uint();
273 if ( !has32BitTypes )
274 if ( TypeId == 0x00FFFFFF )
275 TypeId = read_vbr_uint();
276 return sanitizeTypeId(TypeId);
279 //===----------------------------------------------------------------------===//
281 //===----------------------------------------------------------------------===//
283 /// Determine if a type id has an implicit null value
284 inline bool BytecodeReader::hasImplicitNull(unsigned TyID) {
285 if (!hasExplicitPrimitiveZeros)
286 return TyID != Type::LabelTyID && TyID != Type::VoidTyID;
287 return TyID >= Type::FirstDerivedTyID;
290 /// Obtain a type given a typeid and account for things like compaction tables,
291 /// function level vs module level, and the offsetting for the primitive types.
292 const Type *BytecodeReader::getType(unsigned ID) {
293 if (ID < Type::FirstDerivedTyID)
294 if (const Type *T = Type::getPrimitiveType((Type::TypeID)ID))
295 return T; // Asked for a primitive type...
297 // Otherwise, derived types need offset...
298 ID -= Type::FirstDerivedTyID;
300 if (!CompactionTypes.empty()) {
301 if (ID >= CompactionTypes.size())
302 error("Type ID out of range for compaction table!");
303 return CompactionTypes[ID].first;
306 // Is it a module-level type?
307 if (ID < ModuleTypes.size())
308 return ModuleTypes[ID].get();
310 // Nope, is it a function-level type?
311 ID -= ModuleTypes.size();
312 if (ID < FunctionTypes.size())
313 return FunctionTypes[ID].get();
315 error("Illegal type reference!");
319 /// Get a sanitized type id. This just makes sure that the \p ID
320 /// is both sanitized and not the "type type" of pre-1.3 bytecode.
321 /// @see sanitizeTypeId
322 inline const Type* BytecodeReader::getSanitizedType(unsigned& ID) {
323 if (sanitizeTypeId(ID))
324 error("Invalid type id encountered");
328 /// This method just saves some coding. It uses read_typeid to read
329 /// in a sanitized type id, errors that its not the type type, and
330 /// then calls getType to return the type value.
331 inline const Type* BytecodeReader::readSanitizedType() {
334 error("Invalid type id encountered");
338 /// Get the slot number associated with a type accounting for primitive
339 /// types, compaction tables, and function level vs module level.
340 unsigned BytecodeReader::getTypeSlot(const Type *Ty) {
341 if (Ty->isPrimitiveType())
342 return Ty->getTypeID();
344 // Scan the compaction table for the type if needed.
345 if (!CompactionTypes.empty()) {
346 for (unsigned i = 0, e = CompactionTypes.size(); i != e; ++i)
347 if (CompactionTypes[i].first == Ty)
348 return Type::FirstDerivedTyID + i;
350 error("Couldn't find type specified in compaction table!");
353 // Check the function level types first...
354 TypeListTy::iterator I = std::find(FunctionTypes.begin(),
355 FunctionTypes.end(), Ty);
357 if (I != FunctionTypes.end())
358 return Type::FirstDerivedTyID + ModuleTypes.size() +
359 (&*I - &FunctionTypes[0]);
361 // Check the module level types now...
362 I = std::find(ModuleTypes.begin(), ModuleTypes.end(), Ty);
363 if (I == ModuleTypes.end())
364 error("Didn't find type in ModuleTypes.");
365 return Type::FirstDerivedTyID + (&*I - &ModuleTypes[0]);
368 /// This is just like getType, but when a compaction table is in use, it is
369 /// ignored. It also ignores function level types.
371 const Type *BytecodeReader::getGlobalTableType(unsigned Slot) {
372 if (Slot < Type::FirstDerivedTyID) {
373 const Type *Ty = Type::getPrimitiveType((Type::TypeID)Slot);
375 error("Not a primitive type ID?");
378 Slot -= Type::FirstDerivedTyID;
379 if (Slot >= ModuleTypes.size())
380 error("Illegal compaction table type reference!");
381 return ModuleTypes[Slot];
384 /// This is just like getTypeSlot, but when a compaction table is in use, it
385 /// is ignored. It also ignores function level types.
386 unsigned BytecodeReader::getGlobalTableTypeSlot(const Type *Ty) {
387 if (Ty->isPrimitiveType())
388 return Ty->getTypeID();
389 TypeListTy::iterator I = std::find(ModuleTypes.begin(),
390 ModuleTypes.end(), Ty);
391 if (I == ModuleTypes.end())
392 error("Didn't find type in ModuleTypes.");
393 return Type::FirstDerivedTyID + (&*I - &ModuleTypes[0]);
396 /// Retrieve a value of a given type and slot number, possibly creating
397 /// it if it doesn't already exist.
398 Value * BytecodeReader::getValue(unsigned type, unsigned oNum, bool Create) {
399 assert(type != Type::LabelTyID && "getValue() cannot get blocks!");
402 // If there is a compaction table active, it defines the low-level numbers.
403 // If not, the module values define the low-level numbers.
404 if (CompactionValues.size() > type && !CompactionValues[type].empty()) {
405 if (Num < CompactionValues[type].size())
406 return CompactionValues[type][Num];
407 Num -= CompactionValues[type].size();
409 // By default, the global type id is the type id passed in
410 unsigned GlobalTyID = type;
412 // If the type plane was compactified, figure out the global type ID by
413 // adding the derived type ids and the distance.
414 if (!CompactionTypes.empty() && type >= Type::FirstDerivedTyID)
415 GlobalTyID = CompactionTypes[type-Type::FirstDerivedTyID].second;
417 if (hasImplicitNull(GlobalTyID)) {
419 return Constant::getNullValue(getType(type));
423 if (GlobalTyID < ModuleValues.size() && ModuleValues[GlobalTyID]) {
424 if (Num < ModuleValues[GlobalTyID]->size())
425 return ModuleValues[GlobalTyID]->getOperand(Num);
426 Num -= ModuleValues[GlobalTyID]->size();
430 if (FunctionValues.size() > type &&
431 FunctionValues[type] &&
432 Num < FunctionValues[type]->size())
433 return FunctionValues[type]->getOperand(Num);
435 if (!Create) return 0; // Do not create a placeholder?
437 // Did we already create a place holder?
438 std::pair<unsigned,unsigned> KeyValue(type, oNum);
439 ForwardReferenceMap::iterator I = ForwardReferences.lower_bound(KeyValue);
440 if (I != ForwardReferences.end() && I->first == KeyValue)
441 return I->second; // We have already created this placeholder
443 // If the type exists (it should)
444 if (const Type* Ty = getType(type)) {
445 // Create the place holder
446 Value *Val = new Argument(Ty);
447 ForwardReferences.insert(I, std::make_pair(KeyValue, Val));
450 throw "Can't create placeholder for value of type slot #" + utostr(type);
453 /// This is just like getValue, but when a compaction table is in use, it
454 /// is ignored. Also, no forward references or other fancy features are
456 Value* BytecodeReader::getGlobalTableValue(unsigned TyID, unsigned SlotNo) {
458 return Constant::getNullValue(getType(TyID));
460 if (!CompactionTypes.empty() && TyID >= Type::FirstDerivedTyID) {
461 TyID -= Type::FirstDerivedTyID;
462 if (TyID >= CompactionTypes.size())
463 error("Type ID out of range for compaction table!");
464 TyID = CompactionTypes[TyID].second;
469 if (TyID >= ModuleValues.size() || ModuleValues[TyID] == 0 ||
470 SlotNo >= ModuleValues[TyID]->size()) {
471 if (TyID >= ModuleValues.size() || ModuleValues[TyID] == 0)
472 error("Corrupt compaction table entry!"
473 + utostr(TyID) + ", " + utostr(SlotNo) + ": "
474 + utostr(ModuleValues.size()));
476 error("Corrupt compaction table entry!"
477 + utostr(TyID) + ", " + utostr(SlotNo) + ": "
478 + utostr(ModuleValues.size()) + ", "
479 + utohexstr(reinterpret_cast<uint64_t>(((void*)ModuleValues[TyID])))
481 + utostr(ModuleValues[TyID]->size()));
483 return ModuleValues[TyID]->getOperand(SlotNo);
486 /// Just like getValue, except that it returns a null pointer
487 /// only on error. It always returns a constant (meaning that if the value is
488 /// defined, but is not a constant, that is an error). If the specified
489 /// constant hasn't been parsed yet, a placeholder is defined and used.
490 /// Later, after the real value is parsed, the placeholder is eliminated.
491 Constant* BytecodeReader::getConstantValue(unsigned TypeSlot, unsigned Slot) {
492 if (Value *V = getValue(TypeSlot, Slot, false))
493 if (Constant *C = dyn_cast<Constant>(V))
494 return C; // If we already have the value parsed, just return it
496 error("Value for slot " + utostr(Slot) +
497 " is expected to be a constant!");
499 const Type *Ty = getType(TypeSlot);
500 std::pair<const Type*, unsigned> Key(Ty, Slot);
501 ConstantRefsType::iterator I = ConstantFwdRefs.lower_bound(Key);
503 if (I != ConstantFwdRefs.end() && I->first == Key) {
506 // Create a placeholder for the constant reference and
507 // keep track of the fact that we have a forward ref to recycle it
508 Constant *C = new ConstantPlaceHolder(Ty, Slot);
510 // Keep track of the fact that we have a forward ref to recycle it
511 ConstantFwdRefs.insert(I, std::make_pair(Key, C));
516 //===----------------------------------------------------------------------===//
517 // IR Construction Methods
518 //===----------------------------------------------------------------------===//
520 /// As values are created, they are inserted into the appropriate place
521 /// with this method. The ValueTable argument must be one of ModuleValues
522 /// or FunctionValues data members of this class.
523 unsigned BytecodeReader::insertValue(Value *Val, unsigned type,
524 ValueTable &ValueTab) {
525 assert((!isa<Constant>(Val) || !cast<Constant>(Val)->isNullValue()) ||
526 !hasImplicitNull(type) &&
527 "Cannot read null values from bytecode!");
529 if (ValueTab.size() <= type)
530 ValueTab.resize(type+1);
532 if (!ValueTab[type]) ValueTab[type] = new ValueList();
534 ValueTab[type]->push_back(Val);
536 bool HasOffset = hasImplicitNull(type);
537 return ValueTab[type]->size()-1 + HasOffset;
540 /// Insert the arguments of a function as new values in the reader.
541 void BytecodeReader::insertArguments(Function* F) {
542 const FunctionType *FT = F->getFunctionType();
543 Function::aiterator AI = F->abegin();
544 for (FunctionType::param_iterator It = FT->param_begin();
545 It != FT->param_end(); ++It, ++AI)
546 insertValue(AI, getTypeSlot(AI->getType()), FunctionValues);
549 //===----------------------------------------------------------------------===//
550 // Bytecode Parsing Methods
551 //===----------------------------------------------------------------------===//
553 /// This method parses a single instruction. The instruction is
554 /// inserted at the end of the \p BB provided. The arguments of
555 /// the instruction are provided in the \p Oprnds vector.
556 void BytecodeReader::ParseInstruction(std::vector<unsigned> &Oprnds,
560 // Clear instruction data
564 unsigned Op = read_uint();
566 // bits Instruction format: Common to all formats
567 // --------------------------
568 // 01-00: Opcode type, fixed to 1.
570 Opcode = (Op >> 2) & 63;
571 Oprnds.resize((Op >> 0) & 03);
573 // Extract the operands
574 switch (Oprnds.size()) {
576 // bits Instruction format:
577 // --------------------------
578 // 19-08: Resulting type plane
579 // 31-20: Operand #1 (if set to (2^12-1), then zero operands)
581 iType = (Op >> 8) & 4095;
582 Oprnds[0] = (Op >> 20) & 4095;
583 if (Oprnds[0] == 4095) // Handle special encoding for 0 operands...
587 // bits Instruction format:
588 // --------------------------
589 // 15-08: Resulting type plane
593 iType = (Op >> 8) & 255;
594 Oprnds[0] = (Op >> 16) & 255;
595 Oprnds[1] = (Op >> 24) & 255;
598 // bits Instruction format:
599 // --------------------------
600 // 13-08: Resulting type plane
605 iType = (Op >> 8) & 63;
606 Oprnds[0] = (Op >> 14) & 63;
607 Oprnds[1] = (Op >> 20) & 63;
608 Oprnds[2] = (Op >> 26) & 63;
611 At -= 4; // Hrm, try this again...
612 Opcode = read_vbr_uint();
614 iType = read_vbr_uint();
616 unsigned NumOprnds = read_vbr_uint();
617 Oprnds.resize(NumOprnds);
620 error("Zero-argument instruction found; this is invalid.");
622 for (unsigned i = 0; i != NumOprnds; ++i)
623 Oprnds[i] = read_vbr_uint();
628 const Type *InstTy = getSanitizedType(iType);
630 // We have enough info to inform the handler now.
631 if (Handler) Handler->handleInstruction(Opcode, InstTy, Oprnds, At-SaveAt);
633 // Declare the resulting instruction we'll build.
634 Instruction *Result = 0;
636 // If this is a bytecode format that did not include the unreachable
637 // instruction, bump up all opcodes numbers to make space.
638 if (hasNoUnreachableInst) {
639 if (Opcode >= Instruction::Unreachable &&
645 // Handle binary operators
646 if (Opcode >= Instruction::BinaryOpsBegin &&
647 Opcode < Instruction::BinaryOpsEnd && Oprnds.size() == 2)
648 Result = BinaryOperator::create((Instruction::BinaryOps)Opcode,
649 getValue(iType, Oprnds[0]),
650 getValue(iType, Oprnds[1]));
655 error("Illegal instruction read!");
657 case Instruction::VAArg:
658 Result = new VAArgInst(getValue(iType, Oprnds[0]),
659 getSanitizedType(Oprnds[1]));
661 case Instruction::VANext:
662 Result = new VANextInst(getValue(iType, Oprnds[0]),
663 getSanitizedType(Oprnds[1]));
665 case Instruction::Cast:
666 Result = new CastInst(getValue(iType, Oprnds[0]),
667 getSanitizedType(Oprnds[1]));
669 case Instruction::Select:
670 Result = new SelectInst(getValue(Type::BoolTyID, Oprnds[0]),
671 getValue(iType, Oprnds[1]),
672 getValue(iType, Oprnds[2]));
674 case Instruction::PHI: {
675 if (Oprnds.size() == 0 || (Oprnds.size() & 1))
676 error("Invalid phi node encountered!");
678 PHINode *PN = new PHINode(InstTy);
679 PN->op_reserve(Oprnds.size());
680 for (unsigned i = 0, e = Oprnds.size(); i != e; i += 2)
681 PN->addIncoming(getValue(iType, Oprnds[i]), getBasicBlock(Oprnds[i+1]));
686 case Instruction::Shl:
687 case Instruction::Shr:
688 Result = new ShiftInst((Instruction::OtherOps)Opcode,
689 getValue(iType, Oprnds[0]),
690 getValue(Type::UByteTyID, Oprnds[1]));
692 case Instruction::Ret:
693 if (Oprnds.size() == 0)
694 Result = new ReturnInst();
695 else if (Oprnds.size() == 1)
696 Result = new ReturnInst(getValue(iType, Oprnds[0]));
698 error("Unrecognized instruction!");
701 case Instruction::Br:
702 if (Oprnds.size() == 1)
703 Result = new BranchInst(getBasicBlock(Oprnds[0]));
704 else if (Oprnds.size() == 3)
705 Result = new BranchInst(getBasicBlock(Oprnds[0]),
706 getBasicBlock(Oprnds[1]), getValue(Type::BoolTyID , Oprnds[2]));
708 error("Invalid number of operands for a 'br' instruction!");
710 case Instruction::Switch: {
711 if (Oprnds.size() & 1)
712 error("Switch statement with odd number of arguments!");
714 SwitchInst *I = new SwitchInst(getValue(iType, Oprnds[0]),
715 getBasicBlock(Oprnds[1]));
716 for (unsigned i = 2, e = Oprnds.size(); i != e; i += 2)
717 I->addCase(cast<Constant>(getValue(iType, Oprnds[i])),
718 getBasicBlock(Oprnds[i+1]));
723 case Instruction::Call: {
724 if (Oprnds.size() == 0)
725 error("Invalid call instruction encountered!");
727 Value *F = getValue(iType, Oprnds[0]);
729 // Check to make sure we have a pointer to function type
730 const PointerType *PTy = dyn_cast<PointerType>(F->getType());
731 if (PTy == 0) error("Call to non function pointer value!");
732 const FunctionType *FTy = dyn_cast<FunctionType>(PTy->getElementType());
733 if (FTy == 0) error("Call to non function pointer value!");
735 std::vector<Value *> Params;
736 if (!FTy->isVarArg()) {
737 FunctionType::param_iterator It = FTy->param_begin();
739 for (unsigned i = 1, e = Oprnds.size(); i != e; ++i) {
740 if (It == FTy->param_end())
741 error("Invalid call instruction!");
742 Params.push_back(getValue(getTypeSlot(*It++), Oprnds[i]));
744 if (It != FTy->param_end())
745 error("Invalid call instruction!");
747 Oprnds.erase(Oprnds.begin(), Oprnds.begin()+1);
749 unsigned FirstVariableOperand;
750 if (Oprnds.size() < FTy->getNumParams())
751 error("Call instruction missing operands!");
753 // Read all of the fixed arguments
754 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
755 Params.push_back(getValue(getTypeSlot(FTy->getParamType(i)),Oprnds[i]));
757 FirstVariableOperand = FTy->getNumParams();
759 if ((Oprnds.size()-FirstVariableOperand) & 1)
760 error("Invalid call instruction!"); // Must be pairs of type/value
762 for (unsigned i = FirstVariableOperand, e = Oprnds.size();
764 Params.push_back(getValue(Oprnds[i], Oprnds[i+1]));
767 Result = new CallInst(F, Params);
770 case Instruction::Invoke: {
771 if (Oprnds.size() < 3)
772 error("Invalid invoke instruction!");
773 Value *F = getValue(iType, Oprnds[0]);
775 // Check to make sure we have a pointer to function type
776 const PointerType *PTy = dyn_cast<PointerType>(F->getType());
778 error("Invoke to non function pointer value!");
779 const FunctionType *FTy = dyn_cast<FunctionType>(PTy->getElementType());
781 error("Invoke to non function pointer value!");
783 std::vector<Value *> Params;
784 BasicBlock *Normal, *Except;
786 if (!FTy->isVarArg()) {
787 Normal = getBasicBlock(Oprnds[1]);
788 Except = getBasicBlock(Oprnds[2]);
790 FunctionType::param_iterator It = FTy->param_begin();
791 for (unsigned i = 3, e = Oprnds.size(); i != e; ++i) {
792 if (It == FTy->param_end())
793 error("Invalid invoke instruction!");
794 Params.push_back(getValue(getTypeSlot(*It++), Oprnds[i]));
796 if (It != FTy->param_end())
797 error("Invalid invoke instruction!");
799 Oprnds.erase(Oprnds.begin(), Oprnds.begin()+1);
801 Normal = getBasicBlock(Oprnds[0]);
802 Except = getBasicBlock(Oprnds[1]);
804 unsigned FirstVariableArgument = FTy->getNumParams()+2;
805 for (unsigned i = 2; i != FirstVariableArgument; ++i)
806 Params.push_back(getValue(getTypeSlot(FTy->getParamType(i-2)),
809 if (Oprnds.size()-FirstVariableArgument & 1) // Must be type/value pairs
810 error("Invalid invoke instruction!");
812 for (unsigned i = FirstVariableArgument; i < Oprnds.size(); i += 2)
813 Params.push_back(getValue(Oprnds[i], Oprnds[i+1]));
816 Result = new InvokeInst(F, Normal, Except, Params);
819 case Instruction::Malloc:
820 if (Oprnds.size() > 2)
821 error("Invalid malloc instruction!");
822 if (!isa<PointerType>(InstTy))
823 error("Invalid malloc instruction!");
825 Result = new MallocInst(cast<PointerType>(InstTy)->getElementType(),
826 Oprnds.size() ? getValue(Type::UIntTyID,
830 case Instruction::Alloca:
831 if (Oprnds.size() > 2)
832 error("Invalid alloca instruction!");
833 if (!isa<PointerType>(InstTy))
834 error("Invalid alloca instruction!");
836 Result = new AllocaInst(cast<PointerType>(InstTy)->getElementType(),
837 Oprnds.size() ? getValue(Type::UIntTyID,
840 case Instruction::Free:
841 if (!isa<PointerType>(InstTy))
842 error("Invalid free instruction!");
843 Result = new FreeInst(getValue(iType, Oprnds[0]));
845 case Instruction::GetElementPtr: {
846 if (Oprnds.size() == 0 || !isa<PointerType>(InstTy))
847 error("Invalid getelementptr instruction!");
849 std::vector<Value*> Idx;
851 const Type *NextTy = InstTy;
852 for (unsigned i = 1, e = Oprnds.size(); i != e; ++i) {
853 const CompositeType *TopTy = dyn_cast_or_null<CompositeType>(NextTy);
855 error("Invalid getelementptr instruction!");
857 unsigned ValIdx = Oprnds[i];
859 if (!hasRestrictedGEPTypes) {
860 // Struct indices are always uints, sequential type indices can be any
861 // of the 32 or 64-bit integer types. The actual choice of type is
862 // encoded in the low two bits of the slot number.
863 if (isa<StructType>(TopTy))
864 IdxTy = Type::UIntTyID;
866 switch (ValIdx & 3) {
868 case 0: IdxTy = Type::UIntTyID; break;
869 case 1: IdxTy = Type::IntTyID; break;
870 case 2: IdxTy = Type::ULongTyID; break;
871 case 3: IdxTy = Type::LongTyID; break;
876 IdxTy = isa<StructType>(TopTy) ? Type::UByteTyID : Type::LongTyID;
879 Idx.push_back(getValue(IdxTy, ValIdx));
881 // Convert ubyte struct indices into uint struct indices.
882 if (isa<StructType>(TopTy) && hasRestrictedGEPTypes)
883 if (ConstantUInt *C = dyn_cast<ConstantUInt>(Idx.back()))
884 Idx[Idx.size()-1] = ConstantExpr::getCast(C, Type::UIntTy);
886 NextTy = GetElementPtrInst::getIndexedType(InstTy, Idx, true);
889 Result = new GetElementPtrInst(getValue(iType, Oprnds[0]), Idx);
893 case 62: // volatile load
894 case Instruction::Load:
895 if (Oprnds.size() != 1 || !isa<PointerType>(InstTy))
896 error("Invalid load instruction!");
897 Result = new LoadInst(getValue(iType, Oprnds[0]), "", Opcode == 62);
900 case 63: // volatile store
901 case Instruction::Store: {
902 if (!isa<PointerType>(InstTy) || Oprnds.size() != 2)
903 error("Invalid store instruction!");
905 Value *Ptr = getValue(iType, Oprnds[1]);
906 const Type *ValTy = cast<PointerType>(Ptr->getType())->getElementType();
907 Result = new StoreInst(getValue(getTypeSlot(ValTy), Oprnds[0]), Ptr,
911 case Instruction::Unwind:
912 if (Oprnds.size() != 0) error("Invalid unwind instruction!");
913 Result = new UnwindInst();
915 case Instruction::Unreachable:
916 if (Oprnds.size() != 0) error("Invalid unreachable instruction!");
917 Result = new UnreachableInst();
919 } // end switch(Opcode)
922 if (Result->getType() == InstTy)
925 TypeSlot = getTypeSlot(Result->getType());
927 insertValue(Result, TypeSlot, FunctionValues);
928 BB->getInstList().push_back(Result);
931 /// Get a particular numbered basic block, which might be a forward reference.
932 /// This works together with ParseBasicBlock to handle these forward references
933 /// in a clean manner. This function is used when constructing phi, br, switch,
934 /// and other instructions that reference basic blocks. Blocks are numbered
935 /// sequentially as they appear in the function.
936 BasicBlock *BytecodeReader::getBasicBlock(unsigned ID) {
937 // Make sure there is room in the table...
938 if (ParsedBasicBlocks.size() <= ID) ParsedBasicBlocks.resize(ID+1);
940 // First check to see if this is a backwards reference, i.e., ParseBasicBlock
941 // has already created this block, or if the forward reference has already
943 if (ParsedBasicBlocks[ID])
944 return ParsedBasicBlocks[ID];
946 // Otherwise, the basic block has not yet been created. Do so and add it to
947 // the ParsedBasicBlocks list.
948 return ParsedBasicBlocks[ID] = new BasicBlock();
951 /// In LLVM 1.0 bytecode files, we used to output one basicblock at a time.
952 /// This method reads in one of the basicblock packets. This method is not used
953 /// for bytecode files after LLVM 1.0
954 /// @returns The basic block constructed.
955 BasicBlock *BytecodeReader::ParseBasicBlock(unsigned BlockNo) {
956 if (Handler) Handler->handleBasicBlockBegin(BlockNo);
960 if (ParsedBasicBlocks.size() == BlockNo)
961 ParsedBasicBlocks.push_back(BB = new BasicBlock());
962 else if (ParsedBasicBlocks[BlockNo] == 0)
963 BB = ParsedBasicBlocks[BlockNo] = new BasicBlock();
965 BB = ParsedBasicBlocks[BlockNo];
967 std::vector<unsigned> Operands;
968 while (moreInBlock())
969 ParseInstruction(Operands, BB);
971 if (Handler) Handler->handleBasicBlockEnd(BlockNo);
975 /// Parse all of the BasicBlock's & Instruction's in the body of a function.
976 /// In post 1.0 bytecode files, we no longer emit basic block individually,
977 /// in order to avoid per-basic-block overhead.
978 /// @returns Rhe number of basic blocks encountered.
979 unsigned BytecodeReader::ParseInstructionList(Function* F) {
980 unsigned BlockNo = 0;
981 std::vector<unsigned> Args;
983 while (moreInBlock()) {
984 if (Handler) Handler->handleBasicBlockBegin(BlockNo);
986 if (ParsedBasicBlocks.size() == BlockNo)
987 ParsedBasicBlocks.push_back(BB = new BasicBlock());
988 else if (ParsedBasicBlocks[BlockNo] == 0)
989 BB = ParsedBasicBlocks[BlockNo] = new BasicBlock();
991 BB = ParsedBasicBlocks[BlockNo];
993 F->getBasicBlockList().push_back(BB);
995 // Read instructions into this basic block until we get to a terminator
996 while (moreInBlock() && !BB->getTerminator())
997 ParseInstruction(Args, BB);
999 if (!BB->getTerminator())
1000 error("Non-terminated basic block found!");
1002 if (Handler) Handler->handleBasicBlockEnd(BlockNo-1);
1008 /// Parse a symbol table. This works for both module level and function
1009 /// level symbol tables. For function level symbol tables, the CurrentFunction
1010 /// parameter must be non-zero and the ST parameter must correspond to
1011 /// CurrentFunction's symbol table. For Module level symbol tables, the
1012 /// CurrentFunction argument must be zero.
1013 void BytecodeReader::ParseSymbolTable(Function *CurrentFunction,
1015 if (Handler) Handler->handleSymbolTableBegin(CurrentFunction,ST);
1017 // Allow efficient basic block lookup by number.
1018 std::vector<BasicBlock*> BBMap;
1019 if (CurrentFunction)
1020 for (Function::iterator I = CurrentFunction->begin(),
1021 E = CurrentFunction->end(); I != E; ++I)
1024 /// In LLVM 1.3 we write types separately from values so
1025 /// The types are always first in the symbol table. This is
1026 /// because Type no longer derives from Value.
1027 if (!hasTypeDerivedFromValue) {
1028 // Symtab block header: [num entries]
1029 unsigned NumEntries = read_vbr_uint();
1030 for (unsigned i = 0; i < NumEntries; ++i) {
1031 // Symtab entry: [def slot #][name]
1032 unsigned slot = read_vbr_uint();
1033 std::string Name = read_str();
1034 const Type* T = getType(slot);
1035 ST->insert(Name, T);
1039 while (moreInBlock()) {
1040 // Symtab block header: [num entries][type id number]
1041 unsigned NumEntries = read_vbr_uint();
1043 bool isTypeType = read_typeid(Typ);
1044 const Type *Ty = getType(Typ);
1046 for (unsigned i = 0; i != NumEntries; ++i) {
1047 // Symtab entry: [def slot #][name]
1048 unsigned slot = read_vbr_uint();
1049 std::string Name = read_str();
1051 // if we're reading a pre 1.3 bytecode file and the type plane
1052 // is the "type type", handle it here
1054 const Type* T = getType(slot);
1056 error("Failed type look-up for name '" + Name + "'");
1057 ST->insert(Name, T);
1058 continue; // code below must be short circuited
1061 if (Typ == Type::LabelTyID) {
1062 if (slot < BBMap.size())
1065 V = getValue(Typ, slot, false); // Find mapping...
1068 error("Failed value look-up for name '" + Name + "'");
1069 V->setName(Name, ST);
1073 checkPastBlockEnd("Symbol Table");
1074 if (Handler) Handler->handleSymbolTableEnd();
1077 /// Read in the types portion of a compaction table.
1078 void BytecodeReader::ParseCompactionTypes(unsigned NumEntries) {
1079 for (unsigned i = 0; i != NumEntries; ++i) {
1080 unsigned TypeSlot = 0;
1081 if (read_typeid(TypeSlot))
1082 error("Invalid type in compaction table: type type");
1083 const Type *Typ = getGlobalTableType(TypeSlot);
1084 CompactionTypes.push_back(std::make_pair(Typ, TypeSlot));
1085 if (Handler) Handler->handleCompactionTableType(i, TypeSlot, Typ);
1089 /// Parse a compaction table.
1090 void BytecodeReader::ParseCompactionTable() {
1092 // Notify handler that we're beginning a compaction table.
1093 if (Handler) Handler->handleCompactionTableBegin();
1095 // In LLVM 1.3 Type no longer derives from Value. So,
1096 // we always write them first in the compaction table
1097 // because they can't occupy a "type plane" where the
1099 if (! hasTypeDerivedFromValue) {
1100 unsigned NumEntries = read_vbr_uint();
1101 ParseCompactionTypes(NumEntries);
1104 // Compaction tables live in separate blocks so we have to loop
1105 // until we've read the whole thing.
1106 while (moreInBlock()) {
1107 // Read the number of Value* entries in the compaction table
1108 unsigned NumEntries = read_vbr_uint();
1110 unsigned isTypeType = false;
1112 // Decode the type from value read in. Most compaction table
1113 // planes will have one or two entries in them. If that's the
1114 // case then the length is encoded in the bottom two bits and
1115 // the higher bits encode the type. This saves another VBR value.
1116 if ((NumEntries & 3) == 3) {
1117 // In this case, both low-order bits are set (value 3). This
1118 // is a signal that the typeid follows.
1120 isTypeType = read_typeid(Ty);
1122 // In this case, the low-order bits specify the number of entries
1123 // and the high order bits specify the type.
1124 Ty = NumEntries >> 2;
1125 isTypeType = sanitizeTypeId(Ty);
1129 // if we're reading a pre 1.3 bytecode file and the type plane
1130 // is the "type type", handle it here
1132 ParseCompactionTypes(NumEntries);
1134 // Make sure we have enough room for the plane.
1135 if (Ty >= CompactionValues.size())
1136 CompactionValues.resize(Ty+1);
1138 // Make sure the plane is empty or we have some kind of error.
1139 if (!CompactionValues[Ty].empty())
1140 error("Compaction table plane contains multiple entries!");
1142 // Notify handler about the plane.
1143 if (Handler) Handler->handleCompactionTablePlane(Ty, NumEntries);
1145 // Push the implicit zero.
1146 CompactionValues[Ty].push_back(Constant::getNullValue(getType(Ty)));
1148 // Read in each of the entries, put them in the compaction table
1149 // and notify the handler that we have a new compaction table value.
1150 for (unsigned i = 0; i != NumEntries; ++i) {
1151 unsigned ValSlot = read_vbr_uint();
1152 Value *V = getGlobalTableValue(Ty, ValSlot);
1153 CompactionValues[Ty].push_back(V);
1154 if (Handler) Handler->handleCompactionTableValue(i, Ty, ValSlot);
1158 // Notify handler that the compaction table is done.
1159 if (Handler) Handler->handleCompactionTableEnd();
1162 // Parse a single type. The typeid is read in first. If its a primitive type
1163 // then nothing else needs to be read, we know how to instantiate it. If its
1164 // a derived type, then additional data is read to fill out the type
1166 const Type *BytecodeReader::ParseType() {
1167 unsigned PrimType = 0;
1168 if (read_typeid(PrimType))
1169 error("Invalid type (type type) in type constants!");
1171 const Type *Result = 0;
1172 if ((Result = Type::getPrimitiveType((Type::TypeID)PrimType)))
1176 case Type::FunctionTyID: {
1177 const Type *RetType = readSanitizedType();
1179 unsigned NumParams = read_vbr_uint();
1181 std::vector<const Type*> Params;
1183 Params.push_back(readSanitizedType());
1185 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1186 if (isVarArg) Params.pop_back();
1188 Result = FunctionType::get(RetType, Params, isVarArg);
1191 case Type::ArrayTyID: {
1192 const Type *ElementType = readSanitizedType();
1193 unsigned NumElements = read_vbr_uint();
1194 Result = ArrayType::get(ElementType, NumElements);
1197 case Type::PackedTyID: {
1198 const Type *ElementType = readSanitizedType();
1199 unsigned NumElements = read_vbr_uint();
1200 Result = PackedType::get(ElementType, NumElements);
1203 case Type::StructTyID: {
1204 std::vector<const Type*> Elements;
1206 if (read_typeid(Typ))
1207 error("Invalid element type (type type) for structure!");
1209 while (Typ) { // List is terminated by void/0 typeid
1210 Elements.push_back(getType(Typ));
1211 if (read_typeid(Typ))
1212 error("Invalid element type (type type) for structure!");
1215 Result = StructType::get(Elements);
1218 case Type::PointerTyID: {
1219 Result = PointerType::get(readSanitizedType());
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 // Loop through reading all of the types. Forward types will make use of the
1258 // opaque types just inserted.
1260 for (unsigned i = 0; i != NumEntries; ++i) {
1261 const Type* NewTy = ParseType();
1262 const Type* OldTy = Tab[i].get();
1264 error("Couldn't parse type!");
1266 // Don't directly push the new type on the Tab. Instead we want to replace
1267 // the opaque type we previously inserted with the new concrete value. This
1268 // approach helps with forward references to types. The refinement from the
1269 // abstract (opaque) type to the new type causes all uses of the abstract
1270 // type to use the concrete type (NewTy). This will also cause the opaque
1271 // type to be deleted.
1272 cast<DerivedType>(const_cast<Type*>(OldTy))->refineAbstractTypeTo(NewTy);
1274 // This should have replaced the old opaque type with the new type in the
1275 // value table... or with a preexisting type that was already in the system.
1276 // Let's just make sure it did.
1277 assert(Tab[i] != OldTy && "refineAbstractType didn't work!");
1281 /// Parse a single constant value
1282 Constant *BytecodeReader::ParseConstantValue(unsigned TypeID) {
1283 // We must check for a ConstantExpr before switching by type because
1284 // a ConstantExpr can be of any type, and has no explicit value.
1286 // 0 if not expr; numArgs if is expr
1287 unsigned isExprNumArgs = read_vbr_uint();
1289 if (isExprNumArgs) {
1290 // 'undef' is encoded with 'exprnumargs' == 1.
1291 if (!hasNoUndefValue)
1292 if (--isExprNumArgs == 0)
1293 return UndefValue::get(getType(TypeID));
1295 // FIXME: Encoding of constant exprs could be much more compact!
1296 std::vector<Constant*> ArgVec;
1297 ArgVec.reserve(isExprNumArgs);
1298 unsigned Opcode = read_vbr_uint();
1300 // Bytecode files before LLVM 1.4 need have a missing terminator inst.
1301 if (hasNoUnreachableInst) Opcode++;
1303 // Read the slot number and types of each of the arguments
1304 for (unsigned i = 0; i != isExprNumArgs; ++i) {
1305 unsigned ArgValSlot = read_vbr_uint();
1306 unsigned ArgTypeSlot = 0;
1307 if (read_typeid(ArgTypeSlot))
1308 error("Invalid argument type (type type) for constant value");
1310 // Get the arg value from its slot if it exists, otherwise a placeholder
1311 ArgVec.push_back(getConstantValue(ArgTypeSlot, ArgValSlot));
1314 // Construct a ConstantExpr of the appropriate kind
1315 if (isExprNumArgs == 1) { // All one-operand expressions
1316 if (Opcode != Instruction::Cast)
1317 error("Only cast instruction has one argument for ConstantExpr");
1319 Constant* Result = ConstantExpr::getCast(ArgVec[0], getType(TypeID));
1320 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
1322 } else if (Opcode == Instruction::GetElementPtr) { // GetElementPtr
1323 std::vector<Constant*> IdxList(ArgVec.begin()+1, ArgVec.end());
1325 if (hasRestrictedGEPTypes) {
1326 const Type *BaseTy = ArgVec[0]->getType();
1327 generic_gep_type_iterator<std::vector<Constant*>::iterator>
1328 GTI = gep_type_begin(BaseTy, IdxList.begin(), IdxList.end()),
1329 E = gep_type_end(BaseTy, IdxList.begin(), IdxList.end());
1330 for (unsigned i = 0; GTI != E; ++GTI, ++i)
1331 if (isa<StructType>(*GTI)) {
1332 if (IdxList[i]->getType() != Type::UByteTy)
1333 error("Invalid index for getelementptr!");
1334 IdxList[i] = ConstantExpr::getCast(IdxList[i], Type::UIntTy);
1338 Constant* Result = ConstantExpr::getGetElementPtr(ArgVec[0], IdxList);
1339 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
1341 } else if (Opcode == Instruction::Select) {
1342 if (ArgVec.size() != 3)
1343 error("Select instruction must have three arguments.");
1344 Constant* Result = ConstantExpr::getSelect(ArgVec[0], ArgVec[1],
1346 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
1348 } else { // All other 2-operand expressions
1349 Constant* Result = ConstantExpr::get(Opcode, ArgVec[0], ArgVec[1]);
1350 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
1355 // Ok, not an ConstantExpr. We now know how to read the given type...
1356 const Type *Ty = getType(TypeID);
1357 switch (Ty->getTypeID()) {
1358 case Type::BoolTyID: {
1359 unsigned Val = read_vbr_uint();
1360 if (Val != 0 && Val != 1)
1361 error("Invalid boolean value read.");
1362 Constant* Result = ConstantBool::get(Val == 1);
1363 if (Handler) Handler->handleConstantValue(Result);
1367 case Type::UByteTyID: // Unsigned integer types...
1368 case Type::UShortTyID:
1369 case Type::UIntTyID: {
1370 unsigned Val = read_vbr_uint();
1371 if (!ConstantUInt::isValueValidForType(Ty, Val))
1372 error("Invalid unsigned byte/short/int read.");
1373 Constant* Result = ConstantUInt::get(Ty, Val);
1374 if (Handler) Handler->handleConstantValue(Result);
1378 case Type::ULongTyID: {
1379 Constant* Result = ConstantUInt::get(Ty, read_vbr_uint64());
1380 if (Handler) Handler->handleConstantValue(Result);
1384 case Type::SByteTyID: // Signed integer types...
1385 case Type::ShortTyID:
1386 case Type::IntTyID: {
1387 case Type::LongTyID:
1388 int64_t Val = read_vbr_int64();
1389 if (!ConstantSInt::isValueValidForType(Ty, Val))
1390 error("Invalid signed byte/short/int/long read.");
1391 Constant* Result = ConstantSInt::get(Ty, Val);
1392 if (Handler) Handler->handleConstantValue(Result);
1396 case Type::FloatTyID: {
1399 Constant* Result = ConstantFP::get(Ty, Val);
1400 if (Handler) Handler->handleConstantValue(Result);
1404 case Type::DoubleTyID: {
1407 Constant* Result = ConstantFP::get(Ty, Val);
1408 if (Handler) Handler->handleConstantValue(Result);
1412 case Type::ArrayTyID: {
1413 const ArrayType *AT = cast<ArrayType>(Ty);
1414 unsigned NumElements = AT->getNumElements();
1415 unsigned TypeSlot = getTypeSlot(AT->getElementType());
1416 std::vector<Constant*> Elements;
1417 Elements.reserve(NumElements);
1418 while (NumElements--) // Read all of the elements of the constant.
1419 Elements.push_back(getConstantValue(TypeSlot,
1421 Constant* Result = ConstantArray::get(AT, Elements);
1422 if (Handler) Handler->handleConstantArray(AT, Elements, TypeSlot, Result);
1426 case Type::StructTyID: {
1427 const StructType *ST = cast<StructType>(Ty);
1429 std::vector<Constant *> Elements;
1430 Elements.reserve(ST->getNumElements());
1431 for (unsigned i = 0; i != ST->getNumElements(); ++i)
1432 Elements.push_back(getConstantValue(ST->getElementType(i),
1435 Constant* Result = ConstantStruct::get(ST, Elements);
1436 if (Handler) Handler->handleConstantStruct(ST, Elements, Result);
1440 case Type::PackedTyID: {
1441 const PackedType *PT = cast<PackedType>(Ty);
1442 unsigned NumElements = PT->getNumElements();
1443 unsigned TypeSlot = getTypeSlot(PT->getElementType());
1444 std::vector<Constant*> Elements;
1445 Elements.reserve(NumElements);
1446 while (NumElements--) // Read all of the elements of the constant.
1447 Elements.push_back(getConstantValue(TypeSlot,
1449 Constant* Result = ConstantPacked::get(PT, Elements);
1450 if (Handler) Handler->handleConstantPacked(PT, Elements, TypeSlot, Result);
1454 case Type::PointerTyID: { // ConstantPointerRef value (backwards compat).
1455 const PointerType *PT = cast<PointerType>(Ty);
1456 unsigned Slot = read_vbr_uint();
1458 // Check to see if we have already read this global variable...
1459 Value *Val = getValue(TypeID, Slot, false);
1461 GlobalValue *GV = dyn_cast<GlobalValue>(Val);
1462 if (!GV) error("GlobalValue not in ValueTable!");
1463 if (Handler) Handler->handleConstantPointer(PT, Slot, GV);
1466 error("Forward references are not allowed here.");
1471 error("Don't know how to deserialize constant value of type '" +
1472 Ty->getDescription());
1478 /// Resolve references for constants. This function resolves the forward
1479 /// referenced constants in the ConstantFwdRefs map. It uses the
1480 /// replaceAllUsesWith method of Value class to substitute the placeholder
1481 /// instance with the actual instance.
1482 void BytecodeReader::ResolveReferencesToConstant(Constant *NewV, unsigned Slot){
1483 ConstantRefsType::iterator I =
1484 ConstantFwdRefs.find(std::make_pair(NewV->getType(), Slot));
1485 if (I == ConstantFwdRefs.end()) return; // Never forward referenced?
1487 Value *PH = I->second; // Get the placeholder...
1488 PH->replaceAllUsesWith(NewV);
1489 delete PH; // Delete the old placeholder
1490 ConstantFwdRefs.erase(I); // Remove the map entry for it
1493 /// Parse the constant strings section.
1494 void BytecodeReader::ParseStringConstants(unsigned NumEntries, ValueTable &Tab){
1495 for (; NumEntries; --NumEntries) {
1497 if (read_typeid(Typ))
1498 error("Invalid type (type type) for string constant");
1499 const Type *Ty = getType(Typ);
1500 if (!isa<ArrayType>(Ty))
1501 error("String constant data invalid!");
1503 const ArrayType *ATy = cast<ArrayType>(Ty);
1504 if (ATy->getElementType() != Type::SByteTy &&
1505 ATy->getElementType() != Type::UByteTy)
1506 error("String constant data invalid!");
1508 // Read character data. The type tells us how long the string is.
1509 char Data[ATy->getNumElements()];
1510 read_data(Data, Data+ATy->getNumElements());
1512 std::vector<Constant*> Elements(ATy->getNumElements());
1513 if (ATy->getElementType() == Type::SByteTy)
1514 for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
1515 Elements[i] = ConstantSInt::get(Type::SByteTy, (signed char)Data[i]);
1517 for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
1518 Elements[i] = ConstantUInt::get(Type::UByteTy, (unsigned char)Data[i]);
1520 // Create the constant, inserting it as needed.
1521 Constant *C = ConstantArray::get(ATy, Elements);
1522 unsigned Slot = insertValue(C, Typ, Tab);
1523 ResolveReferencesToConstant(C, Slot);
1524 if (Handler) Handler->handleConstantString(cast<ConstantArray>(C));
1528 /// Parse the constant pool.
1529 void BytecodeReader::ParseConstantPool(ValueTable &Tab,
1530 TypeListTy &TypeTab,
1532 if (Handler) Handler->handleGlobalConstantsBegin();
1534 /// In LLVM 1.3 Type does not derive from Value so the types
1535 /// do not occupy a plane. Consequently, we read the types
1536 /// first in the constant pool.
1537 if (isFunction && !hasTypeDerivedFromValue) {
1538 unsigned NumEntries = read_vbr_uint();
1539 ParseTypes(TypeTab, NumEntries);
1542 while (moreInBlock()) {
1543 unsigned NumEntries = read_vbr_uint();
1545 bool isTypeType = read_typeid(Typ);
1547 /// In LLVM 1.2 and before, Types were written to the
1548 /// bytecode file in the "Type Type" plane (#12).
1549 /// In 1.3 plane 12 is now the label plane. Handle this here.
1551 ParseTypes(TypeTab, NumEntries);
1552 } else if (Typ == Type::VoidTyID) {
1553 /// Use of Type::VoidTyID is a misnomer. It actually means
1554 /// that the following plane is constant strings
1555 assert(&Tab == &ModuleValues && "Cannot read strings in functions!");
1556 ParseStringConstants(NumEntries, Tab);
1558 for (unsigned i = 0; i < NumEntries; ++i) {
1559 Constant *C = ParseConstantValue(Typ);
1560 assert(C && "ParseConstantValue returned NULL!");
1561 unsigned Slot = insertValue(C, Typ, Tab);
1563 // If we are reading a function constant table, make sure that we adjust
1564 // the slot number to be the real global constant number.
1566 if (&Tab != &ModuleValues && Typ < ModuleValues.size() &&
1568 Slot += ModuleValues[Typ]->size();
1569 ResolveReferencesToConstant(C, Slot);
1574 // After we have finished parsing the constant pool, we had better not have
1575 // any dangling references left.
1576 if (!ConstantFwdRefs.empty()) {
1577 typedef std::map<std::pair<const Type*,unsigned>, Constant*> ConstantRefsType;
1578 ConstantRefsType::const_iterator I = ConstantFwdRefs.begin();
1579 const Type* missingType = I->first.first;
1580 Constant* missingConst = I->second;
1581 error(utostr(ConstantFwdRefs.size()) +
1582 " unresolved constant reference exist. First one is '" +
1583 missingConst->getName() + "' of type '" +
1584 missingType->getDescription() + "'.");
1587 checkPastBlockEnd("Constant Pool");
1588 if (Handler) Handler->handleGlobalConstantsEnd();
1591 /// Parse the contents of a function. Note that this function can be
1592 /// called lazily by materializeFunction
1593 /// @see materializeFunction
1594 void BytecodeReader::ParseFunctionBody(Function* F) {
1596 unsigned FuncSize = BlockEnd - At;
1597 GlobalValue::LinkageTypes Linkage = GlobalValue::ExternalLinkage;
1599 unsigned LinkageType = read_vbr_uint();
1600 switch (LinkageType) {
1601 case 0: Linkage = GlobalValue::ExternalLinkage; break;
1602 case 1: Linkage = GlobalValue::WeakLinkage; break;
1603 case 2: Linkage = GlobalValue::AppendingLinkage; break;
1604 case 3: Linkage = GlobalValue::InternalLinkage; break;
1605 case 4: Linkage = GlobalValue::LinkOnceLinkage; break;
1607 error("Invalid linkage type for Function.");
1608 Linkage = GlobalValue::InternalLinkage;
1612 F->setLinkage(Linkage);
1613 if (Handler) Handler->handleFunctionBegin(F,FuncSize);
1615 // Keep track of how many basic blocks we have read in...
1616 unsigned BlockNum = 0;
1617 bool InsertedArguments = false;
1619 BufPtr MyEnd = BlockEnd;
1620 while (At < MyEnd) {
1621 unsigned Type, Size;
1623 read_block(Type, Size);
1626 case BytecodeFormat::ConstantPoolBlockID:
1627 if (!InsertedArguments) {
1628 // Insert arguments into the value table before we parse the first basic
1629 // block in the function, but after we potentially read in the
1630 // compaction table.
1632 InsertedArguments = true;
1635 ParseConstantPool(FunctionValues, FunctionTypes, true);
1638 case BytecodeFormat::CompactionTableBlockID:
1639 ParseCompactionTable();
1642 case BytecodeFormat::BasicBlock: {
1643 if (!InsertedArguments) {
1644 // Insert arguments into the value table before we parse the first basic
1645 // block in the function, but after we potentially read in the
1646 // compaction table.
1648 InsertedArguments = true;
1651 BasicBlock *BB = ParseBasicBlock(BlockNum++);
1652 F->getBasicBlockList().push_back(BB);
1656 case BytecodeFormat::InstructionListBlockID: {
1657 // Insert arguments into the value table before we parse the instruction
1658 // list for the function, but after we potentially read in the compaction
1660 if (!InsertedArguments) {
1662 InsertedArguments = true;
1666 error("Already parsed basic blocks!");
1667 BlockNum = ParseInstructionList(F);
1671 case BytecodeFormat::SymbolTableBlockID:
1672 ParseSymbolTable(F, &F->getSymbolTable());
1678 error("Wrapped around reading bytecode.");
1683 // Malformed bc file if read past end of block.
1687 // Make sure there were no references to non-existant basic blocks.
1688 if (BlockNum != ParsedBasicBlocks.size())
1689 error("Illegal basic block operand reference");
1691 ParsedBasicBlocks.clear();
1693 // Resolve forward references. Replace any uses of a forward reference value
1694 // with the real value.
1695 while (!ForwardReferences.empty()) {
1696 std::map<std::pair<unsigned,unsigned>, Value*>::iterator
1697 I = ForwardReferences.begin();
1698 Value *V = getValue(I->first.first, I->first.second, false);
1699 Value *PlaceHolder = I->second;
1700 PlaceHolder->replaceAllUsesWith(V);
1701 ForwardReferences.erase(I);
1705 // Clear out function-level types...
1706 FunctionTypes.clear();
1707 CompactionTypes.clear();
1708 CompactionValues.clear();
1709 freeTable(FunctionValues);
1711 if (Handler) Handler->handleFunctionEnd(F);
1714 /// This function parses LLVM functions lazily. It obtains the type of the
1715 /// function and records where the body of the function is in the bytecode
1716 /// buffer. The caller can then use the ParseNextFunction and
1717 /// ParseAllFunctionBodies to get handler events for the functions.
1718 void BytecodeReader::ParseFunctionLazily() {
1719 if (FunctionSignatureList.empty())
1720 error("FunctionSignatureList empty!");
1722 Function *Func = FunctionSignatureList.back();
1723 FunctionSignatureList.pop_back();
1725 // Save the information for future reading of the function
1726 LazyFunctionLoadMap[Func] = LazyFunctionInfo(BlockStart, BlockEnd);
1728 // This function has a body but it's not loaded so it appears `External'.
1729 // Mark it as a `Ghost' instead to notify the users that it has a body.
1730 Func->setLinkage(GlobalValue::GhostLinkage);
1732 // Pretend we've `parsed' this function
1736 /// The ParserFunction method lazily parses one function. Use this method to
1737 /// casue the parser to parse a specific function in the module. Note that
1738 /// this will remove the function from what is to be included by
1739 /// ParseAllFunctionBodies.
1740 /// @see ParseAllFunctionBodies
1741 /// @see ParseBytecode
1742 void BytecodeReader::ParseFunction(Function* Func) {
1743 // Find {start, end} pointers and slot in the map. If not there, we're done.
1744 LazyFunctionMap::iterator Fi = LazyFunctionLoadMap.find(Func);
1746 // Make sure we found it
1747 if (Fi == LazyFunctionLoadMap.end()) {
1748 error("Unrecognized function of type " + Func->getType()->getDescription());
1752 BlockStart = At = Fi->second.Buf;
1753 BlockEnd = Fi->second.EndBuf;
1754 assert(Fi->first == Func && "Found wrong function?");
1756 LazyFunctionLoadMap.erase(Fi);
1758 this->ParseFunctionBody(Func);
1761 /// The ParseAllFunctionBodies method parses through all the previously
1762 /// unparsed functions in the bytecode file. If you want to completely parse
1763 /// a bytecode file, this method should be called after Parsebytecode because
1764 /// Parsebytecode only records the locations in the bytecode file of where
1765 /// the function definitions are located. This function uses that information
1766 /// to materialize the functions.
1767 /// @see ParseBytecode
1768 void BytecodeReader::ParseAllFunctionBodies() {
1769 LazyFunctionMap::iterator Fi = LazyFunctionLoadMap.begin();
1770 LazyFunctionMap::iterator Fe = LazyFunctionLoadMap.end();
1773 Function* Func = Fi->first;
1774 BlockStart = At = Fi->second.Buf;
1775 BlockEnd = Fi->second.EndBuf;
1776 this->ParseFunctionBody(Func);
1781 /// Parse the global type list
1782 void BytecodeReader::ParseGlobalTypes() {
1783 // Read the number of types
1784 unsigned NumEntries = read_vbr_uint();
1786 // Ignore the type plane identifier for types if the bc file is pre 1.3
1787 if (hasTypeDerivedFromValue)
1790 ParseTypes(ModuleTypes, NumEntries);
1793 /// Parse the Global info (types, global vars, constants)
1794 void BytecodeReader::ParseModuleGlobalInfo() {
1796 if (Handler) Handler->handleModuleGlobalsBegin();
1798 // Read global variables...
1799 unsigned VarType = read_vbr_uint();
1800 while (VarType != Type::VoidTyID) { // List is terminated by Void
1801 // VarType Fields: bit0 = isConstant, bit1 = hasInitializer, bit2,3,4 =
1802 // Linkage, bit4+ = slot#
1803 unsigned SlotNo = VarType >> 5;
1804 if (sanitizeTypeId(SlotNo))
1805 error("Invalid type (type type) for global var!");
1806 unsigned LinkageID = (VarType >> 2) & 7;
1807 bool isConstant = VarType & 1;
1808 bool hasInitializer = VarType & 2;
1809 GlobalValue::LinkageTypes Linkage;
1811 switch (LinkageID) {
1812 case 0: Linkage = GlobalValue::ExternalLinkage; break;
1813 case 1: Linkage = GlobalValue::WeakLinkage; break;
1814 case 2: Linkage = GlobalValue::AppendingLinkage; break;
1815 case 3: Linkage = GlobalValue::InternalLinkage; break;
1816 case 4: Linkage = GlobalValue::LinkOnceLinkage; break;
1818 error("Unknown linkage type: " + utostr(LinkageID));
1819 Linkage = GlobalValue::InternalLinkage;
1823 const Type *Ty = getType(SlotNo);
1825 error("Global has no type! SlotNo=" + utostr(SlotNo));
1828 if (!isa<PointerType>(Ty)) {
1829 error("Global not a pointer type! Ty= " + Ty->getDescription());
1832 const Type *ElTy = cast<PointerType>(Ty)->getElementType();
1834 // Create the global variable...
1835 GlobalVariable *GV = new GlobalVariable(ElTy, isConstant, Linkage,
1837 insertValue(GV, SlotNo, ModuleValues);
1839 unsigned initSlot = 0;
1840 if (hasInitializer) {
1841 initSlot = read_vbr_uint();
1842 GlobalInits.push_back(std::make_pair(GV, initSlot));
1845 // Notify handler about the global value.
1847 Handler->handleGlobalVariable(ElTy, isConstant, Linkage, SlotNo,initSlot);
1850 VarType = read_vbr_uint();
1853 // Read the function objects for all of the functions that are coming
1854 unsigned FnSignature = read_vbr_uint();
1856 if (hasNoFlagsForFunctions)
1857 FnSignature = (FnSignature << 5) + 1;
1859 // List is terminated by VoidTy.
1860 while ((FnSignature >> 5) != Type::VoidTyID) {
1861 const Type *Ty = getType(FnSignature >> 5);
1862 if (!isa<PointerType>(Ty) ||
1863 !isa<FunctionType>(cast<PointerType>(Ty)->getElementType())) {
1864 error("Function not a pointer to function type! Ty = " +
1865 Ty->getDescription());
1868 // We create functions by passing the underlying FunctionType to create...
1869 const FunctionType* FTy =
1870 cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
1873 // Insert the place holder.
1874 Function* Func = new Function(FTy, GlobalValue::ExternalLinkage,
1876 insertValue(Func, FnSignature >> 5, ModuleValues);
1878 // Flags are not used yet.
1879 unsigned Flags = FnSignature & 31;
1881 // Save this for later so we know type of lazily instantiated functions.
1882 // Note that known-external functions do not have FunctionInfo blocks, so we
1883 // do not add them to the FunctionSignatureList.
1884 if ((Flags & (1 << 4)) == 0)
1885 FunctionSignatureList.push_back(Func);
1887 if (Handler) Handler->handleFunctionDeclaration(Func);
1889 // Get the next function signature.
1890 FnSignature = read_vbr_uint();
1891 if (hasNoFlagsForFunctions)
1892 FnSignature = (FnSignature << 5) + 1;
1895 // Now that the function signature list is set up, reverse it so that we can
1896 // remove elements efficiently from the back of the vector.
1897 std::reverse(FunctionSignatureList.begin(), FunctionSignatureList.end());
1899 // If this bytecode format has dependent library information in it ..
1900 if (!hasNoDependentLibraries) {
1901 // Read in the number of dependent library items that follow
1902 unsigned num_dep_libs = read_vbr_uint();
1903 std::string dep_lib;
1904 while( num_dep_libs-- ) {
1905 dep_lib = read_str();
1906 TheModule->addLibrary(dep_lib);
1908 Handler->handleDependentLibrary(dep_lib);
1912 // Read target triple and place into the module
1913 std::string triple = read_str();
1914 TheModule->setTargetTriple(triple);
1916 Handler->handleTargetTriple(triple);
1919 if (hasInconsistentModuleGlobalInfo)
1922 // This is for future proofing... in the future extra fields may be added that
1923 // we don't understand, so we transparently ignore them.
1927 if (Handler) Handler->handleModuleGlobalsEnd();
1930 /// Parse the version information and decode it by setting flags on the
1931 /// Reader that enable backward compatibility of the reader.
1932 void BytecodeReader::ParseVersionInfo() {
1933 unsigned Version = read_vbr_uint();
1935 // Unpack version number: low four bits are for flags, top bits = version
1936 Module::Endianness Endianness;
1937 Module::PointerSize PointerSize;
1938 Endianness = (Version & 1) ? Module::BigEndian : Module::LittleEndian;
1939 PointerSize = (Version & 2) ? Module::Pointer64 : Module::Pointer32;
1941 bool hasNoEndianness = Version & 4;
1942 bool hasNoPointerSize = Version & 8;
1944 RevisionNum = Version >> 4;
1946 // Default values for the current bytecode version
1947 hasInconsistentModuleGlobalInfo = false;
1948 hasExplicitPrimitiveZeros = false;
1949 hasRestrictedGEPTypes = false;
1950 hasTypeDerivedFromValue = false;
1951 hasLongBlockHeaders = false;
1952 has32BitTypes = false;
1953 hasNoDependentLibraries = false;
1954 hasAlignment = false;
1955 hasInconsistentBBSlotNums = false;
1956 hasVBRByteTypes = false;
1957 hasUnnecessaryModuleBlockId = false;
1958 hasNoUndefValue = false;
1959 hasNoFlagsForFunctions = false;
1960 hasNoUnreachableInst = false;
1962 switch (RevisionNum) {
1963 case 0: // LLVM 1.0, 1.1 (Released)
1964 // Base LLVM 1.0 bytecode format.
1965 hasInconsistentModuleGlobalInfo = true;
1966 hasExplicitPrimitiveZeros = true;
1970 case 1: // LLVM 1.2 (Released)
1971 // LLVM 1.2 added explicit support for emitting strings efficiently.
1973 // Also, it fixed the problem where the size of the ModuleGlobalInfo block
1974 // included the size for the alignment at the end, where the rest of the
1977 // LLVM 1.2 and before required that GEP indices be ubyte constants for
1978 // structures and longs for sequential types.
1979 hasRestrictedGEPTypes = true;
1981 // LLVM 1.2 and before had the Type class derive from Value class. This
1982 // changed in release 1.3 and consequently LLVM 1.3 bytecode files are
1983 // written differently because Types can no longer be part of the
1984 // type planes for Values.
1985 hasTypeDerivedFromValue = true;
1989 case 2: // 1.2.5 (Not Released)
1991 // LLVM 1.2 and earlier had two-word block headers. This is a bit wasteful,
1992 // especially for small files where the 8 bytes per block is a large
1993 // fraction of the total block size. In LLVM 1.3, the block type and length
1994 // are compressed into a single 32-bit unsigned integer. 27 bits for length,
1995 // 5 bits for block type.
1996 hasLongBlockHeaders = true;
1998 // LLVM 1.2 and earlier wrote type slot numbers as vbr_uint32. In LLVM 1.3
1999 // this has been reduced to vbr_uint24. It shouldn't make much difference
2000 // since we haven't run into a module with > 24 million types, but for
2001 // safety the 24-bit restriction has been enforced in 1.3 to free some bits
2002 // in various places and to ensure consistency.
2003 has32BitTypes = true;
2005 // LLVM 1.2 and earlier did not provide a target triple nor a list of
2006 // libraries on which the bytecode is dependent. LLVM 1.3 provides these
2007 // features, for use in future versions of LLVM.
2008 hasNoDependentLibraries = true;
2012 case 3: // LLVM 1.3 (Released)
2013 // LLVM 1.3 and earlier caused alignment bytes to be written on some block
2014 // boundaries and at the end of some strings. In extreme cases (e.g. lots
2015 // of GEP references to a constant array), this can increase the file size
2016 // by 30% or more. In version 1.4 alignment is done away with completely.
2017 hasAlignment = true;
2021 case 4: // 1.3.1 (Not Released)
2022 // In version 4, we did not support the 'undef' constant.
2023 hasNoUndefValue = true;
2025 // In version 4 and above, we did not include space for flags for functions
2026 // in the module info block.
2027 hasNoFlagsForFunctions = true;
2029 // In version 4 and above, we did not include the 'unreachable' instruction
2030 // in the opcode numbering in the bytecode file.
2031 hasNoUnreachableInst = true;
2036 case 5: // 1.x.x (Not Released)
2038 // FIXME: NONE of this is implemented yet!
2040 // In version 5, basic blocks have a minimum index of 0 whereas all the
2041 // other primitives have a minimum index of 1 (because 0 is the "null"
2042 // value. In version 5, we made this consistent.
2043 hasInconsistentBBSlotNums = true;
2045 // In version 5, the types SByte and UByte were encoded as vbr_uint so that
2046 // signed values > 63 and unsigned values >127 would be encoded as two
2047 // bytes. In version 5, they are encoded directly in a single byte.
2048 hasVBRByteTypes = true;
2050 // In version 5, modules begin with a "Module Block" which encodes a 4-byte
2051 // integer value 0x01 to identify the module block. This is unnecessary and
2052 // removed in version 5.
2053 hasUnnecessaryModuleBlockId = true;
2056 error("Unknown bytecode version number: " + itostr(RevisionNum));
2059 if (hasNoEndianness) Endianness = Module::AnyEndianness;
2060 if (hasNoPointerSize) PointerSize = Module::AnyPointerSize;
2062 TheModule->setEndianness(Endianness);
2063 TheModule->setPointerSize(PointerSize);
2065 if (Handler) Handler->handleVersionInfo(RevisionNum, Endianness, PointerSize);
2068 /// Parse a whole module.
2069 void BytecodeReader::ParseModule() {
2070 unsigned Type, Size;
2072 FunctionSignatureList.clear(); // Just in case...
2074 // Read into instance variables...
2078 bool SeenModuleGlobalInfo = false;
2079 bool SeenGlobalTypePlane = false;
2080 BufPtr MyEnd = BlockEnd;
2081 while (At < MyEnd) {
2083 read_block(Type, Size);
2087 case BytecodeFormat::GlobalTypePlaneBlockID:
2088 if (SeenGlobalTypePlane)
2089 error("Two GlobalTypePlane Blocks Encountered!");
2093 SeenGlobalTypePlane = true;
2096 case BytecodeFormat::ModuleGlobalInfoBlockID:
2097 if (SeenModuleGlobalInfo)
2098 error("Two ModuleGlobalInfo Blocks Encountered!");
2099 ParseModuleGlobalInfo();
2100 SeenModuleGlobalInfo = true;
2103 case BytecodeFormat::ConstantPoolBlockID:
2104 ParseConstantPool(ModuleValues, ModuleTypes,false);
2107 case BytecodeFormat::FunctionBlockID:
2108 ParseFunctionLazily();
2111 case BytecodeFormat::SymbolTableBlockID:
2112 ParseSymbolTable(0, &TheModule->getSymbolTable());
2118 error("Unexpected Block of Type #" + utostr(Type) + " encountered!");
2126 // After the module constant pool has been read, we can safely initialize
2127 // global variables...
2128 while (!GlobalInits.empty()) {
2129 GlobalVariable *GV = GlobalInits.back().first;
2130 unsigned Slot = GlobalInits.back().second;
2131 GlobalInits.pop_back();
2133 // Look up the initializer value...
2134 // FIXME: Preserve this type ID!
2136 const llvm::PointerType* GVType = GV->getType();
2137 unsigned TypeSlot = getTypeSlot(GVType->getElementType());
2138 if (Constant *CV = getConstantValue(TypeSlot, Slot)) {
2139 if (GV->hasInitializer())
2140 error("Global *already* has an initializer?!");
2141 if (Handler) Handler->handleGlobalInitializer(GV,CV);
2142 GV->setInitializer(CV);
2144 error("Cannot find initializer value.");
2147 /// Make sure we pulled them all out. If we didn't then there's a declaration
2148 /// but a missing body. That's not allowed.
2149 if (!FunctionSignatureList.empty())
2150 error("Function declared, but bytecode stream ended before definition");
2153 /// This function completely parses a bytecode buffer given by the \p Buf
2154 /// and \p Length parameters.
2155 void BytecodeReader::ParseBytecode(BufPtr Buf, unsigned Length,
2156 const std::string &ModuleID) {
2160 At = MemStart = BlockStart = Buf;
2161 MemEnd = BlockEnd = Buf + Length;
2163 // Create the module
2164 TheModule = new Module(ModuleID);
2166 if (Handler) Handler->handleStart(TheModule, Length);
2168 // Read the four bytes of the signature.
2169 unsigned Sig = read_uint();
2171 // If this is a compressed file
2172 if (Sig == ('l' | ('l' << 8) | ('v' << 16) | ('c' << 24))) {
2174 // Invoke the decompression of the bytecode. Note that we have to skip the
2175 // file's magic number which is not part of the compressed block. Hence,
2176 // the Buf+4 and Length-4. The result goes into decompressedBlock, a data
2177 // member for retention until BytecodeReader is destructed.
2178 unsigned decompressedLength = Compressor::decompressToNewBuffer(
2179 (char*)Buf+4,Length-4,decompressedBlock);
2181 // We must adjust the buffer pointers used by the bytecode reader to point
2182 // into the new decompressed block. After decompression, the
2183 // decompressedBlock will point to a contiguous memory area that has
2184 // the decompressed data.
2185 At = MemStart = BlockStart = Buf = (BufPtr) decompressedBlock;
2186 MemEnd = BlockEnd = Buf + decompressedLength;
2188 // else if this isn't a regular (uncompressed) bytecode file, then its
2189 // and error, generate that now.
2190 } else if (Sig != ('l' | ('l' << 8) | ('v' << 16) | ('m' << 24))) {
2191 error("Invalid bytecode signature: " + utohexstr(Sig));
2194 // Tell the handler we're starting a module
2195 if (Handler) Handler->handleModuleBegin(ModuleID);
2197 // Get the module block and size and verify. This is handled specially
2198 // because the module block/size is always written in long format. Other
2199 // blocks are written in short format so the read_block method is used.
2200 unsigned Type, Size;
2203 if (Type != BytecodeFormat::ModuleBlockID) {
2204 error("Expected Module Block! Type:" + utostr(Type) + ", Size:"
2208 // It looks like the darwin ranlib program is broken, and adds trailing
2209 // garbage to the end of some bytecode files. This hack allows the bc
2210 // reader to ignore trailing garbage on bytecode files.
2211 if (At + Size < MemEnd)
2212 MemEnd = BlockEnd = At+Size;
2214 if (At + Size != MemEnd)
2215 error("Invalid Top Level Block Length! Type:" + utostr(Type)
2216 + ", Size:" + utostr(Size));
2218 // Parse the module contents
2219 this->ParseModule();
2221 // Check for missing functions
2223 error("Function expected, but bytecode stream ended!");
2225 // Tell the handler we're done with the module
2227 Handler->handleModuleEnd(ModuleID);
2229 // Tell the handler we're finished the parse
2230 if (Handler) Handler->handleFinish();
2232 } catch (std::string& errstr) {
2233 if (Handler) Handler->handleError(errstr);
2237 if (decompressedBlock != 0 ) {
2238 ::free(decompressedBlock);
2239 decompressedBlock = 0;
2243 std::string msg("Unknown Exception Occurred");
2244 if (Handler) Handler->handleError(msg);
2248 if (decompressedBlock != 0) {
2249 ::free(decompressedBlock);
2250 decompressedBlock = 0;
2256 //===----------------------------------------------------------------------===//
2257 //=== Default Implementations of Handler Methods
2258 //===----------------------------------------------------------------------===//
2260 BytecodeHandler::~BytecodeHandler() {}