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/ADT/StringExtras.h"
36 /// @brief A class for maintaining the slot number definition
37 /// as a placeholder for the actual definition for forward constants defs.
38 class ConstantPlaceHolder : public ConstantExpr {
39 ConstantPlaceHolder(); // DO NOT IMPLEMENT
40 void operator=(const ConstantPlaceHolder &); // DO NOT IMPLEMENT
43 ConstantPlaceHolder(const Type *Ty)
44 : ConstantExpr(Ty, Instruction::UserOp1, &Op, 1),
45 Op(UndefValue::get(Type::IntTy), this) {
50 // Provide some details on error
51 inline void BytecodeReader::error(std::string err) {
53 err += itostr(RevisionNum) ;
55 err += itostr(At-MemStart);
60 //===----------------------------------------------------------------------===//
61 // Bytecode Reading Methods
62 //===----------------------------------------------------------------------===//
64 /// Determine if the current block being read contains any more data.
65 inline bool BytecodeReader::moreInBlock() {
69 /// Throw an error if we've read past the end of the current block
70 inline void BytecodeReader::checkPastBlockEnd(const char * block_name) {
72 error(std::string("Attempt to read past the end of ") + block_name +
76 /// Align the buffer position to a 32 bit boundary
77 inline void BytecodeReader::align32() {
80 At = (const unsigned char *)((unsigned long)(At+3) & (~3UL));
82 if (Handler) Handler->handleAlignment(At - Save);
84 error("Ran out of data while aligning!");
88 /// Read a whole unsigned integer
89 inline unsigned BytecodeReader::read_uint() {
91 error("Ran out of data reading uint!");
93 return At[-4] | (At[-3] << 8) | (At[-2] << 16) | (At[-1] << 24);
96 /// Read a variable-bit-rate encoded unsigned integer
97 inline unsigned BytecodeReader::read_vbr_uint() {
104 error("Ran out of data reading vbr_uint!");
105 Result |= (unsigned)((*At++) & 0x7F) << Shift;
107 } while (At[-1] & 0x80);
108 if (Handler) Handler->handleVBR32(At-Save);
112 /// Read a variable-bit-rate encoded unsigned 64-bit integer.
113 inline uint64_t BytecodeReader::read_vbr_uint64() {
120 error("Ran out of data reading vbr_uint64!");
121 Result |= (uint64_t)((*At++) & 0x7F) << Shift;
123 } while (At[-1] & 0x80);
124 if (Handler) Handler->handleVBR64(At-Save);
128 /// Read a variable-bit-rate encoded signed 64-bit integer.
129 inline int64_t BytecodeReader::read_vbr_int64() {
130 uint64_t R = read_vbr_uint64();
133 return -(int64_t)(R >> 1);
134 else // There is no such thing as -0 with integers. "-0" really means
135 // 0x8000000000000000.
138 return (int64_t)(R >> 1);
141 /// Read a pascal-style string (length followed by text)
142 inline std::string BytecodeReader::read_str() {
143 unsigned Size = read_vbr_uint();
144 const unsigned char *OldAt = At;
146 if (At > BlockEnd) // Size invalid?
147 error("Ran out of data reading a string!");
148 return std::string((char*)OldAt, Size);
151 /// Read an arbitrary block of data
152 inline void BytecodeReader::read_data(void *Ptr, void *End) {
153 unsigned char *Start = (unsigned char *)Ptr;
154 unsigned Amount = (unsigned char *)End - Start;
155 if (At+Amount > BlockEnd)
156 error("Ran out of data!");
157 std::copy(At, At+Amount, Start);
161 /// Read a float value in little-endian order
162 inline void BytecodeReader::read_float(float& FloatVal) {
163 /// FIXME: This isn't optimal, it has size problems on some platforms
164 /// where FP is not IEEE.
169 FloatUnion.i = At[0] | (At[1] << 8) | (At[2] << 16) | (At[3] << 24);
170 At+=sizeof(uint32_t);
171 FloatVal = FloatUnion.f;
174 /// Read a double value in little-endian order
175 inline void BytecodeReader::read_double(double& DoubleVal) {
176 /// FIXME: This isn't optimal, it has size problems on some platforms
177 /// where FP is not IEEE.
182 DoubleUnion.i = (uint64_t(At[0]) << 0) | (uint64_t(At[1]) << 8) |
183 (uint64_t(At[2]) << 16) | (uint64_t(At[3]) << 24) |
184 (uint64_t(At[4]) << 32) | (uint64_t(At[5]) << 40) |
185 (uint64_t(At[6]) << 48) | (uint64_t(At[7]) << 56);
186 At+=sizeof(uint64_t);
187 DoubleVal = DoubleUnion.d;
190 /// Read a block header and obtain its type and size
191 inline void BytecodeReader::read_block(unsigned &Type, unsigned &Size) {
192 if ( hasLongBlockHeaders ) {
196 case BytecodeFormat::Reserved_DoNotUse :
197 error("Reserved_DoNotUse used as Module Type?");
198 Type = BytecodeFormat::ModuleBlockID; break;
199 case BytecodeFormat::Module:
200 Type = BytecodeFormat::ModuleBlockID; break;
201 case BytecodeFormat::Function:
202 Type = BytecodeFormat::FunctionBlockID; break;
203 case BytecodeFormat::ConstantPool:
204 Type = BytecodeFormat::ConstantPoolBlockID; break;
205 case BytecodeFormat::SymbolTable:
206 Type = BytecodeFormat::SymbolTableBlockID; break;
207 case BytecodeFormat::ModuleGlobalInfo:
208 Type = BytecodeFormat::ModuleGlobalInfoBlockID; break;
209 case BytecodeFormat::GlobalTypePlane:
210 Type = BytecodeFormat::GlobalTypePlaneBlockID; break;
211 case BytecodeFormat::InstructionList:
212 Type = BytecodeFormat::InstructionListBlockID; break;
213 case BytecodeFormat::CompactionTable:
214 Type = BytecodeFormat::CompactionTableBlockID; break;
215 case BytecodeFormat::BasicBlock:
216 /// This block type isn't used after version 1.1. However, we have to
217 /// still allow the value in case this is an old bc format file.
218 /// We just let its value creep thru.
221 error("Invalid block id found: " + utostr(Type));
226 Type = Size & 0x1F; // mask low order five bits
227 Size >>= 5; // get rid of five low order bits, leaving high 27
230 if (At + Size > BlockEnd)
231 error("Attempt to size a block past end of memory");
232 BlockEnd = At + Size;
233 if (Handler) Handler->handleBlock(Type, BlockStart, Size);
237 /// In LLVM 1.2 and before, Types were derived from Value and so they were
238 /// written as part of the type planes along with any other Value. In LLVM
239 /// 1.3 this changed so that Type does not derive from Value. Consequently,
240 /// the BytecodeReader's containers for Values can't contain Types because
241 /// there's no inheritance relationship. This means that the "Type Type"
242 /// plane is defunct along with the Type::TypeTyID TypeID. In LLVM 1.3
243 /// whenever a bytecode construct must have both types and values together,
244 /// the types are always read/written first and then the Values. Furthermore
245 /// since Type::TypeTyID no longer exists, its value (12) now corresponds to
246 /// Type::LabelTyID. In order to overcome this we must "sanitize" all the
247 /// type TypeIDs we encounter. For LLVM 1.3 bytecode files, there's no change.
248 /// For LLVM 1.2 and before, this function will decrement the type id by
249 /// one to account for the missing Type::TypeTyID enumerator if the value is
250 /// larger than 12 (Type::LabelTyID). If the value is exactly 12, then this
251 /// function returns true, otherwise false. This helps detect situations
252 /// where the pre 1.3 bytecode is indicating that what follows is a type.
253 /// @returns true iff type id corresponds to pre 1.3 "type type"
254 inline bool BytecodeReader::sanitizeTypeId(unsigned &TypeId) {
255 if (hasTypeDerivedFromValue) { /// do nothing if 1.3 or later
256 if (TypeId == Type::LabelTyID) {
257 TypeId = Type::VoidTyID; // sanitize it
258 return true; // indicate we got TypeTyID in pre 1.3 bytecode
259 } else if (TypeId > Type::LabelTyID)
260 --TypeId; // shift all planes down because type type plane is missing
265 /// Reads a vbr uint to read in a type id and does the necessary
266 /// conversion on it by calling sanitizeTypeId.
267 /// @returns true iff \p TypeId read corresponds to a pre 1.3 "type type"
268 /// @see sanitizeTypeId
269 inline bool BytecodeReader::read_typeid(unsigned &TypeId) {
270 TypeId = read_vbr_uint();
271 if ( !has32BitTypes )
272 if ( TypeId == 0x00FFFFFF )
273 TypeId = read_vbr_uint();
274 return sanitizeTypeId(TypeId);
277 //===----------------------------------------------------------------------===//
279 //===----------------------------------------------------------------------===//
281 /// Determine if a type id has an implicit null value
282 inline bool BytecodeReader::hasImplicitNull(unsigned TyID) {
283 if (!hasExplicitPrimitiveZeros)
284 return TyID != Type::LabelTyID && TyID != Type::VoidTyID;
285 return TyID >= Type::FirstDerivedTyID;
288 /// Obtain a type given a typeid and account for things like compaction tables,
289 /// function level vs module level, and the offsetting for the primitive types.
290 const Type *BytecodeReader::getType(unsigned ID) {
291 if (ID < Type::FirstDerivedTyID)
292 if (const Type *T = Type::getPrimitiveType((Type::TypeID)ID))
293 return T; // Asked for a primitive type...
295 // Otherwise, derived types need offset...
296 ID -= Type::FirstDerivedTyID;
298 if (!CompactionTypes.empty()) {
299 if (ID >= CompactionTypes.size())
300 error("Type ID out of range for compaction table!");
301 return CompactionTypes[ID].first;
304 // Is it a module-level type?
305 if (ID < ModuleTypes.size())
306 return ModuleTypes[ID].get();
308 // Nope, is it a function-level type?
309 ID -= ModuleTypes.size();
310 if (ID < FunctionTypes.size())
311 return FunctionTypes[ID].get();
313 error("Illegal type reference!");
317 /// Get a sanitized type id. This just makes sure that the \p ID
318 /// is both sanitized and not the "type type" of pre-1.3 bytecode.
319 /// @see sanitizeTypeId
320 inline const Type* BytecodeReader::getSanitizedType(unsigned& ID) {
321 if (sanitizeTypeId(ID))
322 error("Invalid type id encountered");
326 /// This method just saves some coding. It uses read_typeid to read
327 /// in a sanitized type id, errors that its not the type type, and
328 /// then calls getType to return the type value.
329 inline const Type* BytecodeReader::readSanitizedType() {
332 error("Invalid type id encountered");
336 /// Get the slot number associated with a type accounting for primitive
337 /// types, compaction tables, and function level vs module level.
338 unsigned BytecodeReader::getTypeSlot(const Type *Ty) {
339 if (Ty->isPrimitiveType())
340 return Ty->getTypeID();
342 // Scan the compaction table for the type if needed.
343 if (!CompactionTypes.empty()) {
344 for (unsigned i = 0, e = CompactionTypes.size(); i != e; ++i)
345 if (CompactionTypes[i].first == Ty)
346 return Type::FirstDerivedTyID + i;
348 error("Couldn't find type specified in compaction table!");
351 // Check the function level types first...
352 TypeListTy::iterator I = std::find(FunctionTypes.begin(),
353 FunctionTypes.end(), Ty);
355 if (I != FunctionTypes.end())
356 return Type::FirstDerivedTyID + ModuleTypes.size() +
357 (&*I - &FunctionTypes[0]);
359 // Check the module level types now...
360 I = std::find(ModuleTypes.begin(), ModuleTypes.end(), Ty);
361 if (I == ModuleTypes.end())
362 error("Didn't find type in ModuleTypes.");
363 return Type::FirstDerivedTyID + (&*I - &ModuleTypes[0]);
366 /// This is just like getType, but when a compaction table is in use, it is
367 /// ignored. It also ignores function level types.
369 const Type *BytecodeReader::getGlobalTableType(unsigned Slot) {
370 if (Slot < Type::FirstDerivedTyID) {
371 const Type *Ty = Type::getPrimitiveType((Type::TypeID)Slot);
373 error("Not a primitive type ID?");
376 Slot -= Type::FirstDerivedTyID;
377 if (Slot >= ModuleTypes.size())
378 error("Illegal compaction table type reference!");
379 return ModuleTypes[Slot];
382 /// This is just like getTypeSlot, but when a compaction table is in use, it
383 /// is ignored. It also ignores function level types.
384 unsigned BytecodeReader::getGlobalTableTypeSlot(const Type *Ty) {
385 if (Ty->isPrimitiveType())
386 return Ty->getTypeID();
387 TypeListTy::iterator I = std::find(ModuleTypes.begin(),
388 ModuleTypes.end(), Ty);
389 if (I == ModuleTypes.end())
390 error("Didn't find type in ModuleTypes.");
391 return Type::FirstDerivedTyID + (&*I - &ModuleTypes[0]);
394 /// Retrieve a value of a given type and slot number, possibly creating
395 /// it if it doesn't already exist.
396 Value * BytecodeReader::getValue(unsigned type, unsigned oNum, bool Create) {
397 assert(type != Type::LabelTyID && "getValue() cannot get blocks!");
400 // If there is a compaction table active, it defines the low-level numbers.
401 // If not, the module values define the low-level numbers.
402 if (CompactionValues.size() > type && !CompactionValues[type].empty()) {
403 if (Num < CompactionValues[type].size())
404 return CompactionValues[type][Num];
405 Num -= CompactionValues[type].size();
407 // By default, the global type id is the type id passed in
408 unsigned GlobalTyID = type;
410 // If the type plane was compactified, figure out the global type ID by
411 // adding the derived type ids and the distance.
412 if (!CompactionTypes.empty() && type >= Type::FirstDerivedTyID)
413 GlobalTyID = CompactionTypes[type-Type::FirstDerivedTyID].second;
415 if (hasImplicitNull(GlobalTyID)) {
416 const Type *Ty = getType(type);
417 if (!isa<OpaqueType>(Ty)) {
419 return Constant::getNullValue(Ty);
424 if (GlobalTyID < ModuleValues.size() && ModuleValues[GlobalTyID]) {
425 if (Num < ModuleValues[GlobalTyID]->size())
426 return ModuleValues[GlobalTyID]->getOperand(Num);
427 Num -= ModuleValues[GlobalTyID]->size();
431 if (FunctionValues.size() > type &&
432 FunctionValues[type] &&
433 Num < FunctionValues[type]->size())
434 return FunctionValues[type]->getOperand(Num);
436 if (!Create) return 0; // Do not create a placeholder?
438 // Did we already create a place holder?
439 std::pair<unsigned,unsigned> KeyValue(type, oNum);
440 ForwardReferenceMap::iterator I = ForwardReferences.lower_bound(KeyValue);
441 if (I != ForwardReferences.end() && I->first == KeyValue)
442 return I->second; // We have already created this placeholder
444 // If the type exists (it should)
445 if (const Type* Ty = getType(type)) {
446 // Create the place holder
447 Value *Val = new Argument(Ty);
448 ForwardReferences.insert(I, std::make_pair(KeyValue, Val));
451 throw "Can't create placeholder for value of type slot #" + utostr(type);
454 /// This is just like getValue, but when a compaction table is in use, it
455 /// is ignored. Also, no forward references or other fancy features are
457 Value* BytecodeReader::getGlobalTableValue(unsigned TyID, unsigned SlotNo) {
459 return Constant::getNullValue(getType(TyID));
461 if (!CompactionTypes.empty() && TyID >= Type::FirstDerivedTyID) {
462 TyID -= Type::FirstDerivedTyID;
463 if (TyID >= CompactionTypes.size())
464 error("Type ID out of range for compaction table!");
465 TyID = CompactionTypes[TyID].second;
470 if (TyID >= ModuleValues.size() || ModuleValues[TyID] == 0 ||
471 SlotNo >= ModuleValues[TyID]->size()) {
472 if (TyID >= ModuleValues.size() || ModuleValues[TyID] == 0)
473 error("Corrupt compaction table entry!"
474 + utostr(TyID) + ", " + utostr(SlotNo) + ": "
475 + utostr(ModuleValues.size()));
477 error("Corrupt compaction table entry!"
478 + utostr(TyID) + ", " + utostr(SlotNo) + ": "
479 + utostr(ModuleValues.size()) + ", "
480 + utohexstr(reinterpret_cast<uint64_t>(((void*)ModuleValues[TyID])))
482 + utostr(ModuleValues[TyID]->size()));
484 return ModuleValues[TyID]->getOperand(SlotNo);
487 /// Just like getValue, except that it returns a null pointer
488 /// only on error. It always returns a constant (meaning that if the value is
489 /// defined, but is not a constant, that is an error). If the specified
490 /// constant hasn't been parsed yet, a placeholder is defined and used.
491 /// Later, after the real value is parsed, the placeholder is eliminated.
492 Constant* BytecodeReader::getConstantValue(unsigned TypeSlot, unsigned Slot) {
493 if (Value *V = getValue(TypeSlot, Slot, false))
494 if (Constant *C = dyn_cast<Constant>(V))
495 return C; // If we already have the value parsed, just return it
497 error("Value for slot " + utostr(Slot) +
498 " is expected to be a constant!");
500 std::pair<unsigned, unsigned> Key(TypeSlot, 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(getType(TypeSlot));
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) && !isa<OpaqueType>(Val->getType());
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::arg_iterator AI = F->arg_begin();
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 32: { //VANext_old
662 const Type* ArgTy = getValue(iType, Oprnds[0])->getType();
663 Function* NF = TheModule->getOrInsertFunction("llvm.va_copy", ArgTy, ArgTy, 0);
666 //foo = alloca 1 of t
671 AllocaInst* foo = new AllocaInst(ArgTy, 0, "vanext.fix");
672 BB->getInstList().push_back(foo);
673 CallInst* bar = new CallInst(NF, getValue(iType, Oprnds[0]));
674 BB->getInstList().push_back(bar);
675 BB->getInstList().push_back(new StoreInst(bar, foo));
676 Instruction* tmp = new VAArgInst(foo, getSanitizedType(Oprnds[1]));
677 BB->getInstList().push_back(tmp);
678 Result = new LoadInst(foo);
681 case 33: { //VAArg_old
682 const Type* ArgTy = getValue(iType, Oprnds[0])->getType();
683 Function* NF = TheModule->getOrInsertFunction("llvm.va_copy", ArgTy, ArgTy, 0);
686 //foo = alloca 1 of t
690 AllocaInst* foo = new AllocaInst(ArgTy, 0, "vaarg.fix");
691 BB->getInstList().push_back(foo);
692 CallInst* bar = new CallInst(NF, getValue(iType, Oprnds[0]));
693 BB->getInstList().push_back(bar);
694 BB->getInstList().push_back(new StoreInst(bar, foo));
695 Result = new VAArgInst(foo, getSanitizedType(Oprnds[1]));
698 case Instruction::Cast:
699 Result = new CastInst(getValue(iType, Oprnds[0]),
700 getSanitizedType(Oprnds[1]));
702 case Instruction::Select:
703 Result = new SelectInst(getValue(Type::BoolTyID, Oprnds[0]),
704 getValue(iType, Oprnds[1]),
705 getValue(iType, Oprnds[2]));
707 case Instruction::PHI: {
708 if (Oprnds.size() == 0 || (Oprnds.size() & 1))
709 error("Invalid phi node encountered!");
711 PHINode *PN = new PHINode(InstTy);
712 PN->reserveOperandSpace(Oprnds.size());
713 for (unsigned i = 0, e = Oprnds.size(); i != e; i += 2)
714 PN->addIncoming(getValue(iType, Oprnds[i]), getBasicBlock(Oprnds[i+1]));
719 case Instruction::Shl:
720 case Instruction::Shr:
721 Result = new ShiftInst((Instruction::OtherOps)Opcode,
722 getValue(iType, Oprnds[0]),
723 getValue(Type::UByteTyID, Oprnds[1]));
725 case Instruction::Ret:
726 if (Oprnds.size() == 0)
727 Result = new ReturnInst();
728 else if (Oprnds.size() == 1)
729 Result = new ReturnInst(getValue(iType, Oprnds[0]));
731 error("Unrecognized instruction!");
734 case Instruction::Br:
735 if (Oprnds.size() == 1)
736 Result = new BranchInst(getBasicBlock(Oprnds[0]));
737 else if (Oprnds.size() == 3)
738 Result = new BranchInst(getBasicBlock(Oprnds[0]),
739 getBasicBlock(Oprnds[1]), getValue(Type::BoolTyID , Oprnds[2]));
741 error("Invalid number of operands for a 'br' instruction!");
743 case Instruction::Switch: {
744 if (Oprnds.size() & 1)
745 error("Switch statement with odd number of arguments!");
747 SwitchInst *I = new SwitchInst(getValue(iType, Oprnds[0]),
748 getBasicBlock(Oprnds[1]),
750 for (unsigned i = 2, e = Oprnds.size(); i != e; i += 2)
751 I->addCase(cast<ConstantInt>(getValue(iType, Oprnds[i])),
752 getBasicBlock(Oprnds[i+1]));
757 case 58: // Call with extra operand for calling conv
758 case 59: // tail call, Fast CC
759 case 60: // normal call, Fast CC
760 case 61: // tail call, C Calling Conv
761 case Instruction::Call: { // Normal Call, C Calling Convention
762 if (Oprnds.size() == 0)
763 error("Invalid call instruction encountered!");
765 Value *F = getValue(iType, Oprnds[0]);
767 unsigned CallingConv = CallingConv::C;
768 bool isTailCall = false;
770 if (Opcode == 61 || Opcode == 59)
773 // Check to make sure we have a pointer to function type
774 const PointerType *PTy = dyn_cast<PointerType>(F->getType());
775 if (PTy == 0) error("Call to non function pointer value!");
776 const FunctionType *FTy = dyn_cast<FunctionType>(PTy->getElementType());
777 if (FTy == 0) error("Call to non function pointer value!");
779 std::vector<Value *> Params;
780 if (!FTy->isVarArg()) {
781 FunctionType::param_iterator It = FTy->param_begin();
784 isTailCall = Oprnds.back() & 1;
785 CallingConv = Oprnds.back() >> 1;
787 } else if (Opcode == 59 || Opcode == 60)
788 CallingConv = CallingConv::Fast;
790 for (unsigned i = 1, e = Oprnds.size(); i != e; ++i) {
791 if (It == FTy->param_end())
792 error("Invalid call instruction!");
793 Params.push_back(getValue(getTypeSlot(*It++), Oprnds[i]));
795 if (It != FTy->param_end())
796 error("Invalid call instruction!");
798 Oprnds.erase(Oprnds.begin(), Oprnds.begin()+1);
800 unsigned FirstVariableOperand;
801 if (Oprnds.size() < FTy->getNumParams())
802 error("Call instruction missing operands!");
804 // Read all of the fixed arguments
805 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
806 Params.push_back(getValue(getTypeSlot(FTy->getParamType(i)),Oprnds[i]));
808 FirstVariableOperand = FTy->getNumParams();
810 if ((Oprnds.size()-FirstVariableOperand) & 1)
811 error("Invalid call instruction!"); // Must be pairs of type/value
813 for (unsigned i = FirstVariableOperand, e = Oprnds.size();
815 Params.push_back(getValue(Oprnds[i], Oprnds[i+1]));
818 Result = new CallInst(F, Params);
819 if (isTailCall) cast<CallInst>(Result)->setTailCall();
820 if (CallingConv) cast<CallInst>(Result)->setCallingConv(CallingConv);
823 case 56: // Invoke with encoded CC
824 case 57: // Invoke Fast CC
825 case Instruction::Invoke: { // Invoke C CC
826 if (Oprnds.size() < 3)
827 error("Invalid invoke instruction!");
828 Value *F = getValue(iType, Oprnds[0]);
830 // Check to make sure we have a pointer to function type
831 const PointerType *PTy = dyn_cast<PointerType>(F->getType());
833 error("Invoke to non function pointer value!");
834 const FunctionType *FTy = dyn_cast<FunctionType>(PTy->getElementType());
836 error("Invoke to non function pointer value!");
838 std::vector<Value *> Params;
839 BasicBlock *Normal, *Except;
840 unsigned CallingConv = CallingConv::C;
843 CallingConv = CallingConv::Fast;
844 else if (Opcode == 56) {
845 CallingConv = Oprnds.back();
849 if (!FTy->isVarArg()) {
850 Normal = getBasicBlock(Oprnds[1]);
851 Except = getBasicBlock(Oprnds[2]);
853 FunctionType::param_iterator It = FTy->param_begin();
854 for (unsigned i = 3, e = Oprnds.size(); i != e; ++i) {
855 if (It == FTy->param_end())
856 error("Invalid invoke instruction!");
857 Params.push_back(getValue(getTypeSlot(*It++), Oprnds[i]));
859 if (It != FTy->param_end())
860 error("Invalid invoke instruction!");
862 Oprnds.erase(Oprnds.begin(), Oprnds.begin()+1);
864 Normal = getBasicBlock(Oprnds[0]);
865 Except = getBasicBlock(Oprnds[1]);
867 unsigned FirstVariableArgument = FTy->getNumParams()+2;
868 for (unsigned i = 2; i != FirstVariableArgument; ++i)
869 Params.push_back(getValue(getTypeSlot(FTy->getParamType(i-2)),
872 if (Oprnds.size()-FirstVariableArgument & 1) // Must be type/value pairs
873 error("Invalid invoke instruction!");
875 for (unsigned i = FirstVariableArgument; i < Oprnds.size(); i += 2)
876 Params.push_back(getValue(Oprnds[i], Oprnds[i+1]));
879 Result = new InvokeInst(F, Normal, Except, Params);
880 if (CallingConv) cast<InvokeInst>(Result)->setCallingConv(CallingConv);
883 case Instruction::Malloc:
884 if (Oprnds.size() > 2)
885 error("Invalid malloc instruction!");
886 if (!isa<PointerType>(InstTy))
887 error("Invalid malloc instruction!");
889 Result = new MallocInst(cast<PointerType>(InstTy)->getElementType(),
890 Oprnds.size() ? getValue(Type::UIntTyID,
894 case Instruction::Alloca:
895 if (Oprnds.size() > 2)
896 error("Invalid alloca instruction!");
897 if (!isa<PointerType>(InstTy))
898 error("Invalid alloca instruction!");
900 Result = new AllocaInst(cast<PointerType>(InstTy)->getElementType(),
901 Oprnds.size() ? getValue(Type::UIntTyID,
904 case Instruction::Free:
905 if (!isa<PointerType>(InstTy))
906 error("Invalid free instruction!");
907 Result = new FreeInst(getValue(iType, Oprnds[0]));
909 case Instruction::GetElementPtr: {
910 if (Oprnds.size() == 0 || !isa<PointerType>(InstTy))
911 error("Invalid getelementptr instruction!");
913 std::vector<Value*> Idx;
915 const Type *NextTy = InstTy;
916 for (unsigned i = 1, e = Oprnds.size(); i != e; ++i) {
917 const CompositeType *TopTy = dyn_cast_or_null<CompositeType>(NextTy);
919 error("Invalid getelementptr instruction!");
921 unsigned ValIdx = Oprnds[i];
923 if (!hasRestrictedGEPTypes) {
924 // Struct indices are always uints, sequential type indices can be any
925 // of the 32 or 64-bit integer types. The actual choice of type is
926 // encoded in the low two bits of the slot number.
927 if (isa<StructType>(TopTy))
928 IdxTy = Type::UIntTyID;
930 switch (ValIdx & 3) {
932 case 0: IdxTy = Type::UIntTyID; break;
933 case 1: IdxTy = Type::IntTyID; break;
934 case 2: IdxTy = Type::ULongTyID; break;
935 case 3: IdxTy = Type::LongTyID; break;
940 IdxTy = isa<StructType>(TopTy) ? Type::UByteTyID : Type::LongTyID;
943 Idx.push_back(getValue(IdxTy, ValIdx));
945 // Convert ubyte struct indices into uint struct indices.
946 if (isa<StructType>(TopTy) && hasRestrictedGEPTypes)
947 if (ConstantUInt *C = dyn_cast<ConstantUInt>(Idx.back()))
948 Idx[Idx.size()-1] = ConstantExpr::getCast(C, Type::UIntTy);
950 NextTy = GetElementPtrInst::getIndexedType(InstTy, Idx, true);
953 Result = new GetElementPtrInst(getValue(iType, Oprnds[0]), Idx);
957 case 62: // volatile load
958 case Instruction::Load:
959 if (Oprnds.size() != 1 || !isa<PointerType>(InstTy))
960 error("Invalid load instruction!");
961 Result = new LoadInst(getValue(iType, Oprnds[0]), "", Opcode == 62);
964 case 63: // volatile store
965 case Instruction::Store: {
966 if (!isa<PointerType>(InstTy) || Oprnds.size() != 2)
967 error("Invalid store instruction!");
969 Value *Ptr = getValue(iType, Oprnds[1]);
970 const Type *ValTy = cast<PointerType>(Ptr->getType())->getElementType();
971 Result = new StoreInst(getValue(getTypeSlot(ValTy), Oprnds[0]), Ptr,
975 case Instruction::Unwind:
976 if (Oprnds.size() != 0) error("Invalid unwind instruction!");
977 Result = new UnwindInst();
979 case Instruction::Unreachable:
980 if (Oprnds.size() != 0) error("Invalid unreachable instruction!");
981 Result = new UnreachableInst();
983 } // end switch(Opcode)
986 if (Result->getType() == InstTy)
989 TypeSlot = getTypeSlot(Result->getType());
991 insertValue(Result, TypeSlot, FunctionValues);
992 BB->getInstList().push_back(Result);
995 /// Get a particular numbered basic block, which might be a forward reference.
996 /// This works together with ParseBasicBlock to handle these forward references
997 /// in a clean manner. This function is used when constructing phi, br, switch,
998 /// and other instructions that reference basic blocks. Blocks are numbered
999 /// sequentially as they appear in the function.
1000 BasicBlock *BytecodeReader::getBasicBlock(unsigned ID) {
1001 // Make sure there is room in the table...
1002 if (ParsedBasicBlocks.size() <= ID) ParsedBasicBlocks.resize(ID+1);
1004 // First check to see if this is a backwards reference, i.e., ParseBasicBlock
1005 // has already created this block, or if the forward reference has already
1007 if (ParsedBasicBlocks[ID])
1008 return ParsedBasicBlocks[ID];
1010 // Otherwise, the basic block has not yet been created. Do so and add it to
1011 // the ParsedBasicBlocks list.
1012 return ParsedBasicBlocks[ID] = new BasicBlock();
1015 /// In LLVM 1.0 bytecode files, we used to output one basicblock at a time.
1016 /// This method reads in one of the basicblock packets. This method is not used
1017 /// for bytecode files after LLVM 1.0
1018 /// @returns The basic block constructed.
1019 BasicBlock *BytecodeReader::ParseBasicBlock(unsigned BlockNo) {
1020 if (Handler) Handler->handleBasicBlockBegin(BlockNo);
1024 if (ParsedBasicBlocks.size() == BlockNo)
1025 ParsedBasicBlocks.push_back(BB = new BasicBlock());
1026 else if (ParsedBasicBlocks[BlockNo] == 0)
1027 BB = ParsedBasicBlocks[BlockNo] = new BasicBlock();
1029 BB = ParsedBasicBlocks[BlockNo];
1031 std::vector<unsigned> Operands;
1032 while (moreInBlock())
1033 ParseInstruction(Operands, BB);
1035 if (Handler) Handler->handleBasicBlockEnd(BlockNo);
1039 /// Parse all of the BasicBlock's & Instruction's in the body of a function.
1040 /// In post 1.0 bytecode files, we no longer emit basic block individually,
1041 /// in order to avoid per-basic-block overhead.
1042 /// @returns Rhe number of basic blocks encountered.
1043 unsigned BytecodeReader::ParseInstructionList(Function* F) {
1044 unsigned BlockNo = 0;
1045 std::vector<unsigned> Args;
1047 while (moreInBlock()) {
1048 if (Handler) Handler->handleBasicBlockBegin(BlockNo);
1050 if (ParsedBasicBlocks.size() == BlockNo)
1051 ParsedBasicBlocks.push_back(BB = new BasicBlock());
1052 else if (ParsedBasicBlocks[BlockNo] == 0)
1053 BB = ParsedBasicBlocks[BlockNo] = new BasicBlock();
1055 BB = ParsedBasicBlocks[BlockNo];
1057 F->getBasicBlockList().push_back(BB);
1059 // Read instructions into this basic block until we get to a terminator
1060 while (moreInBlock() && !BB->getTerminator())
1061 ParseInstruction(Args, BB);
1063 if (!BB->getTerminator())
1064 error("Non-terminated basic block found!");
1066 if (Handler) Handler->handleBasicBlockEnd(BlockNo-1);
1072 /// Parse a symbol table. This works for both module level and function
1073 /// level symbol tables. For function level symbol tables, the CurrentFunction
1074 /// parameter must be non-zero and the ST parameter must correspond to
1075 /// CurrentFunction's symbol table. For Module level symbol tables, the
1076 /// CurrentFunction argument must be zero.
1077 void BytecodeReader::ParseSymbolTable(Function *CurrentFunction,
1079 if (Handler) Handler->handleSymbolTableBegin(CurrentFunction,ST);
1081 // Allow efficient basic block lookup by number.
1082 std::vector<BasicBlock*> BBMap;
1083 if (CurrentFunction)
1084 for (Function::iterator I = CurrentFunction->begin(),
1085 E = CurrentFunction->end(); I != E; ++I)
1088 /// In LLVM 1.3 we write types separately from values so
1089 /// The types are always first in the symbol table. This is
1090 /// because Type no longer derives from Value.
1091 if (!hasTypeDerivedFromValue) {
1092 // Symtab block header: [num entries]
1093 unsigned NumEntries = read_vbr_uint();
1094 for (unsigned i = 0; i < NumEntries; ++i) {
1095 // Symtab entry: [def slot #][name]
1096 unsigned slot = read_vbr_uint();
1097 std::string Name = read_str();
1098 const Type* T = getType(slot);
1099 ST->insert(Name, T);
1103 while (moreInBlock()) {
1104 // Symtab block header: [num entries][type id number]
1105 unsigned NumEntries = read_vbr_uint();
1107 bool isTypeType = read_typeid(Typ);
1108 const Type *Ty = getType(Typ);
1110 for (unsigned i = 0; i != NumEntries; ++i) {
1111 // Symtab entry: [def slot #][name]
1112 unsigned slot = read_vbr_uint();
1113 std::string Name = read_str();
1115 // if we're reading a pre 1.3 bytecode file and the type plane
1116 // is the "type type", handle it here
1118 const Type* T = getType(slot);
1120 error("Failed type look-up for name '" + Name + "'");
1121 ST->insert(Name, T);
1122 continue; // code below must be short circuited
1125 if (Typ == Type::LabelTyID) {
1126 if (slot < BBMap.size())
1129 V = getValue(Typ, slot, false); // Find mapping...
1132 error("Failed value look-up for name '" + Name + "'");
1137 checkPastBlockEnd("Symbol Table");
1138 if (Handler) Handler->handleSymbolTableEnd();
1141 /// Read in the types portion of a compaction table.
1142 void BytecodeReader::ParseCompactionTypes(unsigned NumEntries) {
1143 for (unsigned i = 0; i != NumEntries; ++i) {
1144 unsigned TypeSlot = 0;
1145 if (read_typeid(TypeSlot))
1146 error("Invalid type in compaction table: type type");
1147 const Type *Typ = getGlobalTableType(TypeSlot);
1148 CompactionTypes.push_back(std::make_pair(Typ, TypeSlot));
1149 if (Handler) Handler->handleCompactionTableType(i, TypeSlot, Typ);
1153 /// Parse a compaction table.
1154 void BytecodeReader::ParseCompactionTable() {
1156 // Notify handler that we're beginning a compaction table.
1157 if (Handler) Handler->handleCompactionTableBegin();
1159 // In LLVM 1.3 Type no longer derives from Value. So,
1160 // we always write them first in the compaction table
1161 // because they can't occupy a "type plane" where the
1163 if (! hasTypeDerivedFromValue) {
1164 unsigned NumEntries = read_vbr_uint();
1165 ParseCompactionTypes(NumEntries);
1168 // Compaction tables live in separate blocks so we have to loop
1169 // until we've read the whole thing.
1170 while (moreInBlock()) {
1171 // Read the number of Value* entries in the compaction table
1172 unsigned NumEntries = read_vbr_uint();
1174 unsigned isTypeType = false;
1176 // Decode the type from value read in. Most compaction table
1177 // planes will have one or two entries in them. If that's the
1178 // case then the length is encoded in the bottom two bits and
1179 // the higher bits encode the type. This saves another VBR value.
1180 if ((NumEntries & 3) == 3) {
1181 // In this case, both low-order bits are set (value 3). This
1182 // is a signal that the typeid follows.
1184 isTypeType = read_typeid(Ty);
1186 // In this case, the low-order bits specify the number of entries
1187 // and the high order bits specify the type.
1188 Ty = NumEntries >> 2;
1189 isTypeType = sanitizeTypeId(Ty);
1193 // if we're reading a pre 1.3 bytecode file and the type plane
1194 // is the "type type", handle it here
1196 ParseCompactionTypes(NumEntries);
1198 // Make sure we have enough room for the plane.
1199 if (Ty >= CompactionValues.size())
1200 CompactionValues.resize(Ty+1);
1202 // Make sure the plane is empty or we have some kind of error.
1203 if (!CompactionValues[Ty].empty())
1204 error("Compaction table plane contains multiple entries!");
1206 // Notify handler about the plane.
1207 if (Handler) Handler->handleCompactionTablePlane(Ty, NumEntries);
1209 // Push the implicit zero.
1210 CompactionValues[Ty].push_back(Constant::getNullValue(getType(Ty)));
1212 // Read in each of the entries, put them in the compaction table
1213 // and notify the handler that we have a new compaction table value.
1214 for (unsigned i = 0; i != NumEntries; ++i) {
1215 unsigned ValSlot = read_vbr_uint();
1216 Value *V = getGlobalTableValue(Ty, ValSlot);
1217 CompactionValues[Ty].push_back(V);
1218 if (Handler) Handler->handleCompactionTableValue(i, Ty, ValSlot);
1222 // Notify handler that the compaction table is done.
1223 if (Handler) Handler->handleCompactionTableEnd();
1226 // Parse a single type. The typeid is read in first. If its a primitive type
1227 // then nothing else needs to be read, we know how to instantiate it. If its
1228 // a derived type, then additional data is read to fill out the type
1230 const Type *BytecodeReader::ParseType() {
1231 unsigned PrimType = 0;
1232 if (read_typeid(PrimType))
1233 error("Invalid type (type type) in type constants!");
1235 const Type *Result = 0;
1236 if ((Result = Type::getPrimitiveType((Type::TypeID)PrimType)))
1240 case Type::FunctionTyID: {
1241 const Type *RetType = readSanitizedType();
1243 unsigned NumParams = read_vbr_uint();
1245 std::vector<const Type*> Params;
1247 Params.push_back(readSanitizedType());
1249 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1250 if (isVarArg) Params.pop_back();
1252 Result = FunctionType::get(RetType, Params, isVarArg);
1255 case Type::ArrayTyID: {
1256 const Type *ElementType = readSanitizedType();
1257 unsigned NumElements = read_vbr_uint();
1258 Result = ArrayType::get(ElementType, NumElements);
1261 case Type::PackedTyID: {
1262 const Type *ElementType = readSanitizedType();
1263 unsigned NumElements = read_vbr_uint();
1264 Result = PackedType::get(ElementType, NumElements);
1267 case Type::StructTyID: {
1268 std::vector<const Type*> Elements;
1270 if (read_typeid(Typ))
1271 error("Invalid element type (type type) for structure!");
1273 while (Typ) { // List is terminated by void/0 typeid
1274 Elements.push_back(getType(Typ));
1275 if (read_typeid(Typ))
1276 error("Invalid element type (type type) for structure!");
1279 Result = StructType::get(Elements);
1282 case Type::PointerTyID: {
1283 Result = PointerType::get(readSanitizedType());
1287 case Type::OpaqueTyID: {
1288 Result = OpaqueType::get();
1293 error("Don't know how to deserialize primitive type " + utostr(PrimType));
1296 if (Handler) Handler->handleType(Result);
1300 // ParseTypes - We have to use this weird code to handle recursive
1301 // types. We know that recursive types will only reference the current slab of
1302 // values in the type plane, but they can forward reference types before they
1303 // have been read. For example, Type #0 might be '{ Ty#1 }' and Type #1 might
1304 // be 'Ty#0*'. When reading Type #0, type number one doesn't exist. To fix
1305 // this ugly problem, we pessimistically insert an opaque type for each type we
1306 // are about to read. This means that forward references will resolve to
1307 // something and when we reread the type later, we can replace the opaque type
1308 // with a new resolved concrete type.
1310 void BytecodeReader::ParseTypes(TypeListTy &Tab, unsigned NumEntries){
1311 assert(Tab.size() == 0 && "should not have read type constants in before!");
1313 // Insert a bunch of opaque types to be resolved later...
1314 Tab.reserve(NumEntries);
1315 for (unsigned i = 0; i != NumEntries; ++i)
1316 Tab.push_back(OpaqueType::get());
1319 Handler->handleTypeList(NumEntries);
1321 // Loop through reading all of the types. Forward types will make use of the
1322 // opaque types just inserted.
1324 for (unsigned i = 0; i != NumEntries; ++i) {
1325 const Type* NewTy = ParseType();
1326 const Type* OldTy = Tab[i].get();
1328 error("Couldn't parse type!");
1330 // Don't directly push the new type on the Tab. Instead we want to replace
1331 // the opaque type we previously inserted with the new concrete value. This
1332 // approach helps with forward references to types. The refinement from the
1333 // abstract (opaque) type to the new type causes all uses of the abstract
1334 // type to use the concrete type (NewTy). This will also cause the opaque
1335 // type to be deleted.
1336 cast<DerivedType>(const_cast<Type*>(OldTy))->refineAbstractTypeTo(NewTy);
1338 // This should have replaced the old opaque type with the new type in the
1339 // value table... or with a preexisting type that was already in the system.
1340 // Let's just make sure it did.
1341 assert(Tab[i] != OldTy && "refineAbstractType didn't work!");
1345 /// Parse a single constant value
1346 Constant *BytecodeReader::ParseConstantValue(unsigned TypeID) {
1347 // We must check for a ConstantExpr before switching by type because
1348 // a ConstantExpr can be of any type, and has no explicit value.
1350 // 0 if not expr; numArgs if is expr
1351 unsigned isExprNumArgs = read_vbr_uint();
1353 if (isExprNumArgs) {
1354 // 'undef' is encoded with 'exprnumargs' == 1.
1355 if (!hasNoUndefValue)
1356 if (--isExprNumArgs == 0)
1357 return UndefValue::get(getType(TypeID));
1359 // FIXME: Encoding of constant exprs could be much more compact!
1360 std::vector<Constant*> ArgVec;
1361 ArgVec.reserve(isExprNumArgs);
1362 unsigned Opcode = read_vbr_uint();
1364 // Bytecode files before LLVM 1.4 need have a missing terminator inst.
1365 if (hasNoUnreachableInst) Opcode++;
1367 // Read the slot number and types of each of the arguments
1368 for (unsigned i = 0; i != isExprNumArgs; ++i) {
1369 unsigned ArgValSlot = read_vbr_uint();
1370 unsigned ArgTypeSlot = 0;
1371 if (read_typeid(ArgTypeSlot))
1372 error("Invalid argument type (type type) for constant value");
1374 // Get the arg value from its slot if it exists, otherwise a placeholder
1375 ArgVec.push_back(getConstantValue(ArgTypeSlot, ArgValSlot));
1378 // Construct a ConstantExpr of the appropriate kind
1379 if (isExprNumArgs == 1) { // All one-operand expressions
1380 if (Opcode != Instruction::Cast)
1381 error("Only cast instruction has one argument for ConstantExpr");
1383 Constant* Result = ConstantExpr::getCast(ArgVec[0], getType(TypeID));
1384 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
1386 } else if (Opcode == Instruction::GetElementPtr) { // GetElementPtr
1387 std::vector<Constant*> IdxList(ArgVec.begin()+1, ArgVec.end());
1389 if (hasRestrictedGEPTypes) {
1390 const Type *BaseTy = ArgVec[0]->getType();
1391 generic_gep_type_iterator<std::vector<Constant*>::iterator>
1392 GTI = gep_type_begin(BaseTy, IdxList.begin(), IdxList.end()),
1393 E = gep_type_end(BaseTy, IdxList.begin(), IdxList.end());
1394 for (unsigned i = 0; GTI != E; ++GTI, ++i)
1395 if (isa<StructType>(*GTI)) {
1396 if (IdxList[i]->getType() != Type::UByteTy)
1397 error("Invalid index for getelementptr!");
1398 IdxList[i] = ConstantExpr::getCast(IdxList[i], Type::UIntTy);
1402 Constant* Result = ConstantExpr::getGetElementPtr(ArgVec[0], IdxList);
1403 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
1405 } else if (Opcode == Instruction::Select) {
1406 if (ArgVec.size() != 3)
1407 error("Select instruction must have three arguments.");
1408 Constant* Result = ConstantExpr::getSelect(ArgVec[0], ArgVec[1],
1410 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
1412 } else { // All other 2-operand expressions
1413 Constant* Result = ConstantExpr::get(Opcode, ArgVec[0], ArgVec[1]);
1414 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
1419 // Ok, not an ConstantExpr. We now know how to read the given type...
1420 const Type *Ty = getType(TypeID);
1421 switch (Ty->getTypeID()) {
1422 case Type::BoolTyID: {
1423 unsigned Val = read_vbr_uint();
1424 if (Val != 0 && Val != 1)
1425 error("Invalid boolean value read.");
1426 Constant* Result = ConstantBool::get(Val == 1);
1427 if (Handler) Handler->handleConstantValue(Result);
1431 case Type::UByteTyID: // Unsigned integer types...
1432 case Type::UShortTyID:
1433 case Type::UIntTyID: {
1434 unsigned Val = read_vbr_uint();
1435 if (!ConstantUInt::isValueValidForType(Ty, Val))
1436 error("Invalid unsigned byte/short/int read.");
1437 Constant* Result = ConstantUInt::get(Ty, Val);
1438 if (Handler) Handler->handleConstantValue(Result);
1442 case Type::ULongTyID: {
1443 Constant* Result = ConstantUInt::get(Ty, read_vbr_uint64());
1444 if (Handler) Handler->handleConstantValue(Result);
1448 case Type::SByteTyID: // Signed integer types...
1449 case Type::ShortTyID:
1450 case Type::IntTyID: {
1451 case Type::LongTyID:
1452 int64_t Val = read_vbr_int64();
1453 if (!ConstantSInt::isValueValidForType(Ty, Val))
1454 error("Invalid signed byte/short/int/long read.");
1455 Constant* Result = ConstantSInt::get(Ty, Val);
1456 if (Handler) Handler->handleConstantValue(Result);
1460 case Type::FloatTyID: {
1463 Constant* Result = ConstantFP::get(Ty, Val);
1464 if (Handler) Handler->handleConstantValue(Result);
1468 case Type::DoubleTyID: {
1471 Constant* Result = ConstantFP::get(Ty, Val);
1472 if (Handler) Handler->handleConstantValue(Result);
1476 case Type::ArrayTyID: {
1477 const ArrayType *AT = cast<ArrayType>(Ty);
1478 unsigned NumElements = AT->getNumElements();
1479 unsigned TypeSlot = getTypeSlot(AT->getElementType());
1480 std::vector<Constant*> Elements;
1481 Elements.reserve(NumElements);
1482 while (NumElements--) // Read all of the elements of the constant.
1483 Elements.push_back(getConstantValue(TypeSlot,
1485 Constant* Result = ConstantArray::get(AT, Elements);
1486 if (Handler) Handler->handleConstantArray(AT, Elements, TypeSlot, Result);
1490 case Type::StructTyID: {
1491 const StructType *ST = cast<StructType>(Ty);
1493 std::vector<Constant *> Elements;
1494 Elements.reserve(ST->getNumElements());
1495 for (unsigned i = 0; i != ST->getNumElements(); ++i)
1496 Elements.push_back(getConstantValue(ST->getElementType(i),
1499 Constant* Result = ConstantStruct::get(ST, Elements);
1500 if (Handler) Handler->handleConstantStruct(ST, Elements, Result);
1504 case Type::PackedTyID: {
1505 const PackedType *PT = cast<PackedType>(Ty);
1506 unsigned NumElements = PT->getNumElements();
1507 unsigned TypeSlot = getTypeSlot(PT->getElementType());
1508 std::vector<Constant*> Elements;
1509 Elements.reserve(NumElements);
1510 while (NumElements--) // Read all of the elements of the constant.
1511 Elements.push_back(getConstantValue(TypeSlot,
1513 Constant* Result = ConstantPacked::get(PT, Elements);
1514 if (Handler) Handler->handleConstantPacked(PT, Elements, TypeSlot, Result);
1518 case Type::PointerTyID: { // ConstantPointerRef value (backwards compat).
1519 const PointerType *PT = cast<PointerType>(Ty);
1520 unsigned Slot = read_vbr_uint();
1522 // Check to see if we have already read this global variable...
1523 Value *Val = getValue(TypeID, Slot, false);
1525 GlobalValue *GV = dyn_cast<GlobalValue>(Val);
1526 if (!GV) error("GlobalValue not in ValueTable!");
1527 if (Handler) Handler->handleConstantPointer(PT, Slot, GV);
1530 error("Forward references are not allowed here.");
1535 error("Don't know how to deserialize constant value of type '" +
1536 Ty->getDescription());
1542 /// Resolve references for constants. This function resolves the forward
1543 /// referenced constants in the ConstantFwdRefs map. It uses the
1544 /// replaceAllUsesWith method of Value class to substitute the placeholder
1545 /// instance with the actual instance.
1546 void BytecodeReader::ResolveReferencesToConstant(Constant *NewV, unsigned Typ,
1548 ConstantRefsType::iterator I =
1549 ConstantFwdRefs.find(std::make_pair(Typ, Slot));
1550 if (I == ConstantFwdRefs.end()) return; // Never forward referenced?
1552 Value *PH = I->second; // Get the placeholder...
1553 PH->replaceAllUsesWith(NewV);
1554 delete PH; // Delete the old placeholder
1555 ConstantFwdRefs.erase(I); // Remove the map entry for it
1558 /// Parse the constant strings section.
1559 void BytecodeReader::ParseStringConstants(unsigned NumEntries, ValueTable &Tab){
1560 for (; NumEntries; --NumEntries) {
1562 if (read_typeid(Typ))
1563 error("Invalid type (type type) for string constant");
1564 const Type *Ty = getType(Typ);
1565 if (!isa<ArrayType>(Ty))
1566 error("String constant data invalid!");
1568 const ArrayType *ATy = cast<ArrayType>(Ty);
1569 if (ATy->getElementType() != Type::SByteTy &&
1570 ATy->getElementType() != Type::UByteTy)
1571 error("String constant data invalid!");
1573 // Read character data. The type tells us how long the string is.
1574 char *Data = reinterpret_cast<char *>(alloca(ATy->getNumElements()));
1575 read_data(Data, Data+ATy->getNumElements());
1577 std::vector<Constant*> Elements(ATy->getNumElements());
1578 if (ATy->getElementType() == Type::SByteTy)
1579 for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
1580 Elements[i] = ConstantSInt::get(Type::SByteTy, (signed char)Data[i]);
1582 for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
1583 Elements[i] = ConstantUInt::get(Type::UByteTy, (unsigned char)Data[i]);
1585 // Create the constant, inserting it as needed.
1586 Constant *C = ConstantArray::get(ATy, Elements);
1587 unsigned Slot = insertValue(C, Typ, Tab);
1588 ResolveReferencesToConstant(C, Typ, Slot);
1589 if (Handler) Handler->handleConstantString(cast<ConstantArray>(C));
1593 /// Parse the constant pool.
1594 void BytecodeReader::ParseConstantPool(ValueTable &Tab,
1595 TypeListTy &TypeTab,
1597 if (Handler) Handler->handleGlobalConstantsBegin();
1599 /// In LLVM 1.3 Type does not derive from Value so the types
1600 /// do not occupy a plane. Consequently, we read the types
1601 /// first in the constant pool.
1602 if (isFunction && !hasTypeDerivedFromValue) {
1603 unsigned NumEntries = read_vbr_uint();
1604 ParseTypes(TypeTab, NumEntries);
1607 while (moreInBlock()) {
1608 unsigned NumEntries = read_vbr_uint();
1610 bool isTypeType = read_typeid(Typ);
1612 /// In LLVM 1.2 and before, Types were written to the
1613 /// bytecode file in the "Type Type" plane (#12).
1614 /// In 1.3 plane 12 is now the label plane. Handle this here.
1616 ParseTypes(TypeTab, NumEntries);
1617 } else if (Typ == Type::VoidTyID) {
1618 /// Use of Type::VoidTyID is a misnomer. It actually means
1619 /// that the following plane is constant strings
1620 assert(&Tab == &ModuleValues && "Cannot read strings in functions!");
1621 ParseStringConstants(NumEntries, Tab);
1623 for (unsigned i = 0; i < NumEntries; ++i) {
1624 Constant *C = ParseConstantValue(Typ);
1625 assert(C && "ParseConstantValue returned NULL!");
1626 unsigned Slot = insertValue(C, Typ, Tab);
1628 // If we are reading a function constant table, make sure that we adjust
1629 // the slot number to be the real global constant number.
1631 if (&Tab != &ModuleValues && Typ < ModuleValues.size() &&
1633 Slot += ModuleValues[Typ]->size();
1634 ResolveReferencesToConstant(C, Typ, Slot);
1639 // After we have finished parsing the constant pool, we had better not have
1640 // any dangling references left.
1641 if (!ConstantFwdRefs.empty()) {
1642 ConstantRefsType::const_iterator I = ConstantFwdRefs.begin();
1643 Constant* missingConst = I->second;
1644 error(utostr(ConstantFwdRefs.size()) +
1645 " unresolved constant reference exist. First one is '" +
1646 missingConst->getName() + "' of type '" +
1647 missingConst->getType()->getDescription() + "'.");
1650 checkPastBlockEnd("Constant Pool");
1651 if (Handler) Handler->handleGlobalConstantsEnd();
1654 /// Parse the contents of a function. Note that this function can be
1655 /// called lazily by materializeFunction
1656 /// @see materializeFunction
1657 void BytecodeReader::ParseFunctionBody(Function* F) {
1659 unsigned FuncSize = BlockEnd - At;
1660 GlobalValue::LinkageTypes Linkage = GlobalValue::ExternalLinkage;
1662 unsigned LinkageType = read_vbr_uint();
1663 switch (LinkageType) {
1664 case 0: Linkage = GlobalValue::ExternalLinkage; break;
1665 case 1: Linkage = GlobalValue::WeakLinkage; break;
1666 case 2: Linkage = GlobalValue::AppendingLinkage; break;
1667 case 3: Linkage = GlobalValue::InternalLinkage; break;
1668 case 4: Linkage = GlobalValue::LinkOnceLinkage; break;
1670 error("Invalid linkage type for Function.");
1671 Linkage = GlobalValue::InternalLinkage;
1675 F->setLinkage(Linkage);
1676 if (Handler) Handler->handleFunctionBegin(F,FuncSize);
1678 // Keep track of how many basic blocks we have read in...
1679 unsigned BlockNum = 0;
1680 bool InsertedArguments = false;
1682 BufPtr MyEnd = BlockEnd;
1683 while (At < MyEnd) {
1684 unsigned Type, Size;
1686 read_block(Type, Size);
1689 case BytecodeFormat::ConstantPoolBlockID:
1690 if (!InsertedArguments) {
1691 // Insert arguments into the value table before we parse the first basic
1692 // block in the function, but after we potentially read in the
1693 // compaction table.
1695 InsertedArguments = true;
1698 ParseConstantPool(FunctionValues, FunctionTypes, true);
1701 case BytecodeFormat::CompactionTableBlockID:
1702 ParseCompactionTable();
1705 case BytecodeFormat::BasicBlock: {
1706 if (!InsertedArguments) {
1707 // Insert arguments into the value table before we parse the first basic
1708 // block in the function, but after we potentially read in the
1709 // compaction table.
1711 InsertedArguments = true;
1714 BasicBlock *BB = ParseBasicBlock(BlockNum++);
1715 F->getBasicBlockList().push_back(BB);
1719 case BytecodeFormat::InstructionListBlockID: {
1720 // Insert arguments into the value table before we parse the instruction
1721 // list for the function, but after we potentially read in the compaction
1723 if (!InsertedArguments) {
1725 InsertedArguments = true;
1729 error("Already parsed basic blocks!");
1730 BlockNum = ParseInstructionList(F);
1734 case BytecodeFormat::SymbolTableBlockID:
1735 ParseSymbolTable(F, &F->getSymbolTable());
1741 error("Wrapped around reading bytecode.");
1746 // Malformed bc file if read past end of block.
1750 // Make sure there were no references to non-existant basic blocks.
1751 if (BlockNum != ParsedBasicBlocks.size())
1752 error("Illegal basic block operand reference");
1754 ParsedBasicBlocks.clear();
1756 // Resolve forward references. Replace any uses of a forward reference value
1757 // with the real value.
1758 while (!ForwardReferences.empty()) {
1759 std::map<std::pair<unsigned,unsigned>, Value*>::iterator
1760 I = ForwardReferences.begin();
1761 Value *V = getValue(I->first.first, I->first.second, false);
1762 Value *PlaceHolder = I->second;
1763 PlaceHolder->replaceAllUsesWith(V);
1764 ForwardReferences.erase(I);
1768 // Clear out function-level types...
1769 FunctionTypes.clear();
1770 CompactionTypes.clear();
1771 CompactionValues.clear();
1772 freeTable(FunctionValues);
1774 if (Handler) Handler->handleFunctionEnd(F);
1777 /// This function parses LLVM functions lazily. It obtains the type of the
1778 /// function and records where the body of the function is in the bytecode
1779 /// buffer. The caller can then use the ParseNextFunction and
1780 /// ParseAllFunctionBodies to get handler events for the functions.
1781 void BytecodeReader::ParseFunctionLazily() {
1782 if (FunctionSignatureList.empty())
1783 error("FunctionSignatureList empty!");
1785 Function *Func = FunctionSignatureList.back();
1786 FunctionSignatureList.pop_back();
1788 // Save the information for future reading of the function
1789 LazyFunctionLoadMap[Func] = LazyFunctionInfo(BlockStart, BlockEnd);
1791 // This function has a body but it's not loaded so it appears `External'.
1792 // Mark it as a `Ghost' instead to notify the users that it has a body.
1793 Func->setLinkage(GlobalValue::GhostLinkage);
1795 // Pretend we've `parsed' this function
1799 /// The ParserFunction method lazily parses one function. Use this method to
1800 /// casue the parser to parse a specific function in the module. Note that
1801 /// this will remove the function from what is to be included by
1802 /// ParseAllFunctionBodies.
1803 /// @see ParseAllFunctionBodies
1804 /// @see ParseBytecode
1805 void BytecodeReader::ParseFunction(Function* Func) {
1806 // Find {start, end} pointers and slot in the map. If not there, we're done.
1807 LazyFunctionMap::iterator Fi = LazyFunctionLoadMap.find(Func);
1809 // Make sure we found it
1810 if (Fi == LazyFunctionLoadMap.end()) {
1811 error("Unrecognized function of type " + Func->getType()->getDescription());
1815 BlockStart = At = Fi->second.Buf;
1816 BlockEnd = Fi->second.EndBuf;
1817 assert(Fi->first == Func && "Found wrong function?");
1819 LazyFunctionLoadMap.erase(Fi);
1821 this->ParseFunctionBody(Func);
1824 /// The ParseAllFunctionBodies method parses through all the previously
1825 /// unparsed functions in the bytecode file. If you want to completely parse
1826 /// a bytecode file, this method should be called after Parsebytecode because
1827 /// Parsebytecode only records the locations in the bytecode file of where
1828 /// the function definitions are located. This function uses that information
1829 /// to materialize the functions.
1830 /// @see ParseBytecode
1831 void BytecodeReader::ParseAllFunctionBodies() {
1832 LazyFunctionMap::iterator Fi = LazyFunctionLoadMap.begin();
1833 LazyFunctionMap::iterator Fe = LazyFunctionLoadMap.end();
1836 Function* Func = Fi->first;
1837 BlockStart = At = Fi->second.Buf;
1838 BlockEnd = Fi->second.EndBuf;
1839 ParseFunctionBody(Func);
1842 LazyFunctionLoadMap.clear();
1845 /// Parse the global type list
1846 void BytecodeReader::ParseGlobalTypes() {
1847 // Read the number of types
1848 unsigned NumEntries = read_vbr_uint();
1850 // Ignore the type plane identifier for types if the bc file is pre 1.3
1851 if (hasTypeDerivedFromValue)
1854 ParseTypes(ModuleTypes, NumEntries);
1857 /// Parse the Global info (types, global vars, constants)
1858 void BytecodeReader::ParseModuleGlobalInfo() {
1860 if (Handler) Handler->handleModuleGlobalsBegin();
1862 // Read global variables...
1863 unsigned VarType = read_vbr_uint();
1864 while (VarType != Type::VoidTyID) { // List is terminated by Void
1865 // VarType Fields: bit0 = isConstant, bit1 = hasInitializer, bit2,3,4 =
1866 // Linkage, bit4+ = slot#
1867 unsigned SlotNo = VarType >> 5;
1868 if (sanitizeTypeId(SlotNo))
1869 error("Invalid type (type type) for global var!");
1870 unsigned LinkageID = (VarType >> 2) & 7;
1871 bool isConstant = VarType & 1;
1872 bool hasInitializer = VarType & 2;
1873 GlobalValue::LinkageTypes Linkage;
1875 switch (LinkageID) {
1876 case 0: Linkage = GlobalValue::ExternalLinkage; break;
1877 case 1: Linkage = GlobalValue::WeakLinkage; break;
1878 case 2: Linkage = GlobalValue::AppendingLinkage; break;
1879 case 3: Linkage = GlobalValue::InternalLinkage; break;
1880 case 4: Linkage = GlobalValue::LinkOnceLinkage; break;
1882 error("Unknown linkage type: " + utostr(LinkageID));
1883 Linkage = GlobalValue::InternalLinkage;
1887 const Type *Ty = getType(SlotNo);
1889 error("Global has no type! SlotNo=" + utostr(SlotNo));
1892 if (!isa<PointerType>(Ty)) {
1893 error("Global not a pointer type! Ty= " + Ty->getDescription());
1896 const Type *ElTy = cast<PointerType>(Ty)->getElementType();
1898 // Create the global variable...
1899 GlobalVariable *GV = new GlobalVariable(ElTy, isConstant, Linkage,
1901 insertValue(GV, SlotNo, ModuleValues);
1903 unsigned initSlot = 0;
1904 if (hasInitializer) {
1905 initSlot = read_vbr_uint();
1906 GlobalInits.push_back(std::make_pair(GV, initSlot));
1909 // Notify handler about the global value.
1911 Handler->handleGlobalVariable(ElTy, isConstant, Linkage, SlotNo,initSlot);
1914 VarType = read_vbr_uint();
1917 // Read the function objects for all of the functions that are coming
1918 unsigned FnSignature = read_vbr_uint();
1920 if (hasNoFlagsForFunctions)
1921 FnSignature = (FnSignature << 5) + 1;
1923 // List is terminated by VoidTy.
1924 while ((FnSignature >> 5) != Type::VoidTyID) {
1925 const Type *Ty = getType(FnSignature >> 5);
1926 if (!isa<PointerType>(Ty) ||
1927 !isa<FunctionType>(cast<PointerType>(Ty)->getElementType())) {
1928 error("Function not a pointer to function type! Ty = " +
1929 Ty->getDescription());
1932 // We create functions by passing the underlying FunctionType to create...
1933 const FunctionType* FTy =
1934 cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
1937 // Insert the place holder.
1938 Function* Func = new Function(FTy, GlobalValue::ExternalLinkage,
1940 insertValue(Func, FnSignature >> 5, ModuleValues);
1942 // Flags are not used yet.
1943 unsigned Flags = FnSignature & 31;
1945 // Save this for later so we know type of lazily instantiated functions.
1946 // Note that known-external functions do not have FunctionInfo blocks, so we
1947 // do not add them to the FunctionSignatureList.
1948 if ((Flags & (1 << 4)) == 0)
1949 FunctionSignatureList.push_back(Func);
1951 // Look at the low bits. If there is a calling conv here, apply it,
1952 // read it as a vbr.
1955 Func->setCallingConv(Flags-1);
1957 Func->setCallingConv(read_vbr_uint());
1959 if (Handler) Handler->handleFunctionDeclaration(Func);
1961 // Get the next function signature.
1962 FnSignature = read_vbr_uint();
1963 if (hasNoFlagsForFunctions)
1964 FnSignature = (FnSignature << 5) + 1;
1967 // Now that the function signature list is set up, reverse it so that we can
1968 // remove elements efficiently from the back of the vector.
1969 std::reverse(FunctionSignatureList.begin(), FunctionSignatureList.end());
1971 // If this bytecode format has dependent library information in it ..
1972 if (!hasNoDependentLibraries) {
1973 // Read in the number of dependent library items that follow
1974 unsigned num_dep_libs = read_vbr_uint();
1975 std::string dep_lib;
1976 while( num_dep_libs-- ) {
1977 dep_lib = read_str();
1978 TheModule->addLibrary(dep_lib);
1980 Handler->handleDependentLibrary(dep_lib);
1984 // Read target triple and place into the module
1985 std::string triple = read_str();
1986 TheModule->setTargetTriple(triple);
1988 Handler->handleTargetTriple(triple);
1991 if (hasInconsistentModuleGlobalInfo)
1994 // This is for future proofing... in the future extra fields may be added that
1995 // we don't understand, so we transparently ignore them.
1999 if (Handler) Handler->handleModuleGlobalsEnd();
2002 /// Parse the version information and decode it by setting flags on the
2003 /// Reader that enable backward compatibility of the reader.
2004 void BytecodeReader::ParseVersionInfo() {
2005 unsigned Version = read_vbr_uint();
2007 // Unpack version number: low four bits are for flags, top bits = version
2008 Module::Endianness Endianness;
2009 Module::PointerSize PointerSize;
2010 Endianness = (Version & 1) ? Module::BigEndian : Module::LittleEndian;
2011 PointerSize = (Version & 2) ? Module::Pointer64 : Module::Pointer32;
2013 bool hasNoEndianness = Version & 4;
2014 bool hasNoPointerSize = Version & 8;
2016 RevisionNum = Version >> 4;
2018 // Default values for the current bytecode version
2019 hasInconsistentModuleGlobalInfo = false;
2020 hasExplicitPrimitiveZeros = false;
2021 hasRestrictedGEPTypes = false;
2022 hasTypeDerivedFromValue = false;
2023 hasLongBlockHeaders = false;
2024 has32BitTypes = false;
2025 hasNoDependentLibraries = false;
2026 hasAlignment = false;
2027 hasNoUndefValue = false;
2028 hasNoFlagsForFunctions = false;
2029 hasNoUnreachableInst = false;
2031 switch (RevisionNum) {
2032 case 0: // LLVM 1.0, 1.1 (Released)
2033 // Base LLVM 1.0 bytecode format.
2034 hasInconsistentModuleGlobalInfo = true;
2035 hasExplicitPrimitiveZeros = true;
2039 case 1: // LLVM 1.2 (Released)
2040 // LLVM 1.2 added explicit support for emitting strings efficiently.
2042 // Also, it fixed the problem where the size of the ModuleGlobalInfo block
2043 // included the size for the alignment at the end, where the rest of the
2046 // LLVM 1.2 and before required that GEP indices be ubyte constants for
2047 // structures and longs for sequential types.
2048 hasRestrictedGEPTypes = true;
2050 // LLVM 1.2 and before had the Type class derive from Value class. This
2051 // changed in release 1.3 and consequently LLVM 1.3 bytecode files are
2052 // written differently because Types can no longer be part of the
2053 // type planes for Values.
2054 hasTypeDerivedFromValue = true;
2058 case 2: // 1.2.5 (Not Released)
2060 // LLVM 1.2 and earlier had two-word block headers. This is a bit wasteful,
2061 // especially for small files where the 8 bytes per block is a large
2062 // fraction of the total block size. In LLVM 1.3, the block type and length
2063 // are compressed into a single 32-bit unsigned integer. 27 bits for length,
2064 // 5 bits for block type.
2065 hasLongBlockHeaders = true;
2067 // LLVM 1.2 and earlier wrote type slot numbers as vbr_uint32. In LLVM 1.3
2068 // this has been reduced to vbr_uint24. It shouldn't make much difference
2069 // since we haven't run into a module with > 24 million types, but for
2070 // safety the 24-bit restriction has been enforced in 1.3 to free some bits
2071 // in various places and to ensure consistency.
2072 has32BitTypes = true;
2074 // LLVM 1.2 and earlier did not provide a target triple nor a list of
2075 // libraries on which the bytecode is dependent. LLVM 1.3 provides these
2076 // features, for use in future versions of LLVM.
2077 hasNoDependentLibraries = true;
2081 case 3: // LLVM 1.3 (Released)
2082 // LLVM 1.3 and earlier caused alignment bytes to be written on some block
2083 // boundaries and at the end of some strings. In extreme cases (e.g. lots
2084 // of GEP references to a constant array), this can increase the file size
2085 // by 30% or more. In version 1.4 alignment is done away with completely.
2086 hasAlignment = true;
2090 case 4: // 1.3.1 (Not Released)
2091 // In version 4, we did not support the 'undef' constant.
2092 hasNoUndefValue = true;
2094 // In version 4 and above, we did not include space for flags for functions
2095 // in the module info block.
2096 hasNoFlagsForFunctions = true;
2098 // In version 4 and above, we did not include the 'unreachable' instruction
2099 // in the opcode numbering in the bytecode file.
2100 hasNoUnreachableInst = true;
2105 case 5: // 1.4 (Released)
2109 error("Unknown bytecode version number: " + itostr(RevisionNum));
2112 if (hasNoEndianness) Endianness = Module::AnyEndianness;
2113 if (hasNoPointerSize) PointerSize = Module::AnyPointerSize;
2115 TheModule->setEndianness(Endianness);
2116 TheModule->setPointerSize(PointerSize);
2118 if (Handler) Handler->handleVersionInfo(RevisionNum, Endianness, PointerSize);
2121 /// Parse a whole module.
2122 void BytecodeReader::ParseModule() {
2123 unsigned Type, Size;
2125 FunctionSignatureList.clear(); // Just in case...
2127 // Read into instance variables...
2131 bool SeenModuleGlobalInfo = false;
2132 bool SeenGlobalTypePlane = false;
2133 BufPtr MyEnd = BlockEnd;
2134 while (At < MyEnd) {
2136 read_block(Type, Size);
2140 case BytecodeFormat::GlobalTypePlaneBlockID:
2141 if (SeenGlobalTypePlane)
2142 error("Two GlobalTypePlane Blocks Encountered!");
2146 SeenGlobalTypePlane = true;
2149 case BytecodeFormat::ModuleGlobalInfoBlockID:
2150 if (SeenModuleGlobalInfo)
2151 error("Two ModuleGlobalInfo Blocks Encountered!");
2152 ParseModuleGlobalInfo();
2153 SeenModuleGlobalInfo = true;
2156 case BytecodeFormat::ConstantPoolBlockID:
2157 ParseConstantPool(ModuleValues, ModuleTypes,false);
2160 case BytecodeFormat::FunctionBlockID:
2161 ParseFunctionLazily();
2164 case BytecodeFormat::SymbolTableBlockID:
2165 ParseSymbolTable(0, &TheModule->getSymbolTable());
2171 error("Unexpected Block of Type #" + utostr(Type) + " encountered!");
2179 // After the module constant pool has been read, we can safely initialize
2180 // global variables...
2181 while (!GlobalInits.empty()) {
2182 GlobalVariable *GV = GlobalInits.back().first;
2183 unsigned Slot = GlobalInits.back().second;
2184 GlobalInits.pop_back();
2186 // Look up the initializer value...
2187 // FIXME: Preserve this type ID!
2189 const llvm::PointerType* GVType = GV->getType();
2190 unsigned TypeSlot = getTypeSlot(GVType->getElementType());
2191 if (Constant *CV = getConstantValue(TypeSlot, Slot)) {
2192 if (GV->hasInitializer())
2193 error("Global *already* has an initializer?!");
2194 if (Handler) Handler->handleGlobalInitializer(GV,CV);
2195 GV->setInitializer(CV);
2197 error("Cannot find initializer value.");
2200 if (!ConstantFwdRefs.empty())
2201 error("Use of undefined constants in a module");
2203 /// Make sure we pulled them all out. If we didn't then there's a declaration
2204 /// but a missing body. That's not allowed.
2205 if (!FunctionSignatureList.empty())
2206 error("Function declared, but bytecode stream ended before definition");
2209 /// This function completely parses a bytecode buffer given by the \p Buf
2210 /// and \p Length parameters.
2211 void BytecodeReader::ParseBytecode(BufPtr Buf, unsigned Length,
2212 const std::string &ModuleID) {
2216 At = MemStart = BlockStart = Buf;
2217 MemEnd = BlockEnd = Buf + Length;
2219 // Create the module
2220 TheModule = new Module(ModuleID);
2222 if (Handler) Handler->handleStart(TheModule, Length);
2224 // Read the four bytes of the signature.
2225 unsigned Sig = read_uint();
2227 // If this is a compressed file
2228 if (Sig == ('l' | ('l' << 8) | ('v' << 16) | ('c' << 24))) {
2230 // Invoke the decompression of the bytecode. Note that we have to skip the
2231 // file's magic number which is not part of the compressed block. Hence,
2232 // the Buf+4 and Length-4. The result goes into decompressedBlock, a data
2233 // member for retention until BytecodeReader is destructed.
2234 unsigned decompressedLength = Compressor::decompressToNewBuffer(
2235 (char*)Buf+4,Length-4,decompressedBlock);
2237 // We must adjust the buffer pointers used by the bytecode reader to point
2238 // into the new decompressed block. After decompression, the
2239 // decompressedBlock will point to a contiguous memory area that has
2240 // the decompressed data.
2241 At = MemStart = BlockStart = Buf = (BufPtr) decompressedBlock;
2242 MemEnd = BlockEnd = Buf + decompressedLength;
2244 // else if this isn't a regular (uncompressed) bytecode file, then its
2245 // and error, generate that now.
2246 } else if (Sig != ('l' | ('l' << 8) | ('v' << 16) | ('m' << 24))) {
2247 error("Invalid bytecode signature: " + utohexstr(Sig));
2250 // Tell the handler we're starting a module
2251 if (Handler) Handler->handleModuleBegin(ModuleID);
2253 // Get the module block and size and verify. This is handled specially
2254 // because the module block/size is always written in long format. Other
2255 // blocks are written in short format so the read_block method is used.
2256 unsigned Type, Size;
2259 if (Type != BytecodeFormat::ModuleBlockID) {
2260 error("Expected Module Block! Type:" + utostr(Type) + ", Size:"
2264 // It looks like the darwin ranlib program is broken, and adds trailing
2265 // garbage to the end of some bytecode files. This hack allows the bc
2266 // reader to ignore trailing garbage on bytecode files.
2267 if (At + Size < MemEnd)
2268 MemEnd = BlockEnd = At+Size;
2270 if (At + Size != MemEnd)
2271 error("Invalid Top Level Block Length! Type:" + utostr(Type)
2272 + ", Size:" + utostr(Size));
2274 // Parse the module contents
2275 this->ParseModule();
2277 // Check for missing functions
2279 error("Function expected, but bytecode stream ended!");
2281 // Tell the handler we're done with the module
2283 Handler->handleModuleEnd(ModuleID);
2285 // Tell the handler we're finished the parse
2286 if (Handler) Handler->handleFinish();
2288 } catch (std::string& errstr) {
2289 if (Handler) Handler->handleError(errstr);
2293 if (decompressedBlock != 0 ) {
2294 ::free(decompressedBlock);
2295 decompressedBlock = 0;
2299 std::string msg("Unknown Exception Occurred");
2300 if (Handler) Handler->handleError(msg);
2304 if (decompressedBlock != 0) {
2305 ::free(decompressedBlock);
2306 decompressedBlock = 0;
2312 //===----------------------------------------------------------------------===//
2313 //=== Default Implementations of Handler Methods
2314 //===----------------------------------------------------------------------===//
2316 BytecodeHandler::~BytecodeHandler() {}