blob: 974a3263aa9376f4eb19f12c383065689568f027 [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"
Jeff Cohene1337212004-12-20 03:23:46 +000022#include "llvm/Config/alloca.h"
Reid Spencer060d25d2004-06-29 23:29:38 +000023#include "llvm/Constants.h"
Reid Spencer04cde2c2004-07-04 11:33:49 +000024#include "llvm/Instructions.h"
25#include "llvm/SymbolTable.h"
Chris Lattner00950542001-06-06 20:29:01 +000026#include "llvm/Bytecode/Format.h"
Reid Spencer060d25d2004-06-29 23:29:38 +000027#include "llvm/Support/GetElementPtrTypeIterator.h"
Reid Spencer17f52c52004-11-06 23:17:23 +000028#include "llvm/Support/Compressor.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000029#include "llvm/ADT/StringExtras.h"
Reid Spencer060d25d2004-06-29 23:29:38 +000030#include <sstream>
Alkis Evlogimenos20aa4742004-09-03 18:19:51 +000031#include <algorithm>
Chris Lattner29b789b2003-11-19 17:27:18 +000032using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000033
Reid Spencer46b002c2004-07-11 17:28:43 +000034namespace {
Chris Lattnercad28bd2005-01-29 00:36:19 +000035 /// @brief A class for maintaining the slot number definition
36 /// as a placeholder for the actual definition for forward constants defs.
37 class ConstantPlaceHolder : public ConstantExpr {
38 ConstantPlaceHolder(); // DO NOT IMPLEMENT
39 void operator=(const ConstantPlaceHolder &); // DO NOT IMPLEMENT
40 public:
Chris Lattner61323322005-01-31 01:11:13 +000041 Use Op;
Chris Lattnercad28bd2005-01-29 00:36:19 +000042 ConstantPlaceHolder(const Type *Ty)
Chris Lattner61323322005-01-31 01:11:13 +000043 : ConstantExpr(Ty, Instruction::UserOp1, &Op, 1),
44 Op(UndefValue::get(Type::IntTy), this) {
45 }
Chris Lattnercad28bd2005-01-29 00:36:19 +000046 };
Reid Spencer46b002c2004-07-11 17:28:43 +000047}
Reid Spencer060d25d2004-06-29 23:29:38 +000048
Reid Spencer24399722004-07-09 22:21:33 +000049// Provide some details on error
50inline void BytecodeReader::error(std::string err) {
51 err += " (Vers=" ;
52 err += itostr(RevisionNum) ;
53 err += ", Pos=" ;
54 err += itostr(At-MemStart);
55 err += ")";
56 throw err;
57}
58
Reid Spencer060d25d2004-06-29 23:29:38 +000059//===----------------------------------------------------------------------===//
60// Bytecode Reading Methods
61//===----------------------------------------------------------------------===//
62
Reid Spencer04cde2c2004-07-04 11:33:49 +000063/// Determine if the current block being read contains any more data.
Reid Spencer060d25d2004-06-29 23:29:38 +000064inline bool BytecodeReader::moreInBlock() {
65 return At < BlockEnd;
Chris Lattner00950542001-06-06 20:29:01 +000066}
67
Reid Spencer04cde2c2004-07-04 11:33:49 +000068/// Throw an error if we've read past the end of the current block
Reid Spencer060d25d2004-06-29 23:29:38 +000069inline void BytecodeReader::checkPastBlockEnd(const char * block_name) {
Reid Spencer46b002c2004-07-11 17:28:43 +000070 if (At > BlockEnd)
Chris Lattnera79e7cc2004-10-16 18:18:16 +000071 error(std::string("Attempt to read past the end of ") + block_name +
72 " block.");
Reid Spencer060d25d2004-06-29 23:29:38 +000073}
Chris Lattner36392bc2003-10-08 21:18:57 +000074
Reid Spencer04cde2c2004-07-04 11:33:49 +000075/// Align the buffer position to a 32 bit boundary
Reid Spencer060d25d2004-06-29 23:29:38 +000076inline void BytecodeReader::align32() {
Reid Spencer38d54be2004-08-17 07:45:14 +000077 if (hasAlignment) {
78 BufPtr Save = At;
79 At = (const unsigned char *)((unsigned long)(At+3) & (~3UL));
80 if (At > Save)
81 if (Handler) Handler->handleAlignment(At - Save);
82 if (At > BlockEnd)
83 error("Ran out of data while aligning!");
84 }
Reid Spencer060d25d2004-06-29 23:29:38 +000085}
86
Reid Spencer04cde2c2004-07-04 11:33:49 +000087/// Read a whole unsigned integer
Reid Spencer060d25d2004-06-29 23:29:38 +000088inline unsigned BytecodeReader::read_uint() {
89 if (At+4 > BlockEnd)
Reid Spencer24399722004-07-09 22:21:33 +000090 error("Ran out of data reading uint!");
Reid Spencer060d25d2004-06-29 23:29:38 +000091 At += 4;
92 return At[-4] | (At[-3] << 8) | (At[-2] << 16) | (At[-1] << 24);
93}
94
Reid Spencer04cde2c2004-07-04 11:33:49 +000095/// Read a variable-bit-rate encoded unsigned integer
Reid Spencer060d25d2004-06-29 23:29:38 +000096inline unsigned BytecodeReader::read_vbr_uint() {
97 unsigned Shift = 0;
98 unsigned Result = 0;
99 BufPtr Save = At;
100
101 do {
102 if (At == BlockEnd)
Reid Spencer24399722004-07-09 22:21:33 +0000103 error("Ran out of data reading vbr_uint!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000104 Result |= (unsigned)((*At++) & 0x7F) << Shift;
105 Shift += 7;
106 } while (At[-1] & 0x80);
Reid Spencer04cde2c2004-07-04 11:33:49 +0000107 if (Handler) Handler->handleVBR32(At-Save);
Reid Spencer060d25d2004-06-29 23:29:38 +0000108 return Result;
109}
110
Reid Spencer04cde2c2004-07-04 11:33:49 +0000111/// Read a variable-bit-rate encoded unsigned 64-bit integer.
Reid Spencer060d25d2004-06-29 23:29:38 +0000112inline uint64_t BytecodeReader::read_vbr_uint64() {
113 unsigned Shift = 0;
114 uint64_t Result = 0;
115 BufPtr Save = At;
116
117 do {
118 if (At == BlockEnd)
Reid Spencer24399722004-07-09 22:21:33 +0000119 error("Ran out of data reading vbr_uint64!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000120 Result |= (uint64_t)((*At++) & 0x7F) << Shift;
121 Shift += 7;
122 } while (At[-1] & 0x80);
Reid Spencer04cde2c2004-07-04 11:33:49 +0000123 if (Handler) Handler->handleVBR64(At-Save);
Reid Spencer060d25d2004-06-29 23:29:38 +0000124 return Result;
125}
126
Reid Spencer04cde2c2004-07-04 11:33:49 +0000127/// Read a variable-bit-rate encoded signed 64-bit integer.
Reid Spencer060d25d2004-06-29 23:29:38 +0000128inline int64_t BytecodeReader::read_vbr_int64() {
129 uint64_t R = read_vbr_uint64();
130 if (R & 1) {
131 if (R != 1)
132 return -(int64_t)(R >> 1);
133 else // There is no such thing as -0 with integers. "-0" really means
134 // 0x8000000000000000.
135 return 1LL << 63;
136 } else
137 return (int64_t)(R >> 1);
138}
139
Reid Spencer04cde2c2004-07-04 11:33:49 +0000140/// Read a pascal-style string (length followed by text)
Reid Spencer060d25d2004-06-29 23:29:38 +0000141inline std::string BytecodeReader::read_str() {
142 unsigned Size = read_vbr_uint();
143 const unsigned char *OldAt = At;
144 At += Size;
145 if (At > BlockEnd) // Size invalid?
Reid Spencer24399722004-07-09 22:21:33 +0000146 error("Ran out of data reading a string!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000147 return std::string((char*)OldAt, Size);
148}
149
Reid Spencer04cde2c2004-07-04 11:33:49 +0000150/// Read an arbitrary block of data
Reid Spencer060d25d2004-06-29 23:29:38 +0000151inline void BytecodeReader::read_data(void *Ptr, void *End) {
152 unsigned char *Start = (unsigned char *)Ptr;
153 unsigned Amount = (unsigned char *)End - Start;
154 if (At+Amount > BlockEnd)
Reid Spencer24399722004-07-09 22:21:33 +0000155 error("Ran out of data!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000156 std::copy(At, At+Amount, Start);
157 At += Amount;
158}
159
Reid Spencer46b002c2004-07-11 17:28:43 +0000160/// Read a float value in little-endian order
161inline void BytecodeReader::read_float(float& FloatVal) {
Reid Spencerada16182004-07-25 21:36:26 +0000162 /// FIXME: This isn't optimal, it has size problems on some platforms
163 /// where FP is not IEEE.
164 union {
165 float f;
166 uint32_t i;
167 } FloatUnion;
168 FloatUnion.i = At[0] | (At[1] << 8) | (At[2] << 16) | (At[3] << 24);
169 At+=sizeof(uint32_t);
170 FloatVal = FloatUnion.f;
Reid Spencer46b002c2004-07-11 17:28:43 +0000171}
172
173/// Read a double value in little-endian order
174inline void BytecodeReader::read_double(double& DoubleVal) {
Reid Spencerada16182004-07-25 21:36:26 +0000175 /// FIXME: This isn't optimal, it has size problems on some platforms
176 /// where FP is not IEEE.
177 union {
178 double d;
179 uint64_t i;
180 } DoubleUnion;
Chris Lattner1d785162004-07-25 23:15:44 +0000181 DoubleUnion.i = (uint64_t(At[0]) << 0) | (uint64_t(At[1]) << 8) |
182 (uint64_t(At[2]) << 16) | (uint64_t(At[3]) << 24) |
Reid Spencerada16182004-07-25 21:36:26 +0000183 (uint64_t(At[4]) << 32) | (uint64_t(At[5]) << 40) |
184 (uint64_t(At[6]) << 48) | (uint64_t(At[7]) << 56);
185 At+=sizeof(uint64_t);
186 DoubleVal = DoubleUnion.d;
Reid Spencer46b002c2004-07-11 17:28:43 +0000187}
188
Reid Spencer04cde2c2004-07-04 11:33:49 +0000189/// Read a block header and obtain its type and size
Reid Spencer060d25d2004-06-29 23:29:38 +0000190inline void BytecodeReader::read_block(unsigned &Type, unsigned &Size) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000191 if ( hasLongBlockHeaders ) {
192 Type = read_uint();
193 Size = read_uint();
194 switch (Type) {
195 case BytecodeFormat::Reserved_DoNotUse :
196 error("Reserved_DoNotUse used as Module Type?");
Reid Spencer5b472d92004-08-21 20:49:23 +0000197 Type = BytecodeFormat::ModuleBlockID; break;
Reid Spencerad89bd62004-07-25 18:07:36 +0000198 case BytecodeFormat::Module:
199 Type = BytecodeFormat::ModuleBlockID; break;
200 case BytecodeFormat::Function:
201 Type = BytecodeFormat::FunctionBlockID; break;
202 case BytecodeFormat::ConstantPool:
203 Type = BytecodeFormat::ConstantPoolBlockID; break;
204 case BytecodeFormat::SymbolTable:
205 Type = BytecodeFormat::SymbolTableBlockID; break;
206 case BytecodeFormat::ModuleGlobalInfo:
207 Type = BytecodeFormat::ModuleGlobalInfoBlockID; break;
208 case BytecodeFormat::GlobalTypePlane:
209 Type = BytecodeFormat::GlobalTypePlaneBlockID; break;
210 case BytecodeFormat::InstructionList:
211 Type = BytecodeFormat::InstructionListBlockID; break;
212 case BytecodeFormat::CompactionTable:
213 Type = BytecodeFormat::CompactionTableBlockID; break;
214 case BytecodeFormat::BasicBlock:
215 /// This block type isn't used after version 1.1. However, we have to
216 /// still allow the value in case this is an old bc format file.
217 /// We just let its value creep thru.
218 break;
219 default:
Reid Spencer5b472d92004-08-21 20:49:23 +0000220 error("Invalid block id found: " + utostr(Type));
Reid Spencerad89bd62004-07-25 18:07:36 +0000221 break;
222 }
223 } else {
224 Size = read_uint();
225 Type = Size & 0x1F; // mask low order five bits
226 Size >>= 5; // get rid of five low order bits, leaving high 27
227 }
Reid Spencer060d25d2004-06-29 23:29:38 +0000228 BlockStart = At;
Reid Spencer46b002c2004-07-11 17:28:43 +0000229 if (At + Size > BlockEnd)
Reid Spencer24399722004-07-09 22:21:33 +0000230 error("Attempt to size a block past end of memory");
Reid Spencer060d25d2004-06-29 23:29:38 +0000231 BlockEnd = At + Size;
Reid Spencer46b002c2004-07-11 17:28:43 +0000232 if (Handler) Handler->handleBlock(Type, BlockStart, Size);
Reid Spencer04cde2c2004-07-04 11:33:49 +0000233}
234
235
236/// In LLVM 1.2 and before, Types were derived from Value and so they were
237/// written as part of the type planes along with any other Value. In LLVM
238/// 1.3 this changed so that Type does not derive from Value. Consequently,
239/// the BytecodeReader's containers for Values can't contain Types because
240/// there's no inheritance relationship. This means that the "Type Type"
241/// plane is defunct along with the Type::TypeTyID TypeID. In LLVM 1.3
242/// whenever a bytecode construct must have both types and values together,
243/// the types are always read/written first and then the Values. Furthermore
244/// since Type::TypeTyID no longer exists, its value (12) now corresponds to
245/// Type::LabelTyID. In order to overcome this we must "sanitize" all the
246/// type TypeIDs we encounter. For LLVM 1.3 bytecode files, there's no change.
247/// For LLVM 1.2 and before, this function will decrement the type id by
248/// one to account for the missing Type::TypeTyID enumerator if the value is
249/// larger than 12 (Type::LabelTyID). If the value is exactly 12, then this
250/// function returns true, otherwise false. This helps detect situations
251/// where the pre 1.3 bytecode is indicating that what follows is a type.
252/// @returns true iff type id corresponds to pre 1.3 "type type"
Reid Spencer46b002c2004-07-11 17:28:43 +0000253inline bool BytecodeReader::sanitizeTypeId(unsigned &TypeId) {
254 if (hasTypeDerivedFromValue) { /// do nothing if 1.3 or later
255 if (TypeId == Type::LabelTyID) {
Reid Spencer04cde2c2004-07-04 11:33:49 +0000256 TypeId = Type::VoidTyID; // sanitize it
257 return true; // indicate we got TypeTyID in pre 1.3 bytecode
Reid Spencer46b002c2004-07-11 17:28:43 +0000258 } else if (TypeId > Type::LabelTyID)
Reid Spencer04cde2c2004-07-04 11:33:49 +0000259 --TypeId; // shift all planes down because type type plane is missing
260 }
261 return false;
262}
263
264/// Reads a vbr uint to read in a type id and does the necessary
265/// conversion on it by calling sanitizeTypeId.
266/// @returns true iff \p TypeId read corresponds to a pre 1.3 "type type"
267/// @see sanitizeTypeId
268inline bool BytecodeReader::read_typeid(unsigned &TypeId) {
269 TypeId = read_vbr_uint();
Reid Spencerad89bd62004-07-25 18:07:36 +0000270 if ( !has32BitTypes )
271 if ( TypeId == 0x00FFFFFF )
272 TypeId = read_vbr_uint();
Reid Spencer04cde2c2004-07-04 11:33:49 +0000273 return sanitizeTypeId(TypeId);
Reid Spencer060d25d2004-06-29 23:29:38 +0000274}
275
276//===----------------------------------------------------------------------===//
277// IR Lookup Methods
278//===----------------------------------------------------------------------===//
279
Reid Spencer04cde2c2004-07-04 11:33:49 +0000280/// Determine if a type id has an implicit null value
Reid Spencer46b002c2004-07-11 17:28:43 +0000281inline bool BytecodeReader::hasImplicitNull(unsigned TyID) {
Reid Spencer060d25d2004-06-29 23:29:38 +0000282 if (!hasExplicitPrimitiveZeros)
Reid Spencer04cde2c2004-07-04 11:33:49 +0000283 return TyID != Type::LabelTyID && TyID != Type::VoidTyID;
Reid Spencer060d25d2004-06-29 23:29:38 +0000284 return TyID >= Type::FirstDerivedTyID;
285}
286
Reid Spencer04cde2c2004-07-04 11:33:49 +0000287/// Obtain a type given a typeid and account for things like compaction tables,
288/// function level vs module level, and the offsetting for the primitive types.
Reid Spencer060d25d2004-06-29 23:29:38 +0000289const Type *BytecodeReader::getType(unsigned ID) {
Chris Lattner89e02532004-01-18 21:08:15 +0000290 if (ID < Type::FirstDerivedTyID)
Chris Lattnerf70c22b2004-06-17 18:19:28 +0000291 if (const Type *T = Type::getPrimitiveType((Type::TypeID)ID))
Chris Lattner927b1852003-10-09 20:22:47 +0000292 return T; // Asked for a primitive type...
Chris Lattner36392bc2003-10-08 21:18:57 +0000293
294 // Otherwise, derived types need offset...
Chris Lattner89e02532004-01-18 21:08:15 +0000295 ID -= Type::FirstDerivedTyID;
296
Reid Spencer060d25d2004-06-29 23:29:38 +0000297 if (!CompactionTypes.empty()) {
298 if (ID >= CompactionTypes.size())
Reid Spencer24399722004-07-09 22:21:33 +0000299 error("Type ID out of range for compaction table!");
Chris Lattner45b5dd22004-08-03 23:41:28 +0000300 return CompactionTypes[ID].first;
Chris Lattner89e02532004-01-18 21:08:15 +0000301 }
Chris Lattner36392bc2003-10-08 21:18:57 +0000302
303 // Is it a module-level type?
Reid Spencer46b002c2004-07-11 17:28:43 +0000304 if (ID < ModuleTypes.size())
305 return ModuleTypes[ID].get();
Chris Lattner36392bc2003-10-08 21:18:57 +0000306
Reid Spencer46b002c2004-07-11 17:28:43 +0000307 // Nope, is it a function-level type?
308 ID -= ModuleTypes.size();
309 if (ID < FunctionTypes.size())
310 return FunctionTypes[ID].get();
Chris Lattner36392bc2003-10-08 21:18:57 +0000311
Reid Spencer46b002c2004-07-11 17:28:43 +0000312 error("Illegal type reference!");
313 return Type::VoidTy;
Chris Lattner00950542001-06-06 20:29:01 +0000314}
315
Reid Spencer04cde2c2004-07-04 11:33:49 +0000316/// Get a sanitized type id. This just makes sure that the \p ID
317/// is both sanitized and not the "type type" of pre-1.3 bytecode.
318/// @see sanitizeTypeId
319inline const Type* BytecodeReader::getSanitizedType(unsigned& ID) {
Reid Spencer46b002c2004-07-11 17:28:43 +0000320 if (sanitizeTypeId(ID))
Reid Spencer24399722004-07-09 22:21:33 +0000321 error("Invalid type id encountered");
Reid Spencer04cde2c2004-07-04 11:33:49 +0000322 return getType(ID);
323}
324
325/// This method just saves some coding. It uses read_typeid to read
Reid Spencer24399722004-07-09 22:21:33 +0000326/// in a sanitized type id, errors that its not the type type, and
Reid Spencer04cde2c2004-07-04 11:33:49 +0000327/// then calls getType to return the type value.
328inline const Type* BytecodeReader::readSanitizedType() {
329 unsigned ID;
Reid Spencer46b002c2004-07-11 17:28:43 +0000330 if (read_typeid(ID))
331 error("Invalid type id encountered");
Reid Spencer04cde2c2004-07-04 11:33:49 +0000332 return getType(ID);
333}
334
335/// Get the slot number associated with a type accounting for primitive
336/// types, compaction tables, and function level vs module level.
Reid Spencer060d25d2004-06-29 23:29:38 +0000337unsigned BytecodeReader::getTypeSlot(const Type *Ty) {
338 if (Ty->isPrimitiveType())
339 return Ty->getTypeID();
340
341 // Scan the compaction table for the type if needed.
342 if (!CompactionTypes.empty()) {
Chris Lattner45b5dd22004-08-03 23:41:28 +0000343 for (unsigned i = 0, e = CompactionTypes.size(); i != e; ++i)
344 if (CompactionTypes[i].first == Ty)
345 return Type::FirstDerivedTyID + i;
Reid Spencer060d25d2004-06-29 23:29:38 +0000346
Chris Lattner45b5dd22004-08-03 23:41:28 +0000347 error("Couldn't find type specified in compaction table!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000348 }
349
350 // Check the function level types first...
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000351 TypeListTy::iterator I = std::find(FunctionTypes.begin(),
352 FunctionTypes.end(), Ty);
Reid Spencer060d25d2004-06-29 23:29:38 +0000353
354 if (I != FunctionTypes.end())
Reid Spencer46b002c2004-07-11 17:28:43 +0000355 return Type::FirstDerivedTyID + ModuleTypes.size() +
356 (&*I - &FunctionTypes[0]);
Reid Spencer060d25d2004-06-29 23:29:38 +0000357
358 // Check the module level types now...
Reid Spencer2da5c3d2004-09-15 17:06:42 +0000359 I = std::find(ModuleTypes.begin(), ModuleTypes.end(), Ty);
Reid Spencer060d25d2004-06-29 23:29:38 +0000360 if (I == ModuleTypes.end())
Reid Spencer24399722004-07-09 22:21:33 +0000361 error("Didn't find type in ModuleTypes.");
Reid Spencer060d25d2004-06-29 23:29:38 +0000362 return Type::FirstDerivedTyID + (&*I - &ModuleTypes[0]);
Chris Lattner80b97342004-01-17 23:25:43 +0000363}
364
Reid Spencer04cde2c2004-07-04 11:33:49 +0000365/// This is just like getType, but when a compaction table is in use, it is
366/// ignored. It also ignores function level types.
367/// @see getType
Reid Spencer060d25d2004-06-29 23:29:38 +0000368const Type *BytecodeReader::getGlobalTableType(unsigned Slot) {
369 if (Slot < Type::FirstDerivedTyID) {
370 const Type *Ty = Type::getPrimitiveType((Type::TypeID)Slot);
Reid Spencer46b002c2004-07-11 17:28:43 +0000371 if (!Ty)
Reid Spencer24399722004-07-09 22:21:33 +0000372 error("Not a primitive type ID?");
Reid Spencer060d25d2004-06-29 23:29:38 +0000373 return Ty;
374 }
375 Slot -= Type::FirstDerivedTyID;
376 if (Slot >= ModuleTypes.size())
Reid Spencer24399722004-07-09 22:21:33 +0000377 error("Illegal compaction table type reference!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000378 return ModuleTypes[Slot];
Chris Lattner52e20b02003-03-19 20:54:26 +0000379}
380
Reid Spencer04cde2c2004-07-04 11:33:49 +0000381/// This is just like getTypeSlot, but when a compaction table is in use, it
382/// is ignored. It also ignores function level types.
Reid Spencer060d25d2004-06-29 23:29:38 +0000383unsigned BytecodeReader::getGlobalTableTypeSlot(const Type *Ty) {
384 if (Ty->isPrimitiveType())
385 return Ty->getTypeID();
Reid Spencer2da5c3d2004-09-15 17:06:42 +0000386 TypeListTy::iterator I = std::find(ModuleTypes.begin(),
Reid Spencer04cde2c2004-07-04 11:33:49 +0000387 ModuleTypes.end(), Ty);
Reid Spencer060d25d2004-06-29 23:29:38 +0000388 if (I == ModuleTypes.end())
Reid Spencer24399722004-07-09 22:21:33 +0000389 error("Didn't find type in ModuleTypes.");
Reid Spencer060d25d2004-06-29 23:29:38 +0000390 return Type::FirstDerivedTyID + (&*I - &ModuleTypes[0]);
391}
392
Reid Spencer04cde2c2004-07-04 11:33:49 +0000393/// Retrieve a value of a given type and slot number, possibly creating
394/// it if it doesn't already exist.
Reid Spencer060d25d2004-06-29 23:29:38 +0000395Value * BytecodeReader::getValue(unsigned type, unsigned oNum, bool Create) {
Chris Lattner4ee8ef22003-10-08 22:52:54 +0000396 assert(type != Type::LabelTyID && "getValue() cannot get blocks!");
Chris Lattner00950542001-06-06 20:29:01 +0000397 unsigned Num = oNum;
Chris Lattner00950542001-06-06 20:29:01 +0000398
Chris Lattner89e02532004-01-18 21:08:15 +0000399 // If there is a compaction table active, it defines the low-level numbers.
400 // If not, the module values define the low-level numbers.
Reid Spencer060d25d2004-06-29 23:29:38 +0000401 if (CompactionValues.size() > type && !CompactionValues[type].empty()) {
402 if (Num < CompactionValues[type].size())
403 return CompactionValues[type][Num];
404 Num -= CompactionValues[type].size();
Chris Lattner89e02532004-01-18 21:08:15 +0000405 } else {
Reid Spencer060d25d2004-06-29 23:29:38 +0000406 // By default, the global type id is the type id passed in
Chris Lattner52f86d62004-01-20 00:54:06 +0000407 unsigned GlobalTyID = type;
Reid Spencer060d25d2004-06-29 23:29:38 +0000408
Chris Lattner45b5dd22004-08-03 23:41:28 +0000409 // If the type plane was compactified, figure out the global type ID by
410 // adding the derived type ids and the distance.
411 if (!CompactionTypes.empty() && type >= Type::FirstDerivedTyID)
412 GlobalTyID = CompactionTypes[type-Type::FirstDerivedTyID].second;
Chris Lattner00950542001-06-06 20:29:01 +0000413
Reid Spencer060d25d2004-06-29 23:29:38 +0000414 if (hasImplicitNull(GlobalTyID)) {
Chris Lattner89e02532004-01-18 21:08:15 +0000415 if (Num == 0)
Reid Spencer04cde2c2004-07-04 11:33:49 +0000416 return Constant::getNullValue(getType(type));
Chris Lattner89e02532004-01-18 21:08:15 +0000417 --Num;
418 }
419
Chris Lattner52f86d62004-01-20 00:54:06 +0000420 if (GlobalTyID < ModuleValues.size() && ModuleValues[GlobalTyID]) {
421 if (Num < ModuleValues[GlobalTyID]->size())
Reid Spencer04cde2c2004-07-04 11:33:49 +0000422 return ModuleValues[GlobalTyID]->getOperand(Num);
Chris Lattner52f86d62004-01-20 00:54:06 +0000423 Num -= ModuleValues[GlobalTyID]->size();
Chris Lattner89e02532004-01-18 21:08:15 +0000424 }
Chris Lattner52e20b02003-03-19 20:54:26 +0000425 }
426
Reid Spencer060d25d2004-06-29 23:29:38 +0000427 if (FunctionValues.size() > type &&
428 FunctionValues[type] &&
429 Num < FunctionValues[type]->size())
430 return FunctionValues[type]->getOperand(Num);
Chris Lattner00950542001-06-06 20:29:01 +0000431
Chris Lattner74734132002-08-17 22:01:27 +0000432 if (!Create) return 0; // Do not create a placeholder?
Chris Lattner00950542001-06-06 20:29:01 +0000433
Reid Spencer551ccae2004-09-01 22:55:40 +0000434 // Did we already create a place holder?
Chris Lattner8eb10ce2003-10-09 06:05:40 +0000435 std::pair<unsigned,unsigned> KeyValue(type, oNum);
Reid Spencer060d25d2004-06-29 23:29:38 +0000436 ForwardReferenceMap::iterator I = ForwardReferences.lower_bound(KeyValue);
Chris Lattner8eb10ce2003-10-09 06:05:40 +0000437 if (I != ForwardReferences.end() && I->first == KeyValue)
438 return I->second; // We have already created this placeholder
439
Reid Spencer551ccae2004-09-01 22:55:40 +0000440 // If the type exists (it should)
441 if (const Type* Ty = getType(type)) {
442 // Create the place holder
443 Value *Val = new Argument(Ty);
444 ForwardReferences.insert(I, std::make_pair(KeyValue, Val));
445 return Val;
446 }
447 throw "Can't create placeholder for value of type slot #" + utostr(type);
Chris Lattner00950542001-06-06 20:29:01 +0000448}
449
Reid Spencer04cde2c2004-07-04 11:33:49 +0000450/// This is just like getValue, but when a compaction table is in use, it
451/// is ignored. Also, no forward references or other fancy features are
452/// supported.
Chris Lattner2c6c14d2004-08-04 00:19:23 +0000453Value* BytecodeReader::getGlobalTableValue(unsigned TyID, unsigned SlotNo) {
454 if (SlotNo == 0)
455 return Constant::getNullValue(getType(TyID));
456
457 if (!CompactionTypes.empty() && TyID >= Type::FirstDerivedTyID) {
458 TyID -= Type::FirstDerivedTyID;
459 if (TyID >= CompactionTypes.size())
460 error("Type ID out of range for compaction table!");
461 TyID = CompactionTypes[TyID].second;
Reid Spencer060d25d2004-06-29 23:29:38 +0000462 }
463
Chris Lattner2c6c14d2004-08-04 00:19:23 +0000464 --SlotNo;
465
Reid Spencer060d25d2004-06-29 23:29:38 +0000466 if (TyID >= ModuleValues.size() || ModuleValues[TyID] == 0 ||
467 SlotNo >= ModuleValues[TyID]->size()) {
Chris Lattner2c6c14d2004-08-04 00:19:23 +0000468 if (TyID >= ModuleValues.size() || ModuleValues[TyID] == 0)
469 error("Corrupt compaction table entry!"
470 + utostr(TyID) + ", " + utostr(SlotNo) + ": "
471 + utostr(ModuleValues.size()));
472 else
473 error("Corrupt compaction table entry!"
474 + utostr(TyID) + ", " + utostr(SlotNo) + ": "
475 + utostr(ModuleValues.size()) + ", "
Reid Spencer9a7e0c52004-08-04 22:56:46 +0000476 + utohexstr(reinterpret_cast<uint64_t>(((void*)ModuleValues[TyID])))
477 + ", "
Chris Lattner2c6c14d2004-08-04 00:19:23 +0000478 + utostr(ModuleValues[TyID]->size()));
Reid Spencer060d25d2004-06-29 23:29:38 +0000479 }
480 return ModuleValues[TyID]->getOperand(SlotNo);
481}
482
Reid Spencer04cde2c2004-07-04 11:33:49 +0000483/// Just like getValue, except that it returns a null pointer
484/// only on error. It always returns a constant (meaning that if the value is
485/// defined, but is not a constant, that is an error). If the specified
486/// constant hasn't been parsed yet, a placeholder is defined and used.
487/// Later, after the real value is parsed, the placeholder is eliminated.
Reid Spencer060d25d2004-06-29 23:29:38 +0000488Constant* BytecodeReader::getConstantValue(unsigned TypeSlot, unsigned Slot) {
489 if (Value *V = getValue(TypeSlot, Slot, false))
490 if (Constant *C = dyn_cast<Constant>(V))
491 return C; // If we already have the value parsed, just return it
Reid Spencer060d25d2004-06-29 23:29:38 +0000492 else
Reid Spencera86037e2004-07-18 00:12:03 +0000493 error("Value for slot " + utostr(Slot) +
494 " is expected to be a constant!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000495
Chris Lattner389bd042004-12-09 06:19:44 +0000496 std::pair<unsigned, unsigned> Key(TypeSlot, Slot);
Reid Spencer060d25d2004-06-29 23:29:38 +0000497 ConstantRefsType::iterator I = ConstantFwdRefs.lower_bound(Key);
498
499 if (I != ConstantFwdRefs.end() && I->first == Key) {
500 return I->second;
501 } else {
502 // Create a placeholder for the constant reference and
503 // keep track of the fact that we have a forward ref to recycle it
Chris Lattner389bd042004-12-09 06:19:44 +0000504 Constant *C = new ConstantPlaceHolder(getType(TypeSlot));
Reid Spencer060d25d2004-06-29 23:29:38 +0000505
506 // Keep track of the fact that we have a forward ref to recycle it
507 ConstantFwdRefs.insert(I, std::make_pair(Key, C));
508 return C;
509 }
510}
511
512//===----------------------------------------------------------------------===//
513// IR Construction Methods
514//===----------------------------------------------------------------------===//
515
Reid Spencer04cde2c2004-07-04 11:33:49 +0000516/// As values are created, they are inserted into the appropriate place
517/// with this method. The ValueTable argument must be one of ModuleValues
518/// or FunctionValues data members of this class.
Reid Spencer46b002c2004-07-11 17:28:43 +0000519unsigned BytecodeReader::insertValue(Value *Val, unsigned type,
520 ValueTable &ValueTab) {
Reid Spencer060d25d2004-06-29 23:29:38 +0000521 assert((!isa<Constant>(Val) || !cast<Constant>(Val)->isNullValue()) ||
Reid Spencer04cde2c2004-07-04 11:33:49 +0000522 !hasImplicitNull(type) &&
523 "Cannot read null values from bytecode!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000524
525 if (ValueTab.size() <= type)
526 ValueTab.resize(type+1);
527
528 if (!ValueTab[type]) ValueTab[type] = new ValueList();
529
530 ValueTab[type]->push_back(Val);
531
532 bool HasOffset = hasImplicitNull(type);
533 return ValueTab[type]->size()-1 + HasOffset;
534}
535
Reid Spencer04cde2c2004-07-04 11:33:49 +0000536/// Insert the arguments of a function as new values in the reader.
Reid Spencer46b002c2004-07-11 17:28:43 +0000537void BytecodeReader::insertArguments(Function* F) {
Reid Spencer060d25d2004-06-29 23:29:38 +0000538 const FunctionType *FT = F->getFunctionType();
Chris Lattnere4d5c442005-03-15 04:54:21 +0000539 Function::arg_iterator AI = F->arg_begin();
Reid Spencer060d25d2004-06-29 23:29:38 +0000540 for (FunctionType::param_iterator It = FT->param_begin();
541 It != FT->param_end(); ++It, ++AI)
542 insertValue(AI, getTypeSlot(AI->getType()), FunctionValues);
543}
544
545//===----------------------------------------------------------------------===//
546// Bytecode Parsing Methods
547//===----------------------------------------------------------------------===//
548
Reid Spencer04cde2c2004-07-04 11:33:49 +0000549/// This method parses a single instruction. The instruction is
550/// inserted at the end of the \p BB provided. The arguments of
Misha Brukman44666b12004-09-28 16:57:46 +0000551/// the instruction are provided in the \p Oprnds vector.
Reid Spencer060d25d2004-06-29 23:29:38 +0000552void BytecodeReader::ParseInstruction(std::vector<unsigned> &Oprnds,
Reid Spencer46b002c2004-07-11 17:28:43 +0000553 BasicBlock* BB) {
Reid Spencer060d25d2004-06-29 23:29:38 +0000554 BufPtr SaveAt = At;
555
556 // Clear instruction data
557 Oprnds.clear();
558 unsigned iType = 0;
559 unsigned Opcode = 0;
560 unsigned Op = read_uint();
561
562 // bits Instruction format: Common to all formats
563 // --------------------------
564 // 01-00: Opcode type, fixed to 1.
565 // 07-02: Opcode
566 Opcode = (Op >> 2) & 63;
567 Oprnds.resize((Op >> 0) & 03);
568
569 // Extract the operands
570 switch (Oprnds.size()) {
571 case 1:
572 // bits Instruction format:
573 // --------------------------
574 // 19-08: Resulting type plane
575 // 31-20: Operand #1 (if set to (2^12-1), then zero operands)
576 //
577 iType = (Op >> 8) & 4095;
578 Oprnds[0] = (Op >> 20) & 4095;
579 if (Oprnds[0] == 4095) // Handle special encoding for 0 operands...
580 Oprnds.resize(0);
581 break;
582 case 2:
583 // bits Instruction format:
584 // --------------------------
585 // 15-08: Resulting type plane
586 // 23-16: Operand #1
587 // 31-24: Operand #2
588 //
589 iType = (Op >> 8) & 255;
590 Oprnds[0] = (Op >> 16) & 255;
591 Oprnds[1] = (Op >> 24) & 255;
592 break;
593 case 3:
594 // bits Instruction format:
595 // --------------------------
596 // 13-08: Resulting type plane
597 // 19-14: Operand #1
598 // 25-20: Operand #2
599 // 31-26: Operand #3
600 //
601 iType = (Op >> 8) & 63;
602 Oprnds[0] = (Op >> 14) & 63;
603 Oprnds[1] = (Op >> 20) & 63;
604 Oprnds[2] = (Op >> 26) & 63;
605 break;
606 case 0:
607 At -= 4; // Hrm, try this again...
608 Opcode = read_vbr_uint();
609 Opcode >>= 2;
610 iType = read_vbr_uint();
611
612 unsigned NumOprnds = read_vbr_uint();
613 Oprnds.resize(NumOprnds);
614
615 if (NumOprnds == 0)
Reid Spencer24399722004-07-09 22:21:33 +0000616 error("Zero-argument instruction found; this is invalid.");
Reid Spencer060d25d2004-06-29 23:29:38 +0000617
618 for (unsigned i = 0; i != NumOprnds; ++i)
619 Oprnds[i] = read_vbr_uint();
620 align32();
621 break;
622 }
623
Reid Spencer04cde2c2004-07-04 11:33:49 +0000624 const Type *InstTy = getSanitizedType(iType);
Reid Spencer060d25d2004-06-29 23:29:38 +0000625
Reid Spencer46b002c2004-07-11 17:28:43 +0000626 // We have enough info to inform the handler now.
Reid Spencer04cde2c2004-07-04 11:33:49 +0000627 if (Handler) Handler->handleInstruction(Opcode, InstTy, Oprnds, At-SaveAt);
Reid Spencer060d25d2004-06-29 23:29:38 +0000628
629 // Declare the resulting instruction we'll build.
630 Instruction *Result = 0;
631
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000632 // If this is a bytecode format that did not include the unreachable
633 // instruction, bump up all opcodes numbers to make space.
634 if (hasNoUnreachableInst) {
635 if (Opcode >= Instruction::Unreachable &&
636 Opcode < 62) {
637 ++Opcode;
638 }
639 }
640
Reid Spencer060d25d2004-06-29 23:29:38 +0000641 // Handle binary operators
642 if (Opcode >= Instruction::BinaryOpsBegin &&
643 Opcode < Instruction::BinaryOpsEnd && Oprnds.size() == 2)
644 Result = BinaryOperator::create((Instruction::BinaryOps)Opcode,
645 getValue(iType, Oprnds[0]),
646 getValue(iType, Oprnds[1]));
647
648 switch (Opcode) {
649 default:
Reid Spencer04cde2c2004-07-04 11:33:49 +0000650 if (Result == 0)
Reid Spencer24399722004-07-09 22:21:33 +0000651 error("Illegal instruction read!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000652 break;
653 case Instruction::VAArg:
Reid Spencer04cde2c2004-07-04 11:33:49 +0000654 Result = new VAArgInst(getValue(iType, Oprnds[0]),
Reid Spencer46b002c2004-07-11 17:28:43 +0000655 getSanitizedType(Oprnds[1]));
Reid Spencer060d25d2004-06-29 23:29:38 +0000656 break;
657 case Instruction::VANext:
Reid Spencer04cde2c2004-07-04 11:33:49 +0000658 Result = new VANextInst(getValue(iType, Oprnds[0]),
Reid Spencer46b002c2004-07-11 17:28:43 +0000659 getSanitizedType(Oprnds[1]));
Reid Spencer060d25d2004-06-29 23:29:38 +0000660 break;
661 case Instruction::Cast:
Reid Spencer04cde2c2004-07-04 11:33:49 +0000662 Result = new CastInst(getValue(iType, Oprnds[0]),
Reid Spencer46b002c2004-07-11 17:28:43 +0000663 getSanitizedType(Oprnds[1]));
Reid Spencer060d25d2004-06-29 23:29:38 +0000664 break;
665 case Instruction::Select:
666 Result = new SelectInst(getValue(Type::BoolTyID, Oprnds[0]),
667 getValue(iType, Oprnds[1]),
668 getValue(iType, Oprnds[2]));
669 break;
670 case Instruction::PHI: {
671 if (Oprnds.size() == 0 || (Oprnds.size() & 1))
Reid Spencer24399722004-07-09 22:21:33 +0000672 error("Invalid phi node encountered!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000673
674 PHINode *PN = new PHINode(InstTy);
Chris Lattnercad28bd2005-01-29 00:36:19 +0000675 PN->reserveOperandSpace(Oprnds.size());
Reid Spencer060d25d2004-06-29 23:29:38 +0000676 for (unsigned i = 0, e = Oprnds.size(); i != e; i += 2)
677 PN->addIncoming(getValue(iType, Oprnds[i]), getBasicBlock(Oprnds[i+1]));
678 Result = PN;
679 break;
680 }
681
682 case Instruction::Shl:
683 case Instruction::Shr:
684 Result = new ShiftInst((Instruction::OtherOps)Opcode,
685 getValue(iType, Oprnds[0]),
686 getValue(Type::UByteTyID, Oprnds[1]));
687 break;
688 case Instruction::Ret:
689 if (Oprnds.size() == 0)
690 Result = new ReturnInst();
691 else if (Oprnds.size() == 1)
692 Result = new ReturnInst(getValue(iType, Oprnds[0]));
693 else
Reid Spencer24399722004-07-09 22:21:33 +0000694 error("Unrecognized instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000695 break;
696
697 case Instruction::Br:
698 if (Oprnds.size() == 1)
699 Result = new BranchInst(getBasicBlock(Oprnds[0]));
700 else if (Oprnds.size() == 3)
701 Result = new BranchInst(getBasicBlock(Oprnds[0]),
Reid Spencer04cde2c2004-07-04 11:33:49 +0000702 getBasicBlock(Oprnds[1]), getValue(Type::BoolTyID , Oprnds[2]));
Reid Spencer060d25d2004-06-29 23:29:38 +0000703 else
Reid Spencer24399722004-07-09 22:21:33 +0000704 error("Invalid number of operands for a 'br' instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000705 break;
706 case Instruction::Switch: {
707 if (Oprnds.size() & 1)
Reid Spencer24399722004-07-09 22:21:33 +0000708 error("Switch statement with odd number of arguments!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000709
710 SwitchInst *I = new SwitchInst(getValue(iType, Oprnds[0]),
Chris Lattnercad28bd2005-01-29 00:36:19 +0000711 getBasicBlock(Oprnds[1]),
712 Oprnds.size()/2-1);
Reid Spencer060d25d2004-06-29 23:29:38 +0000713 for (unsigned i = 2, e = Oprnds.size(); i != e; i += 2)
Chris Lattner7e618232005-02-24 05:26:04 +0000714 I->addCase(cast<ConstantInt>(getValue(iType, Oprnds[i])),
Reid Spencer060d25d2004-06-29 23:29:38 +0000715 getBasicBlock(Oprnds[i+1]));
716 Result = I;
717 break;
718 }
719
720 case Instruction::Call: {
721 if (Oprnds.size() == 0)
Reid Spencer24399722004-07-09 22:21:33 +0000722 error("Invalid call instruction encountered!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000723
724 Value *F = getValue(iType, Oprnds[0]);
725
726 // Check to make sure we have a pointer to function type
727 const PointerType *PTy = dyn_cast<PointerType>(F->getType());
Reid Spencer24399722004-07-09 22:21:33 +0000728 if (PTy == 0) error("Call to non function pointer value!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000729 const FunctionType *FTy = dyn_cast<FunctionType>(PTy->getElementType());
Reid Spencer24399722004-07-09 22:21:33 +0000730 if (FTy == 0) error("Call to non function pointer value!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000731
732 std::vector<Value *> Params;
733 if (!FTy->isVarArg()) {
734 FunctionType::param_iterator It = FTy->param_begin();
735
736 for (unsigned i = 1, e = Oprnds.size(); i != e; ++i) {
737 if (It == FTy->param_end())
Reid Spencer24399722004-07-09 22:21:33 +0000738 error("Invalid call instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000739 Params.push_back(getValue(getTypeSlot(*It++), Oprnds[i]));
740 }
741 if (It != FTy->param_end())
Reid Spencer24399722004-07-09 22:21:33 +0000742 error("Invalid call instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000743 } else {
744 Oprnds.erase(Oprnds.begin(), Oprnds.begin()+1);
745
746 unsigned FirstVariableOperand;
747 if (Oprnds.size() < FTy->getNumParams())
Reid Spencer24399722004-07-09 22:21:33 +0000748 error("Call instruction missing operands!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000749
750 // Read all of the fixed arguments
751 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
752 Params.push_back(getValue(getTypeSlot(FTy->getParamType(i)),Oprnds[i]));
753
754 FirstVariableOperand = FTy->getNumParams();
755
Chris Lattner4a242b32004-10-14 01:39:18 +0000756 if ((Oprnds.size()-FirstVariableOperand) & 1)
757 error("Invalid call instruction!"); // Must be pairs of type/value
Reid Spencer060d25d2004-06-29 23:29:38 +0000758
759 for (unsigned i = FirstVariableOperand, e = Oprnds.size();
Reid Spencer04cde2c2004-07-04 11:33:49 +0000760 i != e; i += 2)
Reid Spencer060d25d2004-06-29 23:29:38 +0000761 Params.push_back(getValue(Oprnds[i], Oprnds[i+1]));
762 }
763
764 Result = new CallInst(F, Params);
765 break;
766 }
767 case Instruction::Invoke: {
Reid Spencer04cde2c2004-07-04 11:33:49 +0000768 if (Oprnds.size() < 3)
Reid Spencer24399722004-07-09 22:21:33 +0000769 error("Invalid invoke instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000770 Value *F = getValue(iType, Oprnds[0]);
771
772 // Check to make sure we have a pointer to function type
773 const PointerType *PTy = dyn_cast<PointerType>(F->getType());
Reid Spencer04cde2c2004-07-04 11:33:49 +0000774 if (PTy == 0)
Reid Spencer24399722004-07-09 22:21:33 +0000775 error("Invoke to non function pointer value!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000776 const FunctionType *FTy = dyn_cast<FunctionType>(PTy->getElementType());
Reid Spencer04cde2c2004-07-04 11:33:49 +0000777 if (FTy == 0)
Reid Spencer24399722004-07-09 22:21:33 +0000778 error("Invoke to non function pointer value!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000779
780 std::vector<Value *> Params;
781 BasicBlock *Normal, *Except;
782
783 if (!FTy->isVarArg()) {
784 Normal = getBasicBlock(Oprnds[1]);
785 Except = getBasicBlock(Oprnds[2]);
786
787 FunctionType::param_iterator It = FTy->param_begin();
788 for (unsigned i = 3, e = Oprnds.size(); i != e; ++i) {
789 if (It == FTy->param_end())
Reid Spencer24399722004-07-09 22:21:33 +0000790 error("Invalid invoke instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000791 Params.push_back(getValue(getTypeSlot(*It++), Oprnds[i]));
792 }
793 if (It != FTy->param_end())
Reid Spencer24399722004-07-09 22:21:33 +0000794 error("Invalid invoke instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000795 } else {
796 Oprnds.erase(Oprnds.begin(), Oprnds.begin()+1);
797
798 Normal = getBasicBlock(Oprnds[0]);
799 Except = getBasicBlock(Oprnds[1]);
800
801 unsigned FirstVariableArgument = FTy->getNumParams()+2;
802 for (unsigned i = 2; i != FirstVariableArgument; ++i)
803 Params.push_back(getValue(getTypeSlot(FTy->getParamType(i-2)),
804 Oprnds[i]));
805
806 if (Oprnds.size()-FirstVariableArgument & 1) // Must be type/value pairs
Reid Spencer24399722004-07-09 22:21:33 +0000807 error("Invalid invoke instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000808
809 for (unsigned i = FirstVariableArgument; i < Oprnds.size(); i += 2)
810 Params.push_back(getValue(Oprnds[i], Oprnds[i+1]));
811 }
812
813 Result = new InvokeInst(F, Normal, Except, Params);
814 break;
815 }
816 case Instruction::Malloc:
Reid Spencer04cde2c2004-07-04 11:33:49 +0000817 if (Oprnds.size() > 2)
Reid Spencer24399722004-07-09 22:21:33 +0000818 error("Invalid malloc instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000819 if (!isa<PointerType>(InstTy))
Reid Spencer24399722004-07-09 22:21:33 +0000820 error("Invalid malloc instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000821
822 Result = new MallocInst(cast<PointerType>(InstTy)->getElementType(),
823 Oprnds.size() ? getValue(Type::UIntTyID,
824 Oprnds[0]) : 0);
825 break;
826
827 case Instruction::Alloca:
Reid Spencer04cde2c2004-07-04 11:33:49 +0000828 if (Oprnds.size() > 2)
Reid Spencer24399722004-07-09 22:21:33 +0000829 error("Invalid alloca instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000830 if (!isa<PointerType>(InstTy))
Reid Spencer24399722004-07-09 22:21:33 +0000831 error("Invalid alloca instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000832
833 Result = new AllocaInst(cast<PointerType>(InstTy)->getElementType(),
834 Oprnds.size() ? getValue(Type::UIntTyID,
Reid Spencer04cde2c2004-07-04 11:33:49 +0000835 Oprnds[0]) :0);
Reid Spencer060d25d2004-06-29 23:29:38 +0000836 break;
837 case Instruction::Free:
838 if (!isa<PointerType>(InstTy))
Reid Spencer24399722004-07-09 22:21:33 +0000839 error("Invalid free instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000840 Result = new FreeInst(getValue(iType, Oprnds[0]));
841 break;
842 case Instruction::GetElementPtr: {
843 if (Oprnds.size() == 0 || !isa<PointerType>(InstTy))
Reid Spencer24399722004-07-09 22:21:33 +0000844 error("Invalid getelementptr instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000845
846 std::vector<Value*> Idx;
847
848 const Type *NextTy = InstTy;
849 for (unsigned i = 1, e = Oprnds.size(); i != e; ++i) {
850 const CompositeType *TopTy = dyn_cast_or_null<CompositeType>(NextTy);
Reid Spencer04cde2c2004-07-04 11:33:49 +0000851 if (!TopTy)
Reid Spencer46b002c2004-07-11 17:28:43 +0000852 error("Invalid getelementptr instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000853
854 unsigned ValIdx = Oprnds[i];
855 unsigned IdxTy = 0;
856 if (!hasRestrictedGEPTypes) {
857 // Struct indices are always uints, sequential type indices can be any
858 // of the 32 or 64-bit integer types. The actual choice of type is
859 // encoded in the low two bits of the slot number.
860 if (isa<StructType>(TopTy))
861 IdxTy = Type::UIntTyID;
862 else {
863 switch (ValIdx & 3) {
864 default:
865 case 0: IdxTy = Type::UIntTyID; break;
866 case 1: IdxTy = Type::IntTyID; break;
867 case 2: IdxTy = Type::ULongTyID; break;
868 case 3: IdxTy = Type::LongTyID; break;
869 }
870 ValIdx >>= 2;
871 }
872 } else {
873 IdxTy = isa<StructType>(TopTy) ? Type::UByteTyID : Type::LongTyID;
874 }
875
876 Idx.push_back(getValue(IdxTy, ValIdx));
877
878 // Convert ubyte struct indices into uint struct indices.
879 if (isa<StructType>(TopTy) && hasRestrictedGEPTypes)
880 if (ConstantUInt *C = dyn_cast<ConstantUInt>(Idx.back()))
881 Idx[Idx.size()-1] = ConstantExpr::getCast(C, Type::UIntTy);
882
883 NextTy = GetElementPtrInst::getIndexedType(InstTy, Idx, true);
884 }
885
886 Result = new GetElementPtrInst(getValue(iType, Oprnds[0]), Idx);
887 break;
888 }
889
890 case 62: // volatile load
891 case Instruction::Load:
892 if (Oprnds.size() != 1 || !isa<PointerType>(InstTy))
Reid Spencer24399722004-07-09 22:21:33 +0000893 error("Invalid load instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000894 Result = new LoadInst(getValue(iType, Oprnds[0]), "", Opcode == 62);
895 break;
896
897 case 63: // volatile store
898 case Instruction::Store: {
899 if (!isa<PointerType>(InstTy) || Oprnds.size() != 2)
Reid Spencer24399722004-07-09 22:21:33 +0000900 error("Invalid store instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000901
902 Value *Ptr = getValue(iType, Oprnds[1]);
903 const Type *ValTy = cast<PointerType>(Ptr->getType())->getElementType();
904 Result = new StoreInst(getValue(getTypeSlot(ValTy), Oprnds[0]), Ptr,
905 Opcode == 63);
906 break;
907 }
908 case Instruction::Unwind:
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000909 if (Oprnds.size() != 0) error("Invalid unwind instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000910 Result = new UnwindInst();
911 break;
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000912 case Instruction::Unreachable:
913 if (Oprnds.size() != 0) error("Invalid unreachable instruction!");
914 Result = new UnreachableInst();
915 break;
Reid Spencer060d25d2004-06-29 23:29:38 +0000916 } // end switch(Opcode)
917
918 unsigned TypeSlot;
919 if (Result->getType() == InstTy)
920 TypeSlot = iType;
921 else
922 TypeSlot = getTypeSlot(Result->getType());
923
924 insertValue(Result, TypeSlot, FunctionValues);
925 BB->getInstList().push_back(Result);
926}
927
Reid Spencer04cde2c2004-07-04 11:33:49 +0000928/// Get a particular numbered basic block, which might be a forward reference.
929/// This works together with ParseBasicBlock to handle these forward references
Chris Lattner4a242b32004-10-14 01:39:18 +0000930/// in a clean manner. This function is used when constructing phi, br, switch,
931/// and other instructions that reference basic blocks. Blocks are numbered
Reid Spencer04cde2c2004-07-04 11:33:49 +0000932/// sequentially as they appear in the function.
Reid Spencer060d25d2004-06-29 23:29:38 +0000933BasicBlock *BytecodeReader::getBasicBlock(unsigned ID) {
Chris Lattner4ee8ef22003-10-08 22:52:54 +0000934 // Make sure there is room in the table...
935 if (ParsedBasicBlocks.size() <= ID) ParsedBasicBlocks.resize(ID+1);
936
937 // First check to see if this is a backwards reference, i.e., ParseBasicBlock
938 // has already created this block, or if the forward reference has already
939 // been created.
940 if (ParsedBasicBlocks[ID])
941 return ParsedBasicBlocks[ID];
942
943 // Otherwise, the basic block has not yet been created. Do so and add it to
944 // the ParsedBasicBlocks list.
945 return ParsedBasicBlocks[ID] = new BasicBlock();
946}
947
Reid Spencer04cde2c2004-07-04 11:33:49 +0000948/// In LLVM 1.0 bytecode files, we used to output one basicblock at a time.
949/// This method reads in one of the basicblock packets. This method is not used
950/// for bytecode files after LLVM 1.0
951/// @returns The basic block constructed.
Reid Spencer46b002c2004-07-11 17:28:43 +0000952BasicBlock *BytecodeReader::ParseBasicBlock(unsigned BlockNo) {
953 if (Handler) Handler->handleBasicBlockBegin(BlockNo);
Reid Spencer060d25d2004-06-29 23:29:38 +0000954
955 BasicBlock *BB = 0;
956
Chris Lattner4ee8ef22003-10-08 22:52:54 +0000957 if (ParsedBasicBlocks.size() == BlockNo)
958 ParsedBasicBlocks.push_back(BB = new BasicBlock());
959 else if (ParsedBasicBlocks[BlockNo] == 0)
960 BB = ParsedBasicBlocks[BlockNo] = new BasicBlock();
961 else
962 BB = ParsedBasicBlocks[BlockNo];
Chris Lattner00950542001-06-06 20:29:01 +0000963
Reid Spencer060d25d2004-06-29 23:29:38 +0000964 std::vector<unsigned> Operands;
Reid Spencer46b002c2004-07-11 17:28:43 +0000965 while (moreInBlock())
Reid Spencer060d25d2004-06-29 23:29:38 +0000966 ParseInstruction(Operands, BB);
Chris Lattner00950542001-06-06 20:29:01 +0000967
Reid Spencer46b002c2004-07-11 17:28:43 +0000968 if (Handler) Handler->handleBasicBlockEnd(BlockNo);
Misha Brukman12c29d12003-09-22 23:38:23 +0000969 return BB;
Chris Lattner00950542001-06-06 20:29:01 +0000970}
971
Reid Spencer04cde2c2004-07-04 11:33:49 +0000972/// Parse all of the BasicBlock's & Instruction's in the body of a function.
973/// In post 1.0 bytecode files, we no longer emit basic block individually,
974/// in order to avoid per-basic-block overhead.
975/// @returns Rhe number of basic blocks encountered.
Reid Spencer060d25d2004-06-29 23:29:38 +0000976unsigned BytecodeReader::ParseInstructionList(Function* F) {
Chris Lattner8d1dbd22003-12-01 07:05:31 +0000977 unsigned BlockNo = 0;
978 std::vector<unsigned> Args;
979
Reid Spencer46b002c2004-07-11 17:28:43 +0000980 while (moreInBlock()) {
981 if (Handler) Handler->handleBasicBlockBegin(BlockNo);
Chris Lattner8d1dbd22003-12-01 07:05:31 +0000982 BasicBlock *BB;
983 if (ParsedBasicBlocks.size() == BlockNo)
984 ParsedBasicBlocks.push_back(BB = new BasicBlock());
985 else if (ParsedBasicBlocks[BlockNo] == 0)
986 BB = ParsedBasicBlocks[BlockNo] = new BasicBlock();
987 else
988 BB = ParsedBasicBlocks[BlockNo];
989 ++BlockNo;
990 F->getBasicBlockList().push_back(BB);
991
992 // Read instructions into this basic block until we get to a terminator
Reid Spencer46b002c2004-07-11 17:28:43 +0000993 while (moreInBlock() && !BB->getTerminator())
Reid Spencer060d25d2004-06-29 23:29:38 +0000994 ParseInstruction(Args, BB);
Chris Lattner8d1dbd22003-12-01 07:05:31 +0000995
996 if (!BB->getTerminator())
Reid Spencer24399722004-07-09 22:21:33 +0000997 error("Non-terminated basic block found!");
Reid Spencer5c15fe52004-07-05 00:57:50 +0000998
Reid Spencer46b002c2004-07-11 17:28:43 +0000999 if (Handler) Handler->handleBasicBlockEnd(BlockNo-1);
Chris Lattner8d1dbd22003-12-01 07:05:31 +00001000 }
1001
1002 return BlockNo;
1003}
1004
Reid Spencer04cde2c2004-07-04 11:33:49 +00001005/// Parse a symbol table. This works for both module level and function
1006/// level symbol tables. For function level symbol tables, the CurrentFunction
1007/// parameter must be non-zero and the ST parameter must correspond to
1008/// CurrentFunction's symbol table. For Module level symbol tables, the
1009/// CurrentFunction argument must be zero.
Reid Spencer060d25d2004-06-29 23:29:38 +00001010void BytecodeReader::ParseSymbolTable(Function *CurrentFunction,
Reid Spencer04cde2c2004-07-04 11:33:49 +00001011 SymbolTable *ST) {
1012 if (Handler) Handler->handleSymbolTableBegin(CurrentFunction,ST);
Reid Spencer060d25d2004-06-29 23:29:38 +00001013
Chris Lattner39cacce2003-10-10 05:43:47 +00001014 // Allow efficient basic block lookup by number.
1015 std::vector<BasicBlock*> BBMap;
1016 if (CurrentFunction)
1017 for (Function::iterator I = CurrentFunction->begin(),
1018 E = CurrentFunction->end(); I != E; ++I)
1019 BBMap.push_back(I);
1020
Reid Spencer04cde2c2004-07-04 11:33:49 +00001021 /// In LLVM 1.3 we write types separately from values so
1022 /// The types are always first in the symbol table. This is
1023 /// because Type no longer derives from Value.
Reid Spencer46b002c2004-07-11 17:28:43 +00001024 if (!hasTypeDerivedFromValue) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001025 // Symtab block header: [num entries]
1026 unsigned NumEntries = read_vbr_uint();
Reid Spencer46b002c2004-07-11 17:28:43 +00001027 for (unsigned i = 0; i < NumEntries; ++i) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001028 // Symtab entry: [def slot #][name]
1029 unsigned slot = read_vbr_uint();
1030 std::string Name = read_str();
1031 const Type* T = getType(slot);
1032 ST->insert(Name, T);
1033 }
1034 }
1035
Reid Spencer46b002c2004-07-11 17:28:43 +00001036 while (moreInBlock()) {
Chris Lattner00950542001-06-06 20:29:01 +00001037 // Symtab block header: [num entries][type id number]
Reid Spencer060d25d2004-06-29 23:29:38 +00001038 unsigned NumEntries = read_vbr_uint();
Reid Spencer04cde2c2004-07-04 11:33:49 +00001039 unsigned Typ = 0;
1040 bool isTypeType = read_typeid(Typ);
Chris Lattner00950542001-06-06 20:29:01 +00001041 const Type *Ty = getType(Typ);
Chris Lattner1d670cc2001-09-07 16:37:43 +00001042
Chris Lattner7dc3a2e2003-10-13 14:57:53 +00001043 for (unsigned i = 0; i != NumEntries; ++i) {
Chris Lattner00950542001-06-06 20:29:01 +00001044 // Symtab entry: [def slot #][name]
Reid Spencer060d25d2004-06-29 23:29:38 +00001045 unsigned slot = read_vbr_uint();
1046 std::string Name = read_str();
Chris Lattner00950542001-06-06 20:29:01 +00001047
Reid Spencer04cde2c2004-07-04 11:33:49 +00001048 // if we're reading a pre 1.3 bytecode file and the type plane
1049 // is the "type type", handle it here
Reid Spencer46b002c2004-07-11 17:28:43 +00001050 if (isTypeType) {
1051 const Type* T = getType(slot);
1052 if (T == 0)
1053 error("Failed type look-up for name '" + Name + "'");
1054 ST->insert(Name, T);
1055 continue; // code below must be short circuited
Chris Lattner39cacce2003-10-10 05:43:47 +00001056 } else {
Reid Spencer46b002c2004-07-11 17:28:43 +00001057 Value *V = 0;
1058 if (Typ == Type::LabelTyID) {
1059 if (slot < BBMap.size())
1060 V = BBMap[slot];
1061 } else {
1062 V = getValue(Typ, slot, false); // Find mapping...
1063 }
1064 if (V == 0)
1065 error("Failed value look-up for name '" + Name + "'");
Chris Lattner7acff252005-03-05 19:05:20 +00001066 V->setName(Name);
Chris Lattner39cacce2003-10-10 05:43:47 +00001067 }
Chris Lattner00950542001-06-06 20:29:01 +00001068 }
1069 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001070 checkPastBlockEnd("Symbol Table");
Reid Spencer04cde2c2004-07-04 11:33:49 +00001071 if (Handler) Handler->handleSymbolTableEnd();
Chris Lattner00950542001-06-06 20:29:01 +00001072}
1073
Reid Spencer04cde2c2004-07-04 11:33:49 +00001074/// Read in the types portion of a compaction table.
Reid Spencer46b002c2004-07-11 17:28:43 +00001075void BytecodeReader::ParseCompactionTypes(unsigned NumEntries) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001076 for (unsigned i = 0; i != NumEntries; ++i) {
1077 unsigned TypeSlot = 0;
Reid Spencer46b002c2004-07-11 17:28:43 +00001078 if (read_typeid(TypeSlot))
Reid Spencer24399722004-07-09 22:21:33 +00001079 error("Invalid type in compaction table: type type");
Reid Spencer04cde2c2004-07-04 11:33:49 +00001080 const Type *Typ = getGlobalTableType(TypeSlot);
Chris Lattner45b5dd22004-08-03 23:41:28 +00001081 CompactionTypes.push_back(std::make_pair(Typ, TypeSlot));
Reid Spencer46b002c2004-07-11 17:28:43 +00001082 if (Handler) Handler->handleCompactionTableType(i, TypeSlot, Typ);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001083 }
1084}
1085
1086/// Parse a compaction table.
Reid Spencer060d25d2004-06-29 23:29:38 +00001087void BytecodeReader::ParseCompactionTable() {
1088
Reid Spencer46b002c2004-07-11 17:28:43 +00001089 // Notify handler that we're beginning a compaction table.
Reid Spencer04cde2c2004-07-04 11:33:49 +00001090 if (Handler) Handler->handleCompactionTableBegin();
1091
Reid Spencer46b002c2004-07-11 17:28:43 +00001092 // In LLVM 1.3 Type no longer derives from Value. So,
1093 // we always write them first in the compaction table
1094 // because they can't occupy a "type plane" where the
1095 // Values reside.
1096 if (! hasTypeDerivedFromValue) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001097 unsigned NumEntries = read_vbr_uint();
Reid Spencer46b002c2004-07-11 17:28:43 +00001098 ParseCompactionTypes(NumEntries);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001099 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001100
Reid Spencer46b002c2004-07-11 17:28:43 +00001101 // Compaction tables live in separate blocks so we have to loop
1102 // until we've read the whole thing.
1103 while (moreInBlock()) {
1104 // Read the number of Value* entries in the compaction table
Reid Spencer060d25d2004-06-29 23:29:38 +00001105 unsigned NumEntries = read_vbr_uint();
Reid Spencer04cde2c2004-07-04 11:33:49 +00001106 unsigned Ty = 0;
1107 unsigned isTypeType = false;
Reid Spencer060d25d2004-06-29 23:29:38 +00001108
Reid Spencer46b002c2004-07-11 17:28:43 +00001109 // Decode the type from value read in. Most compaction table
1110 // planes will have one or two entries in them. If that's the
1111 // case then the length is encoded in the bottom two bits and
1112 // the higher bits encode the type. This saves another VBR value.
Reid Spencer060d25d2004-06-29 23:29:38 +00001113 if ((NumEntries & 3) == 3) {
Reid Spencer46b002c2004-07-11 17:28:43 +00001114 // In this case, both low-order bits are set (value 3). This
1115 // is a signal that the typeid follows.
Reid Spencer060d25d2004-06-29 23:29:38 +00001116 NumEntries >>= 2;
Reid Spencer04cde2c2004-07-04 11:33:49 +00001117 isTypeType = read_typeid(Ty);
Reid Spencer060d25d2004-06-29 23:29:38 +00001118 } else {
Reid Spencer46b002c2004-07-11 17:28:43 +00001119 // In this case, the low-order bits specify the number of entries
1120 // and the high order bits specify the type.
Reid Spencer060d25d2004-06-29 23:29:38 +00001121 Ty = NumEntries >> 2;
Reid Spencer04cde2c2004-07-04 11:33:49 +00001122 isTypeType = sanitizeTypeId(Ty);
Reid Spencer060d25d2004-06-29 23:29:38 +00001123 NumEntries &= 3;
1124 }
1125
Reid Spencer04cde2c2004-07-04 11:33:49 +00001126 // if we're reading a pre 1.3 bytecode file and the type plane
1127 // is the "type type", handle it here
Reid Spencer46b002c2004-07-11 17:28:43 +00001128 if (isTypeType) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001129 ParseCompactionTypes(NumEntries);
Reid Spencer060d25d2004-06-29 23:29:38 +00001130 } else {
Chris Lattner2c6c14d2004-08-04 00:19:23 +00001131 // Make sure we have enough room for the plane.
Reid Spencer04cde2c2004-07-04 11:33:49 +00001132 if (Ty >= CompactionValues.size())
Reid Spencer46b002c2004-07-11 17:28:43 +00001133 CompactionValues.resize(Ty+1);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001134
Chris Lattner2c6c14d2004-08-04 00:19:23 +00001135 // Make sure the plane is empty or we have some kind of error.
Reid Spencer04cde2c2004-07-04 11:33:49 +00001136 if (!CompactionValues[Ty].empty())
Reid Spencer46b002c2004-07-11 17:28:43 +00001137 error("Compaction table plane contains multiple entries!");
Reid Spencer04cde2c2004-07-04 11:33:49 +00001138
Chris Lattner2c6c14d2004-08-04 00:19:23 +00001139 // Notify handler about the plane.
Reid Spencer46b002c2004-07-11 17:28:43 +00001140 if (Handler) Handler->handleCompactionTablePlane(Ty, NumEntries);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001141
Chris Lattner2c6c14d2004-08-04 00:19:23 +00001142 // Push the implicit zero.
1143 CompactionValues[Ty].push_back(Constant::getNullValue(getType(Ty)));
Reid Spencer46b002c2004-07-11 17:28:43 +00001144
1145 // Read in each of the entries, put them in the compaction table
1146 // and notify the handler that we have a new compaction table value.
Reid Spencer060d25d2004-06-29 23:29:38 +00001147 for (unsigned i = 0; i != NumEntries; ++i) {
Reid Spencer46b002c2004-07-11 17:28:43 +00001148 unsigned ValSlot = read_vbr_uint();
Chris Lattner2c6c14d2004-08-04 00:19:23 +00001149 Value *V = getGlobalTableValue(Ty, ValSlot);
Reid Spencer46b002c2004-07-11 17:28:43 +00001150 CompactionValues[Ty].push_back(V);
Chris Lattner2c6c14d2004-08-04 00:19:23 +00001151 if (Handler) Handler->handleCompactionTableValue(i, Ty, ValSlot);
Reid Spencer060d25d2004-06-29 23:29:38 +00001152 }
1153 }
1154 }
Reid Spencer46b002c2004-07-11 17:28:43 +00001155 // Notify handler that the compaction table is done.
Reid Spencer04cde2c2004-07-04 11:33:49 +00001156 if (Handler) Handler->handleCompactionTableEnd();
Reid Spencer060d25d2004-06-29 23:29:38 +00001157}
1158
Reid Spencer46b002c2004-07-11 17:28:43 +00001159// Parse a single type. The typeid is read in first. If its a primitive type
1160// then nothing else needs to be read, we know how to instantiate it. If its
1161// a derived type, then additional data is read to fill out the type
1162// definition.
1163const Type *BytecodeReader::ParseType() {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001164 unsigned PrimType = 0;
Reid Spencer46b002c2004-07-11 17:28:43 +00001165 if (read_typeid(PrimType))
Reid Spencer24399722004-07-09 22:21:33 +00001166 error("Invalid type (type type) in type constants!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001167
1168 const Type *Result = 0;
1169 if ((Result = Type::getPrimitiveType((Type::TypeID)PrimType)))
1170 return Result;
1171
1172 switch (PrimType) {
1173 case Type::FunctionTyID: {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001174 const Type *RetType = readSanitizedType();
Reid Spencer060d25d2004-06-29 23:29:38 +00001175
1176 unsigned NumParams = read_vbr_uint();
1177
1178 std::vector<const Type*> Params;
Reid Spencer04cde2c2004-07-04 11:33:49 +00001179 while (NumParams--)
1180 Params.push_back(readSanitizedType());
Reid Spencer060d25d2004-06-29 23:29:38 +00001181
1182 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1183 if (isVarArg) Params.pop_back();
1184
1185 Result = FunctionType::get(RetType, Params, isVarArg);
1186 break;
1187 }
1188 case Type::ArrayTyID: {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001189 const Type *ElementType = readSanitizedType();
Reid Spencer060d25d2004-06-29 23:29:38 +00001190 unsigned NumElements = read_vbr_uint();
Reid Spencer060d25d2004-06-29 23:29:38 +00001191 Result = ArrayType::get(ElementType, NumElements);
1192 break;
1193 }
Brian Gaeke715c90b2004-08-20 06:00:58 +00001194 case Type::PackedTyID: {
1195 const Type *ElementType = readSanitizedType();
1196 unsigned NumElements = read_vbr_uint();
1197 Result = PackedType::get(ElementType, NumElements);
1198 break;
1199 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001200 case Type::StructTyID: {
1201 std::vector<const Type*> Elements;
Reid Spencer04cde2c2004-07-04 11:33:49 +00001202 unsigned Typ = 0;
Reid Spencer46b002c2004-07-11 17:28:43 +00001203 if (read_typeid(Typ))
Reid Spencer24399722004-07-09 22:21:33 +00001204 error("Invalid element type (type type) for structure!");
1205
Reid Spencer060d25d2004-06-29 23:29:38 +00001206 while (Typ) { // List is terminated by void/0 typeid
1207 Elements.push_back(getType(Typ));
Reid Spencer46b002c2004-07-11 17:28:43 +00001208 if (read_typeid(Typ))
1209 error("Invalid element type (type type) for structure!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001210 }
1211
1212 Result = StructType::get(Elements);
1213 break;
1214 }
1215 case Type::PointerTyID: {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001216 Result = PointerType::get(readSanitizedType());
Reid Spencer060d25d2004-06-29 23:29:38 +00001217 break;
1218 }
1219
1220 case Type::OpaqueTyID: {
1221 Result = OpaqueType::get();
1222 break;
1223 }
1224
1225 default:
Reid Spencer24399722004-07-09 22:21:33 +00001226 error("Don't know how to deserialize primitive type " + utostr(PrimType));
Reid Spencer060d25d2004-06-29 23:29:38 +00001227 break;
1228 }
Reid Spencer46b002c2004-07-11 17:28:43 +00001229 if (Handler) Handler->handleType(Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001230 return Result;
1231}
1232
Reid Spencer5b472d92004-08-21 20:49:23 +00001233// ParseTypes - We have to use this weird code to handle recursive
Reid Spencer060d25d2004-06-29 23:29:38 +00001234// types. We know that recursive types will only reference the current slab of
1235// values in the type plane, but they can forward reference types before they
1236// have been read. For example, Type #0 might be '{ Ty#1 }' and Type #1 might
1237// be 'Ty#0*'. When reading Type #0, type number one doesn't exist. To fix
1238// this ugly problem, we pessimistically insert an opaque type for each type we
1239// are about to read. This means that forward references will resolve to
1240// something and when we reread the type later, we can replace the opaque type
1241// with a new resolved concrete type.
1242//
Reid Spencer46b002c2004-07-11 17:28:43 +00001243void BytecodeReader::ParseTypes(TypeListTy &Tab, unsigned NumEntries){
Reid Spencer060d25d2004-06-29 23:29:38 +00001244 assert(Tab.size() == 0 && "should not have read type constants in before!");
1245
1246 // Insert a bunch of opaque types to be resolved later...
1247 Tab.reserve(NumEntries);
1248 for (unsigned i = 0; i != NumEntries; ++i)
1249 Tab.push_back(OpaqueType::get());
1250
Reid Spencer5b472d92004-08-21 20:49:23 +00001251 if (Handler)
1252 Handler->handleTypeList(NumEntries);
1253
Reid Spencer060d25d2004-06-29 23:29:38 +00001254 // Loop through reading all of the types. Forward types will make use of the
1255 // opaque types just inserted.
1256 //
1257 for (unsigned i = 0; i != NumEntries; ++i) {
Reid Spencer46b002c2004-07-11 17:28:43 +00001258 const Type* NewTy = ParseType();
Reid Spencer04cde2c2004-07-04 11:33:49 +00001259 const Type* OldTy = Tab[i].get();
1260 if (NewTy == 0)
Reid Spencer24399722004-07-09 22:21:33 +00001261 error("Couldn't parse type!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001262
1263 // Don't directly push the new type on the Tab. Instead we want to replace
1264 // the opaque type we previously inserted with the new concrete value. This
1265 // approach helps with forward references to types. The refinement from the
1266 // abstract (opaque) type to the new type causes all uses of the abstract
1267 // type to use the concrete type (NewTy). This will also cause the opaque
1268 // type to be deleted.
1269 cast<DerivedType>(const_cast<Type*>(OldTy))->refineAbstractTypeTo(NewTy);
1270
1271 // This should have replaced the old opaque type with the new type in the
1272 // value table... or with a preexisting type that was already in the system.
1273 // Let's just make sure it did.
1274 assert(Tab[i] != OldTy && "refineAbstractType didn't work!");
1275 }
1276}
1277
Reid Spencer04cde2c2004-07-04 11:33:49 +00001278/// Parse a single constant value
Reid Spencer46b002c2004-07-11 17:28:43 +00001279Constant *BytecodeReader::ParseConstantValue(unsigned TypeID) {
Reid Spencer060d25d2004-06-29 23:29:38 +00001280 // We must check for a ConstantExpr before switching by type because
1281 // a ConstantExpr can be of any type, and has no explicit value.
1282 //
1283 // 0 if not expr; numArgs if is expr
1284 unsigned isExprNumArgs = read_vbr_uint();
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001285
Reid Spencer060d25d2004-06-29 23:29:38 +00001286 if (isExprNumArgs) {
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001287 // 'undef' is encoded with 'exprnumargs' == 1.
1288 if (!hasNoUndefValue)
1289 if (--isExprNumArgs == 0)
1290 return UndefValue::get(getType(TypeID));
1291
Reid Spencer060d25d2004-06-29 23:29:38 +00001292 // FIXME: Encoding of constant exprs could be much more compact!
1293 std::vector<Constant*> ArgVec;
1294 ArgVec.reserve(isExprNumArgs);
1295 unsigned Opcode = read_vbr_uint();
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001296
1297 // Bytecode files before LLVM 1.4 need have a missing terminator inst.
1298 if (hasNoUnreachableInst) Opcode++;
Reid Spencer060d25d2004-06-29 23:29:38 +00001299
1300 // Read the slot number and types of each of the arguments
1301 for (unsigned i = 0; i != isExprNumArgs; ++i) {
1302 unsigned ArgValSlot = read_vbr_uint();
Reid Spencer04cde2c2004-07-04 11:33:49 +00001303 unsigned ArgTypeSlot = 0;
Reid Spencer46b002c2004-07-11 17:28:43 +00001304 if (read_typeid(ArgTypeSlot))
1305 error("Invalid argument type (type type) for constant value");
Reid Spencer060d25d2004-06-29 23:29:38 +00001306
1307 // Get the arg value from its slot if it exists, otherwise a placeholder
1308 ArgVec.push_back(getConstantValue(ArgTypeSlot, ArgValSlot));
1309 }
1310
1311 // Construct a ConstantExpr of the appropriate kind
1312 if (isExprNumArgs == 1) { // All one-operand expressions
Reid Spencer46b002c2004-07-11 17:28:43 +00001313 if (Opcode != Instruction::Cast)
Chris Lattner02dce162004-12-04 05:28:27 +00001314 error("Only cast instruction has one argument for ConstantExpr");
Reid Spencer46b002c2004-07-11 17:28:43 +00001315
Reid Spencer060d25d2004-06-29 23:29:38 +00001316 Constant* Result = ConstantExpr::getCast(ArgVec[0], getType(TypeID));
Reid Spencer04cde2c2004-07-04 11:33:49 +00001317 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001318 return Result;
1319 } else if (Opcode == Instruction::GetElementPtr) { // GetElementPtr
1320 std::vector<Constant*> IdxList(ArgVec.begin()+1, ArgVec.end());
1321
1322 if (hasRestrictedGEPTypes) {
1323 const Type *BaseTy = ArgVec[0]->getType();
1324 generic_gep_type_iterator<std::vector<Constant*>::iterator>
1325 GTI = gep_type_begin(BaseTy, IdxList.begin(), IdxList.end()),
1326 E = gep_type_end(BaseTy, IdxList.begin(), IdxList.end());
1327 for (unsigned i = 0; GTI != E; ++GTI, ++i)
1328 if (isa<StructType>(*GTI)) {
1329 if (IdxList[i]->getType() != Type::UByteTy)
Reid Spencer24399722004-07-09 22:21:33 +00001330 error("Invalid index for getelementptr!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001331 IdxList[i] = ConstantExpr::getCast(IdxList[i], Type::UIntTy);
1332 }
1333 }
1334
1335 Constant* Result = ConstantExpr::getGetElementPtr(ArgVec[0], IdxList);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001336 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001337 return Result;
1338 } else if (Opcode == Instruction::Select) {
Reid Spencer46b002c2004-07-11 17:28:43 +00001339 if (ArgVec.size() != 3)
1340 error("Select instruction must have three arguments.");
Reid Spencer060d25d2004-06-29 23:29:38 +00001341 Constant* Result = ConstantExpr::getSelect(ArgVec[0], ArgVec[1],
Reid Spencer04cde2c2004-07-04 11:33:49 +00001342 ArgVec[2]);
1343 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001344 return Result;
1345 } else { // All other 2-operand expressions
1346 Constant* Result = ConstantExpr::get(Opcode, ArgVec[0], ArgVec[1]);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001347 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001348 return Result;
1349 }
1350 }
1351
1352 // Ok, not an ConstantExpr. We now know how to read the given type...
1353 const Type *Ty = getType(TypeID);
1354 switch (Ty->getTypeID()) {
1355 case Type::BoolTyID: {
1356 unsigned Val = read_vbr_uint();
1357 if (Val != 0 && Val != 1)
Reid Spencer24399722004-07-09 22:21:33 +00001358 error("Invalid boolean value read.");
Reid Spencer060d25d2004-06-29 23:29:38 +00001359 Constant* Result = ConstantBool::get(Val == 1);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001360 if (Handler) Handler->handleConstantValue(Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001361 return Result;
1362 }
1363
1364 case Type::UByteTyID: // Unsigned integer types...
1365 case Type::UShortTyID:
1366 case Type::UIntTyID: {
1367 unsigned Val = read_vbr_uint();
1368 if (!ConstantUInt::isValueValidForType(Ty, Val))
Reid Spencer24399722004-07-09 22:21:33 +00001369 error("Invalid unsigned byte/short/int read.");
Reid Spencer060d25d2004-06-29 23:29:38 +00001370 Constant* Result = ConstantUInt::get(Ty, Val);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001371 if (Handler) Handler->handleConstantValue(Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001372 return Result;
1373 }
1374
1375 case Type::ULongTyID: {
1376 Constant* Result = ConstantUInt::get(Ty, read_vbr_uint64());
Reid Spencer04cde2c2004-07-04 11:33:49 +00001377 if (Handler) Handler->handleConstantValue(Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001378 return Result;
1379 }
1380
1381 case Type::SByteTyID: // Signed integer types...
1382 case Type::ShortTyID:
1383 case Type::IntTyID: {
1384 case Type::LongTyID:
1385 int64_t Val = read_vbr_int64();
1386 if (!ConstantSInt::isValueValidForType(Ty, Val))
Reid Spencer24399722004-07-09 22:21:33 +00001387 error("Invalid signed byte/short/int/long read.");
Reid Spencer060d25d2004-06-29 23:29:38 +00001388 Constant* Result = ConstantSInt::get(Ty, Val);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001389 if (Handler) Handler->handleConstantValue(Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001390 return Result;
1391 }
1392
1393 case Type::FloatTyID: {
Reid Spencer46b002c2004-07-11 17:28:43 +00001394 float Val;
1395 read_float(Val);
1396 Constant* Result = ConstantFP::get(Ty, Val);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001397 if (Handler) Handler->handleConstantValue(Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001398 return Result;
1399 }
1400
1401 case Type::DoubleTyID: {
1402 double Val;
Reid Spencer46b002c2004-07-11 17:28:43 +00001403 read_double(Val);
Reid Spencer060d25d2004-06-29 23:29:38 +00001404 Constant* Result = ConstantFP::get(Ty, Val);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001405 if (Handler) Handler->handleConstantValue(Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001406 return Result;
1407 }
1408
Reid Spencer060d25d2004-06-29 23:29:38 +00001409 case Type::ArrayTyID: {
1410 const ArrayType *AT = cast<ArrayType>(Ty);
1411 unsigned NumElements = AT->getNumElements();
1412 unsigned TypeSlot = getTypeSlot(AT->getElementType());
1413 std::vector<Constant*> Elements;
1414 Elements.reserve(NumElements);
1415 while (NumElements--) // Read all of the elements of the constant.
1416 Elements.push_back(getConstantValue(TypeSlot,
1417 read_vbr_uint()));
1418 Constant* Result = ConstantArray::get(AT, Elements);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001419 if (Handler) Handler->handleConstantArray(AT, Elements, TypeSlot, Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001420 return Result;
1421 }
1422
1423 case Type::StructTyID: {
1424 const StructType *ST = cast<StructType>(Ty);
1425
1426 std::vector<Constant *> Elements;
1427 Elements.reserve(ST->getNumElements());
1428 for (unsigned i = 0; i != ST->getNumElements(); ++i)
1429 Elements.push_back(getConstantValue(ST->getElementType(i),
1430 read_vbr_uint()));
1431
1432 Constant* Result = ConstantStruct::get(ST, Elements);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001433 if (Handler) Handler->handleConstantStruct(ST, Elements, Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001434 return Result;
1435 }
1436
Brian Gaeke715c90b2004-08-20 06:00:58 +00001437 case Type::PackedTyID: {
1438 const PackedType *PT = cast<PackedType>(Ty);
1439 unsigned NumElements = PT->getNumElements();
1440 unsigned TypeSlot = getTypeSlot(PT->getElementType());
1441 std::vector<Constant*> Elements;
1442 Elements.reserve(NumElements);
1443 while (NumElements--) // Read all of the elements of the constant.
1444 Elements.push_back(getConstantValue(TypeSlot,
1445 read_vbr_uint()));
1446 Constant* Result = ConstantPacked::get(PT, Elements);
1447 if (Handler) Handler->handleConstantPacked(PT, Elements, TypeSlot, Result);
1448 return Result;
1449 }
1450
Chris Lattner638c3812004-11-19 16:24:05 +00001451 case Type::PointerTyID: { // ConstantPointerRef value (backwards compat).
Reid Spencer060d25d2004-06-29 23:29:38 +00001452 const PointerType *PT = cast<PointerType>(Ty);
1453 unsigned Slot = read_vbr_uint();
1454
1455 // Check to see if we have already read this global variable...
1456 Value *Val = getValue(TypeID, Slot, false);
Reid Spencer060d25d2004-06-29 23:29:38 +00001457 if (Val) {
Chris Lattnerbcb11cf2004-07-27 02:34:49 +00001458 GlobalValue *GV = dyn_cast<GlobalValue>(Val);
1459 if (!GV) error("GlobalValue not in ValueTable!");
1460 if (Handler) Handler->handleConstantPointer(PT, Slot, GV);
1461 return GV;
Reid Spencer060d25d2004-06-29 23:29:38 +00001462 } else {
Reid Spencer24399722004-07-09 22:21:33 +00001463 error("Forward references are not allowed here.");
Reid Spencer060d25d2004-06-29 23:29:38 +00001464 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001465 }
1466
1467 default:
Reid Spencer24399722004-07-09 22:21:33 +00001468 error("Don't know how to deserialize constant value of type '" +
Reid Spencer060d25d2004-06-29 23:29:38 +00001469 Ty->getDescription());
1470 break;
1471 }
Reid Spencer24399722004-07-09 22:21:33 +00001472 return 0;
Reid Spencer060d25d2004-06-29 23:29:38 +00001473}
1474
Reid Spencer04cde2c2004-07-04 11:33:49 +00001475/// Resolve references for constants. This function resolves the forward
1476/// referenced constants in the ConstantFwdRefs map. It uses the
1477/// replaceAllUsesWith method of Value class to substitute the placeholder
1478/// instance with the actual instance.
Chris Lattner389bd042004-12-09 06:19:44 +00001479void BytecodeReader::ResolveReferencesToConstant(Constant *NewV, unsigned Typ,
1480 unsigned Slot) {
Chris Lattner29b789b2003-11-19 17:27:18 +00001481 ConstantRefsType::iterator I =
Chris Lattner389bd042004-12-09 06:19:44 +00001482 ConstantFwdRefs.find(std::make_pair(Typ, Slot));
Chris Lattner29b789b2003-11-19 17:27:18 +00001483 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.
Jeff Cohene1337212004-12-20 03:23:46 +00001507 char *Data = reinterpret_cast<char *>(alloca(ATy->getNumElements()));
Reid Spencer060d25d2004-06-29 23:29:38 +00001508 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);
Chris Lattner389bd042004-12-09 06:19:44 +00001521 ResolveReferencesToConstant(C, Typ, 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();
Chris Lattner389bd042004-12-09 06:19:44 +00001567 ResolveReferencesToConstant(C, Typ, Slot);
Reid Spencer060d25d2004-06-29 23:29:38 +00001568 }
1569 }
1570 }
Chris Lattner02dce162004-12-04 05:28:27 +00001571
1572 // After we have finished parsing the constant pool, we had better not have
1573 // any dangling references left.
Reid Spencer3c391272004-12-04 22:19:53 +00001574 if (!ConstantFwdRefs.empty()) {
Reid Spencer3c391272004-12-04 22:19:53 +00001575 ConstantRefsType::const_iterator I = ConstantFwdRefs.begin();
Reid Spencer3c391272004-12-04 22:19:53 +00001576 Constant* missingConst = I->second;
1577 error(utostr(ConstantFwdRefs.size()) +
1578 " unresolved constant reference exist. First one is '" +
1579 missingConst->getName() + "' of type '" +
Chris Lattner389bd042004-12-09 06:19:44 +00001580 missingConst->getType()->getDescription() + "'.");
Reid Spencer3c391272004-12-04 22:19:53 +00001581 }
Chris Lattner02dce162004-12-04 05:28:27 +00001582
Reid Spencer060d25d2004-06-29 23:29:38 +00001583 checkPastBlockEnd("Constant Pool");
Reid Spencer04cde2c2004-07-04 11:33:49 +00001584 if (Handler) Handler->handleGlobalConstantsEnd();
Reid Spencer060d25d2004-06-29 23:29:38 +00001585}
Chris Lattner00950542001-06-06 20:29:01 +00001586
Reid Spencer04cde2c2004-07-04 11:33:49 +00001587/// Parse the contents of a function. Note that this function can be
1588/// called lazily by materializeFunction
1589/// @see materializeFunction
Reid Spencer46b002c2004-07-11 17:28:43 +00001590void BytecodeReader::ParseFunctionBody(Function* F) {
Reid Spencer060d25d2004-06-29 23:29:38 +00001591
1592 unsigned FuncSize = BlockEnd - At;
Chris Lattnere3869c82003-04-16 21:16:05 +00001593 GlobalValue::LinkageTypes Linkage = GlobalValue::ExternalLinkage;
1594
Reid Spencer060d25d2004-06-29 23:29:38 +00001595 unsigned LinkageType = read_vbr_uint();
Chris Lattnerc08912f2004-01-14 16:44:44 +00001596 switch (LinkageType) {
1597 case 0: Linkage = GlobalValue::ExternalLinkage; break;
1598 case 1: Linkage = GlobalValue::WeakLinkage; break;
1599 case 2: Linkage = GlobalValue::AppendingLinkage; break;
1600 case 3: Linkage = GlobalValue::InternalLinkage; break;
1601 case 4: Linkage = GlobalValue::LinkOnceLinkage; break;
Reid Spencer060d25d2004-06-29 23:29:38 +00001602 default:
Reid Spencer24399722004-07-09 22:21:33 +00001603 error("Invalid linkage type for Function.");
Reid Spencer060d25d2004-06-29 23:29:38 +00001604 Linkage = GlobalValue::InternalLinkage;
1605 break;
Chris Lattnere3869c82003-04-16 21:16:05 +00001606 }
Chris Lattnerd23b1d32001-11-26 18:56:10 +00001607
Reid Spencer46b002c2004-07-11 17:28:43 +00001608 F->setLinkage(Linkage);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001609 if (Handler) Handler->handleFunctionBegin(F,FuncSize);
Chris Lattner00950542001-06-06 20:29:01 +00001610
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001611 // Keep track of how many basic blocks we have read in...
1612 unsigned BlockNum = 0;
Chris Lattner89e02532004-01-18 21:08:15 +00001613 bool InsertedArguments = false;
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001614
Reid Spencer060d25d2004-06-29 23:29:38 +00001615 BufPtr MyEnd = BlockEnd;
Reid Spencer46b002c2004-07-11 17:28:43 +00001616 while (At < MyEnd) {
Chris Lattner00950542001-06-06 20:29:01 +00001617 unsigned Type, Size;
Reid Spencer060d25d2004-06-29 23:29:38 +00001618 BufPtr OldAt = At;
1619 read_block(Type, Size);
Chris Lattner00950542001-06-06 20:29:01 +00001620
1621 switch (Type) {
Reid Spencerad89bd62004-07-25 18:07:36 +00001622 case BytecodeFormat::ConstantPoolBlockID:
Chris Lattner89e02532004-01-18 21:08:15 +00001623 if (!InsertedArguments) {
1624 // Insert arguments into the value table before we parse the first basic
1625 // block in the function, but after we potentially read in the
1626 // compaction table.
Reid Spencer04cde2c2004-07-04 11:33:49 +00001627 insertArguments(F);
Chris Lattner89e02532004-01-18 21:08:15 +00001628 InsertedArguments = true;
1629 }
1630
Reid Spencer04cde2c2004-07-04 11:33:49 +00001631 ParseConstantPool(FunctionValues, FunctionTypes, true);
Chris Lattner00950542001-06-06 20:29:01 +00001632 break;
1633
Reid Spencerad89bd62004-07-25 18:07:36 +00001634 case BytecodeFormat::CompactionTableBlockID:
Reid Spencer060d25d2004-06-29 23:29:38 +00001635 ParseCompactionTable();
Chris Lattner89e02532004-01-18 21:08:15 +00001636 break;
1637
Chris Lattner00950542001-06-06 20:29:01 +00001638 case BytecodeFormat::BasicBlock: {
Chris Lattner89e02532004-01-18 21:08:15 +00001639 if (!InsertedArguments) {
1640 // Insert arguments into the value table before we parse the first basic
1641 // block in the function, but after we potentially read in the
1642 // compaction table.
Reid Spencer04cde2c2004-07-04 11:33:49 +00001643 insertArguments(F);
Chris Lattner89e02532004-01-18 21:08:15 +00001644 InsertedArguments = true;
1645 }
1646
Reid Spencer060d25d2004-06-29 23:29:38 +00001647 BasicBlock *BB = ParseBasicBlock(BlockNum++);
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001648 F->getBasicBlockList().push_back(BB);
Chris Lattner00950542001-06-06 20:29:01 +00001649 break;
1650 }
1651
Reid Spencerad89bd62004-07-25 18:07:36 +00001652 case BytecodeFormat::InstructionListBlockID: {
Chris Lattner89e02532004-01-18 21:08:15 +00001653 // Insert arguments into the value table before we parse the instruction
1654 // list for the function, but after we potentially read in the compaction
1655 // table.
1656 if (!InsertedArguments) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001657 insertArguments(F);
Chris Lattner89e02532004-01-18 21:08:15 +00001658 InsertedArguments = true;
1659 }
1660
Reid Spencer060d25d2004-06-29 23:29:38 +00001661 if (BlockNum)
Reid Spencer24399722004-07-09 22:21:33 +00001662 error("Already parsed basic blocks!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001663 BlockNum = ParseInstructionList(F);
Chris Lattner8d1dbd22003-12-01 07:05:31 +00001664 break;
1665 }
1666
Reid Spencerad89bd62004-07-25 18:07:36 +00001667 case BytecodeFormat::SymbolTableBlockID:
Reid Spencer060d25d2004-06-29 23:29:38 +00001668 ParseSymbolTable(F, &F->getSymbolTable());
Chris Lattner00950542001-06-06 20:29:01 +00001669 break;
1670
1671 default:
Reid Spencer060d25d2004-06-29 23:29:38 +00001672 At += Size;
1673 if (OldAt > At)
Reid Spencer24399722004-07-09 22:21:33 +00001674 error("Wrapped around reading bytecode.");
Chris Lattner00950542001-06-06 20:29:01 +00001675 break;
1676 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001677 BlockEnd = MyEnd;
Chris Lattner1d670cc2001-09-07 16:37:43 +00001678
Misha Brukman12c29d12003-09-22 23:38:23 +00001679 // Malformed bc file if read past end of block.
Reid Spencer060d25d2004-06-29 23:29:38 +00001680 align32();
Chris Lattner00950542001-06-06 20:29:01 +00001681 }
1682
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001683 // Make sure there were no references to non-existant basic blocks.
1684 if (BlockNum != ParsedBasicBlocks.size())
Reid Spencer24399722004-07-09 22:21:33 +00001685 error("Illegal basic block operand reference");
Reid Spencer060d25d2004-06-29 23:29:38 +00001686
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001687 ParsedBasicBlocks.clear();
1688
Chris Lattner97330cf2003-10-09 23:10:14 +00001689 // Resolve forward references. Replace any uses of a forward reference value
1690 // with the real value.
Chris Lattner8eb10ce2003-10-09 06:05:40 +00001691 while (!ForwardReferences.empty()) {
Chris Lattnerc4d69162004-12-09 04:51:50 +00001692 std::map<std::pair<unsigned,unsigned>, Value*>::iterator
1693 I = ForwardReferences.begin();
1694 Value *V = getValue(I->first.first, I->first.second, false);
Chris Lattner8eb10ce2003-10-09 06:05:40 +00001695 Value *PlaceHolder = I->second;
Chris Lattnerc4d69162004-12-09 04:51:50 +00001696 PlaceHolder->replaceAllUsesWith(V);
Chris Lattner8eb10ce2003-10-09 06:05:40 +00001697 ForwardReferences.erase(I);
Chris Lattner8eb10ce2003-10-09 06:05:40 +00001698 delete PlaceHolder;
Chris Lattner6e448022003-10-08 21:51:46 +00001699 }
Chris Lattner00950542001-06-06 20:29:01 +00001700
Misha Brukman12c29d12003-09-22 23:38:23 +00001701 // Clear out function-level types...
Reid Spencer060d25d2004-06-29 23:29:38 +00001702 FunctionTypes.clear();
1703 CompactionTypes.clear();
1704 CompactionValues.clear();
1705 freeTable(FunctionValues);
1706
Reid Spencer04cde2c2004-07-04 11:33:49 +00001707 if (Handler) Handler->handleFunctionEnd(F);
Chris Lattner00950542001-06-06 20:29:01 +00001708}
1709
Reid Spencer04cde2c2004-07-04 11:33:49 +00001710/// This function parses LLVM functions lazily. It obtains the type of the
1711/// function and records where the body of the function is in the bytecode
1712/// buffer. The caller can then use the ParseNextFunction and
1713/// ParseAllFunctionBodies to get handler events for the functions.
Reid Spencer060d25d2004-06-29 23:29:38 +00001714void BytecodeReader::ParseFunctionLazily() {
1715 if (FunctionSignatureList.empty())
Reid Spencer24399722004-07-09 22:21:33 +00001716 error("FunctionSignatureList empty!");
Chris Lattner89e02532004-01-18 21:08:15 +00001717
Reid Spencer060d25d2004-06-29 23:29:38 +00001718 Function *Func = FunctionSignatureList.back();
1719 FunctionSignatureList.pop_back();
Chris Lattner24102432004-01-18 22:35:34 +00001720
Reid Spencer060d25d2004-06-29 23:29:38 +00001721 // Save the information for future reading of the function
1722 LazyFunctionLoadMap[Func] = LazyFunctionInfo(BlockStart, BlockEnd);
Chris Lattner89e02532004-01-18 21:08:15 +00001723
Misha Brukmana3e6ad62004-11-14 21:02:55 +00001724 // This function has a body but it's not loaded so it appears `External'.
1725 // Mark it as a `Ghost' instead to notify the users that it has a body.
1726 Func->setLinkage(GlobalValue::GhostLinkage);
1727
Reid Spencer060d25d2004-06-29 23:29:38 +00001728 // Pretend we've `parsed' this function
1729 At = BlockEnd;
1730}
Chris Lattner89e02532004-01-18 21:08:15 +00001731
Reid Spencer04cde2c2004-07-04 11:33:49 +00001732/// The ParserFunction method lazily parses one function. Use this method to
1733/// casue the parser to parse a specific function in the module. Note that
1734/// this will remove the function from what is to be included by
1735/// ParseAllFunctionBodies.
1736/// @see ParseAllFunctionBodies
1737/// @see ParseBytecode
Reid Spencer060d25d2004-06-29 23:29:38 +00001738void BytecodeReader::ParseFunction(Function* Func) {
1739 // Find {start, end} pointers and slot in the map. If not there, we're done.
1740 LazyFunctionMap::iterator Fi = LazyFunctionLoadMap.find(Func);
Chris Lattner89e02532004-01-18 21:08:15 +00001741
Reid Spencer060d25d2004-06-29 23:29:38 +00001742 // Make sure we found it
Reid Spencer46b002c2004-07-11 17:28:43 +00001743 if (Fi == LazyFunctionLoadMap.end()) {
Reid Spencer24399722004-07-09 22:21:33 +00001744 error("Unrecognized function of type " + Func->getType()->getDescription());
Reid Spencer060d25d2004-06-29 23:29:38 +00001745 return;
Chris Lattner89e02532004-01-18 21:08:15 +00001746 }
1747
Reid Spencer060d25d2004-06-29 23:29:38 +00001748 BlockStart = At = Fi->second.Buf;
1749 BlockEnd = Fi->second.EndBuf;
Reid Spencer24399722004-07-09 22:21:33 +00001750 assert(Fi->first == Func && "Found wrong function?");
Reid Spencer060d25d2004-06-29 23:29:38 +00001751
1752 LazyFunctionLoadMap.erase(Fi);
1753
Reid Spencer46b002c2004-07-11 17:28:43 +00001754 this->ParseFunctionBody(Func);
Chris Lattner89e02532004-01-18 21:08:15 +00001755}
1756
Reid Spencer04cde2c2004-07-04 11:33:49 +00001757/// The ParseAllFunctionBodies method parses through all the previously
1758/// unparsed functions in the bytecode file. If you want to completely parse
1759/// a bytecode file, this method should be called after Parsebytecode because
1760/// Parsebytecode only records the locations in the bytecode file of where
1761/// the function definitions are located. This function uses that information
1762/// to materialize the functions.
1763/// @see ParseBytecode
Reid Spencer060d25d2004-06-29 23:29:38 +00001764void BytecodeReader::ParseAllFunctionBodies() {
1765 LazyFunctionMap::iterator Fi = LazyFunctionLoadMap.begin();
1766 LazyFunctionMap::iterator Fe = LazyFunctionLoadMap.end();
Chris Lattner89e02532004-01-18 21:08:15 +00001767
Reid Spencer46b002c2004-07-11 17:28:43 +00001768 while (Fi != Fe) {
Reid Spencer060d25d2004-06-29 23:29:38 +00001769 Function* Func = Fi->first;
1770 BlockStart = At = Fi->second.Buf;
1771 BlockEnd = Fi->second.EndBuf;
Chris Lattnerb52f1c22005-02-13 17:48:18 +00001772 ParseFunctionBody(Func);
Reid Spencer060d25d2004-06-29 23:29:38 +00001773 ++Fi;
1774 }
Chris Lattnerb52f1c22005-02-13 17:48:18 +00001775 LazyFunctionLoadMap.clear();
Reid Spencer060d25d2004-06-29 23:29:38 +00001776}
Chris Lattner89e02532004-01-18 21:08:15 +00001777
Reid Spencer04cde2c2004-07-04 11:33:49 +00001778/// Parse the global type list
Reid Spencer060d25d2004-06-29 23:29:38 +00001779void BytecodeReader::ParseGlobalTypes() {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001780 // Read the number of types
1781 unsigned NumEntries = read_vbr_uint();
Reid Spencer011bed52004-07-09 21:13:53 +00001782
1783 // Ignore the type plane identifier for types if the bc file is pre 1.3
1784 if (hasTypeDerivedFromValue)
1785 read_vbr_uint();
1786
Reid Spencer46b002c2004-07-11 17:28:43 +00001787 ParseTypes(ModuleTypes, NumEntries);
Reid Spencer060d25d2004-06-29 23:29:38 +00001788}
1789
Reid Spencer04cde2c2004-07-04 11:33:49 +00001790/// Parse the Global info (types, global vars, constants)
Reid Spencer060d25d2004-06-29 23:29:38 +00001791void BytecodeReader::ParseModuleGlobalInfo() {
1792
Reid Spencer04cde2c2004-07-04 11:33:49 +00001793 if (Handler) Handler->handleModuleGlobalsBegin();
Chris Lattner00950542001-06-06 20:29:01 +00001794
Chris Lattner70cc3392001-09-10 07:58:01 +00001795 // Read global variables...
Reid Spencer060d25d2004-06-29 23:29:38 +00001796 unsigned VarType = read_vbr_uint();
Chris Lattner70cc3392001-09-10 07:58:01 +00001797 while (VarType != Type::VoidTyID) { // List is terminated by Void
Chris Lattner9dd87702004-04-03 23:43:42 +00001798 // VarType Fields: bit0 = isConstant, bit1 = hasInitializer, bit2,3,4 =
1799 // Linkage, bit4+ = slot#
1800 unsigned SlotNo = VarType >> 5;
Reid Spencer46b002c2004-07-11 17:28:43 +00001801 if (sanitizeTypeId(SlotNo))
Reid Spencer24399722004-07-09 22:21:33 +00001802 error("Invalid type (type type) for global var!");
Chris Lattner9dd87702004-04-03 23:43:42 +00001803 unsigned LinkageID = (VarType >> 2) & 7;
Reid Spencer060d25d2004-06-29 23:29:38 +00001804 bool isConstant = VarType & 1;
1805 bool hasInitializer = VarType & 2;
Chris Lattnere3869c82003-04-16 21:16:05 +00001806 GlobalValue::LinkageTypes Linkage;
1807
Chris Lattnerc08912f2004-01-14 16:44:44 +00001808 switch (LinkageID) {
Chris Lattnerc08912f2004-01-14 16:44:44 +00001809 case 0: Linkage = GlobalValue::ExternalLinkage; break;
1810 case 1: Linkage = GlobalValue::WeakLinkage; break;
1811 case 2: Linkage = GlobalValue::AppendingLinkage; break;
1812 case 3: Linkage = GlobalValue::InternalLinkage; break;
1813 case 4: Linkage = GlobalValue::LinkOnceLinkage; break;
Reid Spencer060d25d2004-06-29 23:29:38 +00001814 default:
Reid Spencer24399722004-07-09 22:21:33 +00001815 error("Unknown linkage type: " + utostr(LinkageID));
Reid Spencer060d25d2004-06-29 23:29:38 +00001816 Linkage = GlobalValue::InternalLinkage;
1817 break;
Chris Lattnere3869c82003-04-16 21:16:05 +00001818 }
1819
1820 const Type *Ty = getType(SlotNo);
Reid Spencer46b002c2004-07-11 17:28:43 +00001821 if (!Ty) {
Reid Spencer24399722004-07-09 22:21:33 +00001822 error("Global has no type! SlotNo=" + utostr(SlotNo));
Reid Spencer060d25d2004-06-29 23:29:38 +00001823 }
1824
Reid Spencer46b002c2004-07-11 17:28:43 +00001825 if (!isa<PointerType>(Ty)) {
Reid Spencer24399722004-07-09 22:21:33 +00001826 error("Global not a pointer type! Ty= " + Ty->getDescription());
Reid Spencer060d25d2004-06-29 23:29:38 +00001827 }
Chris Lattner70cc3392001-09-10 07:58:01 +00001828
Chris Lattner52e20b02003-03-19 20:54:26 +00001829 const Type *ElTy = cast<PointerType>(Ty)->getElementType();
Chris Lattnerd70684f2001-09-18 04:01:05 +00001830
Chris Lattner70cc3392001-09-10 07:58:01 +00001831 // Create the global variable...
Reid Spencer060d25d2004-06-29 23:29:38 +00001832 GlobalVariable *GV = new GlobalVariable(ElTy, isConstant, Linkage,
Chris Lattner52e20b02003-03-19 20:54:26 +00001833 0, "", TheModule);
Chris Lattner29b789b2003-11-19 17:27:18 +00001834 insertValue(GV, SlotNo, ModuleValues);
Chris Lattner05950c32001-10-13 06:47:01 +00001835
Reid Spencer060d25d2004-06-29 23:29:38 +00001836 unsigned initSlot = 0;
1837 if (hasInitializer) {
1838 initSlot = read_vbr_uint();
1839 GlobalInits.push_back(std::make_pair(GV, initSlot));
1840 }
1841
1842 // Notify handler about the global value.
Chris Lattner4a242b32004-10-14 01:39:18 +00001843 if (Handler)
1844 Handler->handleGlobalVariable(ElTy, isConstant, Linkage, SlotNo,initSlot);
Reid Spencer060d25d2004-06-29 23:29:38 +00001845
1846 // Get next item
1847 VarType = read_vbr_uint();
Chris Lattner70cc3392001-09-10 07:58:01 +00001848 }
1849
Chris Lattner52e20b02003-03-19 20:54:26 +00001850 // Read the function objects for all of the functions that are coming
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001851 unsigned FnSignature = read_vbr_uint();
Reid Spencer24399722004-07-09 22:21:33 +00001852
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001853 if (hasNoFlagsForFunctions)
1854 FnSignature = (FnSignature << 5) + 1;
1855
1856 // List is terminated by VoidTy.
1857 while ((FnSignature >> 5) != Type::VoidTyID) {
1858 const Type *Ty = getType(FnSignature >> 5);
Chris Lattner927b1852003-10-09 20:22:47 +00001859 if (!isa<PointerType>(Ty) ||
Reid Spencer060d25d2004-06-29 23:29:38 +00001860 !isa<FunctionType>(cast<PointerType>(Ty)->getElementType())) {
Reid Spencer24399722004-07-09 22:21:33 +00001861 error("Function not a pointer to function type! Ty = " +
Reid Spencer46b002c2004-07-11 17:28:43 +00001862 Ty->getDescription());
Reid Spencer060d25d2004-06-29 23:29:38 +00001863 }
Chris Lattner8cdc6b72002-10-23 00:51:54 +00001864
Chris Lattner2a7b6ba2003-03-06 17:15:19 +00001865 // We create functions by passing the underlying FunctionType to create...
Reid Spencer060d25d2004-06-29 23:29:38 +00001866 const FunctionType* FTy =
1867 cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
Chris Lattner00950542001-06-06 20:29:01 +00001868
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001869
Chris Lattner18549c22004-11-15 21:43:03 +00001870 // Insert the place holder.
1871 Function* Func = new Function(FTy, GlobalValue::ExternalLinkage,
Reid Spencer04cde2c2004-07-04 11:33:49 +00001872 "", TheModule);
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001873 insertValue(Func, FnSignature >> 5, ModuleValues);
1874
1875 // Flags are not used yet.
Chris Lattner97fbc502004-11-15 22:38:52 +00001876 unsigned Flags = FnSignature & 31;
Chris Lattner00950542001-06-06 20:29:01 +00001877
Chris Lattner97fbc502004-11-15 22:38:52 +00001878 // Save this for later so we know type of lazily instantiated functions.
1879 // Note that known-external functions do not have FunctionInfo blocks, so we
1880 // do not add them to the FunctionSignatureList.
1881 if ((Flags & (1 << 4)) == 0)
1882 FunctionSignatureList.push_back(Func);
Chris Lattner52e20b02003-03-19 20:54:26 +00001883
Reid Spencer04cde2c2004-07-04 11:33:49 +00001884 if (Handler) Handler->handleFunctionDeclaration(Func);
Reid Spencer060d25d2004-06-29 23:29:38 +00001885
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001886 // Get the next function signature.
1887 FnSignature = read_vbr_uint();
1888 if (hasNoFlagsForFunctions)
1889 FnSignature = (FnSignature << 5) + 1;
Chris Lattner00950542001-06-06 20:29:01 +00001890 }
1891
Chris Lattner74734132002-08-17 22:01:27 +00001892 // Now that the function signature list is set up, reverse it so that we can
1893 // remove elements efficiently from the back of the vector.
1894 std::reverse(FunctionSignatureList.begin(), FunctionSignatureList.end());
Chris Lattner00950542001-06-06 20:29:01 +00001895
Reid Spencerad89bd62004-07-25 18:07:36 +00001896 // If this bytecode format has dependent library information in it ..
1897 if (!hasNoDependentLibraries) {
1898 // Read in the number of dependent library items that follow
1899 unsigned num_dep_libs = read_vbr_uint();
1900 std::string dep_lib;
1901 while( num_dep_libs-- ) {
1902 dep_lib = read_str();
Reid Spencerada16182004-07-25 21:36:26 +00001903 TheModule->addLibrary(dep_lib);
Reid Spencer5b472d92004-08-21 20:49:23 +00001904 if (Handler)
1905 Handler->handleDependentLibrary(dep_lib);
Reid Spencerad89bd62004-07-25 18:07:36 +00001906 }
1907
Reid Spencer5b472d92004-08-21 20:49:23 +00001908
Reid Spencerad89bd62004-07-25 18:07:36 +00001909 // Read target triple and place into the module
1910 std::string triple = read_str();
1911 TheModule->setTargetTriple(triple);
Reid Spencer5b472d92004-08-21 20:49:23 +00001912 if (Handler)
1913 Handler->handleTargetTriple(triple);
Reid Spencerad89bd62004-07-25 18:07:36 +00001914 }
1915
1916 if (hasInconsistentModuleGlobalInfo)
1917 align32();
1918
Chris Lattner00950542001-06-06 20:29:01 +00001919 // This is for future proofing... in the future extra fields may be added that
1920 // we don't understand, so we transparently ignore them.
1921 //
Reid Spencer060d25d2004-06-29 23:29:38 +00001922 At = BlockEnd;
1923
Reid Spencer04cde2c2004-07-04 11:33:49 +00001924 if (Handler) Handler->handleModuleGlobalsEnd();
Chris Lattner00950542001-06-06 20:29:01 +00001925}
1926
Reid Spencer04cde2c2004-07-04 11:33:49 +00001927/// Parse the version information and decode it by setting flags on the
1928/// Reader that enable backward compatibility of the reader.
Reid Spencer060d25d2004-06-29 23:29:38 +00001929void BytecodeReader::ParseVersionInfo() {
1930 unsigned Version = read_vbr_uint();
Chris Lattner036b8aa2003-03-06 17:55:45 +00001931
1932 // Unpack version number: low four bits are for flags, top bits = version
Chris Lattnerd445c6b2003-08-24 13:47:36 +00001933 Module::Endianness Endianness;
1934 Module::PointerSize PointerSize;
1935 Endianness = (Version & 1) ? Module::BigEndian : Module::LittleEndian;
1936 PointerSize = (Version & 2) ? Module::Pointer64 : Module::Pointer32;
1937
1938 bool hasNoEndianness = Version & 4;
1939 bool hasNoPointerSize = Version & 8;
1940
1941 RevisionNum = Version >> 4;
Chris Lattnere3869c82003-04-16 21:16:05 +00001942
1943 // Default values for the current bytecode version
Chris Lattner44d0eeb2004-01-15 17:55:01 +00001944 hasInconsistentModuleGlobalInfo = false;
Chris Lattner80b97342004-01-17 23:25:43 +00001945 hasExplicitPrimitiveZeros = false;
Chris Lattner5fa428f2004-04-05 01:27:26 +00001946 hasRestrictedGEPTypes = false;
Reid Spencer04cde2c2004-07-04 11:33:49 +00001947 hasTypeDerivedFromValue = false;
Reid Spencerad89bd62004-07-25 18:07:36 +00001948 hasLongBlockHeaders = false;
Reid Spencerad89bd62004-07-25 18:07:36 +00001949 has32BitTypes = false;
1950 hasNoDependentLibraries = false;
Reid Spencer38d54be2004-08-17 07:45:14 +00001951 hasAlignment = false;
Reid Spencer5b472d92004-08-21 20:49:23 +00001952 hasInconsistentBBSlotNums = false;
1953 hasVBRByteTypes = false;
1954 hasUnnecessaryModuleBlockId = false;
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001955 hasNoUndefValue = false;
1956 hasNoFlagsForFunctions = false;
1957 hasNoUnreachableInst = false;
Chris Lattner036b8aa2003-03-06 17:55:45 +00001958
1959 switch (RevisionNum) {
Reid Spencer5b472d92004-08-21 20:49:23 +00001960 case 0: // LLVM 1.0, 1.1 (Released)
Chris Lattner9e893e82004-01-14 23:35:21 +00001961 // Base LLVM 1.0 bytecode format.
Chris Lattner44d0eeb2004-01-15 17:55:01 +00001962 hasInconsistentModuleGlobalInfo = true;
Chris Lattner80b97342004-01-17 23:25:43 +00001963 hasExplicitPrimitiveZeros = true;
Reid Spencer04cde2c2004-07-04 11:33:49 +00001964
Chris Lattner80b97342004-01-17 23:25:43 +00001965 // FALL THROUGH
Reid Spencer5b472d92004-08-21 20:49:23 +00001966
1967 case 1: // LLVM 1.2 (Released)
Chris Lattner9e893e82004-01-14 23:35:21 +00001968 // LLVM 1.2 added explicit support for emitting strings efficiently.
Chris Lattner44d0eeb2004-01-15 17:55:01 +00001969
1970 // Also, it fixed the problem where the size of the ModuleGlobalInfo block
1971 // included the size for the alignment at the end, where the rest of the
1972 // blocks did not.
Chris Lattner5fa428f2004-04-05 01:27:26 +00001973
1974 // LLVM 1.2 and before required that GEP indices be ubyte constants for
1975 // structures and longs for sequential types.
1976 hasRestrictedGEPTypes = true;
1977
Reid Spencer04cde2c2004-07-04 11:33:49 +00001978 // LLVM 1.2 and before had the Type class derive from Value class. This
1979 // changed in release 1.3 and consequently LLVM 1.3 bytecode files are
1980 // written differently because Types can no longer be part of the
1981 // type planes for Values.
1982 hasTypeDerivedFromValue = true;
1983
Chris Lattner5fa428f2004-04-05 01:27:26 +00001984 // FALL THROUGH
Reid Spencerad89bd62004-07-25 18:07:36 +00001985
Reid Spencer5b472d92004-08-21 20:49:23 +00001986 case 2: // 1.2.5 (Not Released)
Reid Spencerad89bd62004-07-25 18:07:36 +00001987
Reid Spencer5b472d92004-08-21 20:49:23 +00001988 // LLVM 1.2 and earlier had two-word block headers. This is a bit wasteful,
Chris Lattner4a242b32004-10-14 01:39:18 +00001989 // especially for small files where the 8 bytes per block is a large
1990 // fraction of the total block size. In LLVM 1.3, the block type and length
1991 // are compressed into a single 32-bit unsigned integer. 27 bits for length,
1992 // 5 bits for block type.
Reid Spencerad89bd62004-07-25 18:07:36 +00001993 hasLongBlockHeaders = true;
1994
Reid Spencer5b472d92004-08-21 20:49:23 +00001995 // LLVM 1.2 and earlier wrote type slot numbers as vbr_uint32. In LLVM 1.3
Chris Lattner4a242b32004-10-14 01:39:18 +00001996 // this has been reduced to vbr_uint24. It shouldn't make much difference
1997 // since we haven't run into a module with > 24 million types, but for
1998 // safety the 24-bit restriction has been enforced in 1.3 to free some bits
1999 // in various places and to ensure consistency.
Reid Spencerad89bd62004-07-25 18:07:36 +00002000 has32BitTypes = true;
2001
Reid Spencer5b472d92004-08-21 20:49:23 +00002002 // LLVM 1.2 and earlier did not provide a target triple nor a list of
2003 // libraries on which the bytecode is dependent. LLVM 1.3 provides these
2004 // features, for use in future versions of LLVM.
Reid Spencerad89bd62004-07-25 18:07:36 +00002005 hasNoDependentLibraries = true;
2006
2007 // FALL THROUGH
Reid Spencer5b472d92004-08-21 20:49:23 +00002008
2009 case 3: // LLVM 1.3 (Released)
2010 // LLVM 1.3 and earlier caused alignment bytes to be written on some block
2011 // boundaries and at the end of some strings. In extreme cases (e.g. lots
2012 // of GEP references to a constant array), this can increase the file size
2013 // by 30% or more. In version 1.4 alignment is done away with completely.
Reid Spencer38d54be2004-08-17 07:45:14 +00002014 hasAlignment = true;
2015
2016 // FALL THROUGH
Reid Spencer5b472d92004-08-21 20:49:23 +00002017
2018 case 4: // 1.3.1 (Not Released)
Chris Lattnera79e7cc2004-10-16 18:18:16 +00002019 // In version 4, we did not support the 'undef' constant.
2020 hasNoUndefValue = true;
2021
2022 // In version 4 and above, we did not include space for flags for functions
2023 // in the module info block.
2024 hasNoFlagsForFunctions = true;
2025
2026 // In version 4 and above, we did not include the 'unreachable' instruction
2027 // in the opcode numbering in the bytecode file.
2028 hasNoUnreachableInst = true;
Chris Lattner2e7ec122004-10-16 18:56:02 +00002029 break;
Chris Lattnera79e7cc2004-10-16 18:18:16 +00002030
2031 // FALL THROUGH
2032
2033 case 5: // 1.x.x (Not Released)
Chris Lattnera79e7cc2004-10-16 18:18:16 +00002034 break;
Chris Lattner2e7ec122004-10-16 18:56:02 +00002035 // FIXME: NONE of this is implemented yet!
Chris Lattnera79e7cc2004-10-16 18:18:16 +00002036
2037 // In version 5, basic blocks have a minimum index of 0 whereas all the
Reid Spencer5b472d92004-08-21 20:49:23 +00002038 // other primitives have a minimum index of 1 (because 0 is the "null"
2039 // value. In version 5, we made this consistent.
2040 hasInconsistentBBSlotNums = true;
Chris Lattnerc08912f2004-01-14 16:44:44 +00002041
Chris Lattnera79e7cc2004-10-16 18:18:16 +00002042 // In version 5, the types SByte and UByte were encoded as vbr_uint so that
Reid Spencer5b472d92004-08-21 20:49:23 +00002043 // signed values > 63 and unsigned values >127 would be encoded as two
2044 // bytes. In version 5, they are encoded directly in a single byte.
2045 hasVBRByteTypes = true;
2046
Chris Lattnera79e7cc2004-10-16 18:18:16 +00002047 // In version 5, modules begin with a "Module Block" which encodes a 4-byte
Reid Spencer5b472d92004-08-21 20:49:23 +00002048 // integer value 0x01 to identify the module block. This is unnecessary and
2049 // removed in version 5.
2050 hasUnnecessaryModuleBlockId = true;
2051
Chris Lattner036b8aa2003-03-06 17:55:45 +00002052 default:
Reid Spencer24399722004-07-09 22:21:33 +00002053 error("Unknown bytecode version number: " + itostr(RevisionNum));
Chris Lattner036b8aa2003-03-06 17:55:45 +00002054 }
2055
Chris Lattnerd445c6b2003-08-24 13:47:36 +00002056 if (hasNoEndianness) Endianness = Module::AnyEndianness;
2057 if (hasNoPointerSize) PointerSize = Module::AnyPointerSize;
Chris Lattner76e38962003-04-22 18:15:10 +00002058
Brian Gaekefe2102b2004-07-14 20:33:13 +00002059 TheModule->setEndianness(Endianness);
2060 TheModule->setPointerSize(PointerSize);
2061
Reid Spencer46b002c2004-07-11 17:28:43 +00002062 if (Handler) Handler->handleVersionInfo(RevisionNum, Endianness, PointerSize);
Chris Lattner036b8aa2003-03-06 17:55:45 +00002063}
2064
Reid Spencer04cde2c2004-07-04 11:33:49 +00002065/// Parse a whole module.
Reid Spencer060d25d2004-06-29 23:29:38 +00002066void BytecodeReader::ParseModule() {
Chris Lattner00950542001-06-06 20:29:01 +00002067 unsigned Type, Size;
Chris Lattner00950542001-06-06 20:29:01 +00002068
Reid Spencer060d25d2004-06-29 23:29:38 +00002069 FunctionSignatureList.clear(); // Just in case...
Chris Lattner00950542001-06-06 20:29:01 +00002070
2071 // Read into instance variables...
Reid Spencer060d25d2004-06-29 23:29:38 +00002072 ParseVersionInfo();
Reid Spencerad89bd62004-07-25 18:07:36 +00002073 align32();
Chris Lattner00950542001-06-06 20:29:01 +00002074
Reid Spencer060d25d2004-06-29 23:29:38 +00002075 bool SeenModuleGlobalInfo = false;
2076 bool SeenGlobalTypePlane = false;
2077 BufPtr MyEnd = BlockEnd;
2078 while (At < MyEnd) {
2079 BufPtr OldAt = At;
2080 read_block(Type, Size);
2081
Chris Lattner00950542001-06-06 20:29:01 +00002082 switch (Type) {
Reid Spencer060d25d2004-06-29 23:29:38 +00002083
Reid Spencerad89bd62004-07-25 18:07:36 +00002084 case BytecodeFormat::GlobalTypePlaneBlockID:
Reid Spencer46b002c2004-07-11 17:28:43 +00002085 if (SeenGlobalTypePlane)
Reid Spencer24399722004-07-09 22:21:33 +00002086 error("Two GlobalTypePlane Blocks Encountered!");
Reid Spencer060d25d2004-06-29 23:29:38 +00002087
Reid Spencer5b472d92004-08-21 20:49:23 +00002088 if (Size > 0)
2089 ParseGlobalTypes();
Reid Spencer060d25d2004-06-29 23:29:38 +00002090 SeenGlobalTypePlane = true;
Chris Lattner52e20b02003-03-19 20:54:26 +00002091 break;
2092
Reid Spencerad89bd62004-07-25 18:07:36 +00002093 case BytecodeFormat::ModuleGlobalInfoBlockID:
Reid Spencer46b002c2004-07-11 17:28:43 +00002094 if (SeenModuleGlobalInfo)
Reid Spencer24399722004-07-09 22:21:33 +00002095 error("Two ModuleGlobalInfo Blocks Encountered!");
Reid Spencer060d25d2004-06-29 23:29:38 +00002096 ParseModuleGlobalInfo();
2097 SeenModuleGlobalInfo = true;
Chris Lattner52e20b02003-03-19 20:54:26 +00002098 break;
2099
Reid Spencerad89bd62004-07-25 18:07:36 +00002100 case BytecodeFormat::ConstantPoolBlockID:
Reid Spencer04cde2c2004-07-04 11:33:49 +00002101 ParseConstantPool(ModuleValues, ModuleTypes,false);
Chris Lattner00950542001-06-06 20:29:01 +00002102 break;
2103
Reid Spencerad89bd62004-07-25 18:07:36 +00002104 case BytecodeFormat::FunctionBlockID:
Reid Spencer060d25d2004-06-29 23:29:38 +00002105 ParseFunctionLazily();
Chris Lattner00950542001-06-06 20:29:01 +00002106 break;
Chris Lattner00950542001-06-06 20:29:01 +00002107
Reid Spencerad89bd62004-07-25 18:07:36 +00002108 case BytecodeFormat::SymbolTableBlockID:
Reid Spencer060d25d2004-06-29 23:29:38 +00002109 ParseSymbolTable(0, &TheModule->getSymbolTable());
Chris Lattner00950542001-06-06 20:29:01 +00002110 break;
Reid Spencer060d25d2004-06-29 23:29:38 +00002111
Chris Lattner00950542001-06-06 20:29:01 +00002112 default:
Reid Spencer060d25d2004-06-29 23:29:38 +00002113 At += Size;
2114 if (OldAt > At) {
Reid Spencer46b002c2004-07-11 17:28:43 +00002115 error("Unexpected Block of Type #" + utostr(Type) + " encountered!");
Reid Spencer060d25d2004-06-29 23:29:38 +00002116 }
Chris Lattner00950542001-06-06 20:29:01 +00002117 break;
2118 }
Reid Spencer060d25d2004-06-29 23:29:38 +00002119 BlockEnd = MyEnd;
2120 align32();
Chris Lattner00950542001-06-06 20:29:01 +00002121 }
2122
Chris Lattner52e20b02003-03-19 20:54:26 +00002123 // After the module constant pool has been read, we can safely initialize
2124 // global variables...
2125 while (!GlobalInits.empty()) {
2126 GlobalVariable *GV = GlobalInits.back().first;
2127 unsigned Slot = GlobalInits.back().second;
2128 GlobalInits.pop_back();
2129
2130 // Look up the initializer value...
Chris Lattner29b789b2003-11-19 17:27:18 +00002131 // FIXME: Preserve this type ID!
Reid Spencer060d25d2004-06-29 23:29:38 +00002132
2133 const llvm::PointerType* GVType = GV->getType();
2134 unsigned TypeSlot = getTypeSlot(GVType->getElementType());
Chris Lattner93361992004-01-15 18:45:25 +00002135 if (Constant *CV = getConstantValue(TypeSlot, Slot)) {
Misha Brukman12c29d12003-09-22 23:38:23 +00002136 if (GV->hasInitializer())
Reid Spencer24399722004-07-09 22:21:33 +00002137 error("Global *already* has an initializer?!");
Reid Spencer04cde2c2004-07-04 11:33:49 +00002138 if (Handler) Handler->handleGlobalInitializer(GV,CV);
Chris Lattner93361992004-01-15 18:45:25 +00002139 GV->setInitializer(CV);
Chris Lattner52e20b02003-03-19 20:54:26 +00002140 } else
Reid Spencer24399722004-07-09 22:21:33 +00002141 error("Cannot find initializer value.");
Chris Lattner52e20b02003-03-19 20:54:26 +00002142 }
2143
Reid Spencer060d25d2004-06-29 23:29:38 +00002144 /// Make sure we pulled them all out. If we didn't then there's a declaration
2145 /// but a missing body. That's not allowed.
Misha Brukman12c29d12003-09-22 23:38:23 +00002146 if (!FunctionSignatureList.empty())
Reid Spencer24399722004-07-09 22:21:33 +00002147 error("Function declared, but bytecode stream ended before definition");
Chris Lattner00950542001-06-06 20:29:01 +00002148}
2149
Reid Spencer04cde2c2004-07-04 11:33:49 +00002150/// This function completely parses a bytecode buffer given by the \p Buf
2151/// and \p Length parameters.
Reid Spencer46b002c2004-07-11 17:28:43 +00002152void BytecodeReader::ParseBytecode(BufPtr Buf, unsigned Length,
Reid Spencer5b472d92004-08-21 20:49:23 +00002153 const std::string &ModuleID) {
Misha Brukmane0dd0d42003-09-23 16:15:29 +00002154
Reid Spencer060d25d2004-06-29 23:29:38 +00002155 try {
Chris Lattner3af4b4f2004-11-30 16:58:18 +00002156 RevisionNum = 0;
Reid Spencer060d25d2004-06-29 23:29:38 +00002157 At = MemStart = BlockStart = Buf;
2158 MemEnd = BlockEnd = Buf + Length;
Misha Brukmane0dd0d42003-09-23 16:15:29 +00002159
Reid Spencer060d25d2004-06-29 23:29:38 +00002160 // Create the module
2161 TheModule = new Module(ModuleID);
Chris Lattner00950542001-06-06 20:29:01 +00002162
Reid Spencer04cde2c2004-07-04 11:33:49 +00002163 if (Handler) Handler->handleStart(TheModule, Length);
Reid Spencer060d25d2004-06-29 23:29:38 +00002164
Reid Spencerf0c977c2004-11-07 18:20:55 +00002165 // Read the four bytes of the signature.
2166 unsigned Sig = read_uint();
Reid Spencer17f52c52004-11-06 23:17:23 +00002167
Reid Spencerf0c977c2004-11-07 18:20:55 +00002168 // If this is a compressed file
2169 if (Sig == ('l' | ('l' << 8) | ('v' << 16) | ('c' << 24))) {
Reid Spencer17f52c52004-11-06 23:17:23 +00002170
Reid Spencerf0c977c2004-11-07 18:20:55 +00002171 // Invoke the decompression of the bytecode. Note that we have to skip the
2172 // file's magic number which is not part of the compressed block. Hence,
Reid Spencer61aaf2e2004-11-14 21:59:21 +00002173 // the Buf+4 and Length-4. The result goes into decompressedBlock, a data
2174 // member for retention until BytecodeReader is destructed.
2175 unsigned decompressedLength = Compressor::decompressToNewBuffer(
2176 (char*)Buf+4,Length-4,decompressedBlock);
Reid Spencerf0c977c2004-11-07 18:20:55 +00002177
2178 // We must adjust the buffer pointers used by the bytecode reader to point
Reid Spencer61aaf2e2004-11-14 21:59:21 +00002179 // into the new decompressed block. After decompression, the
2180 // decompressedBlock will point to a contiguous memory area that has
Reid Spencerf0c977c2004-11-07 18:20:55 +00002181 // the decompressed data.
Reid Spencer61aaf2e2004-11-14 21:59:21 +00002182 At = MemStart = BlockStart = Buf = (BufPtr) decompressedBlock;
Reid Spencerf0c977c2004-11-07 18:20:55 +00002183 MemEnd = BlockEnd = Buf + decompressedLength;
Reid Spencer17f52c52004-11-06 23:17:23 +00002184
Reid Spencerf0c977c2004-11-07 18:20:55 +00002185 // else if this isn't a regular (uncompressed) bytecode file, then its
2186 // and error, generate that now.
2187 } else if (Sig != ('l' | ('l' << 8) | ('v' << 16) | ('m' << 24))) {
2188 error("Invalid bytecode signature: " + utohexstr(Sig));
Reid Spencer060d25d2004-06-29 23:29:38 +00002189 }
2190
Reid Spencer060d25d2004-06-29 23:29:38 +00002191 // Tell the handler we're starting a module
Reid Spencer04cde2c2004-07-04 11:33:49 +00002192 if (Handler) Handler->handleModuleBegin(ModuleID);
Reid Spencer060d25d2004-06-29 23:29:38 +00002193
Reid Spencerad89bd62004-07-25 18:07:36 +00002194 // Get the module block and size and verify. This is handled specially
2195 // because the module block/size is always written in long format. Other
2196 // blocks are written in short format so the read_block method is used.
Reid Spencer060d25d2004-06-29 23:29:38 +00002197 unsigned Type, Size;
Reid Spencerad89bd62004-07-25 18:07:36 +00002198 Type = read_uint();
2199 Size = read_uint();
2200 if (Type != BytecodeFormat::ModuleBlockID) {
Reid Spencer24399722004-07-09 22:21:33 +00002201 error("Expected Module Block! Type:" + utostr(Type) + ", Size:"
Reid Spencer46b002c2004-07-11 17:28:43 +00002202 + utostr(Size));
Reid Spencer060d25d2004-06-29 23:29:38 +00002203 }
Chris Lattner56bc8942004-09-27 16:59:06 +00002204
2205 // It looks like the darwin ranlib program is broken, and adds trailing
2206 // garbage to the end of some bytecode files. This hack allows the bc
2207 // reader to ignore trailing garbage on bytecode files.
2208 if (At + Size < MemEnd)
2209 MemEnd = BlockEnd = At+Size;
2210
2211 if (At + Size != MemEnd)
Reid Spencer24399722004-07-09 22:21:33 +00002212 error("Invalid Top Level Block Length! Type:" + utostr(Type)
Reid Spencer46b002c2004-07-11 17:28:43 +00002213 + ", Size:" + utostr(Size));
Reid Spencer060d25d2004-06-29 23:29:38 +00002214
2215 // Parse the module contents
2216 this->ParseModule();
2217
Reid Spencer060d25d2004-06-29 23:29:38 +00002218 // Check for missing functions
Reid Spencer46b002c2004-07-11 17:28:43 +00002219 if (hasFunctions())
Reid Spencer24399722004-07-09 22:21:33 +00002220 error("Function expected, but bytecode stream ended!");
Reid Spencer060d25d2004-06-29 23:29:38 +00002221
Reid Spencer5c15fe52004-07-05 00:57:50 +00002222 // Tell the handler we're done with the module
2223 if (Handler)
2224 Handler->handleModuleEnd(ModuleID);
2225
2226 // Tell the handler we're finished the parse
Reid Spencer04cde2c2004-07-04 11:33:49 +00002227 if (Handler) Handler->handleFinish();
Reid Spencer060d25d2004-06-29 23:29:38 +00002228
Reid Spencer46b002c2004-07-11 17:28:43 +00002229 } catch (std::string& errstr) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00002230 if (Handler) Handler->handleError(errstr);
Reid Spencer060d25d2004-06-29 23:29:38 +00002231 freeState();
Chris Lattner2a7b6ba2003-03-06 17:15:19 +00002232 delete TheModule;
2233 TheModule = 0;
Chris Lattner3bdad692004-11-15 21:55:33 +00002234 if (decompressedBlock != 0 ) {
Reid Spencer61aaf2e2004-11-14 21:59:21 +00002235 ::free(decompressedBlock);
Chris Lattner3bdad692004-11-15 21:55:33 +00002236 decompressedBlock = 0;
2237 }
Chris Lattnerb0b7c0d2003-09-26 14:44:52 +00002238 throw;
Reid Spencer060d25d2004-06-29 23:29:38 +00002239 } catch (...) {
2240 std::string msg("Unknown Exception Occurred");
Reid Spencer04cde2c2004-07-04 11:33:49 +00002241 if (Handler) Handler->handleError(msg);
Reid Spencer060d25d2004-06-29 23:29:38 +00002242 freeState();
2243 delete TheModule;
2244 TheModule = 0;
Chris Lattner3bdad692004-11-15 21:55:33 +00002245 if (decompressedBlock != 0) {
Reid Spencer61aaf2e2004-11-14 21:59:21 +00002246 ::free(decompressedBlock);
Chris Lattner3bdad692004-11-15 21:55:33 +00002247 decompressedBlock = 0;
2248 }
Reid Spencer060d25d2004-06-29 23:29:38 +00002249 throw msg;
Chris Lattner2a7b6ba2003-03-06 17:15:19 +00002250 }
Chris Lattner00950542001-06-06 20:29:01 +00002251}
Reid Spencer060d25d2004-06-29 23:29:38 +00002252
2253//===----------------------------------------------------------------------===//
2254//=== Default Implementations of Handler Methods
2255//===----------------------------------------------------------------------===//
2256
2257BytecodeHandler::~BytecodeHandler() {}
Reid Spencer060d25d2004-06-29 23:29:38 +00002258
2259// vim: sw=2