blob: e08656822d7fcbec25921a6094434b9b787954f3 [file] [log] [blame]
Chris Lattnerd6b65252001-10-24 01:15:12 +00001//===- Reader.cpp - Code to read bytecode files ---------------------------===//
John Criswellb576c942003-10-20 19:43:21 +00002//
3// The LLVM Compiler Infrastructure
4//
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.
7//
8//===----------------------------------------------------------------------===//
Chris Lattner00950542001-06-06 20:29:01 +00009//
10// This library implements the functionality defined in llvm/Bytecode/Reader.h
11//
12// Note that this library should be as fast as possible, reentrant, and
13// threadsafe!!
14//
Chris Lattner00950542001-06-06 20:29:01 +000015// TODO: Allow passing in an option to ignore the symbol table
16//
Chris Lattnerd6b65252001-10-24 01:15:12 +000017//===----------------------------------------------------------------------===//
Chris Lattner00950542001-06-06 20:29:01 +000018
Reid Spencer060d25d2004-06-29 23:29:38 +000019#include "Reader.h"
20#include "llvm/Bytecode/BytecodeHandler.h"
21#include "llvm/BasicBlock.h"
22#include "llvm/Constants.h"
Reid Spencer04cde2c2004-07-04 11:33:49 +000023#include "llvm/Instructions.h"
24#include "llvm/SymbolTable.h"
Chris Lattner00950542001-06-06 20:29:01 +000025#include "llvm/Bytecode/Format.h"
Reid Spencer060d25d2004-06-29 23:29:38 +000026#include "llvm/Support/GetElementPtrTypeIterator.h"
Reid Spencer17f52c52004-11-06 23:17:23 +000027#include "llvm/Support/Compressor.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000028#include "llvm/ADT/StringExtras.h"
Reid Spencer060d25d2004-06-29 23:29:38 +000029#include <sstream>
Alkis Evlogimenos20aa4742004-09-03 18:19:51 +000030#include <algorithm>
Chris Lattner29b789b2003-11-19 17:27:18 +000031using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000032
Reid Spencer46b002c2004-07-11 17:28:43 +000033namespace {
34
Reid Spencer060d25d2004-06-29 23:29:38 +000035/// @brief A class for maintaining the slot number definition
Reid Spencer46b002c2004-07-11 17:28:43 +000036/// as a placeholder for the actual definition for forward constants defs.
37class ConstantPlaceHolder : public ConstantExpr {
Reid Spencer060d25d2004-06-29 23:29:38 +000038 unsigned ID;
Reid Spencer46b002c2004-07-11 17:28:43 +000039 ConstantPlaceHolder(); // DO NOT IMPLEMENT
40 void operator=(const ConstantPlaceHolder &); // DO NOT IMPLEMENT
Reid Spencer060d25d2004-06-29 23:29:38 +000041public:
Reid Spencer46b002c2004-07-11 17:28:43 +000042 ConstantPlaceHolder(const Type *Ty, unsigned id)
43 : ConstantExpr(Instruction::UserOp1, Constant::getNullValue(Ty), Ty),
44 ID(id) {}
Reid Spencer060d25d2004-06-29 23:29:38 +000045 unsigned getID() { return ID; }
46};
Chris Lattner9e460f22003-10-04 20:00:03 +000047
Reid Spencer46b002c2004-07-11 17:28:43 +000048}
Reid Spencer060d25d2004-06-29 23:29:38 +000049
Reid Spencer24399722004-07-09 22:21:33 +000050// Provide some details on error
51inline void BytecodeReader::error(std::string err) {
52 err += " (Vers=" ;
53 err += itostr(RevisionNum) ;
54 err += ", Pos=" ;
55 err += itostr(At-MemStart);
56 err += ")";
57 throw err;
58}
59
Reid Spencer060d25d2004-06-29 23:29:38 +000060//===----------------------------------------------------------------------===//
61// Bytecode Reading Methods
62//===----------------------------------------------------------------------===//
63
Reid Spencer04cde2c2004-07-04 11:33:49 +000064/// Determine if the current block being read contains any more data.
Reid Spencer060d25d2004-06-29 23:29:38 +000065inline bool BytecodeReader::moreInBlock() {
66 return At < BlockEnd;
Chris Lattner00950542001-06-06 20:29:01 +000067}
68
Reid Spencer04cde2c2004-07-04 11:33:49 +000069/// Throw an error if we've read past the end of the current block
Reid Spencer060d25d2004-06-29 23:29:38 +000070inline void BytecodeReader::checkPastBlockEnd(const char * block_name) {
Reid Spencer46b002c2004-07-11 17:28:43 +000071 if (At > BlockEnd)
Chris Lattnera79e7cc2004-10-16 18:18:16 +000072 error(std::string("Attempt to read past the end of ") + block_name +
73 " block.");
Reid Spencer060d25d2004-06-29 23:29:38 +000074}
Chris Lattner36392bc2003-10-08 21:18:57 +000075
Reid Spencer04cde2c2004-07-04 11:33:49 +000076/// Align the buffer position to a 32 bit boundary
Reid Spencer060d25d2004-06-29 23:29:38 +000077inline void BytecodeReader::align32() {
Reid Spencer38d54be2004-08-17 07:45:14 +000078 if (hasAlignment) {
79 BufPtr Save = At;
80 At = (const unsigned char *)((unsigned long)(At+3) & (~3UL));
81 if (At > Save)
82 if (Handler) Handler->handleAlignment(At - Save);
83 if (At > BlockEnd)
84 error("Ran out of data while aligning!");
85 }
Reid Spencer060d25d2004-06-29 23:29:38 +000086}
87
Reid Spencer04cde2c2004-07-04 11:33:49 +000088/// Read a whole unsigned integer
Reid Spencer060d25d2004-06-29 23:29:38 +000089inline unsigned BytecodeReader::read_uint() {
90 if (At+4 > BlockEnd)
Reid Spencer24399722004-07-09 22:21:33 +000091 error("Ran out of data reading uint!");
Reid Spencer060d25d2004-06-29 23:29:38 +000092 At += 4;
93 return At[-4] | (At[-3] << 8) | (At[-2] << 16) | (At[-1] << 24);
94}
95
Reid Spencer04cde2c2004-07-04 11:33:49 +000096/// Read a variable-bit-rate encoded unsigned integer
Reid Spencer060d25d2004-06-29 23:29:38 +000097inline unsigned BytecodeReader::read_vbr_uint() {
98 unsigned Shift = 0;
99 unsigned Result = 0;
100 BufPtr Save = At;
101
102 do {
103 if (At == BlockEnd)
Reid Spencer24399722004-07-09 22:21:33 +0000104 error("Ran out of data reading vbr_uint!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000105 Result |= (unsigned)((*At++) & 0x7F) << Shift;
106 Shift += 7;
107 } while (At[-1] & 0x80);
Reid Spencer04cde2c2004-07-04 11:33:49 +0000108 if (Handler) Handler->handleVBR32(At-Save);
Reid Spencer060d25d2004-06-29 23:29:38 +0000109 return Result;
110}
111
Reid Spencer04cde2c2004-07-04 11:33:49 +0000112/// Read a variable-bit-rate encoded unsigned 64-bit integer.
Reid Spencer060d25d2004-06-29 23:29:38 +0000113inline uint64_t BytecodeReader::read_vbr_uint64() {
114 unsigned Shift = 0;
115 uint64_t Result = 0;
116 BufPtr Save = At;
117
118 do {
119 if (At == BlockEnd)
Reid Spencer24399722004-07-09 22:21:33 +0000120 error("Ran out of data reading vbr_uint64!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000121 Result |= (uint64_t)((*At++) & 0x7F) << Shift;
122 Shift += 7;
123 } while (At[-1] & 0x80);
Reid Spencer04cde2c2004-07-04 11:33:49 +0000124 if (Handler) Handler->handleVBR64(At-Save);
Reid Spencer060d25d2004-06-29 23:29:38 +0000125 return Result;
126}
127
Reid Spencer04cde2c2004-07-04 11:33:49 +0000128/// Read a variable-bit-rate encoded signed 64-bit integer.
Reid Spencer060d25d2004-06-29 23:29:38 +0000129inline int64_t BytecodeReader::read_vbr_int64() {
130 uint64_t R = read_vbr_uint64();
131 if (R & 1) {
132 if (R != 1)
133 return -(int64_t)(R >> 1);
134 else // There is no such thing as -0 with integers. "-0" really means
135 // 0x8000000000000000.
136 return 1LL << 63;
137 } else
138 return (int64_t)(R >> 1);
139}
140
Reid Spencer04cde2c2004-07-04 11:33:49 +0000141/// Read a pascal-style string (length followed by text)
Reid Spencer060d25d2004-06-29 23:29:38 +0000142inline std::string BytecodeReader::read_str() {
143 unsigned Size = read_vbr_uint();
144 const unsigned char *OldAt = At;
145 At += Size;
146 if (At > BlockEnd) // Size invalid?
Reid Spencer24399722004-07-09 22:21:33 +0000147 error("Ran out of data reading a string!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000148 return std::string((char*)OldAt, Size);
149}
150
Reid Spencer04cde2c2004-07-04 11:33:49 +0000151/// Read an arbitrary block of data
Reid Spencer060d25d2004-06-29 23:29:38 +0000152inline 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)
Reid Spencer24399722004-07-09 22:21:33 +0000156 error("Ran out of data!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000157 std::copy(At, At+Amount, Start);
158 At += Amount;
159}
160
Reid Spencer46b002c2004-07-11 17:28:43 +0000161/// Read a float value in little-endian order
162inline void BytecodeReader::read_float(float& FloatVal) {
Reid Spencerada16182004-07-25 21:36:26 +0000163 /// FIXME: This isn't optimal, it has size problems on some platforms
164 /// where FP is not IEEE.
165 union {
166 float f;
167 uint32_t i;
168 } FloatUnion;
169 FloatUnion.i = At[0] | (At[1] << 8) | (At[2] << 16) | (At[3] << 24);
170 At+=sizeof(uint32_t);
171 FloatVal = FloatUnion.f;
Reid Spencer46b002c2004-07-11 17:28:43 +0000172}
173
174/// Read a double value in little-endian order
175inline void BytecodeReader::read_double(double& DoubleVal) {
Reid Spencerada16182004-07-25 21:36:26 +0000176 /// FIXME: This isn't optimal, it has size problems on some platforms
177 /// where FP is not IEEE.
178 union {
179 double d;
180 uint64_t i;
181 } DoubleUnion;
Chris Lattner1d785162004-07-25 23:15:44 +0000182 DoubleUnion.i = (uint64_t(At[0]) << 0) | (uint64_t(At[1]) << 8) |
183 (uint64_t(At[2]) << 16) | (uint64_t(At[3]) << 24) |
Reid Spencerada16182004-07-25 21:36:26 +0000184 (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;
Reid Spencer46b002c2004-07-11 17:28:43 +0000188}
189
Reid Spencer04cde2c2004-07-04 11:33:49 +0000190/// Read a block header and obtain its type and size
Reid Spencer060d25d2004-06-29 23:29:38 +0000191inline void BytecodeReader::read_block(unsigned &Type, unsigned &Size) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000192 if ( hasLongBlockHeaders ) {
193 Type = read_uint();
194 Size = read_uint();
195 switch (Type) {
196 case BytecodeFormat::Reserved_DoNotUse :
197 error("Reserved_DoNotUse used as Module Type?");
Reid Spencer5b472d92004-08-21 20:49:23 +0000198 Type = BytecodeFormat::ModuleBlockID; break;
Reid Spencerad89bd62004-07-25 18:07:36 +0000199 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.
219 break;
220 default:
Reid Spencer5b472d92004-08-21 20:49:23 +0000221 error("Invalid block id found: " + utostr(Type));
Reid Spencerad89bd62004-07-25 18:07:36 +0000222 break;
223 }
224 } else {
225 Size = read_uint();
226 Type = Size & 0x1F; // mask low order five bits
227 Size >>= 5; // get rid of five low order bits, leaving high 27
228 }
Reid Spencer060d25d2004-06-29 23:29:38 +0000229 BlockStart = At;
Reid Spencer46b002c2004-07-11 17:28:43 +0000230 if (At + Size > BlockEnd)
Reid Spencer24399722004-07-09 22:21:33 +0000231 error("Attempt to size a block past end of memory");
Reid Spencer060d25d2004-06-29 23:29:38 +0000232 BlockEnd = At + Size;
Reid Spencer46b002c2004-07-11 17:28:43 +0000233 if (Handler) Handler->handleBlock(Type, BlockStart, Size);
Reid Spencer04cde2c2004-07-04 11:33:49 +0000234}
235
236
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"
Reid Spencer46b002c2004-07-11 17:28:43 +0000254inline bool BytecodeReader::sanitizeTypeId(unsigned &TypeId) {
255 if (hasTypeDerivedFromValue) { /// do nothing if 1.3 or later
256 if (TypeId == Type::LabelTyID) {
Reid Spencer04cde2c2004-07-04 11:33:49 +0000257 TypeId = Type::VoidTyID; // sanitize it
258 return true; // indicate we got TypeTyID in pre 1.3 bytecode
Reid Spencer46b002c2004-07-11 17:28:43 +0000259 } else if (TypeId > Type::LabelTyID)
Reid Spencer04cde2c2004-07-04 11:33:49 +0000260 --TypeId; // shift all planes down because type type plane is missing
261 }
262 return false;
263}
264
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
269inline bool BytecodeReader::read_typeid(unsigned &TypeId) {
270 TypeId = read_vbr_uint();
Reid Spencerad89bd62004-07-25 18:07:36 +0000271 if ( !has32BitTypes )
272 if ( TypeId == 0x00FFFFFF )
273 TypeId = read_vbr_uint();
Reid Spencer04cde2c2004-07-04 11:33:49 +0000274 return sanitizeTypeId(TypeId);
Reid Spencer060d25d2004-06-29 23:29:38 +0000275}
276
277//===----------------------------------------------------------------------===//
278// IR Lookup Methods
279//===----------------------------------------------------------------------===//
280
Reid Spencer04cde2c2004-07-04 11:33:49 +0000281/// Determine if a type id has an implicit null value
Reid Spencer46b002c2004-07-11 17:28:43 +0000282inline bool BytecodeReader::hasImplicitNull(unsigned TyID) {
Reid Spencer060d25d2004-06-29 23:29:38 +0000283 if (!hasExplicitPrimitiveZeros)
Reid Spencer04cde2c2004-07-04 11:33:49 +0000284 return TyID != Type::LabelTyID && TyID != Type::VoidTyID;
Reid Spencer060d25d2004-06-29 23:29:38 +0000285 return TyID >= Type::FirstDerivedTyID;
286}
287
Reid Spencer04cde2c2004-07-04 11:33:49 +0000288/// 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.
Reid Spencer060d25d2004-06-29 23:29:38 +0000290const Type *BytecodeReader::getType(unsigned ID) {
Chris Lattner89e02532004-01-18 21:08:15 +0000291 if (ID < Type::FirstDerivedTyID)
Chris Lattnerf70c22b2004-06-17 18:19:28 +0000292 if (const Type *T = Type::getPrimitiveType((Type::TypeID)ID))
Chris Lattner927b1852003-10-09 20:22:47 +0000293 return T; // Asked for a primitive type...
Chris Lattner36392bc2003-10-08 21:18:57 +0000294
295 // Otherwise, derived types need offset...
Chris Lattner89e02532004-01-18 21:08:15 +0000296 ID -= Type::FirstDerivedTyID;
297
Reid Spencer060d25d2004-06-29 23:29:38 +0000298 if (!CompactionTypes.empty()) {
299 if (ID >= CompactionTypes.size())
Reid Spencer24399722004-07-09 22:21:33 +0000300 error("Type ID out of range for compaction table!");
Chris Lattner45b5dd22004-08-03 23:41:28 +0000301 return CompactionTypes[ID].first;
Chris Lattner89e02532004-01-18 21:08:15 +0000302 }
Chris Lattner36392bc2003-10-08 21:18:57 +0000303
304 // Is it a module-level type?
Reid Spencer46b002c2004-07-11 17:28:43 +0000305 if (ID < ModuleTypes.size())
306 return ModuleTypes[ID].get();
Chris Lattner36392bc2003-10-08 21:18:57 +0000307
Reid Spencer46b002c2004-07-11 17:28:43 +0000308 // Nope, is it a function-level type?
309 ID -= ModuleTypes.size();
310 if (ID < FunctionTypes.size())
311 return FunctionTypes[ID].get();
Chris Lattner36392bc2003-10-08 21:18:57 +0000312
Reid Spencer46b002c2004-07-11 17:28:43 +0000313 error("Illegal type reference!");
314 return Type::VoidTy;
Chris Lattner00950542001-06-06 20:29:01 +0000315}
316
Reid Spencer04cde2c2004-07-04 11:33:49 +0000317/// 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
320inline const Type* BytecodeReader::getSanitizedType(unsigned& ID) {
Reid Spencer46b002c2004-07-11 17:28:43 +0000321 if (sanitizeTypeId(ID))
Reid Spencer24399722004-07-09 22:21:33 +0000322 error("Invalid type id encountered");
Reid Spencer04cde2c2004-07-04 11:33:49 +0000323 return getType(ID);
324}
325
326/// This method just saves some coding. It uses read_typeid to read
Reid Spencer24399722004-07-09 22:21:33 +0000327/// in a sanitized type id, errors that its not the type type, and
Reid Spencer04cde2c2004-07-04 11:33:49 +0000328/// then calls getType to return the type value.
329inline const Type* BytecodeReader::readSanitizedType() {
330 unsigned ID;
Reid Spencer46b002c2004-07-11 17:28:43 +0000331 if (read_typeid(ID))
332 error("Invalid type id encountered");
Reid Spencer04cde2c2004-07-04 11:33:49 +0000333 return getType(ID);
334}
335
336/// Get the slot number associated with a type accounting for primitive
337/// types, compaction tables, and function level vs module level.
Reid Spencer060d25d2004-06-29 23:29:38 +0000338unsigned BytecodeReader::getTypeSlot(const Type *Ty) {
339 if (Ty->isPrimitiveType())
340 return Ty->getTypeID();
341
342 // Scan the compaction table for the type if needed.
343 if (!CompactionTypes.empty()) {
Chris Lattner45b5dd22004-08-03 23:41:28 +0000344 for (unsigned i = 0, e = CompactionTypes.size(); i != e; ++i)
345 if (CompactionTypes[i].first == Ty)
346 return Type::FirstDerivedTyID + i;
Reid Spencer060d25d2004-06-29 23:29:38 +0000347
Chris Lattner45b5dd22004-08-03 23:41:28 +0000348 error("Couldn't find type specified in compaction table!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000349 }
350
351 // Check the function level types first...
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000352 TypeListTy::iterator I = std::find(FunctionTypes.begin(),
353 FunctionTypes.end(), Ty);
Reid Spencer060d25d2004-06-29 23:29:38 +0000354
355 if (I != FunctionTypes.end())
Reid Spencer46b002c2004-07-11 17:28:43 +0000356 return Type::FirstDerivedTyID + ModuleTypes.size() +
357 (&*I - &FunctionTypes[0]);
Reid Spencer060d25d2004-06-29 23:29:38 +0000358
359 // Check the module level types now...
Reid Spencer2da5c3d2004-09-15 17:06:42 +0000360 I = std::find(ModuleTypes.begin(), ModuleTypes.end(), Ty);
Reid Spencer060d25d2004-06-29 23:29:38 +0000361 if (I == ModuleTypes.end())
Reid Spencer24399722004-07-09 22:21:33 +0000362 error("Didn't find type in ModuleTypes.");
Reid Spencer060d25d2004-06-29 23:29:38 +0000363 return Type::FirstDerivedTyID + (&*I - &ModuleTypes[0]);
Chris Lattner80b97342004-01-17 23:25:43 +0000364}
365
Reid Spencer04cde2c2004-07-04 11:33:49 +0000366/// This is just like getType, but when a compaction table is in use, it is
367/// ignored. It also ignores function level types.
368/// @see getType
Reid Spencer060d25d2004-06-29 23:29:38 +0000369const Type *BytecodeReader::getGlobalTableType(unsigned Slot) {
370 if (Slot < Type::FirstDerivedTyID) {
371 const Type *Ty = Type::getPrimitiveType((Type::TypeID)Slot);
Reid Spencer46b002c2004-07-11 17:28:43 +0000372 if (!Ty)
Reid Spencer24399722004-07-09 22:21:33 +0000373 error("Not a primitive type ID?");
Reid Spencer060d25d2004-06-29 23:29:38 +0000374 return Ty;
375 }
376 Slot -= Type::FirstDerivedTyID;
377 if (Slot >= ModuleTypes.size())
Reid Spencer24399722004-07-09 22:21:33 +0000378 error("Illegal compaction table type reference!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000379 return ModuleTypes[Slot];
Chris Lattner52e20b02003-03-19 20:54:26 +0000380}
381
Reid Spencer04cde2c2004-07-04 11:33:49 +0000382/// This is just like getTypeSlot, but when a compaction table is in use, it
383/// is ignored. It also ignores function level types.
Reid Spencer060d25d2004-06-29 23:29:38 +0000384unsigned BytecodeReader::getGlobalTableTypeSlot(const Type *Ty) {
385 if (Ty->isPrimitiveType())
386 return Ty->getTypeID();
Reid Spencer2da5c3d2004-09-15 17:06:42 +0000387 TypeListTy::iterator I = std::find(ModuleTypes.begin(),
Reid Spencer04cde2c2004-07-04 11:33:49 +0000388 ModuleTypes.end(), Ty);
Reid Spencer060d25d2004-06-29 23:29:38 +0000389 if (I == ModuleTypes.end())
Reid Spencer24399722004-07-09 22:21:33 +0000390 error("Didn't find type in ModuleTypes.");
Reid Spencer060d25d2004-06-29 23:29:38 +0000391 return Type::FirstDerivedTyID + (&*I - &ModuleTypes[0]);
392}
393
Reid Spencer04cde2c2004-07-04 11:33:49 +0000394/// Retrieve a value of a given type and slot number, possibly creating
395/// it if it doesn't already exist.
Reid Spencer060d25d2004-06-29 23:29:38 +0000396Value * BytecodeReader::getValue(unsigned type, unsigned oNum, bool Create) {
Chris Lattner4ee8ef22003-10-08 22:52:54 +0000397 assert(type != Type::LabelTyID && "getValue() cannot get blocks!");
Chris Lattner00950542001-06-06 20:29:01 +0000398 unsigned Num = oNum;
Chris Lattner00950542001-06-06 20:29:01 +0000399
Chris Lattner89e02532004-01-18 21:08:15 +0000400 // If there is a compaction table active, it defines the low-level numbers.
401 // If not, the module values define the low-level numbers.
Reid Spencer060d25d2004-06-29 23:29:38 +0000402 if (CompactionValues.size() > type && !CompactionValues[type].empty()) {
403 if (Num < CompactionValues[type].size())
404 return CompactionValues[type][Num];
405 Num -= CompactionValues[type].size();
Chris Lattner89e02532004-01-18 21:08:15 +0000406 } else {
Reid Spencer060d25d2004-06-29 23:29:38 +0000407 // By default, the global type id is the type id passed in
Chris Lattner52f86d62004-01-20 00:54:06 +0000408 unsigned GlobalTyID = type;
Reid Spencer060d25d2004-06-29 23:29:38 +0000409
Chris Lattner45b5dd22004-08-03 23:41:28 +0000410 // 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;
Chris Lattner00950542001-06-06 20:29:01 +0000414
Reid Spencer060d25d2004-06-29 23:29:38 +0000415 if (hasImplicitNull(GlobalTyID)) {
Chris Lattner89e02532004-01-18 21:08:15 +0000416 if (Num == 0)
Reid Spencer04cde2c2004-07-04 11:33:49 +0000417 return Constant::getNullValue(getType(type));
Chris Lattner89e02532004-01-18 21:08:15 +0000418 --Num;
419 }
420
Chris Lattner52f86d62004-01-20 00:54:06 +0000421 if (GlobalTyID < ModuleValues.size() && ModuleValues[GlobalTyID]) {
422 if (Num < ModuleValues[GlobalTyID]->size())
Reid Spencer04cde2c2004-07-04 11:33:49 +0000423 return ModuleValues[GlobalTyID]->getOperand(Num);
Chris Lattner52f86d62004-01-20 00:54:06 +0000424 Num -= ModuleValues[GlobalTyID]->size();
Chris Lattner89e02532004-01-18 21:08:15 +0000425 }
Chris Lattner52e20b02003-03-19 20:54:26 +0000426 }
427
Reid Spencer060d25d2004-06-29 23:29:38 +0000428 if (FunctionValues.size() > type &&
429 FunctionValues[type] &&
430 Num < FunctionValues[type]->size())
431 return FunctionValues[type]->getOperand(Num);
Chris Lattner00950542001-06-06 20:29:01 +0000432
Chris Lattner74734132002-08-17 22:01:27 +0000433 if (!Create) return 0; // Do not create a placeholder?
Chris Lattner00950542001-06-06 20:29:01 +0000434
Reid Spencer551ccae2004-09-01 22:55:40 +0000435 // Did we already create a place holder?
Chris Lattner8eb10ce2003-10-09 06:05:40 +0000436 std::pair<unsigned,unsigned> KeyValue(type, oNum);
Reid Spencer060d25d2004-06-29 23:29:38 +0000437 ForwardReferenceMap::iterator I = ForwardReferences.lower_bound(KeyValue);
Chris Lattner8eb10ce2003-10-09 06:05:40 +0000438 if (I != ForwardReferences.end() && I->first == KeyValue)
439 return I->second; // We have already created this placeholder
440
Reid Spencer551ccae2004-09-01 22:55:40 +0000441 // If the type exists (it should)
442 if (const Type* Ty = getType(type)) {
443 // Create the place holder
444 Value *Val = new Argument(Ty);
445 ForwardReferences.insert(I, std::make_pair(KeyValue, Val));
446 return Val;
447 }
448 throw "Can't create placeholder for value of type slot #" + utostr(type);
Chris Lattner00950542001-06-06 20:29:01 +0000449}
450
Reid Spencer04cde2c2004-07-04 11:33:49 +0000451/// This is just like getValue, but when a compaction table is in use, it
452/// is ignored. Also, no forward references or other fancy features are
453/// supported.
Chris Lattner2c6c14d2004-08-04 00:19:23 +0000454Value* BytecodeReader::getGlobalTableValue(unsigned TyID, unsigned SlotNo) {
455 if (SlotNo == 0)
456 return Constant::getNullValue(getType(TyID));
457
458 if (!CompactionTypes.empty() && TyID >= Type::FirstDerivedTyID) {
459 TyID -= Type::FirstDerivedTyID;
460 if (TyID >= CompactionTypes.size())
461 error("Type ID out of range for compaction table!");
462 TyID = CompactionTypes[TyID].second;
Reid Spencer060d25d2004-06-29 23:29:38 +0000463 }
464
Chris Lattner2c6c14d2004-08-04 00:19:23 +0000465 --SlotNo;
466
Reid Spencer060d25d2004-06-29 23:29:38 +0000467 if (TyID >= ModuleValues.size() || ModuleValues[TyID] == 0 ||
468 SlotNo >= ModuleValues[TyID]->size()) {
Chris Lattner2c6c14d2004-08-04 00:19:23 +0000469 if (TyID >= ModuleValues.size() || ModuleValues[TyID] == 0)
470 error("Corrupt compaction table entry!"
471 + utostr(TyID) + ", " + utostr(SlotNo) + ": "
472 + utostr(ModuleValues.size()));
473 else
474 error("Corrupt compaction table entry!"
475 + utostr(TyID) + ", " + utostr(SlotNo) + ": "
476 + utostr(ModuleValues.size()) + ", "
Reid Spencer9a7e0c52004-08-04 22:56:46 +0000477 + utohexstr(reinterpret_cast<uint64_t>(((void*)ModuleValues[TyID])))
478 + ", "
Chris Lattner2c6c14d2004-08-04 00:19:23 +0000479 + utostr(ModuleValues[TyID]->size()));
Reid Spencer060d25d2004-06-29 23:29:38 +0000480 }
481 return ModuleValues[TyID]->getOperand(SlotNo);
482}
483
Reid Spencer04cde2c2004-07-04 11:33:49 +0000484/// Just like getValue, except that it returns a null pointer
485/// only on error. It always returns a constant (meaning that if the value is
486/// defined, but is not a constant, that is an error). If the specified
487/// constant hasn't been parsed yet, a placeholder is defined and used.
488/// Later, after the real value is parsed, the placeholder is eliminated.
Reid Spencer060d25d2004-06-29 23:29:38 +0000489Constant* BytecodeReader::getConstantValue(unsigned TypeSlot, unsigned Slot) {
490 if (Value *V = getValue(TypeSlot, Slot, false))
491 if (Constant *C = dyn_cast<Constant>(V))
492 return C; // If we already have the value parsed, just return it
Reid Spencer060d25d2004-06-29 23:29:38 +0000493 else
Reid Spencera86037e2004-07-18 00:12:03 +0000494 error("Value for slot " + utostr(Slot) +
495 " is expected to be a constant!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000496
497 const Type *Ty = getType(TypeSlot);
498 std::pair<const Type*, unsigned> Key(Ty, Slot);
499 ConstantRefsType::iterator I = ConstantFwdRefs.lower_bound(Key);
500
501 if (I != ConstantFwdRefs.end() && I->first == Key) {
502 return I->second;
503 } else {
504 // Create a placeholder for the constant reference and
505 // keep track of the fact that we have a forward ref to recycle it
Reid Spencer46b002c2004-07-11 17:28:43 +0000506 Constant *C = new ConstantPlaceHolder(Ty, Slot);
Reid Spencer060d25d2004-06-29 23:29:38 +0000507
508 // Keep track of the fact that we have a forward ref to recycle it
509 ConstantFwdRefs.insert(I, std::make_pair(Key, C));
510 return C;
511 }
512}
513
514//===----------------------------------------------------------------------===//
515// IR Construction Methods
516//===----------------------------------------------------------------------===//
517
Reid Spencer04cde2c2004-07-04 11:33:49 +0000518/// As values are created, they are inserted into the appropriate place
519/// with this method. The ValueTable argument must be one of ModuleValues
520/// or FunctionValues data members of this class.
Reid Spencer46b002c2004-07-11 17:28:43 +0000521unsigned BytecodeReader::insertValue(Value *Val, unsigned type,
522 ValueTable &ValueTab) {
Reid Spencer060d25d2004-06-29 23:29:38 +0000523 assert((!isa<Constant>(Val) || !cast<Constant>(Val)->isNullValue()) ||
Reid Spencer04cde2c2004-07-04 11:33:49 +0000524 !hasImplicitNull(type) &&
525 "Cannot read null values from bytecode!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000526
527 if (ValueTab.size() <= type)
528 ValueTab.resize(type+1);
529
530 if (!ValueTab[type]) ValueTab[type] = new ValueList();
531
532 ValueTab[type]->push_back(Val);
533
534 bool HasOffset = hasImplicitNull(type);
535 return ValueTab[type]->size()-1 + HasOffset;
536}
537
Reid Spencer04cde2c2004-07-04 11:33:49 +0000538/// Insert the arguments of a function as new values in the reader.
Reid Spencer46b002c2004-07-11 17:28:43 +0000539void BytecodeReader::insertArguments(Function* F) {
Reid Spencer060d25d2004-06-29 23:29:38 +0000540 const FunctionType *FT = F->getFunctionType();
541 Function::aiterator AI = F->abegin();
542 for (FunctionType::param_iterator It = FT->param_begin();
543 It != FT->param_end(); ++It, ++AI)
544 insertValue(AI, getTypeSlot(AI->getType()), FunctionValues);
545}
546
547//===----------------------------------------------------------------------===//
548// Bytecode Parsing Methods
549//===----------------------------------------------------------------------===//
550
Reid Spencer04cde2c2004-07-04 11:33:49 +0000551/// This method parses a single instruction. The instruction is
552/// inserted at the end of the \p BB provided. The arguments of
Misha Brukman44666b12004-09-28 16:57:46 +0000553/// the instruction are provided in the \p Oprnds vector.
Reid Spencer060d25d2004-06-29 23:29:38 +0000554void BytecodeReader::ParseInstruction(std::vector<unsigned> &Oprnds,
Reid Spencer46b002c2004-07-11 17:28:43 +0000555 BasicBlock* BB) {
Reid Spencer060d25d2004-06-29 23:29:38 +0000556 BufPtr SaveAt = At;
557
558 // Clear instruction data
559 Oprnds.clear();
560 unsigned iType = 0;
561 unsigned Opcode = 0;
562 unsigned Op = read_uint();
563
564 // bits Instruction format: Common to all formats
565 // --------------------------
566 // 01-00: Opcode type, fixed to 1.
567 // 07-02: Opcode
568 Opcode = (Op >> 2) & 63;
569 Oprnds.resize((Op >> 0) & 03);
570
571 // Extract the operands
572 switch (Oprnds.size()) {
573 case 1:
574 // bits Instruction format:
575 // --------------------------
576 // 19-08: Resulting type plane
577 // 31-20: Operand #1 (if set to (2^12-1), then zero operands)
578 //
579 iType = (Op >> 8) & 4095;
580 Oprnds[0] = (Op >> 20) & 4095;
581 if (Oprnds[0] == 4095) // Handle special encoding for 0 operands...
582 Oprnds.resize(0);
583 break;
584 case 2:
585 // bits Instruction format:
586 // --------------------------
587 // 15-08: Resulting type plane
588 // 23-16: Operand #1
589 // 31-24: Operand #2
590 //
591 iType = (Op >> 8) & 255;
592 Oprnds[0] = (Op >> 16) & 255;
593 Oprnds[1] = (Op >> 24) & 255;
594 break;
595 case 3:
596 // bits Instruction format:
597 // --------------------------
598 // 13-08: Resulting type plane
599 // 19-14: Operand #1
600 // 25-20: Operand #2
601 // 31-26: Operand #3
602 //
603 iType = (Op >> 8) & 63;
604 Oprnds[0] = (Op >> 14) & 63;
605 Oprnds[1] = (Op >> 20) & 63;
606 Oprnds[2] = (Op >> 26) & 63;
607 break;
608 case 0:
609 At -= 4; // Hrm, try this again...
610 Opcode = read_vbr_uint();
611 Opcode >>= 2;
612 iType = read_vbr_uint();
613
614 unsigned NumOprnds = read_vbr_uint();
615 Oprnds.resize(NumOprnds);
616
617 if (NumOprnds == 0)
Reid Spencer24399722004-07-09 22:21:33 +0000618 error("Zero-argument instruction found; this is invalid.");
Reid Spencer060d25d2004-06-29 23:29:38 +0000619
620 for (unsigned i = 0; i != NumOprnds; ++i)
621 Oprnds[i] = read_vbr_uint();
622 align32();
623 break;
624 }
625
Reid Spencer04cde2c2004-07-04 11:33:49 +0000626 const Type *InstTy = getSanitizedType(iType);
Reid Spencer060d25d2004-06-29 23:29:38 +0000627
Reid Spencer46b002c2004-07-11 17:28:43 +0000628 // We have enough info to inform the handler now.
Reid Spencer04cde2c2004-07-04 11:33:49 +0000629 if (Handler) Handler->handleInstruction(Opcode, InstTy, Oprnds, At-SaveAt);
Reid Spencer060d25d2004-06-29 23:29:38 +0000630
631 // Declare the resulting instruction we'll build.
632 Instruction *Result = 0;
633
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000634 // If this is a bytecode format that did not include the unreachable
635 // instruction, bump up all opcodes numbers to make space.
636 if (hasNoUnreachableInst) {
637 if (Opcode >= Instruction::Unreachable &&
638 Opcode < 62) {
639 ++Opcode;
640 }
641 }
642
Reid Spencer060d25d2004-06-29 23:29:38 +0000643 // Handle binary operators
644 if (Opcode >= Instruction::BinaryOpsBegin &&
645 Opcode < Instruction::BinaryOpsEnd && Oprnds.size() == 2)
646 Result = BinaryOperator::create((Instruction::BinaryOps)Opcode,
647 getValue(iType, Oprnds[0]),
648 getValue(iType, Oprnds[1]));
649
650 switch (Opcode) {
651 default:
Reid Spencer04cde2c2004-07-04 11:33:49 +0000652 if (Result == 0)
Reid Spencer24399722004-07-09 22:21:33 +0000653 error("Illegal instruction read!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000654 break;
655 case Instruction::VAArg:
Reid Spencer04cde2c2004-07-04 11:33:49 +0000656 Result = new VAArgInst(getValue(iType, Oprnds[0]),
Reid Spencer46b002c2004-07-11 17:28:43 +0000657 getSanitizedType(Oprnds[1]));
Reid Spencer060d25d2004-06-29 23:29:38 +0000658 break;
659 case Instruction::VANext:
Reid Spencer04cde2c2004-07-04 11:33:49 +0000660 Result = new VANextInst(getValue(iType, Oprnds[0]),
Reid Spencer46b002c2004-07-11 17:28:43 +0000661 getSanitizedType(Oprnds[1]));
Reid Spencer060d25d2004-06-29 23:29:38 +0000662 break;
663 case Instruction::Cast:
Reid Spencer04cde2c2004-07-04 11:33:49 +0000664 Result = new CastInst(getValue(iType, Oprnds[0]),
Reid Spencer46b002c2004-07-11 17:28:43 +0000665 getSanitizedType(Oprnds[1]));
Reid Spencer060d25d2004-06-29 23:29:38 +0000666 break;
667 case Instruction::Select:
668 Result = new SelectInst(getValue(Type::BoolTyID, Oprnds[0]),
669 getValue(iType, Oprnds[1]),
670 getValue(iType, Oprnds[2]));
671 break;
672 case Instruction::PHI: {
673 if (Oprnds.size() == 0 || (Oprnds.size() & 1))
Reid Spencer24399722004-07-09 22:21:33 +0000674 error("Invalid phi node encountered!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000675
676 PHINode *PN = new PHINode(InstTy);
677 PN->op_reserve(Oprnds.size());
678 for (unsigned i = 0, e = Oprnds.size(); i != e; i += 2)
679 PN->addIncoming(getValue(iType, Oprnds[i]), getBasicBlock(Oprnds[i+1]));
680 Result = PN;
681 break;
682 }
683
684 case Instruction::Shl:
685 case Instruction::Shr:
686 Result = new ShiftInst((Instruction::OtherOps)Opcode,
687 getValue(iType, Oprnds[0]),
688 getValue(Type::UByteTyID, Oprnds[1]));
689 break;
690 case Instruction::Ret:
691 if (Oprnds.size() == 0)
692 Result = new ReturnInst();
693 else if (Oprnds.size() == 1)
694 Result = new ReturnInst(getValue(iType, Oprnds[0]));
695 else
Reid Spencer24399722004-07-09 22:21:33 +0000696 error("Unrecognized instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000697 break;
698
699 case Instruction::Br:
700 if (Oprnds.size() == 1)
701 Result = new BranchInst(getBasicBlock(Oprnds[0]));
702 else if (Oprnds.size() == 3)
703 Result = new BranchInst(getBasicBlock(Oprnds[0]),
Reid Spencer04cde2c2004-07-04 11:33:49 +0000704 getBasicBlock(Oprnds[1]), getValue(Type::BoolTyID , Oprnds[2]));
Reid Spencer060d25d2004-06-29 23:29:38 +0000705 else
Reid Spencer24399722004-07-09 22:21:33 +0000706 error("Invalid number of operands for a 'br' instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000707 break;
708 case Instruction::Switch: {
709 if (Oprnds.size() & 1)
Reid Spencer24399722004-07-09 22:21:33 +0000710 error("Switch statement with odd number of arguments!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000711
712 SwitchInst *I = new SwitchInst(getValue(iType, Oprnds[0]),
713 getBasicBlock(Oprnds[1]));
714 for (unsigned i = 2, e = Oprnds.size(); i != e; i += 2)
715 I->addCase(cast<Constant>(getValue(iType, Oprnds[i])),
716 getBasicBlock(Oprnds[i+1]));
717 Result = I;
718 break;
719 }
720
721 case Instruction::Call: {
722 if (Oprnds.size() == 0)
Reid Spencer24399722004-07-09 22:21:33 +0000723 error("Invalid call instruction encountered!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000724
725 Value *F = getValue(iType, Oprnds[0]);
726
727 // Check to make sure we have a pointer to function type
728 const PointerType *PTy = dyn_cast<PointerType>(F->getType());
Reid Spencer24399722004-07-09 22:21:33 +0000729 if (PTy == 0) error("Call to non function pointer value!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000730 const FunctionType *FTy = dyn_cast<FunctionType>(PTy->getElementType());
Reid Spencer24399722004-07-09 22:21:33 +0000731 if (FTy == 0) error("Call to non function pointer value!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000732
733 std::vector<Value *> Params;
734 if (!FTy->isVarArg()) {
735 FunctionType::param_iterator It = FTy->param_begin();
736
737 for (unsigned i = 1, e = Oprnds.size(); i != e; ++i) {
738 if (It == FTy->param_end())
Reid Spencer24399722004-07-09 22:21:33 +0000739 error("Invalid call instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000740 Params.push_back(getValue(getTypeSlot(*It++), Oprnds[i]));
741 }
742 if (It != FTy->param_end())
Reid Spencer24399722004-07-09 22:21:33 +0000743 error("Invalid call instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000744 } else {
745 Oprnds.erase(Oprnds.begin(), Oprnds.begin()+1);
746
747 unsigned FirstVariableOperand;
748 if (Oprnds.size() < FTy->getNumParams())
Reid Spencer24399722004-07-09 22:21:33 +0000749 error("Call instruction missing operands!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000750
751 // Read all of the fixed arguments
752 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
753 Params.push_back(getValue(getTypeSlot(FTy->getParamType(i)),Oprnds[i]));
754
755 FirstVariableOperand = FTy->getNumParams();
756
Chris Lattner4a242b32004-10-14 01:39:18 +0000757 if ((Oprnds.size()-FirstVariableOperand) & 1)
758 error("Invalid call instruction!"); // Must be pairs of type/value
Reid Spencer060d25d2004-06-29 23:29:38 +0000759
760 for (unsigned i = FirstVariableOperand, e = Oprnds.size();
Reid Spencer04cde2c2004-07-04 11:33:49 +0000761 i != e; i += 2)
Reid Spencer060d25d2004-06-29 23:29:38 +0000762 Params.push_back(getValue(Oprnds[i], Oprnds[i+1]));
763 }
764
765 Result = new CallInst(F, Params);
766 break;
767 }
768 case Instruction::Invoke: {
Reid Spencer04cde2c2004-07-04 11:33:49 +0000769 if (Oprnds.size() < 3)
Reid Spencer24399722004-07-09 22:21:33 +0000770 error("Invalid invoke instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000771 Value *F = getValue(iType, Oprnds[0]);
772
773 // Check to make sure we have a pointer to function type
774 const PointerType *PTy = dyn_cast<PointerType>(F->getType());
Reid Spencer04cde2c2004-07-04 11:33:49 +0000775 if (PTy == 0)
Reid Spencer24399722004-07-09 22:21:33 +0000776 error("Invoke to non function pointer value!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000777 const FunctionType *FTy = dyn_cast<FunctionType>(PTy->getElementType());
Reid Spencer04cde2c2004-07-04 11:33:49 +0000778 if (FTy == 0)
Reid Spencer24399722004-07-09 22:21:33 +0000779 error("Invoke to non function pointer value!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000780
781 std::vector<Value *> Params;
782 BasicBlock *Normal, *Except;
783
784 if (!FTy->isVarArg()) {
785 Normal = getBasicBlock(Oprnds[1]);
786 Except = getBasicBlock(Oprnds[2]);
787
788 FunctionType::param_iterator It = FTy->param_begin();
789 for (unsigned i = 3, e = Oprnds.size(); i != e; ++i) {
790 if (It == FTy->param_end())
Reid Spencer24399722004-07-09 22:21:33 +0000791 error("Invalid invoke instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000792 Params.push_back(getValue(getTypeSlot(*It++), Oprnds[i]));
793 }
794 if (It != FTy->param_end())
Reid Spencer24399722004-07-09 22:21:33 +0000795 error("Invalid invoke instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000796 } else {
797 Oprnds.erase(Oprnds.begin(), Oprnds.begin()+1);
798
799 Normal = getBasicBlock(Oprnds[0]);
800 Except = getBasicBlock(Oprnds[1]);
801
802 unsigned FirstVariableArgument = FTy->getNumParams()+2;
803 for (unsigned i = 2; i != FirstVariableArgument; ++i)
804 Params.push_back(getValue(getTypeSlot(FTy->getParamType(i-2)),
805 Oprnds[i]));
806
807 if (Oprnds.size()-FirstVariableArgument & 1) // Must be type/value pairs
Reid Spencer24399722004-07-09 22:21:33 +0000808 error("Invalid invoke instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000809
810 for (unsigned i = FirstVariableArgument; i < Oprnds.size(); i += 2)
811 Params.push_back(getValue(Oprnds[i], Oprnds[i+1]));
812 }
813
814 Result = new InvokeInst(F, Normal, Except, Params);
815 break;
816 }
817 case Instruction::Malloc:
Reid Spencer04cde2c2004-07-04 11:33:49 +0000818 if (Oprnds.size() > 2)
Reid Spencer24399722004-07-09 22:21:33 +0000819 error("Invalid malloc instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000820 if (!isa<PointerType>(InstTy))
Reid Spencer24399722004-07-09 22:21:33 +0000821 error("Invalid malloc instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000822
823 Result = new MallocInst(cast<PointerType>(InstTy)->getElementType(),
824 Oprnds.size() ? getValue(Type::UIntTyID,
825 Oprnds[0]) : 0);
826 break;
827
828 case Instruction::Alloca:
Reid Spencer04cde2c2004-07-04 11:33:49 +0000829 if (Oprnds.size() > 2)
Reid Spencer24399722004-07-09 22:21:33 +0000830 error("Invalid alloca instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000831 if (!isa<PointerType>(InstTy))
Reid Spencer24399722004-07-09 22:21:33 +0000832 error("Invalid alloca instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000833
834 Result = new AllocaInst(cast<PointerType>(InstTy)->getElementType(),
835 Oprnds.size() ? getValue(Type::UIntTyID,
Reid Spencer04cde2c2004-07-04 11:33:49 +0000836 Oprnds[0]) :0);
Reid Spencer060d25d2004-06-29 23:29:38 +0000837 break;
838 case Instruction::Free:
839 if (!isa<PointerType>(InstTy))
Reid Spencer24399722004-07-09 22:21:33 +0000840 error("Invalid free instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000841 Result = new FreeInst(getValue(iType, Oprnds[0]));
842 break;
843 case Instruction::GetElementPtr: {
844 if (Oprnds.size() == 0 || !isa<PointerType>(InstTy))
Reid Spencer24399722004-07-09 22:21:33 +0000845 error("Invalid getelementptr instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000846
847 std::vector<Value*> Idx;
848
849 const Type *NextTy = InstTy;
850 for (unsigned i = 1, e = Oprnds.size(); i != e; ++i) {
851 const CompositeType *TopTy = dyn_cast_or_null<CompositeType>(NextTy);
Reid Spencer04cde2c2004-07-04 11:33:49 +0000852 if (!TopTy)
Reid Spencer46b002c2004-07-11 17:28:43 +0000853 error("Invalid getelementptr instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000854
855 unsigned ValIdx = Oprnds[i];
856 unsigned IdxTy = 0;
857 if (!hasRestrictedGEPTypes) {
858 // Struct indices are always uints, sequential type indices can be any
859 // of the 32 or 64-bit integer types. The actual choice of type is
860 // encoded in the low two bits of the slot number.
861 if (isa<StructType>(TopTy))
862 IdxTy = Type::UIntTyID;
863 else {
864 switch (ValIdx & 3) {
865 default:
866 case 0: IdxTy = Type::UIntTyID; break;
867 case 1: IdxTy = Type::IntTyID; break;
868 case 2: IdxTy = Type::ULongTyID; break;
869 case 3: IdxTy = Type::LongTyID; break;
870 }
871 ValIdx >>= 2;
872 }
873 } else {
874 IdxTy = isa<StructType>(TopTy) ? Type::UByteTyID : Type::LongTyID;
875 }
876
877 Idx.push_back(getValue(IdxTy, ValIdx));
878
879 // Convert ubyte struct indices into uint struct indices.
880 if (isa<StructType>(TopTy) && hasRestrictedGEPTypes)
881 if (ConstantUInt *C = dyn_cast<ConstantUInt>(Idx.back()))
882 Idx[Idx.size()-1] = ConstantExpr::getCast(C, Type::UIntTy);
883
884 NextTy = GetElementPtrInst::getIndexedType(InstTy, Idx, true);
885 }
886
887 Result = new GetElementPtrInst(getValue(iType, Oprnds[0]), Idx);
888 break;
889 }
890
891 case 62: // volatile load
892 case Instruction::Load:
893 if (Oprnds.size() != 1 || !isa<PointerType>(InstTy))
Reid Spencer24399722004-07-09 22:21:33 +0000894 error("Invalid load instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000895 Result = new LoadInst(getValue(iType, Oprnds[0]), "", Opcode == 62);
896 break;
897
898 case 63: // volatile store
899 case Instruction::Store: {
900 if (!isa<PointerType>(InstTy) || Oprnds.size() != 2)
Reid Spencer24399722004-07-09 22:21:33 +0000901 error("Invalid store instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000902
903 Value *Ptr = getValue(iType, Oprnds[1]);
904 const Type *ValTy = cast<PointerType>(Ptr->getType())->getElementType();
905 Result = new StoreInst(getValue(getTypeSlot(ValTy), Oprnds[0]), Ptr,
906 Opcode == 63);
907 break;
908 }
909 case Instruction::Unwind:
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000910 if (Oprnds.size() != 0) error("Invalid unwind instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000911 Result = new UnwindInst();
912 break;
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000913 case Instruction::Unreachable:
914 if (Oprnds.size() != 0) error("Invalid unreachable instruction!");
915 Result = new UnreachableInst();
916 break;
Reid Spencer060d25d2004-06-29 23:29:38 +0000917 } // end switch(Opcode)
918
919 unsigned TypeSlot;
920 if (Result->getType() == InstTy)
921 TypeSlot = iType;
922 else
923 TypeSlot = getTypeSlot(Result->getType());
924
925 insertValue(Result, TypeSlot, FunctionValues);
926 BB->getInstList().push_back(Result);
927}
928
Reid Spencer04cde2c2004-07-04 11:33:49 +0000929/// Get a particular numbered basic block, which might be a forward reference.
930/// This works together with ParseBasicBlock to handle these forward references
Chris Lattner4a242b32004-10-14 01:39:18 +0000931/// in a clean manner. This function is used when constructing phi, br, switch,
932/// and other instructions that reference basic blocks. Blocks are numbered
Reid Spencer04cde2c2004-07-04 11:33:49 +0000933/// sequentially as they appear in the function.
Reid Spencer060d25d2004-06-29 23:29:38 +0000934BasicBlock *BytecodeReader::getBasicBlock(unsigned ID) {
Chris Lattner4ee8ef22003-10-08 22:52:54 +0000935 // Make sure there is room in the table...
936 if (ParsedBasicBlocks.size() <= ID) ParsedBasicBlocks.resize(ID+1);
937
938 // First check to see if this is a backwards reference, i.e., ParseBasicBlock
939 // has already created this block, or if the forward reference has already
940 // been created.
941 if (ParsedBasicBlocks[ID])
942 return ParsedBasicBlocks[ID];
943
944 // Otherwise, the basic block has not yet been created. Do so and add it to
945 // the ParsedBasicBlocks list.
946 return ParsedBasicBlocks[ID] = new BasicBlock();
947}
948
Reid Spencer04cde2c2004-07-04 11:33:49 +0000949/// In LLVM 1.0 bytecode files, we used to output one basicblock at a time.
950/// This method reads in one of the basicblock packets. This method is not used
951/// for bytecode files after LLVM 1.0
952/// @returns The basic block constructed.
Reid Spencer46b002c2004-07-11 17:28:43 +0000953BasicBlock *BytecodeReader::ParseBasicBlock(unsigned BlockNo) {
954 if (Handler) Handler->handleBasicBlockBegin(BlockNo);
Reid Spencer060d25d2004-06-29 23:29:38 +0000955
956 BasicBlock *BB = 0;
957
Chris Lattner4ee8ef22003-10-08 22:52:54 +0000958 if (ParsedBasicBlocks.size() == BlockNo)
959 ParsedBasicBlocks.push_back(BB = new BasicBlock());
960 else if (ParsedBasicBlocks[BlockNo] == 0)
961 BB = ParsedBasicBlocks[BlockNo] = new BasicBlock();
962 else
963 BB = ParsedBasicBlocks[BlockNo];
Chris Lattner00950542001-06-06 20:29:01 +0000964
Reid Spencer060d25d2004-06-29 23:29:38 +0000965 std::vector<unsigned> Operands;
Reid Spencer46b002c2004-07-11 17:28:43 +0000966 while (moreInBlock())
Reid Spencer060d25d2004-06-29 23:29:38 +0000967 ParseInstruction(Operands, BB);
Chris Lattner00950542001-06-06 20:29:01 +0000968
Reid Spencer46b002c2004-07-11 17:28:43 +0000969 if (Handler) Handler->handleBasicBlockEnd(BlockNo);
Misha Brukman12c29d12003-09-22 23:38:23 +0000970 return BB;
Chris Lattner00950542001-06-06 20:29:01 +0000971}
972
Reid Spencer04cde2c2004-07-04 11:33:49 +0000973/// Parse all of the BasicBlock's & Instruction's in the body of a function.
974/// In post 1.0 bytecode files, we no longer emit basic block individually,
975/// in order to avoid per-basic-block overhead.
976/// @returns Rhe number of basic blocks encountered.
Reid Spencer060d25d2004-06-29 23:29:38 +0000977unsigned BytecodeReader::ParseInstructionList(Function* F) {
Chris Lattner8d1dbd22003-12-01 07:05:31 +0000978 unsigned BlockNo = 0;
979 std::vector<unsigned> Args;
980
Reid Spencer46b002c2004-07-11 17:28:43 +0000981 while (moreInBlock()) {
982 if (Handler) Handler->handleBasicBlockBegin(BlockNo);
Chris Lattner8d1dbd22003-12-01 07:05:31 +0000983 BasicBlock *BB;
984 if (ParsedBasicBlocks.size() == BlockNo)
985 ParsedBasicBlocks.push_back(BB = new BasicBlock());
986 else if (ParsedBasicBlocks[BlockNo] == 0)
987 BB = ParsedBasicBlocks[BlockNo] = new BasicBlock();
988 else
989 BB = ParsedBasicBlocks[BlockNo];
990 ++BlockNo;
991 F->getBasicBlockList().push_back(BB);
992
993 // Read instructions into this basic block until we get to a terminator
Reid Spencer46b002c2004-07-11 17:28:43 +0000994 while (moreInBlock() && !BB->getTerminator())
Reid Spencer060d25d2004-06-29 23:29:38 +0000995 ParseInstruction(Args, BB);
Chris Lattner8d1dbd22003-12-01 07:05:31 +0000996
997 if (!BB->getTerminator())
Reid Spencer24399722004-07-09 22:21:33 +0000998 error("Non-terminated basic block found!");
Reid Spencer5c15fe52004-07-05 00:57:50 +0000999
Reid Spencer46b002c2004-07-11 17:28:43 +00001000 if (Handler) Handler->handleBasicBlockEnd(BlockNo-1);
Chris Lattner8d1dbd22003-12-01 07:05:31 +00001001 }
1002
1003 return BlockNo;
1004}
1005
Reid Spencer04cde2c2004-07-04 11:33:49 +00001006/// Parse a symbol table. This works for both module level and function
1007/// level symbol tables. For function level symbol tables, the CurrentFunction
1008/// parameter must be non-zero and the ST parameter must correspond to
1009/// CurrentFunction's symbol table. For Module level symbol tables, the
1010/// CurrentFunction argument must be zero.
Reid Spencer060d25d2004-06-29 23:29:38 +00001011void BytecodeReader::ParseSymbolTable(Function *CurrentFunction,
Reid Spencer04cde2c2004-07-04 11:33:49 +00001012 SymbolTable *ST) {
1013 if (Handler) Handler->handleSymbolTableBegin(CurrentFunction,ST);
Reid Spencer060d25d2004-06-29 23:29:38 +00001014
Chris Lattner39cacce2003-10-10 05:43:47 +00001015 // Allow efficient basic block lookup by number.
1016 std::vector<BasicBlock*> BBMap;
1017 if (CurrentFunction)
1018 for (Function::iterator I = CurrentFunction->begin(),
1019 E = CurrentFunction->end(); I != E; ++I)
1020 BBMap.push_back(I);
1021
Reid Spencer04cde2c2004-07-04 11:33:49 +00001022 /// In LLVM 1.3 we write types separately from values so
1023 /// The types are always first in the symbol table. This is
1024 /// because Type no longer derives from Value.
Reid Spencer46b002c2004-07-11 17:28:43 +00001025 if (!hasTypeDerivedFromValue) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001026 // Symtab block header: [num entries]
1027 unsigned NumEntries = read_vbr_uint();
Reid Spencer46b002c2004-07-11 17:28:43 +00001028 for (unsigned i = 0; i < NumEntries; ++i) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001029 // Symtab entry: [def slot #][name]
1030 unsigned slot = read_vbr_uint();
1031 std::string Name = read_str();
1032 const Type* T = getType(slot);
1033 ST->insert(Name, T);
1034 }
1035 }
1036
Reid Spencer46b002c2004-07-11 17:28:43 +00001037 while (moreInBlock()) {
Chris Lattner00950542001-06-06 20:29:01 +00001038 // Symtab block header: [num entries][type id number]
Reid Spencer060d25d2004-06-29 23:29:38 +00001039 unsigned NumEntries = read_vbr_uint();
Reid Spencer04cde2c2004-07-04 11:33:49 +00001040 unsigned Typ = 0;
1041 bool isTypeType = read_typeid(Typ);
Chris Lattner00950542001-06-06 20:29:01 +00001042 const Type *Ty = getType(Typ);
Chris Lattner1d670cc2001-09-07 16:37:43 +00001043
Chris Lattner7dc3a2e2003-10-13 14:57:53 +00001044 for (unsigned i = 0; i != NumEntries; ++i) {
Chris Lattner00950542001-06-06 20:29:01 +00001045 // Symtab entry: [def slot #][name]
Reid Spencer060d25d2004-06-29 23:29:38 +00001046 unsigned slot = read_vbr_uint();
1047 std::string Name = read_str();
Chris Lattner00950542001-06-06 20:29:01 +00001048
Reid Spencer04cde2c2004-07-04 11:33:49 +00001049 // if we're reading a pre 1.3 bytecode file and the type plane
1050 // is the "type type", handle it here
Reid Spencer46b002c2004-07-11 17:28:43 +00001051 if (isTypeType) {
1052 const Type* T = getType(slot);
1053 if (T == 0)
1054 error("Failed type look-up for name '" + Name + "'");
1055 ST->insert(Name, T);
1056 continue; // code below must be short circuited
Chris Lattner39cacce2003-10-10 05:43:47 +00001057 } else {
Reid Spencer46b002c2004-07-11 17:28:43 +00001058 Value *V = 0;
1059 if (Typ == Type::LabelTyID) {
1060 if (slot < BBMap.size())
1061 V = BBMap[slot];
1062 } else {
1063 V = getValue(Typ, slot, false); // Find mapping...
1064 }
1065 if (V == 0)
1066 error("Failed value look-up for name '" + Name + "'");
1067 V->setName(Name, ST);
Chris Lattner39cacce2003-10-10 05:43:47 +00001068 }
Chris Lattner00950542001-06-06 20:29:01 +00001069 }
1070 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001071 checkPastBlockEnd("Symbol Table");
Reid Spencer04cde2c2004-07-04 11:33:49 +00001072 if (Handler) Handler->handleSymbolTableEnd();
Chris Lattner00950542001-06-06 20:29:01 +00001073}
1074
Reid Spencer04cde2c2004-07-04 11:33:49 +00001075/// Read in the types portion of a compaction table.
Reid Spencer46b002c2004-07-11 17:28:43 +00001076void BytecodeReader::ParseCompactionTypes(unsigned NumEntries) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001077 for (unsigned i = 0; i != NumEntries; ++i) {
1078 unsigned TypeSlot = 0;
Reid Spencer46b002c2004-07-11 17:28:43 +00001079 if (read_typeid(TypeSlot))
Reid Spencer24399722004-07-09 22:21:33 +00001080 error("Invalid type in compaction table: type type");
Reid Spencer04cde2c2004-07-04 11:33:49 +00001081 const Type *Typ = getGlobalTableType(TypeSlot);
Chris Lattner45b5dd22004-08-03 23:41:28 +00001082 CompactionTypes.push_back(std::make_pair(Typ, TypeSlot));
Reid Spencer46b002c2004-07-11 17:28:43 +00001083 if (Handler) Handler->handleCompactionTableType(i, TypeSlot, Typ);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001084 }
1085}
1086
1087/// Parse a compaction table.
Reid Spencer060d25d2004-06-29 23:29:38 +00001088void BytecodeReader::ParseCompactionTable() {
1089
Reid Spencer46b002c2004-07-11 17:28:43 +00001090 // Notify handler that we're beginning a compaction table.
Reid Spencer04cde2c2004-07-04 11:33:49 +00001091 if (Handler) Handler->handleCompactionTableBegin();
1092
Reid Spencer46b002c2004-07-11 17:28:43 +00001093 // In LLVM 1.3 Type no longer derives from Value. So,
1094 // we always write them first in the compaction table
1095 // because they can't occupy a "type plane" where the
1096 // Values reside.
1097 if (! hasTypeDerivedFromValue) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001098 unsigned NumEntries = read_vbr_uint();
Reid Spencer46b002c2004-07-11 17:28:43 +00001099 ParseCompactionTypes(NumEntries);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001100 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001101
Reid Spencer46b002c2004-07-11 17:28:43 +00001102 // Compaction tables live in separate blocks so we have to loop
1103 // until we've read the whole thing.
1104 while (moreInBlock()) {
1105 // Read the number of Value* entries in the compaction table
Reid Spencer060d25d2004-06-29 23:29:38 +00001106 unsigned NumEntries = read_vbr_uint();
Reid Spencer04cde2c2004-07-04 11:33:49 +00001107 unsigned Ty = 0;
1108 unsigned isTypeType = false;
Reid Spencer060d25d2004-06-29 23:29:38 +00001109
Reid Spencer46b002c2004-07-11 17:28:43 +00001110 // Decode the type from value read in. Most compaction table
1111 // planes will have one or two entries in them. If that's the
1112 // case then the length is encoded in the bottom two bits and
1113 // the higher bits encode the type. This saves another VBR value.
Reid Spencer060d25d2004-06-29 23:29:38 +00001114 if ((NumEntries & 3) == 3) {
Reid Spencer46b002c2004-07-11 17:28:43 +00001115 // In this case, both low-order bits are set (value 3). This
1116 // is a signal that the typeid follows.
Reid Spencer060d25d2004-06-29 23:29:38 +00001117 NumEntries >>= 2;
Reid Spencer04cde2c2004-07-04 11:33:49 +00001118 isTypeType = read_typeid(Ty);
Reid Spencer060d25d2004-06-29 23:29:38 +00001119 } else {
Reid Spencer46b002c2004-07-11 17:28:43 +00001120 // In this case, the low-order bits specify the number of entries
1121 // and the high order bits specify the type.
Reid Spencer060d25d2004-06-29 23:29:38 +00001122 Ty = NumEntries >> 2;
Reid Spencer04cde2c2004-07-04 11:33:49 +00001123 isTypeType = sanitizeTypeId(Ty);
Reid Spencer060d25d2004-06-29 23:29:38 +00001124 NumEntries &= 3;
1125 }
1126
Reid Spencer04cde2c2004-07-04 11:33:49 +00001127 // if we're reading a pre 1.3 bytecode file and the type plane
1128 // is the "type type", handle it here
Reid Spencer46b002c2004-07-11 17:28:43 +00001129 if (isTypeType) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001130 ParseCompactionTypes(NumEntries);
Reid Spencer060d25d2004-06-29 23:29:38 +00001131 } else {
Chris Lattner2c6c14d2004-08-04 00:19:23 +00001132 // Make sure we have enough room for the plane.
Reid Spencer04cde2c2004-07-04 11:33:49 +00001133 if (Ty >= CompactionValues.size())
Reid Spencer46b002c2004-07-11 17:28:43 +00001134 CompactionValues.resize(Ty+1);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001135
Chris Lattner2c6c14d2004-08-04 00:19:23 +00001136 // Make sure the plane is empty or we have some kind of error.
Reid Spencer04cde2c2004-07-04 11:33:49 +00001137 if (!CompactionValues[Ty].empty())
Reid Spencer46b002c2004-07-11 17:28:43 +00001138 error("Compaction table plane contains multiple entries!");
Reid Spencer04cde2c2004-07-04 11:33:49 +00001139
Chris Lattner2c6c14d2004-08-04 00:19:23 +00001140 // Notify handler about the plane.
Reid Spencer46b002c2004-07-11 17:28:43 +00001141 if (Handler) Handler->handleCompactionTablePlane(Ty, NumEntries);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001142
Chris Lattner2c6c14d2004-08-04 00:19:23 +00001143 // Push the implicit zero.
1144 CompactionValues[Ty].push_back(Constant::getNullValue(getType(Ty)));
Reid Spencer46b002c2004-07-11 17:28:43 +00001145
1146 // Read in each of the entries, put them in the compaction table
1147 // and notify the handler that we have a new compaction table value.
Reid Spencer060d25d2004-06-29 23:29:38 +00001148 for (unsigned i = 0; i != NumEntries; ++i) {
Reid Spencer46b002c2004-07-11 17:28:43 +00001149 unsigned ValSlot = read_vbr_uint();
Chris Lattner2c6c14d2004-08-04 00:19:23 +00001150 Value *V = getGlobalTableValue(Ty, ValSlot);
Reid Spencer46b002c2004-07-11 17:28:43 +00001151 CompactionValues[Ty].push_back(V);
Chris Lattner2c6c14d2004-08-04 00:19:23 +00001152 if (Handler) Handler->handleCompactionTableValue(i, Ty, ValSlot);
Reid Spencer060d25d2004-06-29 23:29:38 +00001153 }
1154 }
1155 }
Reid Spencer46b002c2004-07-11 17:28:43 +00001156 // Notify handler that the compaction table is done.
Reid Spencer04cde2c2004-07-04 11:33:49 +00001157 if (Handler) Handler->handleCompactionTableEnd();
Reid Spencer060d25d2004-06-29 23:29:38 +00001158}
1159
Reid Spencer46b002c2004-07-11 17:28:43 +00001160// Parse a single type. The typeid is read in first. If its a primitive type
1161// then nothing else needs to be read, we know how to instantiate it. If its
1162// a derived type, then additional data is read to fill out the type
1163// definition.
1164const Type *BytecodeReader::ParseType() {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001165 unsigned PrimType = 0;
Reid Spencer46b002c2004-07-11 17:28:43 +00001166 if (read_typeid(PrimType))
Reid Spencer24399722004-07-09 22:21:33 +00001167 error("Invalid type (type type) in type constants!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001168
1169 const Type *Result = 0;
1170 if ((Result = Type::getPrimitiveType((Type::TypeID)PrimType)))
1171 return Result;
1172
1173 switch (PrimType) {
1174 case Type::FunctionTyID: {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001175 const Type *RetType = readSanitizedType();
Reid Spencer060d25d2004-06-29 23:29:38 +00001176
1177 unsigned NumParams = read_vbr_uint();
1178
1179 std::vector<const Type*> Params;
Reid Spencer04cde2c2004-07-04 11:33:49 +00001180 while (NumParams--)
1181 Params.push_back(readSanitizedType());
Reid Spencer060d25d2004-06-29 23:29:38 +00001182
1183 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1184 if (isVarArg) Params.pop_back();
1185
1186 Result = FunctionType::get(RetType, Params, isVarArg);
1187 break;
1188 }
1189 case Type::ArrayTyID: {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001190 const Type *ElementType = readSanitizedType();
Reid Spencer060d25d2004-06-29 23:29:38 +00001191 unsigned NumElements = read_vbr_uint();
Reid Spencer060d25d2004-06-29 23:29:38 +00001192 Result = ArrayType::get(ElementType, NumElements);
1193 break;
1194 }
Brian Gaeke715c90b2004-08-20 06:00:58 +00001195 case Type::PackedTyID: {
1196 const Type *ElementType = readSanitizedType();
1197 unsigned NumElements = read_vbr_uint();
1198 Result = PackedType::get(ElementType, NumElements);
1199 break;
1200 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001201 case Type::StructTyID: {
1202 std::vector<const Type*> Elements;
Reid Spencer04cde2c2004-07-04 11:33:49 +00001203 unsigned Typ = 0;
Reid Spencer46b002c2004-07-11 17:28:43 +00001204 if (read_typeid(Typ))
Reid Spencer24399722004-07-09 22:21:33 +00001205 error("Invalid element type (type type) for structure!");
1206
Reid Spencer060d25d2004-06-29 23:29:38 +00001207 while (Typ) { // List is terminated by void/0 typeid
1208 Elements.push_back(getType(Typ));
Reid Spencer46b002c2004-07-11 17:28:43 +00001209 if (read_typeid(Typ))
1210 error("Invalid element type (type type) for structure!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001211 }
1212
1213 Result = StructType::get(Elements);
1214 break;
1215 }
1216 case Type::PointerTyID: {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001217 Result = PointerType::get(readSanitizedType());
Reid Spencer060d25d2004-06-29 23:29:38 +00001218 break;
1219 }
1220
1221 case Type::OpaqueTyID: {
1222 Result = OpaqueType::get();
1223 break;
1224 }
1225
1226 default:
Reid Spencer24399722004-07-09 22:21:33 +00001227 error("Don't know how to deserialize primitive type " + utostr(PrimType));
Reid Spencer060d25d2004-06-29 23:29:38 +00001228 break;
1229 }
Reid Spencer46b002c2004-07-11 17:28:43 +00001230 if (Handler) Handler->handleType(Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001231 return Result;
1232}
1233
Reid Spencer5b472d92004-08-21 20:49:23 +00001234// ParseTypes - We have to use this weird code to handle recursive
Reid Spencer060d25d2004-06-29 23:29:38 +00001235// types. We know that recursive types will only reference the current slab of
1236// values in the type plane, but they can forward reference types before they
1237// have been read. For example, Type #0 might be '{ Ty#1 }' and Type #1 might
1238// be 'Ty#0*'. When reading Type #0, type number one doesn't exist. To fix
1239// this ugly problem, we pessimistically insert an opaque type for each type we
1240// are about to read. This means that forward references will resolve to
1241// something and when we reread the type later, we can replace the opaque type
1242// with a new resolved concrete type.
1243//
Reid Spencer46b002c2004-07-11 17:28:43 +00001244void BytecodeReader::ParseTypes(TypeListTy &Tab, unsigned NumEntries){
Reid Spencer060d25d2004-06-29 23:29:38 +00001245 assert(Tab.size() == 0 && "should not have read type constants in before!");
1246
1247 // Insert a bunch of opaque types to be resolved later...
1248 Tab.reserve(NumEntries);
1249 for (unsigned i = 0; i != NumEntries; ++i)
1250 Tab.push_back(OpaqueType::get());
1251
Reid Spencer5b472d92004-08-21 20:49:23 +00001252 if (Handler)
1253 Handler->handleTypeList(NumEntries);
1254
Reid Spencer060d25d2004-06-29 23:29:38 +00001255 // Loop through reading all of the types. Forward types will make use of the
1256 // opaque types just inserted.
1257 //
1258 for (unsigned i = 0; i != NumEntries; ++i) {
Reid Spencer46b002c2004-07-11 17:28:43 +00001259 const Type* NewTy = ParseType();
Reid Spencer04cde2c2004-07-04 11:33:49 +00001260 const Type* OldTy = Tab[i].get();
1261 if (NewTy == 0)
Reid Spencer24399722004-07-09 22:21:33 +00001262 error("Couldn't parse type!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001263
1264 // Don't directly push the new type on the Tab. Instead we want to replace
1265 // the opaque type we previously inserted with the new concrete value. This
1266 // approach helps with forward references to types. The refinement from the
1267 // abstract (opaque) type to the new type causes all uses of the abstract
1268 // type to use the concrete type (NewTy). This will also cause the opaque
1269 // type to be deleted.
1270 cast<DerivedType>(const_cast<Type*>(OldTy))->refineAbstractTypeTo(NewTy);
1271
1272 // This should have replaced the old opaque type with the new type in the
1273 // value table... or with a preexisting type that was already in the system.
1274 // Let's just make sure it did.
1275 assert(Tab[i] != OldTy && "refineAbstractType didn't work!");
1276 }
1277}
1278
Reid Spencer04cde2c2004-07-04 11:33:49 +00001279/// Parse a single constant value
Reid Spencer46b002c2004-07-11 17:28:43 +00001280Constant *BytecodeReader::ParseConstantValue(unsigned TypeID) {
Reid Spencer060d25d2004-06-29 23:29:38 +00001281 // We must check for a ConstantExpr before switching by type because
1282 // a ConstantExpr can be of any type, and has no explicit value.
1283 //
1284 // 0 if not expr; numArgs if is expr
1285 unsigned isExprNumArgs = read_vbr_uint();
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001286
Reid Spencer060d25d2004-06-29 23:29:38 +00001287 if (isExprNumArgs) {
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001288 // 'undef' is encoded with 'exprnumargs' == 1.
1289 if (!hasNoUndefValue)
1290 if (--isExprNumArgs == 0)
1291 return UndefValue::get(getType(TypeID));
1292
Reid Spencer060d25d2004-06-29 23:29:38 +00001293 // FIXME: Encoding of constant exprs could be much more compact!
1294 std::vector<Constant*> ArgVec;
1295 ArgVec.reserve(isExprNumArgs);
1296 unsigned Opcode = read_vbr_uint();
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001297
1298 // Bytecode files before LLVM 1.4 need have a missing terminator inst.
1299 if (hasNoUnreachableInst) Opcode++;
Reid Spencer060d25d2004-06-29 23:29:38 +00001300
1301 // Read the slot number and types of each of the arguments
1302 for (unsigned i = 0; i != isExprNumArgs; ++i) {
1303 unsigned ArgValSlot = read_vbr_uint();
Reid Spencer04cde2c2004-07-04 11:33:49 +00001304 unsigned ArgTypeSlot = 0;
Reid Spencer46b002c2004-07-11 17:28:43 +00001305 if (read_typeid(ArgTypeSlot))
1306 error("Invalid argument type (type type) for constant value");
Reid Spencer060d25d2004-06-29 23:29:38 +00001307
1308 // Get the arg value from its slot if it exists, otherwise a placeholder
1309 ArgVec.push_back(getConstantValue(ArgTypeSlot, ArgValSlot));
1310 }
1311
1312 // Construct a ConstantExpr of the appropriate kind
1313 if (isExprNumArgs == 1) { // All one-operand expressions
Reid Spencer46b002c2004-07-11 17:28:43 +00001314 if (Opcode != Instruction::Cast)
1315 error("Only Cast instruction has one argument for ConstantExpr");
1316
Reid Spencer060d25d2004-06-29 23:29:38 +00001317 Constant* Result = ConstantExpr::getCast(ArgVec[0], getType(TypeID));
Reid Spencer04cde2c2004-07-04 11:33:49 +00001318 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001319 return Result;
1320 } else if (Opcode == Instruction::GetElementPtr) { // GetElementPtr
1321 std::vector<Constant*> IdxList(ArgVec.begin()+1, ArgVec.end());
1322
1323 if (hasRestrictedGEPTypes) {
1324 const Type *BaseTy = ArgVec[0]->getType();
1325 generic_gep_type_iterator<std::vector<Constant*>::iterator>
1326 GTI = gep_type_begin(BaseTy, IdxList.begin(), IdxList.end()),
1327 E = gep_type_end(BaseTy, IdxList.begin(), IdxList.end());
1328 for (unsigned i = 0; GTI != E; ++GTI, ++i)
1329 if (isa<StructType>(*GTI)) {
1330 if (IdxList[i]->getType() != Type::UByteTy)
Reid Spencer24399722004-07-09 22:21:33 +00001331 error("Invalid index for getelementptr!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001332 IdxList[i] = ConstantExpr::getCast(IdxList[i], Type::UIntTy);
1333 }
1334 }
1335
1336 Constant* Result = ConstantExpr::getGetElementPtr(ArgVec[0], IdxList);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001337 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001338 return Result;
1339 } else if (Opcode == Instruction::Select) {
Reid Spencer46b002c2004-07-11 17:28:43 +00001340 if (ArgVec.size() != 3)
1341 error("Select instruction must have three arguments.");
Reid Spencer060d25d2004-06-29 23:29:38 +00001342 Constant* Result = ConstantExpr::getSelect(ArgVec[0], ArgVec[1],
Reid Spencer04cde2c2004-07-04 11:33:49 +00001343 ArgVec[2]);
1344 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001345 return Result;
1346 } else { // All other 2-operand expressions
1347 Constant* Result = ConstantExpr::get(Opcode, ArgVec[0], ArgVec[1]);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001348 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001349 return Result;
1350 }
1351 }
1352
1353 // Ok, not an ConstantExpr. We now know how to read the given type...
1354 const Type *Ty = getType(TypeID);
1355 switch (Ty->getTypeID()) {
1356 case Type::BoolTyID: {
1357 unsigned Val = read_vbr_uint();
1358 if (Val != 0 && Val != 1)
Reid Spencer24399722004-07-09 22:21:33 +00001359 error("Invalid boolean value read.");
Reid Spencer060d25d2004-06-29 23:29:38 +00001360 Constant* Result = ConstantBool::get(Val == 1);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001361 if (Handler) Handler->handleConstantValue(Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001362 return Result;
1363 }
1364
1365 case Type::UByteTyID: // Unsigned integer types...
1366 case Type::UShortTyID:
1367 case Type::UIntTyID: {
1368 unsigned Val = read_vbr_uint();
1369 if (!ConstantUInt::isValueValidForType(Ty, Val))
Reid Spencer24399722004-07-09 22:21:33 +00001370 error("Invalid unsigned byte/short/int read.");
Reid Spencer060d25d2004-06-29 23:29:38 +00001371 Constant* Result = ConstantUInt::get(Ty, Val);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001372 if (Handler) Handler->handleConstantValue(Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001373 return Result;
1374 }
1375
1376 case Type::ULongTyID: {
1377 Constant* Result = ConstantUInt::get(Ty, read_vbr_uint64());
Reid Spencer04cde2c2004-07-04 11:33:49 +00001378 if (Handler) Handler->handleConstantValue(Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001379 return Result;
1380 }
1381
1382 case Type::SByteTyID: // Signed integer types...
1383 case Type::ShortTyID:
1384 case Type::IntTyID: {
1385 case Type::LongTyID:
1386 int64_t Val = read_vbr_int64();
1387 if (!ConstantSInt::isValueValidForType(Ty, Val))
Reid Spencer24399722004-07-09 22:21:33 +00001388 error("Invalid signed byte/short/int/long read.");
Reid Spencer060d25d2004-06-29 23:29:38 +00001389 Constant* Result = ConstantSInt::get(Ty, Val);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001390 if (Handler) Handler->handleConstantValue(Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001391 return Result;
1392 }
1393
1394 case Type::FloatTyID: {
Reid Spencer46b002c2004-07-11 17:28:43 +00001395 float Val;
1396 read_float(Val);
1397 Constant* Result = ConstantFP::get(Ty, Val);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001398 if (Handler) Handler->handleConstantValue(Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001399 return Result;
1400 }
1401
1402 case Type::DoubleTyID: {
1403 double Val;
Reid Spencer46b002c2004-07-11 17:28:43 +00001404 read_double(Val);
Reid Spencer060d25d2004-06-29 23:29:38 +00001405 Constant* Result = ConstantFP::get(Ty, Val);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001406 if (Handler) Handler->handleConstantValue(Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001407 return Result;
1408 }
1409
Reid Spencer060d25d2004-06-29 23:29:38 +00001410 case Type::ArrayTyID: {
1411 const ArrayType *AT = cast<ArrayType>(Ty);
1412 unsigned NumElements = AT->getNumElements();
1413 unsigned TypeSlot = getTypeSlot(AT->getElementType());
1414 std::vector<Constant*> Elements;
1415 Elements.reserve(NumElements);
1416 while (NumElements--) // Read all of the elements of the constant.
1417 Elements.push_back(getConstantValue(TypeSlot,
1418 read_vbr_uint()));
1419 Constant* Result = ConstantArray::get(AT, Elements);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001420 if (Handler) Handler->handleConstantArray(AT, Elements, TypeSlot, Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001421 return Result;
1422 }
1423
1424 case Type::StructTyID: {
1425 const StructType *ST = cast<StructType>(Ty);
1426
1427 std::vector<Constant *> Elements;
1428 Elements.reserve(ST->getNumElements());
1429 for (unsigned i = 0; i != ST->getNumElements(); ++i)
1430 Elements.push_back(getConstantValue(ST->getElementType(i),
1431 read_vbr_uint()));
1432
1433 Constant* Result = ConstantStruct::get(ST, Elements);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001434 if (Handler) Handler->handleConstantStruct(ST, Elements, Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001435 return Result;
1436 }
1437
Brian Gaeke715c90b2004-08-20 06:00:58 +00001438 case Type::PackedTyID: {
1439 const PackedType *PT = cast<PackedType>(Ty);
1440 unsigned NumElements = PT->getNumElements();
1441 unsigned TypeSlot = getTypeSlot(PT->getElementType());
1442 std::vector<Constant*> Elements;
1443 Elements.reserve(NumElements);
1444 while (NumElements--) // Read all of the elements of the constant.
1445 Elements.push_back(getConstantValue(TypeSlot,
1446 read_vbr_uint()));
1447 Constant* Result = ConstantPacked::get(PT, Elements);
1448 if (Handler) Handler->handleConstantPacked(PT, Elements, TypeSlot, Result);
1449 return Result;
1450 }
1451
Chris Lattner638c3812004-11-19 16:24:05 +00001452 case Type::PointerTyID: { // ConstantPointerRef value (backwards compat).
Reid Spencer060d25d2004-06-29 23:29:38 +00001453 const PointerType *PT = cast<PointerType>(Ty);
1454 unsigned Slot = read_vbr_uint();
1455
1456 // Check to see if we have already read this global variable...
1457 Value *Val = getValue(TypeID, Slot, false);
Reid Spencer060d25d2004-06-29 23:29:38 +00001458 if (Val) {
Chris Lattnerbcb11cf2004-07-27 02:34:49 +00001459 GlobalValue *GV = dyn_cast<GlobalValue>(Val);
1460 if (!GV) error("GlobalValue not in ValueTable!");
1461 if (Handler) Handler->handleConstantPointer(PT, Slot, GV);
1462 return GV;
Reid Spencer060d25d2004-06-29 23:29:38 +00001463 } else {
Reid Spencer24399722004-07-09 22:21:33 +00001464 error("Forward references are not allowed here.");
Reid Spencer060d25d2004-06-29 23:29:38 +00001465 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001466 }
1467
1468 default:
Reid Spencer24399722004-07-09 22:21:33 +00001469 error("Don't know how to deserialize constant value of type '" +
Reid Spencer060d25d2004-06-29 23:29:38 +00001470 Ty->getDescription());
1471 break;
1472 }
Reid Spencer24399722004-07-09 22:21:33 +00001473 return 0;
Reid Spencer060d25d2004-06-29 23:29:38 +00001474}
1475
Reid Spencer04cde2c2004-07-04 11:33:49 +00001476/// Resolve references for constants. This function resolves the forward
1477/// referenced constants in the ConstantFwdRefs map. It uses the
1478/// replaceAllUsesWith method of Value class to substitute the placeholder
1479/// instance with the actual instance.
Reid Spencer060d25d2004-06-29 23:29:38 +00001480void BytecodeReader::ResolveReferencesToConstant(Constant *NewV, unsigned Slot){
Chris Lattner29b789b2003-11-19 17:27:18 +00001481 ConstantRefsType::iterator I =
1482 ConstantFwdRefs.find(std::make_pair(NewV->getType(), Slot));
1483 if (I == ConstantFwdRefs.end()) return; // Never forward referenced?
Chris Lattner00950542001-06-06 20:29:01 +00001484
Chris Lattner29b789b2003-11-19 17:27:18 +00001485 Value *PH = I->second; // Get the placeholder...
1486 PH->replaceAllUsesWith(NewV);
1487 delete PH; // Delete the old placeholder
1488 ConstantFwdRefs.erase(I); // Remove the map entry for it
Vikram S. Advec1e4a812002-07-14 23:04:18 +00001489}
1490
Reid Spencer04cde2c2004-07-04 11:33:49 +00001491/// Parse the constant strings section.
Reid Spencer060d25d2004-06-29 23:29:38 +00001492void BytecodeReader::ParseStringConstants(unsigned NumEntries, ValueTable &Tab){
1493 for (; NumEntries; --NumEntries) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001494 unsigned Typ = 0;
Reid Spencer46b002c2004-07-11 17:28:43 +00001495 if (read_typeid(Typ))
Reid Spencer24399722004-07-09 22:21:33 +00001496 error("Invalid type (type type) for string constant");
Reid Spencer060d25d2004-06-29 23:29:38 +00001497 const Type *Ty = getType(Typ);
1498 if (!isa<ArrayType>(Ty))
Reid Spencer24399722004-07-09 22:21:33 +00001499 error("String constant data invalid!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001500
1501 const ArrayType *ATy = cast<ArrayType>(Ty);
1502 if (ATy->getElementType() != Type::SByteTy &&
1503 ATy->getElementType() != Type::UByteTy)
Reid Spencer24399722004-07-09 22:21:33 +00001504 error("String constant data invalid!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001505
1506 // Read character data. The type tells us how long the string is.
1507 char Data[ATy->getNumElements()];
1508 read_data(Data, Data+ATy->getNumElements());
Chris Lattner52e20b02003-03-19 20:54:26 +00001509
Reid Spencer060d25d2004-06-29 23:29:38 +00001510 std::vector<Constant*> Elements(ATy->getNumElements());
1511 if (ATy->getElementType() == Type::SByteTy)
1512 for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
1513 Elements[i] = ConstantSInt::get(Type::SByteTy, (signed char)Data[i]);
1514 else
1515 for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
1516 Elements[i] = ConstantUInt::get(Type::UByteTy, (unsigned char)Data[i]);
Misha Brukman12c29d12003-09-22 23:38:23 +00001517
Reid Spencer060d25d2004-06-29 23:29:38 +00001518 // Create the constant, inserting it as needed.
1519 Constant *C = ConstantArray::get(ATy, Elements);
1520 unsigned Slot = insertValue(C, Typ, Tab);
1521 ResolveReferencesToConstant(C, Slot);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001522 if (Handler) Handler->handleConstantString(cast<ConstantArray>(C));
Reid Spencer060d25d2004-06-29 23:29:38 +00001523 }
Misha Brukman12c29d12003-09-22 23:38:23 +00001524}
1525
Reid Spencer04cde2c2004-07-04 11:33:49 +00001526/// Parse the constant pool.
Reid Spencer060d25d2004-06-29 23:29:38 +00001527void BytecodeReader::ParseConstantPool(ValueTable &Tab,
Reid Spencer04cde2c2004-07-04 11:33:49 +00001528 TypeListTy &TypeTab,
Reid Spencer46b002c2004-07-11 17:28:43 +00001529 bool isFunction) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001530 if (Handler) Handler->handleGlobalConstantsBegin();
1531
1532 /// In LLVM 1.3 Type does not derive from Value so the types
1533 /// do not occupy a plane. Consequently, we read the types
1534 /// first in the constant pool.
Reid Spencer46b002c2004-07-11 17:28:43 +00001535 if (isFunction && !hasTypeDerivedFromValue) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001536 unsigned NumEntries = read_vbr_uint();
Reid Spencer46b002c2004-07-11 17:28:43 +00001537 ParseTypes(TypeTab, NumEntries);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001538 }
1539
Reid Spencer46b002c2004-07-11 17:28:43 +00001540 while (moreInBlock()) {
Reid Spencer060d25d2004-06-29 23:29:38 +00001541 unsigned NumEntries = read_vbr_uint();
Reid Spencer04cde2c2004-07-04 11:33:49 +00001542 unsigned Typ = 0;
1543 bool isTypeType = read_typeid(Typ);
1544
1545 /// In LLVM 1.2 and before, Types were written to the
1546 /// bytecode file in the "Type Type" plane (#12).
1547 /// In 1.3 plane 12 is now the label plane. Handle this here.
Reid Spencer46b002c2004-07-11 17:28:43 +00001548 if (isTypeType) {
1549 ParseTypes(TypeTab, NumEntries);
Reid Spencer060d25d2004-06-29 23:29:38 +00001550 } else if (Typ == Type::VoidTyID) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001551 /// Use of Type::VoidTyID is a misnomer. It actually means
1552 /// that the following plane is constant strings
Reid Spencer060d25d2004-06-29 23:29:38 +00001553 assert(&Tab == &ModuleValues && "Cannot read strings in functions!");
1554 ParseStringConstants(NumEntries, Tab);
1555 } else {
1556 for (unsigned i = 0; i < NumEntries; ++i) {
1557 Constant *C = ParseConstantValue(Typ);
1558 assert(C && "ParseConstantValue returned NULL!");
1559 unsigned Slot = insertValue(C, Typ, Tab);
Chris Lattner29b789b2003-11-19 17:27:18 +00001560
Reid Spencer060d25d2004-06-29 23:29:38 +00001561 // If we are reading a function constant table, make sure that we adjust
1562 // the slot number to be the real global constant number.
1563 //
1564 if (&Tab != &ModuleValues && Typ < ModuleValues.size() &&
1565 ModuleValues[Typ])
1566 Slot += ModuleValues[Typ]->size();
1567 ResolveReferencesToConstant(C, Slot);
1568 }
1569 }
1570 }
1571 checkPastBlockEnd("Constant Pool");
Reid Spencer04cde2c2004-07-04 11:33:49 +00001572 if (Handler) Handler->handleGlobalConstantsEnd();
Reid Spencer060d25d2004-06-29 23:29:38 +00001573}
Chris Lattner00950542001-06-06 20:29:01 +00001574
Reid Spencer04cde2c2004-07-04 11:33:49 +00001575/// Parse the contents of a function. Note that this function can be
1576/// called lazily by materializeFunction
1577/// @see materializeFunction
Reid Spencer46b002c2004-07-11 17:28:43 +00001578void BytecodeReader::ParseFunctionBody(Function* F) {
Reid Spencer060d25d2004-06-29 23:29:38 +00001579
1580 unsigned FuncSize = BlockEnd - At;
Chris Lattnere3869c82003-04-16 21:16:05 +00001581 GlobalValue::LinkageTypes Linkage = GlobalValue::ExternalLinkage;
1582
Reid Spencer060d25d2004-06-29 23:29:38 +00001583 unsigned LinkageType = read_vbr_uint();
Chris Lattnerc08912f2004-01-14 16:44:44 +00001584 switch (LinkageType) {
1585 case 0: Linkage = GlobalValue::ExternalLinkage; break;
1586 case 1: Linkage = GlobalValue::WeakLinkage; break;
1587 case 2: Linkage = GlobalValue::AppendingLinkage; break;
1588 case 3: Linkage = GlobalValue::InternalLinkage; break;
1589 case 4: Linkage = GlobalValue::LinkOnceLinkage; break;
Reid Spencer060d25d2004-06-29 23:29:38 +00001590 default:
Reid Spencer24399722004-07-09 22:21:33 +00001591 error("Invalid linkage type for Function.");
Reid Spencer060d25d2004-06-29 23:29:38 +00001592 Linkage = GlobalValue::InternalLinkage;
1593 break;
Chris Lattnere3869c82003-04-16 21:16:05 +00001594 }
Chris Lattnerd23b1d32001-11-26 18:56:10 +00001595
Reid Spencer46b002c2004-07-11 17:28:43 +00001596 F->setLinkage(Linkage);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001597 if (Handler) Handler->handleFunctionBegin(F,FuncSize);
Chris Lattner00950542001-06-06 20:29:01 +00001598
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001599 // Keep track of how many basic blocks we have read in...
1600 unsigned BlockNum = 0;
Chris Lattner89e02532004-01-18 21:08:15 +00001601 bool InsertedArguments = false;
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001602
Reid Spencer060d25d2004-06-29 23:29:38 +00001603 BufPtr MyEnd = BlockEnd;
Reid Spencer46b002c2004-07-11 17:28:43 +00001604 while (At < MyEnd) {
Chris Lattner00950542001-06-06 20:29:01 +00001605 unsigned Type, Size;
Reid Spencer060d25d2004-06-29 23:29:38 +00001606 BufPtr OldAt = At;
1607 read_block(Type, Size);
Chris Lattner00950542001-06-06 20:29:01 +00001608
1609 switch (Type) {
Reid Spencerad89bd62004-07-25 18:07:36 +00001610 case BytecodeFormat::ConstantPoolBlockID:
Chris Lattner89e02532004-01-18 21:08:15 +00001611 if (!InsertedArguments) {
1612 // Insert arguments into the value table before we parse the first basic
1613 // block in the function, but after we potentially read in the
1614 // compaction table.
Reid Spencer04cde2c2004-07-04 11:33:49 +00001615 insertArguments(F);
Chris Lattner89e02532004-01-18 21:08:15 +00001616 InsertedArguments = true;
1617 }
1618
Reid Spencer04cde2c2004-07-04 11:33:49 +00001619 ParseConstantPool(FunctionValues, FunctionTypes, true);
Chris Lattner00950542001-06-06 20:29:01 +00001620 break;
1621
Reid Spencerad89bd62004-07-25 18:07:36 +00001622 case BytecodeFormat::CompactionTableBlockID:
Reid Spencer060d25d2004-06-29 23:29:38 +00001623 ParseCompactionTable();
Chris Lattner89e02532004-01-18 21:08:15 +00001624 break;
1625
Chris Lattner00950542001-06-06 20:29:01 +00001626 case BytecodeFormat::BasicBlock: {
Chris Lattner89e02532004-01-18 21:08:15 +00001627 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.
Reid Spencer04cde2c2004-07-04 11:33:49 +00001631 insertArguments(F);
Chris Lattner89e02532004-01-18 21:08:15 +00001632 InsertedArguments = true;
1633 }
1634
Reid Spencer060d25d2004-06-29 23:29:38 +00001635 BasicBlock *BB = ParseBasicBlock(BlockNum++);
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001636 F->getBasicBlockList().push_back(BB);
Chris Lattner00950542001-06-06 20:29:01 +00001637 break;
1638 }
1639
Reid Spencerad89bd62004-07-25 18:07:36 +00001640 case BytecodeFormat::InstructionListBlockID: {
Chris Lattner89e02532004-01-18 21:08:15 +00001641 // Insert arguments into the value table before we parse the instruction
1642 // list for the function, but after we potentially read in the compaction
1643 // table.
1644 if (!InsertedArguments) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001645 insertArguments(F);
Chris Lattner89e02532004-01-18 21:08:15 +00001646 InsertedArguments = true;
1647 }
1648
Reid Spencer060d25d2004-06-29 23:29:38 +00001649 if (BlockNum)
Reid Spencer24399722004-07-09 22:21:33 +00001650 error("Already parsed basic blocks!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001651 BlockNum = ParseInstructionList(F);
Chris Lattner8d1dbd22003-12-01 07:05:31 +00001652 break;
1653 }
1654
Reid Spencerad89bd62004-07-25 18:07:36 +00001655 case BytecodeFormat::SymbolTableBlockID:
Reid Spencer060d25d2004-06-29 23:29:38 +00001656 ParseSymbolTable(F, &F->getSymbolTable());
Chris Lattner00950542001-06-06 20:29:01 +00001657 break;
1658
1659 default:
Reid Spencer060d25d2004-06-29 23:29:38 +00001660 At += Size;
1661 if (OldAt > At)
Reid Spencer24399722004-07-09 22:21:33 +00001662 error("Wrapped around reading bytecode.");
Chris Lattner00950542001-06-06 20:29:01 +00001663 break;
1664 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001665 BlockEnd = MyEnd;
Chris Lattner1d670cc2001-09-07 16:37:43 +00001666
Misha Brukman12c29d12003-09-22 23:38:23 +00001667 // Malformed bc file if read past end of block.
Reid Spencer060d25d2004-06-29 23:29:38 +00001668 align32();
Chris Lattner00950542001-06-06 20:29:01 +00001669 }
1670
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001671 // Make sure there were no references to non-existant basic blocks.
1672 if (BlockNum != ParsedBasicBlocks.size())
Reid Spencer24399722004-07-09 22:21:33 +00001673 error("Illegal basic block operand reference");
Reid Spencer060d25d2004-06-29 23:29:38 +00001674
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001675 ParsedBasicBlocks.clear();
1676
Chris Lattner97330cf2003-10-09 23:10:14 +00001677 // Resolve forward references. Replace any uses of a forward reference value
1678 // with the real value.
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001679
Chris Lattner97330cf2003-10-09 23:10:14 +00001680 // replaceAllUsesWith is very inefficient for instructions which have a LARGE
1681 // number of operands. PHI nodes often have forward references, and can also
1682 // often have a very large number of operands.
Chris Lattner89e02532004-01-18 21:08:15 +00001683 //
1684 // FIXME: REEVALUATE. replaceAllUsesWith is _much_ faster now, and this code
1685 // should be simplified back to using it!
1686 //
Chris Lattner97330cf2003-10-09 23:10:14 +00001687 std::map<Value*, Value*> ForwardRefMapping;
1688 for (std::map<std::pair<unsigned,unsigned>, Value*>::iterator
1689 I = ForwardReferences.begin(), E = ForwardReferences.end();
1690 I != E; ++I)
1691 ForwardRefMapping[I->second] = getValue(I->first.first, I->first.second,
1692 false);
1693
1694 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
1695 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
1696 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
Reid Spencer5b472d92004-08-21 20:49:23 +00001697 if (Value* V = I->getOperand(i))
1698 if (Argument *A = dyn_cast<Argument>(V)) {
1699 std::map<Value*, Value*>::iterator It = ForwardRefMapping.find(A);
1700 if (It != ForwardRefMapping.end()) I->setOperand(i, It->second);
1701 }
Chris Lattner97330cf2003-10-09 23:10:14 +00001702
Chris Lattner8eb10ce2003-10-09 06:05:40 +00001703 while (!ForwardReferences.empty()) {
Chris Lattner35d2ca62003-10-09 22:39:30 +00001704 std::map<std::pair<unsigned,unsigned>, Value*>::iterator I =
1705 ForwardReferences.begin();
Chris Lattner8eb10ce2003-10-09 06:05:40 +00001706 Value *PlaceHolder = I->second;
1707 ForwardReferences.erase(I);
Chris Lattner00950542001-06-06 20:29:01 +00001708
Chris Lattner8eb10ce2003-10-09 06:05:40 +00001709 // Now that all the uses are gone, delete the placeholder...
1710 // If we couldn't find a def (error case), then leak a little
1711 // memory, because otherwise we can't remove all uses!
1712 delete PlaceHolder;
Chris Lattner6e448022003-10-08 21:51:46 +00001713 }
Chris Lattner00950542001-06-06 20:29:01 +00001714
Misha Brukman12c29d12003-09-22 23:38:23 +00001715 // Clear out function-level types...
Reid Spencer060d25d2004-06-29 23:29:38 +00001716 FunctionTypes.clear();
1717 CompactionTypes.clear();
1718 CompactionValues.clear();
1719 freeTable(FunctionValues);
1720
Reid Spencer04cde2c2004-07-04 11:33:49 +00001721 if (Handler) Handler->handleFunctionEnd(F);
Chris Lattner00950542001-06-06 20:29:01 +00001722}
1723
Reid Spencer04cde2c2004-07-04 11:33:49 +00001724/// This function parses LLVM functions lazily. It obtains the type of the
1725/// function and records where the body of the function is in the bytecode
1726/// buffer. The caller can then use the ParseNextFunction and
1727/// ParseAllFunctionBodies to get handler events for the functions.
Reid Spencer060d25d2004-06-29 23:29:38 +00001728void BytecodeReader::ParseFunctionLazily() {
1729 if (FunctionSignatureList.empty())
Reid Spencer24399722004-07-09 22:21:33 +00001730 error("FunctionSignatureList empty!");
Chris Lattner89e02532004-01-18 21:08:15 +00001731
Reid Spencer060d25d2004-06-29 23:29:38 +00001732 Function *Func = FunctionSignatureList.back();
1733 FunctionSignatureList.pop_back();
Chris Lattner24102432004-01-18 22:35:34 +00001734
Reid Spencer060d25d2004-06-29 23:29:38 +00001735 // Save the information for future reading of the function
1736 LazyFunctionLoadMap[Func] = LazyFunctionInfo(BlockStart, BlockEnd);
Chris Lattner89e02532004-01-18 21:08:15 +00001737
Misha Brukmana3e6ad62004-11-14 21:02:55 +00001738 // This function has a body but it's not loaded so it appears `External'.
1739 // Mark it as a `Ghost' instead to notify the users that it has a body.
1740 Func->setLinkage(GlobalValue::GhostLinkage);
1741
Reid Spencer060d25d2004-06-29 23:29:38 +00001742 // Pretend we've `parsed' this function
1743 At = BlockEnd;
1744}
Chris Lattner89e02532004-01-18 21:08:15 +00001745
Reid Spencer04cde2c2004-07-04 11:33:49 +00001746/// The ParserFunction method lazily parses one function. Use this method to
1747/// casue the parser to parse a specific function in the module. Note that
1748/// this will remove the function from what is to be included by
1749/// ParseAllFunctionBodies.
1750/// @see ParseAllFunctionBodies
1751/// @see ParseBytecode
Reid Spencer060d25d2004-06-29 23:29:38 +00001752void BytecodeReader::ParseFunction(Function* Func) {
1753 // Find {start, end} pointers and slot in the map. If not there, we're done.
1754 LazyFunctionMap::iterator Fi = LazyFunctionLoadMap.find(Func);
Chris Lattner89e02532004-01-18 21:08:15 +00001755
Reid Spencer060d25d2004-06-29 23:29:38 +00001756 // Make sure we found it
Reid Spencer46b002c2004-07-11 17:28:43 +00001757 if (Fi == LazyFunctionLoadMap.end()) {
Reid Spencer24399722004-07-09 22:21:33 +00001758 error("Unrecognized function of type " + Func->getType()->getDescription());
Reid Spencer060d25d2004-06-29 23:29:38 +00001759 return;
Chris Lattner89e02532004-01-18 21:08:15 +00001760 }
1761
Reid Spencer060d25d2004-06-29 23:29:38 +00001762 BlockStart = At = Fi->second.Buf;
1763 BlockEnd = Fi->second.EndBuf;
Reid Spencer24399722004-07-09 22:21:33 +00001764 assert(Fi->first == Func && "Found wrong function?");
Reid Spencer060d25d2004-06-29 23:29:38 +00001765
1766 LazyFunctionLoadMap.erase(Fi);
1767
Reid Spencer46b002c2004-07-11 17:28:43 +00001768 this->ParseFunctionBody(Func);
Chris Lattner89e02532004-01-18 21:08:15 +00001769}
1770
Reid Spencer04cde2c2004-07-04 11:33:49 +00001771/// The ParseAllFunctionBodies method parses through all the previously
1772/// unparsed functions in the bytecode file. If you want to completely parse
1773/// a bytecode file, this method should be called after Parsebytecode because
1774/// Parsebytecode only records the locations in the bytecode file of where
1775/// the function definitions are located. This function uses that information
1776/// to materialize the functions.
1777/// @see ParseBytecode
Reid Spencer060d25d2004-06-29 23:29:38 +00001778void BytecodeReader::ParseAllFunctionBodies() {
1779 LazyFunctionMap::iterator Fi = LazyFunctionLoadMap.begin();
1780 LazyFunctionMap::iterator Fe = LazyFunctionLoadMap.end();
Chris Lattner89e02532004-01-18 21:08:15 +00001781
Reid Spencer46b002c2004-07-11 17:28:43 +00001782 while (Fi != Fe) {
Reid Spencer060d25d2004-06-29 23:29:38 +00001783 Function* Func = Fi->first;
1784 BlockStart = At = Fi->second.Buf;
1785 BlockEnd = Fi->second.EndBuf;
1786 this->ParseFunctionBody(Func);
1787 ++Fi;
1788 }
1789}
Chris Lattner89e02532004-01-18 21:08:15 +00001790
Reid Spencer04cde2c2004-07-04 11:33:49 +00001791/// Parse the global type list
Reid Spencer060d25d2004-06-29 23:29:38 +00001792void BytecodeReader::ParseGlobalTypes() {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001793 // Read the number of types
1794 unsigned NumEntries = read_vbr_uint();
Reid Spencer011bed52004-07-09 21:13:53 +00001795
1796 // Ignore the type plane identifier for types if the bc file is pre 1.3
1797 if (hasTypeDerivedFromValue)
1798 read_vbr_uint();
1799
Reid Spencer46b002c2004-07-11 17:28:43 +00001800 ParseTypes(ModuleTypes, NumEntries);
Reid Spencer060d25d2004-06-29 23:29:38 +00001801}
1802
Reid Spencer04cde2c2004-07-04 11:33:49 +00001803/// Parse the Global info (types, global vars, constants)
Reid Spencer060d25d2004-06-29 23:29:38 +00001804void BytecodeReader::ParseModuleGlobalInfo() {
1805
Reid Spencer04cde2c2004-07-04 11:33:49 +00001806 if (Handler) Handler->handleModuleGlobalsBegin();
Chris Lattner00950542001-06-06 20:29:01 +00001807
Chris Lattner70cc3392001-09-10 07:58:01 +00001808 // Read global variables...
Reid Spencer060d25d2004-06-29 23:29:38 +00001809 unsigned VarType = read_vbr_uint();
Chris Lattner70cc3392001-09-10 07:58:01 +00001810 while (VarType != Type::VoidTyID) { // List is terminated by Void
Chris Lattner9dd87702004-04-03 23:43:42 +00001811 // VarType Fields: bit0 = isConstant, bit1 = hasInitializer, bit2,3,4 =
1812 // Linkage, bit4+ = slot#
1813 unsigned SlotNo = VarType >> 5;
Reid Spencer46b002c2004-07-11 17:28:43 +00001814 if (sanitizeTypeId(SlotNo))
Reid Spencer24399722004-07-09 22:21:33 +00001815 error("Invalid type (type type) for global var!");
Chris Lattner9dd87702004-04-03 23:43:42 +00001816 unsigned LinkageID = (VarType >> 2) & 7;
Reid Spencer060d25d2004-06-29 23:29:38 +00001817 bool isConstant = VarType & 1;
1818 bool hasInitializer = VarType & 2;
Chris Lattnere3869c82003-04-16 21:16:05 +00001819 GlobalValue::LinkageTypes Linkage;
1820
Chris Lattnerc08912f2004-01-14 16:44:44 +00001821 switch (LinkageID) {
Chris Lattnerc08912f2004-01-14 16:44:44 +00001822 case 0: Linkage = GlobalValue::ExternalLinkage; break;
1823 case 1: Linkage = GlobalValue::WeakLinkage; break;
1824 case 2: Linkage = GlobalValue::AppendingLinkage; break;
1825 case 3: Linkage = GlobalValue::InternalLinkage; break;
1826 case 4: Linkage = GlobalValue::LinkOnceLinkage; break;
Reid Spencer060d25d2004-06-29 23:29:38 +00001827 default:
Reid Spencer24399722004-07-09 22:21:33 +00001828 error("Unknown linkage type: " + utostr(LinkageID));
Reid Spencer060d25d2004-06-29 23:29:38 +00001829 Linkage = GlobalValue::InternalLinkage;
1830 break;
Chris Lattnere3869c82003-04-16 21:16:05 +00001831 }
1832
1833 const Type *Ty = getType(SlotNo);
Reid Spencer46b002c2004-07-11 17:28:43 +00001834 if (!Ty) {
Reid Spencer24399722004-07-09 22:21:33 +00001835 error("Global has no type! SlotNo=" + utostr(SlotNo));
Reid Spencer060d25d2004-06-29 23:29:38 +00001836 }
1837
Reid Spencer46b002c2004-07-11 17:28:43 +00001838 if (!isa<PointerType>(Ty)) {
Reid Spencer24399722004-07-09 22:21:33 +00001839 error("Global not a pointer type! Ty= " + Ty->getDescription());
Reid Spencer060d25d2004-06-29 23:29:38 +00001840 }
Chris Lattner70cc3392001-09-10 07:58:01 +00001841
Chris Lattner52e20b02003-03-19 20:54:26 +00001842 const Type *ElTy = cast<PointerType>(Ty)->getElementType();
Chris Lattnerd70684f2001-09-18 04:01:05 +00001843
Chris Lattner70cc3392001-09-10 07:58:01 +00001844 // Create the global variable...
Reid Spencer060d25d2004-06-29 23:29:38 +00001845 GlobalVariable *GV = new GlobalVariable(ElTy, isConstant, Linkage,
Chris Lattner52e20b02003-03-19 20:54:26 +00001846 0, "", TheModule);
Chris Lattner29b789b2003-11-19 17:27:18 +00001847 insertValue(GV, SlotNo, ModuleValues);
Chris Lattner05950c32001-10-13 06:47:01 +00001848
Reid Spencer060d25d2004-06-29 23:29:38 +00001849 unsigned initSlot = 0;
1850 if (hasInitializer) {
1851 initSlot = read_vbr_uint();
1852 GlobalInits.push_back(std::make_pair(GV, initSlot));
1853 }
1854
1855 // Notify handler about the global value.
Chris Lattner4a242b32004-10-14 01:39:18 +00001856 if (Handler)
1857 Handler->handleGlobalVariable(ElTy, isConstant, Linkage, SlotNo,initSlot);
Reid Spencer060d25d2004-06-29 23:29:38 +00001858
1859 // Get next item
1860 VarType = read_vbr_uint();
Chris Lattner70cc3392001-09-10 07:58:01 +00001861 }
1862
Chris Lattner52e20b02003-03-19 20:54:26 +00001863 // Read the function objects for all of the functions that are coming
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001864 unsigned FnSignature = read_vbr_uint();
Reid Spencer24399722004-07-09 22:21:33 +00001865
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001866 if (hasNoFlagsForFunctions)
1867 FnSignature = (FnSignature << 5) + 1;
1868
1869 // List is terminated by VoidTy.
1870 while ((FnSignature >> 5) != Type::VoidTyID) {
1871 const Type *Ty = getType(FnSignature >> 5);
Chris Lattner927b1852003-10-09 20:22:47 +00001872 if (!isa<PointerType>(Ty) ||
Reid Spencer060d25d2004-06-29 23:29:38 +00001873 !isa<FunctionType>(cast<PointerType>(Ty)->getElementType())) {
Reid Spencer24399722004-07-09 22:21:33 +00001874 error("Function not a pointer to function type! Ty = " +
Reid Spencer46b002c2004-07-11 17:28:43 +00001875 Ty->getDescription());
Reid Spencer060d25d2004-06-29 23:29:38 +00001876 }
Chris Lattner8cdc6b72002-10-23 00:51:54 +00001877
Chris Lattner2a7b6ba2003-03-06 17:15:19 +00001878 // We create functions by passing the underlying FunctionType to create...
Reid Spencer060d25d2004-06-29 23:29:38 +00001879 const FunctionType* FTy =
1880 cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
Chris Lattner00950542001-06-06 20:29:01 +00001881
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001882
Chris Lattner18549c22004-11-15 21:43:03 +00001883 // Insert the place holder.
1884 Function* Func = new Function(FTy, GlobalValue::ExternalLinkage,
Reid Spencer04cde2c2004-07-04 11:33:49 +00001885 "", TheModule);
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001886 insertValue(Func, FnSignature >> 5, ModuleValues);
1887
1888 // Flags are not used yet.
Chris Lattner97fbc502004-11-15 22:38:52 +00001889 unsigned Flags = FnSignature & 31;
Chris Lattner00950542001-06-06 20:29:01 +00001890
Chris Lattner97fbc502004-11-15 22:38:52 +00001891 // Save this for later so we know type of lazily instantiated functions.
1892 // Note that known-external functions do not have FunctionInfo blocks, so we
1893 // do not add them to the FunctionSignatureList.
1894 if ((Flags & (1 << 4)) == 0)
1895 FunctionSignatureList.push_back(Func);
Chris Lattner52e20b02003-03-19 20:54:26 +00001896
Reid Spencer04cde2c2004-07-04 11:33:49 +00001897 if (Handler) Handler->handleFunctionDeclaration(Func);
Reid Spencer060d25d2004-06-29 23:29:38 +00001898
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001899 // Get the next function signature.
1900 FnSignature = read_vbr_uint();
1901 if (hasNoFlagsForFunctions)
1902 FnSignature = (FnSignature << 5) + 1;
Chris Lattner00950542001-06-06 20:29:01 +00001903 }
1904
Chris Lattner74734132002-08-17 22:01:27 +00001905 // Now that the function signature list is set up, reverse it so that we can
1906 // remove elements efficiently from the back of the vector.
1907 std::reverse(FunctionSignatureList.begin(), FunctionSignatureList.end());
Chris Lattner00950542001-06-06 20:29:01 +00001908
Reid Spencerad89bd62004-07-25 18:07:36 +00001909 // If this bytecode format has dependent library information in it ..
1910 if (!hasNoDependentLibraries) {
1911 // Read in the number of dependent library items that follow
1912 unsigned num_dep_libs = read_vbr_uint();
1913 std::string dep_lib;
1914 while( num_dep_libs-- ) {
1915 dep_lib = read_str();
Reid Spencerada16182004-07-25 21:36:26 +00001916 TheModule->addLibrary(dep_lib);
Reid Spencer5b472d92004-08-21 20:49:23 +00001917 if (Handler)
1918 Handler->handleDependentLibrary(dep_lib);
Reid Spencerad89bd62004-07-25 18:07:36 +00001919 }
1920
Reid Spencer5b472d92004-08-21 20:49:23 +00001921
Reid Spencerad89bd62004-07-25 18:07:36 +00001922 // Read target triple and place into the module
1923 std::string triple = read_str();
1924 TheModule->setTargetTriple(triple);
Reid Spencer5b472d92004-08-21 20:49:23 +00001925 if (Handler)
1926 Handler->handleTargetTriple(triple);
Reid Spencerad89bd62004-07-25 18:07:36 +00001927 }
1928
1929 if (hasInconsistentModuleGlobalInfo)
1930 align32();
1931
Chris Lattner00950542001-06-06 20:29:01 +00001932 // This is for future proofing... in the future extra fields may be added that
1933 // we don't understand, so we transparently ignore them.
1934 //
Reid Spencer060d25d2004-06-29 23:29:38 +00001935 At = BlockEnd;
1936
Reid Spencer04cde2c2004-07-04 11:33:49 +00001937 if (Handler) Handler->handleModuleGlobalsEnd();
Chris Lattner00950542001-06-06 20:29:01 +00001938}
1939
Reid Spencer04cde2c2004-07-04 11:33:49 +00001940/// Parse the version information and decode it by setting flags on the
1941/// Reader that enable backward compatibility of the reader.
Reid Spencer060d25d2004-06-29 23:29:38 +00001942void BytecodeReader::ParseVersionInfo() {
1943 unsigned Version = read_vbr_uint();
Chris Lattner036b8aa2003-03-06 17:55:45 +00001944
1945 // Unpack version number: low four bits are for flags, top bits = version
Chris Lattnerd445c6b2003-08-24 13:47:36 +00001946 Module::Endianness Endianness;
1947 Module::PointerSize PointerSize;
1948 Endianness = (Version & 1) ? Module::BigEndian : Module::LittleEndian;
1949 PointerSize = (Version & 2) ? Module::Pointer64 : Module::Pointer32;
1950
1951 bool hasNoEndianness = Version & 4;
1952 bool hasNoPointerSize = Version & 8;
1953
1954 RevisionNum = Version >> 4;
Chris Lattnere3869c82003-04-16 21:16:05 +00001955
1956 // Default values for the current bytecode version
Chris Lattner44d0eeb2004-01-15 17:55:01 +00001957 hasInconsistentModuleGlobalInfo = false;
Chris Lattner80b97342004-01-17 23:25:43 +00001958 hasExplicitPrimitiveZeros = false;
Chris Lattner5fa428f2004-04-05 01:27:26 +00001959 hasRestrictedGEPTypes = false;
Reid Spencer04cde2c2004-07-04 11:33:49 +00001960 hasTypeDerivedFromValue = false;
Reid Spencerad89bd62004-07-25 18:07:36 +00001961 hasLongBlockHeaders = false;
Reid Spencerad89bd62004-07-25 18:07:36 +00001962 has32BitTypes = false;
1963 hasNoDependentLibraries = false;
Reid Spencer38d54be2004-08-17 07:45:14 +00001964 hasAlignment = false;
Reid Spencer5b472d92004-08-21 20:49:23 +00001965 hasInconsistentBBSlotNums = false;
1966 hasVBRByteTypes = false;
1967 hasUnnecessaryModuleBlockId = false;
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001968 hasNoUndefValue = false;
1969 hasNoFlagsForFunctions = false;
1970 hasNoUnreachableInst = false;
Chris Lattner036b8aa2003-03-06 17:55:45 +00001971
1972 switch (RevisionNum) {
Reid Spencer5b472d92004-08-21 20:49:23 +00001973 case 0: // LLVM 1.0, 1.1 (Released)
Chris Lattner9e893e82004-01-14 23:35:21 +00001974 // Base LLVM 1.0 bytecode format.
Chris Lattner44d0eeb2004-01-15 17:55:01 +00001975 hasInconsistentModuleGlobalInfo = true;
Chris Lattner80b97342004-01-17 23:25:43 +00001976 hasExplicitPrimitiveZeros = true;
Reid Spencer04cde2c2004-07-04 11:33:49 +00001977
Chris Lattner80b97342004-01-17 23:25:43 +00001978 // FALL THROUGH
Reid Spencer5b472d92004-08-21 20:49:23 +00001979
1980 case 1: // LLVM 1.2 (Released)
Chris Lattner9e893e82004-01-14 23:35:21 +00001981 // LLVM 1.2 added explicit support for emitting strings efficiently.
Chris Lattner44d0eeb2004-01-15 17:55:01 +00001982
1983 // Also, it fixed the problem where the size of the ModuleGlobalInfo block
1984 // included the size for the alignment at the end, where the rest of the
1985 // blocks did not.
Chris Lattner5fa428f2004-04-05 01:27:26 +00001986
1987 // LLVM 1.2 and before required that GEP indices be ubyte constants for
1988 // structures and longs for sequential types.
1989 hasRestrictedGEPTypes = true;
1990
Reid Spencer04cde2c2004-07-04 11:33:49 +00001991 // LLVM 1.2 and before had the Type class derive from Value class. This
1992 // changed in release 1.3 and consequently LLVM 1.3 bytecode files are
1993 // written differently because Types can no longer be part of the
1994 // type planes for Values.
1995 hasTypeDerivedFromValue = true;
1996
Chris Lattner5fa428f2004-04-05 01:27:26 +00001997 // FALL THROUGH
Reid Spencerad89bd62004-07-25 18:07:36 +00001998
Reid Spencer5b472d92004-08-21 20:49:23 +00001999 case 2: // 1.2.5 (Not Released)
Reid Spencerad89bd62004-07-25 18:07:36 +00002000
Reid Spencer5b472d92004-08-21 20:49:23 +00002001 // LLVM 1.2 and earlier had two-word block headers. This is a bit wasteful,
Chris Lattner4a242b32004-10-14 01:39:18 +00002002 // especially for small files where the 8 bytes per block is a large
2003 // fraction of the total block size. In LLVM 1.3, the block type and length
2004 // are compressed into a single 32-bit unsigned integer. 27 bits for length,
2005 // 5 bits for block type.
Reid Spencerad89bd62004-07-25 18:07:36 +00002006 hasLongBlockHeaders = true;
2007
Reid Spencer5b472d92004-08-21 20:49:23 +00002008 // LLVM 1.2 and earlier wrote type slot numbers as vbr_uint32. In LLVM 1.3
Chris Lattner4a242b32004-10-14 01:39:18 +00002009 // this has been reduced to vbr_uint24. It shouldn't make much difference
2010 // since we haven't run into a module with > 24 million types, but for
2011 // safety the 24-bit restriction has been enforced in 1.3 to free some bits
2012 // in various places and to ensure consistency.
Reid Spencerad89bd62004-07-25 18:07:36 +00002013 has32BitTypes = true;
2014
Reid Spencer5b472d92004-08-21 20:49:23 +00002015 // LLVM 1.2 and earlier did not provide a target triple nor a list of
2016 // libraries on which the bytecode is dependent. LLVM 1.3 provides these
2017 // features, for use in future versions of LLVM.
Reid Spencerad89bd62004-07-25 18:07:36 +00002018 hasNoDependentLibraries = true;
2019
2020 // FALL THROUGH
Reid Spencer5b472d92004-08-21 20:49:23 +00002021
2022 case 3: // LLVM 1.3 (Released)
2023 // LLVM 1.3 and earlier caused alignment bytes to be written on some block
2024 // boundaries and at the end of some strings. In extreme cases (e.g. lots
2025 // of GEP references to a constant array), this can increase the file size
2026 // by 30% or more. In version 1.4 alignment is done away with completely.
Reid Spencer38d54be2004-08-17 07:45:14 +00002027 hasAlignment = true;
2028
2029 // FALL THROUGH
Reid Spencer5b472d92004-08-21 20:49:23 +00002030
2031 case 4: // 1.3.1 (Not Released)
Chris Lattnera79e7cc2004-10-16 18:18:16 +00002032 // In version 4, we did not support the 'undef' constant.
2033 hasNoUndefValue = true;
2034
2035 // In version 4 and above, we did not include space for flags for functions
2036 // in the module info block.
2037 hasNoFlagsForFunctions = true;
2038
2039 // In version 4 and above, we did not include the 'unreachable' instruction
2040 // in the opcode numbering in the bytecode file.
2041 hasNoUnreachableInst = true;
Chris Lattner2e7ec122004-10-16 18:56:02 +00002042 break;
Chris Lattnera79e7cc2004-10-16 18:18:16 +00002043
2044 // FALL THROUGH
2045
2046 case 5: // 1.x.x (Not Released)
Chris Lattnera79e7cc2004-10-16 18:18:16 +00002047 break;
Chris Lattner2e7ec122004-10-16 18:56:02 +00002048 // FIXME: NONE of this is implemented yet!
Chris Lattnera79e7cc2004-10-16 18:18:16 +00002049
2050 // In version 5, basic blocks have a minimum index of 0 whereas all the
Reid Spencer5b472d92004-08-21 20:49:23 +00002051 // other primitives have a minimum index of 1 (because 0 is the "null"
2052 // value. In version 5, we made this consistent.
2053 hasInconsistentBBSlotNums = true;
Chris Lattnerc08912f2004-01-14 16:44:44 +00002054
Chris Lattnera79e7cc2004-10-16 18:18:16 +00002055 // In version 5, the types SByte and UByte were encoded as vbr_uint so that
Reid Spencer5b472d92004-08-21 20:49:23 +00002056 // signed values > 63 and unsigned values >127 would be encoded as two
2057 // bytes. In version 5, they are encoded directly in a single byte.
2058 hasVBRByteTypes = true;
2059
Chris Lattnera79e7cc2004-10-16 18:18:16 +00002060 // In version 5, modules begin with a "Module Block" which encodes a 4-byte
Reid Spencer5b472d92004-08-21 20:49:23 +00002061 // integer value 0x01 to identify the module block. This is unnecessary and
2062 // removed in version 5.
2063 hasUnnecessaryModuleBlockId = true;
2064
Chris Lattner036b8aa2003-03-06 17:55:45 +00002065 default:
Reid Spencer24399722004-07-09 22:21:33 +00002066 error("Unknown bytecode version number: " + itostr(RevisionNum));
Chris Lattner036b8aa2003-03-06 17:55:45 +00002067 }
2068
Chris Lattnerd445c6b2003-08-24 13:47:36 +00002069 if (hasNoEndianness) Endianness = Module::AnyEndianness;
2070 if (hasNoPointerSize) PointerSize = Module::AnyPointerSize;
Chris Lattner76e38962003-04-22 18:15:10 +00002071
Brian Gaekefe2102b2004-07-14 20:33:13 +00002072 TheModule->setEndianness(Endianness);
2073 TheModule->setPointerSize(PointerSize);
2074
Reid Spencer46b002c2004-07-11 17:28:43 +00002075 if (Handler) Handler->handleVersionInfo(RevisionNum, Endianness, PointerSize);
Chris Lattner036b8aa2003-03-06 17:55:45 +00002076}
2077
Reid Spencer04cde2c2004-07-04 11:33:49 +00002078/// Parse a whole module.
Reid Spencer060d25d2004-06-29 23:29:38 +00002079void BytecodeReader::ParseModule() {
Chris Lattner00950542001-06-06 20:29:01 +00002080 unsigned Type, Size;
Chris Lattner00950542001-06-06 20:29:01 +00002081
Reid Spencer060d25d2004-06-29 23:29:38 +00002082 FunctionSignatureList.clear(); // Just in case...
Chris Lattner00950542001-06-06 20:29:01 +00002083
2084 // Read into instance variables...
Reid Spencer060d25d2004-06-29 23:29:38 +00002085 ParseVersionInfo();
Reid Spencerad89bd62004-07-25 18:07:36 +00002086 align32();
Chris Lattner00950542001-06-06 20:29:01 +00002087
Reid Spencer060d25d2004-06-29 23:29:38 +00002088 bool SeenModuleGlobalInfo = false;
2089 bool SeenGlobalTypePlane = false;
2090 BufPtr MyEnd = BlockEnd;
2091 while (At < MyEnd) {
2092 BufPtr OldAt = At;
2093 read_block(Type, Size);
2094
Chris Lattner00950542001-06-06 20:29:01 +00002095 switch (Type) {
Reid Spencer060d25d2004-06-29 23:29:38 +00002096
Reid Spencerad89bd62004-07-25 18:07:36 +00002097 case BytecodeFormat::GlobalTypePlaneBlockID:
Reid Spencer46b002c2004-07-11 17:28:43 +00002098 if (SeenGlobalTypePlane)
Reid Spencer24399722004-07-09 22:21:33 +00002099 error("Two GlobalTypePlane Blocks Encountered!");
Reid Spencer060d25d2004-06-29 23:29:38 +00002100
Reid Spencer5b472d92004-08-21 20:49:23 +00002101 if (Size > 0)
2102 ParseGlobalTypes();
Reid Spencer060d25d2004-06-29 23:29:38 +00002103 SeenGlobalTypePlane = true;
Chris Lattner52e20b02003-03-19 20:54:26 +00002104 break;
2105
Reid Spencerad89bd62004-07-25 18:07:36 +00002106 case BytecodeFormat::ModuleGlobalInfoBlockID:
Reid Spencer46b002c2004-07-11 17:28:43 +00002107 if (SeenModuleGlobalInfo)
Reid Spencer24399722004-07-09 22:21:33 +00002108 error("Two ModuleGlobalInfo Blocks Encountered!");
Reid Spencer060d25d2004-06-29 23:29:38 +00002109 ParseModuleGlobalInfo();
2110 SeenModuleGlobalInfo = true;
Chris Lattner52e20b02003-03-19 20:54:26 +00002111 break;
2112
Reid Spencerad89bd62004-07-25 18:07:36 +00002113 case BytecodeFormat::ConstantPoolBlockID:
Reid Spencer04cde2c2004-07-04 11:33:49 +00002114 ParseConstantPool(ModuleValues, ModuleTypes,false);
Chris Lattner00950542001-06-06 20:29:01 +00002115 break;
2116
Reid Spencerad89bd62004-07-25 18:07:36 +00002117 case BytecodeFormat::FunctionBlockID:
Reid Spencer060d25d2004-06-29 23:29:38 +00002118 ParseFunctionLazily();
Chris Lattner00950542001-06-06 20:29:01 +00002119 break;
Chris Lattner00950542001-06-06 20:29:01 +00002120
Reid Spencerad89bd62004-07-25 18:07:36 +00002121 case BytecodeFormat::SymbolTableBlockID:
Reid Spencer060d25d2004-06-29 23:29:38 +00002122 ParseSymbolTable(0, &TheModule->getSymbolTable());
Chris Lattner00950542001-06-06 20:29:01 +00002123 break;
Reid Spencer060d25d2004-06-29 23:29:38 +00002124
Chris Lattner00950542001-06-06 20:29:01 +00002125 default:
Reid Spencer060d25d2004-06-29 23:29:38 +00002126 At += Size;
2127 if (OldAt > At) {
Reid Spencer46b002c2004-07-11 17:28:43 +00002128 error("Unexpected Block of Type #" + utostr(Type) + " encountered!");
Reid Spencer060d25d2004-06-29 23:29:38 +00002129 }
Chris Lattner00950542001-06-06 20:29:01 +00002130 break;
2131 }
Reid Spencer060d25d2004-06-29 23:29:38 +00002132 BlockEnd = MyEnd;
2133 align32();
Chris Lattner00950542001-06-06 20:29:01 +00002134 }
2135
Chris Lattner52e20b02003-03-19 20:54:26 +00002136 // After the module constant pool has been read, we can safely initialize
2137 // global variables...
2138 while (!GlobalInits.empty()) {
2139 GlobalVariable *GV = GlobalInits.back().first;
2140 unsigned Slot = GlobalInits.back().second;
2141 GlobalInits.pop_back();
2142
2143 // Look up the initializer value...
Chris Lattner29b789b2003-11-19 17:27:18 +00002144 // FIXME: Preserve this type ID!
Reid Spencer060d25d2004-06-29 23:29:38 +00002145
2146 const llvm::PointerType* GVType = GV->getType();
2147 unsigned TypeSlot = getTypeSlot(GVType->getElementType());
Chris Lattner93361992004-01-15 18:45:25 +00002148 if (Constant *CV = getConstantValue(TypeSlot, Slot)) {
Misha Brukman12c29d12003-09-22 23:38:23 +00002149 if (GV->hasInitializer())
Reid Spencer24399722004-07-09 22:21:33 +00002150 error("Global *already* has an initializer?!");
Reid Spencer04cde2c2004-07-04 11:33:49 +00002151 if (Handler) Handler->handleGlobalInitializer(GV,CV);
Chris Lattner93361992004-01-15 18:45:25 +00002152 GV->setInitializer(CV);
Chris Lattner52e20b02003-03-19 20:54:26 +00002153 } else
Reid Spencer24399722004-07-09 22:21:33 +00002154 error("Cannot find initializer value.");
Chris Lattner52e20b02003-03-19 20:54:26 +00002155 }
2156
Reid Spencer060d25d2004-06-29 23:29:38 +00002157 /// Make sure we pulled them all out. If we didn't then there's a declaration
2158 /// but a missing body. That's not allowed.
Misha Brukman12c29d12003-09-22 23:38:23 +00002159 if (!FunctionSignatureList.empty())
Reid Spencer24399722004-07-09 22:21:33 +00002160 error("Function declared, but bytecode stream ended before definition");
Chris Lattner00950542001-06-06 20:29:01 +00002161}
2162
Reid Spencer04cde2c2004-07-04 11:33:49 +00002163/// This function completely parses a bytecode buffer given by the \p Buf
2164/// and \p Length parameters.
Reid Spencer46b002c2004-07-11 17:28:43 +00002165void BytecodeReader::ParseBytecode(BufPtr Buf, unsigned Length,
Reid Spencer5b472d92004-08-21 20:49:23 +00002166 const std::string &ModuleID) {
Misha Brukmane0dd0d42003-09-23 16:15:29 +00002167
Reid Spencer060d25d2004-06-29 23:29:38 +00002168 try {
2169 At = MemStart = BlockStart = Buf;
2170 MemEnd = BlockEnd = Buf + Length;
Misha Brukmane0dd0d42003-09-23 16:15:29 +00002171
Reid Spencer060d25d2004-06-29 23:29:38 +00002172 // Create the module
2173 TheModule = new Module(ModuleID);
Chris Lattner00950542001-06-06 20:29:01 +00002174
Reid Spencer04cde2c2004-07-04 11:33:49 +00002175 if (Handler) Handler->handleStart(TheModule, Length);
Reid Spencer060d25d2004-06-29 23:29:38 +00002176
Reid Spencerf0c977c2004-11-07 18:20:55 +00002177 // Read the four bytes of the signature.
2178 unsigned Sig = read_uint();
Reid Spencer17f52c52004-11-06 23:17:23 +00002179
Reid Spencerf0c977c2004-11-07 18:20:55 +00002180 // If this is a compressed file
2181 if (Sig == ('l' | ('l' << 8) | ('v' << 16) | ('c' << 24))) {
Reid Spencer17f52c52004-11-06 23:17:23 +00002182
Reid Spencerf0c977c2004-11-07 18:20:55 +00002183 // Invoke the decompression of the bytecode. Note that we have to skip the
2184 // file's magic number which is not part of the compressed block. Hence,
Reid Spencer61aaf2e2004-11-14 21:59:21 +00002185 // the Buf+4 and Length-4. The result goes into decompressedBlock, a data
2186 // member for retention until BytecodeReader is destructed.
2187 unsigned decompressedLength = Compressor::decompressToNewBuffer(
2188 (char*)Buf+4,Length-4,decompressedBlock);
Reid Spencerf0c977c2004-11-07 18:20:55 +00002189
2190 // We must adjust the buffer pointers used by the bytecode reader to point
Reid Spencer61aaf2e2004-11-14 21:59:21 +00002191 // into the new decompressed block. After decompression, the
2192 // decompressedBlock will point to a contiguous memory area that has
Reid Spencerf0c977c2004-11-07 18:20:55 +00002193 // the decompressed data.
Reid Spencer61aaf2e2004-11-14 21:59:21 +00002194 At = MemStart = BlockStart = Buf = (BufPtr) decompressedBlock;
Reid Spencerf0c977c2004-11-07 18:20:55 +00002195 MemEnd = BlockEnd = Buf + decompressedLength;
Reid Spencer17f52c52004-11-06 23:17:23 +00002196
Reid Spencerf0c977c2004-11-07 18:20:55 +00002197 // else if this isn't a regular (uncompressed) bytecode file, then its
2198 // and error, generate that now.
2199 } else if (Sig != ('l' | ('l' << 8) | ('v' << 16) | ('m' << 24))) {
2200 error("Invalid bytecode signature: " + utohexstr(Sig));
Reid Spencer060d25d2004-06-29 23:29:38 +00002201 }
2202
Reid Spencer060d25d2004-06-29 23:29:38 +00002203 // Tell the handler we're starting a module
Reid Spencer04cde2c2004-07-04 11:33:49 +00002204 if (Handler) Handler->handleModuleBegin(ModuleID);
Reid Spencer060d25d2004-06-29 23:29:38 +00002205
Reid Spencerad89bd62004-07-25 18:07:36 +00002206 // Get the module block and size and verify. This is handled specially
2207 // because the module block/size is always written in long format. Other
2208 // blocks are written in short format so the read_block method is used.
Reid Spencer060d25d2004-06-29 23:29:38 +00002209 unsigned Type, Size;
Reid Spencerad89bd62004-07-25 18:07:36 +00002210 Type = read_uint();
2211 Size = read_uint();
2212 if (Type != BytecodeFormat::ModuleBlockID) {
Reid Spencer24399722004-07-09 22:21:33 +00002213 error("Expected Module Block! Type:" + utostr(Type) + ", Size:"
Reid Spencer46b002c2004-07-11 17:28:43 +00002214 + utostr(Size));
Reid Spencer060d25d2004-06-29 23:29:38 +00002215 }
Chris Lattner56bc8942004-09-27 16:59:06 +00002216
2217 // It looks like the darwin ranlib program is broken, and adds trailing
2218 // garbage to the end of some bytecode files. This hack allows the bc
2219 // reader to ignore trailing garbage on bytecode files.
2220 if (At + Size < MemEnd)
2221 MemEnd = BlockEnd = At+Size;
2222
2223 if (At + Size != MemEnd)
Reid Spencer24399722004-07-09 22:21:33 +00002224 error("Invalid Top Level Block Length! Type:" + utostr(Type)
Reid Spencer46b002c2004-07-11 17:28:43 +00002225 + ", Size:" + utostr(Size));
Reid Spencer060d25d2004-06-29 23:29:38 +00002226
2227 // Parse the module contents
2228 this->ParseModule();
2229
Reid Spencer060d25d2004-06-29 23:29:38 +00002230 // Check for missing functions
Reid Spencer46b002c2004-07-11 17:28:43 +00002231 if (hasFunctions())
Reid Spencer24399722004-07-09 22:21:33 +00002232 error("Function expected, but bytecode stream ended!");
Reid Spencer060d25d2004-06-29 23:29:38 +00002233
Reid Spencer5c15fe52004-07-05 00:57:50 +00002234 // Tell the handler we're done with the module
2235 if (Handler)
2236 Handler->handleModuleEnd(ModuleID);
2237
2238 // Tell the handler we're finished the parse
Reid Spencer04cde2c2004-07-04 11:33:49 +00002239 if (Handler) Handler->handleFinish();
Reid Spencer060d25d2004-06-29 23:29:38 +00002240
Reid Spencer46b002c2004-07-11 17:28:43 +00002241 } catch (std::string& errstr) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00002242 if (Handler) Handler->handleError(errstr);
Reid Spencer060d25d2004-06-29 23:29:38 +00002243 freeState();
Chris Lattner2a7b6ba2003-03-06 17:15:19 +00002244 delete TheModule;
2245 TheModule = 0;
Chris Lattner3bdad692004-11-15 21:55:33 +00002246 if (decompressedBlock != 0 ) {
Reid Spencer61aaf2e2004-11-14 21:59:21 +00002247 ::free(decompressedBlock);
Chris Lattner3bdad692004-11-15 21:55:33 +00002248 decompressedBlock = 0;
2249 }
Chris Lattnerb0b7c0d2003-09-26 14:44:52 +00002250 throw;
Reid Spencer060d25d2004-06-29 23:29:38 +00002251 } catch (...) {
2252 std::string msg("Unknown Exception Occurred");
Reid Spencer04cde2c2004-07-04 11:33:49 +00002253 if (Handler) Handler->handleError(msg);
Reid Spencer060d25d2004-06-29 23:29:38 +00002254 freeState();
2255 delete TheModule;
2256 TheModule = 0;
Chris Lattner3bdad692004-11-15 21:55:33 +00002257 if (decompressedBlock != 0) {
Reid Spencer61aaf2e2004-11-14 21:59:21 +00002258 ::free(decompressedBlock);
Chris Lattner3bdad692004-11-15 21:55:33 +00002259 decompressedBlock = 0;
2260 }
Reid Spencer060d25d2004-06-29 23:29:38 +00002261 throw msg;
Chris Lattner2a7b6ba2003-03-06 17:15:19 +00002262 }
Chris Lattner00950542001-06-06 20:29:01 +00002263}
Reid Spencer060d25d2004-06-29 23:29:38 +00002264
2265//===----------------------------------------------------------------------===//
2266//=== Default Implementations of Handler Methods
2267//===----------------------------------------------------------------------===//
2268
2269BytecodeHandler::~BytecodeHandler() {}
Reid Spencer060d25d2004-06-29 23:29:38 +00002270
2271// vim: sw=2