blob: 13fecc53dfe08721fecdbc6f0dd58477448ffb58 [file] [log] [blame]
Chris Lattnerd6b65252001-10-24 01:15:12 +00001//===- Reader.cpp - Code to read bytecode files ---------------------------===//
John Criswellb576c942003-10-20 19:43:21 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
Chris Lattner00950542001-06-06 20:29:01 +00009//
10// This library implements the functionality defined in llvm/Bytecode/Reader.h
11//
12// Note that this library should be as fast as possible, reentrant, and
13// threadsafe!!
14//
Chris Lattner00950542001-06-06 20:29:01 +000015// TODO: Allow passing in an option to ignore the symbol table
16//
Chris Lattnerd6b65252001-10-24 01:15:12 +000017//===----------------------------------------------------------------------===//
Chris Lattner00950542001-06-06 20:29:01 +000018
Reid Spencer060d25d2004-06-29 23:29:38 +000019#include "Reader.h"
20#include "llvm/Bytecode/BytecodeHandler.h"
21#include "llvm/BasicBlock.h"
22#include "llvm/Constants.h"
Reid Spencer04cde2c2004-07-04 11:33:49 +000023#include "llvm/Instructions.h"
24#include "llvm/SymbolTable.h"
Chris Lattner00950542001-06-06 20:29:01 +000025#include "llvm/Bytecode/Format.h"
Reid Spencer060d25d2004-06-29 23:29:38 +000026#include "llvm/Support/GetElementPtrTypeIterator.h"
Misha Brukman12c29d12003-09-22 23:38:23 +000027#include "Support/StringExtras.h"
Reid Spencer060d25d2004-06-29 23:29:38 +000028#include <sstream>
Chris Lattner29b789b2003-11-19 17:27:18 +000029using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000030
Reid Spencer46b002c2004-07-11 17:28:43 +000031namespace {
32
Reid Spencer060d25d2004-06-29 23:29:38 +000033/// @brief A class for maintaining the slot number definition
Reid Spencer46b002c2004-07-11 17:28:43 +000034/// as a placeholder for the actual definition for forward constants defs.
35class ConstantPlaceHolder : public ConstantExpr {
Reid Spencer060d25d2004-06-29 23:29:38 +000036 unsigned ID;
Reid Spencer46b002c2004-07-11 17:28:43 +000037 ConstantPlaceHolder(); // DO NOT IMPLEMENT
38 void operator=(const ConstantPlaceHolder &); // DO NOT IMPLEMENT
Reid Spencer060d25d2004-06-29 23:29:38 +000039public:
Reid Spencer46b002c2004-07-11 17:28:43 +000040 ConstantPlaceHolder(const Type *Ty, unsigned id)
41 : ConstantExpr(Instruction::UserOp1, Constant::getNullValue(Ty), Ty),
42 ID(id) {}
Reid Spencer060d25d2004-06-29 23:29:38 +000043 unsigned getID() { return ID; }
44};
Chris Lattner9e460f22003-10-04 20:00:03 +000045
Reid Spencer46b002c2004-07-11 17:28:43 +000046}
Reid Spencer060d25d2004-06-29 23:29:38 +000047
Reid Spencer24399722004-07-09 22:21:33 +000048// Provide some details on error
49inline void BytecodeReader::error(std::string err) {
50 err += " (Vers=" ;
51 err += itostr(RevisionNum) ;
52 err += ", Pos=" ;
53 err += itostr(At-MemStart);
54 err += ")";
55 throw err;
56}
57
Reid Spencer060d25d2004-06-29 23:29:38 +000058//===----------------------------------------------------------------------===//
59// Bytecode Reading Methods
60//===----------------------------------------------------------------------===//
61
Reid Spencer04cde2c2004-07-04 11:33:49 +000062/// Determine if the current block being read contains any more data.
Reid Spencer060d25d2004-06-29 23:29:38 +000063inline bool BytecodeReader::moreInBlock() {
64 return At < BlockEnd;
Chris Lattner00950542001-06-06 20:29:01 +000065}
66
Reid Spencer04cde2c2004-07-04 11:33:49 +000067/// Throw an error if we've read past the end of the current block
Reid Spencer060d25d2004-06-29 23:29:38 +000068inline void BytecodeReader::checkPastBlockEnd(const char * block_name) {
Reid Spencer46b002c2004-07-11 17:28:43 +000069 if (At > BlockEnd)
Reid Spencer24399722004-07-09 22:21:33 +000070 error(std::string("Attempt to read past the end of ") + block_name + " block.");
Reid Spencer060d25d2004-06-29 23:29:38 +000071}
Chris Lattner36392bc2003-10-08 21:18:57 +000072
Reid Spencer04cde2c2004-07-04 11:33:49 +000073/// Align the buffer position to a 32 bit boundary
Reid Spencer060d25d2004-06-29 23:29:38 +000074inline void BytecodeReader::align32() {
75 BufPtr Save = At;
76 At = (const unsigned char *)((unsigned long)(At+3) & (~3UL));
Reid Spencer46b002c2004-07-11 17:28:43 +000077 if (At > Save)
78 if (Handler) Handler->handleAlignment(At - Save);
Reid Spencer060d25d2004-06-29 23:29:38 +000079 if (At > BlockEnd)
Reid Spencer24399722004-07-09 22:21:33 +000080 error("Ran out of data while aligning!");
Reid Spencer060d25d2004-06-29 23:29:38 +000081}
82
Reid Spencer04cde2c2004-07-04 11:33:49 +000083/// Read a whole unsigned integer
Reid Spencer060d25d2004-06-29 23:29:38 +000084inline unsigned BytecodeReader::read_uint() {
85 if (At+4 > BlockEnd)
Reid Spencer24399722004-07-09 22:21:33 +000086 error("Ran out of data reading uint!");
Reid Spencer060d25d2004-06-29 23:29:38 +000087 At += 4;
88 return At[-4] | (At[-3] << 8) | (At[-2] << 16) | (At[-1] << 24);
89}
90
Reid Spencer04cde2c2004-07-04 11:33:49 +000091/// Read a variable-bit-rate encoded unsigned integer
Reid Spencer060d25d2004-06-29 23:29:38 +000092inline unsigned BytecodeReader::read_vbr_uint() {
93 unsigned Shift = 0;
94 unsigned Result = 0;
95 BufPtr Save = At;
96
97 do {
98 if (At == BlockEnd)
Reid Spencer24399722004-07-09 22:21:33 +000099 error("Ran out of data reading vbr_uint!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000100 Result |= (unsigned)((*At++) & 0x7F) << Shift;
101 Shift += 7;
102 } while (At[-1] & 0x80);
Reid Spencer04cde2c2004-07-04 11:33:49 +0000103 if (Handler) Handler->handleVBR32(At-Save);
Reid Spencer060d25d2004-06-29 23:29:38 +0000104 return Result;
105}
106
Reid Spencer04cde2c2004-07-04 11:33:49 +0000107/// Read a variable-bit-rate encoded unsigned 64-bit integer.
Reid Spencer060d25d2004-06-29 23:29:38 +0000108inline uint64_t BytecodeReader::read_vbr_uint64() {
109 unsigned Shift = 0;
110 uint64_t Result = 0;
111 BufPtr Save = At;
112
113 do {
114 if (At == BlockEnd)
Reid Spencer24399722004-07-09 22:21:33 +0000115 error("Ran out of data reading vbr_uint64!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000116 Result |= (uint64_t)((*At++) & 0x7F) << Shift;
117 Shift += 7;
118 } while (At[-1] & 0x80);
Reid Spencer04cde2c2004-07-04 11:33:49 +0000119 if (Handler) Handler->handleVBR64(At-Save);
Reid Spencer060d25d2004-06-29 23:29:38 +0000120 return Result;
121}
122
Reid Spencer04cde2c2004-07-04 11:33:49 +0000123/// Read a variable-bit-rate encoded signed 64-bit integer.
Reid Spencer060d25d2004-06-29 23:29:38 +0000124inline int64_t BytecodeReader::read_vbr_int64() {
125 uint64_t R = read_vbr_uint64();
126 if (R & 1) {
127 if (R != 1)
128 return -(int64_t)(R >> 1);
129 else // There is no such thing as -0 with integers. "-0" really means
130 // 0x8000000000000000.
131 return 1LL << 63;
132 } else
133 return (int64_t)(R >> 1);
134}
135
Reid Spencer04cde2c2004-07-04 11:33:49 +0000136/// Read a pascal-style string (length followed by text)
Reid Spencer060d25d2004-06-29 23:29:38 +0000137inline std::string BytecodeReader::read_str() {
138 unsigned Size = read_vbr_uint();
139 const unsigned char *OldAt = At;
140 At += Size;
141 if (At > BlockEnd) // Size invalid?
Reid Spencer24399722004-07-09 22:21:33 +0000142 error("Ran out of data reading a string!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000143 return std::string((char*)OldAt, Size);
144}
145
Reid Spencer04cde2c2004-07-04 11:33:49 +0000146/// Read an arbitrary block of data
Reid Spencer060d25d2004-06-29 23:29:38 +0000147inline void BytecodeReader::read_data(void *Ptr, void *End) {
148 unsigned char *Start = (unsigned char *)Ptr;
149 unsigned Amount = (unsigned char *)End - Start;
150 if (At+Amount > BlockEnd)
Reid Spencer24399722004-07-09 22:21:33 +0000151 error("Ran out of data!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000152 std::copy(At, At+Amount, Start);
153 At += Amount;
154}
155
Reid Spencer46b002c2004-07-11 17:28:43 +0000156/// Read a float value in little-endian order
157inline void BytecodeReader::read_float(float& FloatVal) {
Reid Spencerada16182004-07-25 21:36:26 +0000158 /// FIXME: This isn't optimal, it has size problems on some platforms
159 /// where FP is not IEEE.
160 union {
161 float f;
162 uint32_t i;
163 } FloatUnion;
164 FloatUnion.i = At[0] | (At[1] << 8) | (At[2] << 16) | (At[3] << 24);
165 At+=sizeof(uint32_t);
166 FloatVal = FloatUnion.f;
Reid Spencer46b002c2004-07-11 17:28:43 +0000167}
168
169/// Read a double value in little-endian order
170inline void BytecodeReader::read_double(double& DoubleVal) {
Reid Spencerada16182004-07-25 21:36:26 +0000171 /// FIXME: This isn't optimal, it has size problems on some platforms
172 /// where FP is not IEEE.
173 union {
174 double d;
175 uint64_t i;
176 } DoubleUnion;
Chris Lattner1d785162004-07-25 23:15:44 +0000177 DoubleUnion.i = (uint64_t(At[0]) << 0) | (uint64_t(At[1]) << 8) |
178 (uint64_t(At[2]) << 16) | (uint64_t(At[3]) << 24) |
Reid Spencerada16182004-07-25 21:36:26 +0000179 (uint64_t(At[4]) << 32) | (uint64_t(At[5]) << 40) |
180 (uint64_t(At[6]) << 48) | (uint64_t(At[7]) << 56);
181 At+=sizeof(uint64_t);
182 DoubleVal = DoubleUnion.d;
Reid Spencer46b002c2004-07-11 17:28:43 +0000183}
184
Reid Spencer04cde2c2004-07-04 11:33:49 +0000185/// Read a block header and obtain its type and size
Reid Spencer060d25d2004-06-29 23:29:38 +0000186inline void BytecodeReader::read_block(unsigned &Type, unsigned &Size) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000187 if ( hasLongBlockHeaders ) {
188 Type = read_uint();
189 Size = read_uint();
190 switch (Type) {
191 case BytecodeFormat::Reserved_DoNotUse :
192 error("Reserved_DoNotUse used as Module Type?");
193 Type = BytecodeFormat::Module; break;
194 case BytecodeFormat::Module:
195 Type = BytecodeFormat::ModuleBlockID; break;
196 case BytecodeFormat::Function:
197 Type = BytecodeFormat::FunctionBlockID; break;
198 case BytecodeFormat::ConstantPool:
199 Type = BytecodeFormat::ConstantPoolBlockID; break;
200 case BytecodeFormat::SymbolTable:
201 Type = BytecodeFormat::SymbolTableBlockID; break;
202 case BytecodeFormat::ModuleGlobalInfo:
203 Type = BytecodeFormat::ModuleGlobalInfoBlockID; break;
204 case BytecodeFormat::GlobalTypePlane:
205 Type = BytecodeFormat::GlobalTypePlaneBlockID; break;
206 case BytecodeFormat::InstructionList:
207 Type = BytecodeFormat::InstructionListBlockID; break;
208 case BytecodeFormat::CompactionTable:
209 Type = BytecodeFormat::CompactionTableBlockID; break;
210 case BytecodeFormat::BasicBlock:
211 /// This block type isn't used after version 1.1. However, we have to
212 /// still allow the value in case this is an old bc format file.
213 /// We just let its value creep thru.
214 break;
215 default:
216 error("Invalid module type found: " + utostr(Type));
217 break;
218 }
219 } else {
220 Size = read_uint();
221 Type = Size & 0x1F; // mask low order five bits
222 Size >>= 5; // get rid of five low order bits, leaving high 27
223 }
Reid Spencer060d25d2004-06-29 23:29:38 +0000224 BlockStart = At;
Reid Spencer46b002c2004-07-11 17:28:43 +0000225 if (At + Size > BlockEnd)
Reid Spencer24399722004-07-09 22:21:33 +0000226 error("Attempt to size a block past end of memory");
Reid Spencer060d25d2004-06-29 23:29:38 +0000227 BlockEnd = At + Size;
Reid Spencer46b002c2004-07-11 17:28:43 +0000228 if (Handler) Handler->handleBlock(Type, BlockStart, Size);
Reid Spencer04cde2c2004-07-04 11:33:49 +0000229}
230
231
232/// In LLVM 1.2 and before, Types were derived from Value and so they were
233/// written as part of the type planes along with any other Value. In LLVM
234/// 1.3 this changed so that Type does not derive from Value. Consequently,
235/// the BytecodeReader's containers for Values can't contain Types because
236/// there's no inheritance relationship. This means that the "Type Type"
237/// plane is defunct along with the Type::TypeTyID TypeID. In LLVM 1.3
238/// whenever a bytecode construct must have both types and values together,
239/// the types are always read/written first and then the Values. Furthermore
240/// since Type::TypeTyID no longer exists, its value (12) now corresponds to
241/// Type::LabelTyID. In order to overcome this we must "sanitize" all the
242/// type TypeIDs we encounter. For LLVM 1.3 bytecode files, there's no change.
243/// For LLVM 1.2 and before, this function will decrement the type id by
244/// one to account for the missing Type::TypeTyID enumerator if the value is
245/// larger than 12 (Type::LabelTyID). If the value is exactly 12, then this
246/// function returns true, otherwise false. This helps detect situations
247/// where the pre 1.3 bytecode is indicating that what follows is a type.
248/// @returns true iff type id corresponds to pre 1.3 "type type"
Reid Spencer46b002c2004-07-11 17:28:43 +0000249inline bool BytecodeReader::sanitizeTypeId(unsigned &TypeId) {
250 if (hasTypeDerivedFromValue) { /// do nothing if 1.3 or later
251 if (TypeId == Type::LabelTyID) {
Reid Spencer04cde2c2004-07-04 11:33:49 +0000252 TypeId = Type::VoidTyID; // sanitize it
253 return true; // indicate we got TypeTyID in pre 1.3 bytecode
Reid Spencer46b002c2004-07-11 17:28:43 +0000254 } else if (TypeId > Type::LabelTyID)
Reid Spencer04cde2c2004-07-04 11:33:49 +0000255 --TypeId; // shift all planes down because type type plane is missing
256 }
257 return false;
258}
259
260/// Reads a vbr uint to read in a type id and does the necessary
261/// conversion on it by calling sanitizeTypeId.
262/// @returns true iff \p TypeId read corresponds to a pre 1.3 "type type"
263/// @see sanitizeTypeId
264inline bool BytecodeReader::read_typeid(unsigned &TypeId) {
265 TypeId = read_vbr_uint();
Reid Spencerad89bd62004-07-25 18:07:36 +0000266 if ( !has32BitTypes )
267 if ( TypeId == 0x00FFFFFF )
268 TypeId = read_vbr_uint();
Reid Spencer04cde2c2004-07-04 11:33:49 +0000269 return sanitizeTypeId(TypeId);
Reid Spencer060d25d2004-06-29 23:29:38 +0000270}
271
272//===----------------------------------------------------------------------===//
273// IR Lookup Methods
274//===----------------------------------------------------------------------===//
275
Reid Spencer04cde2c2004-07-04 11:33:49 +0000276/// Determine if a type id has an implicit null value
Reid Spencer46b002c2004-07-11 17:28:43 +0000277inline bool BytecodeReader::hasImplicitNull(unsigned TyID) {
Reid Spencer060d25d2004-06-29 23:29:38 +0000278 if (!hasExplicitPrimitiveZeros)
Reid Spencer04cde2c2004-07-04 11:33:49 +0000279 return TyID != Type::LabelTyID && TyID != Type::VoidTyID;
Reid Spencer060d25d2004-06-29 23:29:38 +0000280 return TyID >= Type::FirstDerivedTyID;
281}
282
Reid Spencer04cde2c2004-07-04 11:33:49 +0000283/// Obtain a type given a typeid and account for things like compaction tables,
284/// function level vs module level, and the offsetting for the primitive types.
Reid Spencer060d25d2004-06-29 23:29:38 +0000285const Type *BytecodeReader::getType(unsigned ID) {
Chris Lattner89e02532004-01-18 21:08:15 +0000286 if (ID < Type::FirstDerivedTyID)
Chris Lattnerf70c22b2004-06-17 18:19:28 +0000287 if (const Type *T = Type::getPrimitiveType((Type::TypeID)ID))
Chris Lattner927b1852003-10-09 20:22:47 +0000288 return T; // Asked for a primitive type...
Chris Lattner36392bc2003-10-08 21:18:57 +0000289
290 // Otherwise, derived types need offset...
Chris Lattner89e02532004-01-18 21:08:15 +0000291 ID -= Type::FirstDerivedTyID;
292
Reid Spencer060d25d2004-06-29 23:29:38 +0000293 if (!CompactionTypes.empty()) {
294 if (ID >= CompactionTypes.size())
Reid Spencer24399722004-07-09 22:21:33 +0000295 error("Type ID out of range for compaction table!");
Chris Lattner45b5dd22004-08-03 23:41:28 +0000296 return CompactionTypes[ID].first;
Chris Lattner89e02532004-01-18 21:08:15 +0000297 }
Chris Lattner36392bc2003-10-08 21:18:57 +0000298
299 // Is it a module-level type?
Reid Spencer46b002c2004-07-11 17:28:43 +0000300 if (ID < ModuleTypes.size())
301 return ModuleTypes[ID].get();
Chris Lattner36392bc2003-10-08 21:18:57 +0000302
Reid Spencer46b002c2004-07-11 17:28:43 +0000303 // Nope, is it a function-level type?
304 ID -= ModuleTypes.size();
305 if (ID < FunctionTypes.size())
306 return FunctionTypes[ID].get();
Chris Lattner36392bc2003-10-08 21:18:57 +0000307
Reid Spencer46b002c2004-07-11 17:28:43 +0000308 error("Illegal type reference!");
309 return Type::VoidTy;
Chris Lattner00950542001-06-06 20:29:01 +0000310}
311
Reid Spencer04cde2c2004-07-04 11:33:49 +0000312/// Get a sanitized type id. This just makes sure that the \p ID
313/// is both sanitized and not the "type type" of pre-1.3 bytecode.
314/// @see sanitizeTypeId
315inline const Type* BytecodeReader::getSanitizedType(unsigned& ID) {
Reid Spencer46b002c2004-07-11 17:28:43 +0000316 if (sanitizeTypeId(ID))
Reid Spencer24399722004-07-09 22:21:33 +0000317 error("Invalid type id encountered");
Reid Spencer04cde2c2004-07-04 11:33:49 +0000318 return getType(ID);
319}
320
321/// This method just saves some coding. It uses read_typeid to read
Reid Spencer24399722004-07-09 22:21:33 +0000322/// in a sanitized type id, errors that its not the type type, and
Reid Spencer04cde2c2004-07-04 11:33:49 +0000323/// then calls getType to return the type value.
324inline const Type* BytecodeReader::readSanitizedType() {
325 unsigned ID;
Reid Spencer46b002c2004-07-11 17:28:43 +0000326 if (read_typeid(ID))
327 error("Invalid type id encountered");
Reid Spencer04cde2c2004-07-04 11:33:49 +0000328 return getType(ID);
329}
330
331/// Get the slot number associated with a type accounting for primitive
332/// types, compaction tables, and function level vs module level.
Reid Spencer060d25d2004-06-29 23:29:38 +0000333unsigned BytecodeReader::getTypeSlot(const Type *Ty) {
334 if (Ty->isPrimitiveType())
335 return Ty->getTypeID();
336
337 // Scan the compaction table for the type if needed.
338 if (!CompactionTypes.empty()) {
Chris Lattner45b5dd22004-08-03 23:41:28 +0000339 for (unsigned i = 0, e = CompactionTypes.size(); i != e; ++i)
340 if (CompactionTypes[i].first == Ty)
341 return Type::FirstDerivedTyID + i;
Reid Spencer060d25d2004-06-29 23:29:38 +0000342
Chris Lattner45b5dd22004-08-03 23:41:28 +0000343 error("Couldn't find type specified in compaction table!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000344 }
345
346 // Check the function level types first...
347 TypeListTy::iterator I = find(FunctionTypes.begin(), FunctionTypes.end(), Ty);
348
349 if (I != FunctionTypes.end())
Reid Spencer46b002c2004-07-11 17:28:43 +0000350 return Type::FirstDerivedTyID + ModuleTypes.size() +
351 (&*I - &FunctionTypes[0]);
Reid Spencer060d25d2004-06-29 23:29:38 +0000352
353 // Check the module level types now...
354 I = find(ModuleTypes.begin(), ModuleTypes.end(), Ty);
355 if (I == ModuleTypes.end())
Reid Spencer24399722004-07-09 22:21:33 +0000356 error("Didn't find type in ModuleTypes.");
Reid Spencer060d25d2004-06-29 23:29:38 +0000357 return Type::FirstDerivedTyID + (&*I - &ModuleTypes[0]);
Chris Lattner80b97342004-01-17 23:25:43 +0000358}
359
Reid Spencer04cde2c2004-07-04 11:33:49 +0000360/// This is just like getType, but when a compaction table is in use, it is
361/// ignored. It also ignores function level types.
362/// @see getType
Reid Spencer060d25d2004-06-29 23:29:38 +0000363const Type *BytecodeReader::getGlobalTableType(unsigned Slot) {
364 if (Slot < Type::FirstDerivedTyID) {
365 const Type *Ty = Type::getPrimitiveType((Type::TypeID)Slot);
Reid Spencer46b002c2004-07-11 17:28:43 +0000366 if (!Ty)
Reid Spencer24399722004-07-09 22:21:33 +0000367 error("Not a primitive type ID?");
Reid Spencer060d25d2004-06-29 23:29:38 +0000368 return Ty;
369 }
370 Slot -= Type::FirstDerivedTyID;
371 if (Slot >= ModuleTypes.size())
Reid Spencer24399722004-07-09 22:21:33 +0000372 error("Illegal compaction table type reference!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000373 return ModuleTypes[Slot];
Chris Lattner52e20b02003-03-19 20:54:26 +0000374}
375
Reid Spencer04cde2c2004-07-04 11:33:49 +0000376/// This is just like getTypeSlot, but when a compaction table is in use, it
377/// is ignored. It also ignores function level types.
Reid Spencer060d25d2004-06-29 23:29:38 +0000378unsigned BytecodeReader::getGlobalTableTypeSlot(const Type *Ty) {
379 if (Ty->isPrimitiveType())
380 return Ty->getTypeID();
381 TypeListTy::iterator I = find(ModuleTypes.begin(),
Reid Spencer04cde2c2004-07-04 11:33:49 +0000382 ModuleTypes.end(), Ty);
Reid Spencer060d25d2004-06-29 23:29:38 +0000383 if (I == ModuleTypes.end())
Reid Spencer24399722004-07-09 22:21:33 +0000384 error("Didn't find type in ModuleTypes.");
Reid Spencer060d25d2004-06-29 23:29:38 +0000385 return Type::FirstDerivedTyID + (&*I - &ModuleTypes[0]);
386}
387
Reid Spencer04cde2c2004-07-04 11:33:49 +0000388/// Retrieve a value of a given type and slot number, possibly creating
389/// it if it doesn't already exist.
Reid Spencer060d25d2004-06-29 23:29:38 +0000390Value * BytecodeReader::getValue(unsigned type, unsigned oNum, bool Create) {
Chris Lattner4ee8ef22003-10-08 22:52:54 +0000391 assert(type != Type::LabelTyID && "getValue() cannot get blocks!");
Chris Lattner00950542001-06-06 20:29:01 +0000392 unsigned Num = oNum;
Chris Lattner00950542001-06-06 20:29:01 +0000393
Chris Lattner89e02532004-01-18 21:08:15 +0000394 // If there is a compaction table active, it defines the low-level numbers.
395 // If not, the module values define the low-level numbers.
Reid Spencer060d25d2004-06-29 23:29:38 +0000396 if (CompactionValues.size() > type && !CompactionValues[type].empty()) {
397 if (Num < CompactionValues[type].size())
398 return CompactionValues[type][Num];
399 Num -= CompactionValues[type].size();
Chris Lattner89e02532004-01-18 21:08:15 +0000400 } else {
Reid Spencer060d25d2004-06-29 23:29:38 +0000401 // By default, the global type id is the type id passed in
Chris Lattner52f86d62004-01-20 00:54:06 +0000402 unsigned GlobalTyID = type;
Reid Spencer060d25d2004-06-29 23:29:38 +0000403
Chris Lattner45b5dd22004-08-03 23:41:28 +0000404 // If the type plane was compactified, figure out the global type ID by
405 // adding the derived type ids and the distance.
406 if (!CompactionTypes.empty() && type >= Type::FirstDerivedTyID)
407 GlobalTyID = CompactionTypes[type-Type::FirstDerivedTyID].second;
Chris Lattner00950542001-06-06 20:29:01 +0000408
Reid Spencer060d25d2004-06-29 23:29:38 +0000409 if (hasImplicitNull(GlobalTyID)) {
Chris Lattner89e02532004-01-18 21:08:15 +0000410 if (Num == 0)
Reid Spencer04cde2c2004-07-04 11:33:49 +0000411 return Constant::getNullValue(getType(type));
Chris Lattner89e02532004-01-18 21:08:15 +0000412 --Num;
413 }
414
Chris Lattner52f86d62004-01-20 00:54:06 +0000415 if (GlobalTyID < ModuleValues.size() && ModuleValues[GlobalTyID]) {
416 if (Num < ModuleValues[GlobalTyID]->size())
Reid Spencer04cde2c2004-07-04 11:33:49 +0000417 return ModuleValues[GlobalTyID]->getOperand(Num);
Chris Lattner52f86d62004-01-20 00:54:06 +0000418 Num -= ModuleValues[GlobalTyID]->size();
Chris Lattner89e02532004-01-18 21:08:15 +0000419 }
Chris Lattner52e20b02003-03-19 20:54:26 +0000420 }
421
Reid Spencer060d25d2004-06-29 23:29:38 +0000422 if (FunctionValues.size() > type &&
423 FunctionValues[type] &&
424 Num < FunctionValues[type]->size())
425 return FunctionValues[type]->getOperand(Num);
Chris Lattner00950542001-06-06 20:29:01 +0000426
Chris Lattner74734132002-08-17 22:01:27 +0000427 if (!Create) return 0; // Do not create a placeholder?
Chris Lattner00950542001-06-06 20:29:01 +0000428
Chris Lattner8eb10ce2003-10-09 06:05:40 +0000429 std::pair<unsigned,unsigned> KeyValue(type, oNum);
Reid Spencer060d25d2004-06-29 23:29:38 +0000430 ForwardReferenceMap::iterator I = ForwardReferences.lower_bound(KeyValue);
Chris Lattner8eb10ce2003-10-09 06:05:40 +0000431 if (I != ForwardReferences.end() && I->first == KeyValue)
432 return I->second; // We have already created this placeholder
433
Chris Lattnerbf43ac62003-10-09 06:14:26 +0000434 Value *Val = new Argument(getType(type));
Chris Lattner8eb10ce2003-10-09 06:05:40 +0000435 ForwardReferences.insert(I, std::make_pair(KeyValue, Val));
Chris Lattner36392bc2003-10-08 21:18:57 +0000436 return Val;
Chris Lattner00950542001-06-06 20:29:01 +0000437}
438
Reid Spencer04cde2c2004-07-04 11:33:49 +0000439/// This is just like getValue, but when a compaction table is in use, it
440/// is ignored. Also, no forward references or other fancy features are
441/// supported.
Reid Spencer060d25d2004-06-29 23:29:38 +0000442Value* BytecodeReader::getGlobalTableValue(const Type *Ty, unsigned SlotNo) {
443 // FIXME: getTypeSlot is inefficient!
444 unsigned TyID = getGlobalTableTypeSlot(Ty);
445
446 if (TyID != Type::LabelTyID) {
447 if (SlotNo == 0)
448 return Constant::getNullValue(Ty);
449 --SlotNo;
450 }
451
452 if (TyID >= ModuleValues.size() || ModuleValues[TyID] == 0 ||
453 SlotNo >= ModuleValues[TyID]->size()) {
Reid Spencer24399722004-07-09 22:21:33 +0000454 error("Corrupt compaction table entry!"
455 + utostr(TyID) + ", " + utostr(SlotNo) + ": "
Reid Spencer46b002c2004-07-11 17:28:43 +0000456 + utostr(ModuleValues.size()) + ", "
Brian Gaeke0859e522004-07-13 07:37:43 +0000457 + utohexstr(intptr_t((void*)ModuleValues[TyID])) + ", "
Reid Spencer46b002c2004-07-11 17:28:43 +0000458 + utostr(ModuleValues[TyID]->size()));
Reid Spencer060d25d2004-06-29 23:29:38 +0000459 }
460 return ModuleValues[TyID]->getOperand(SlotNo);
461}
462
Reid Spencer04cde2c2004-07-04 11:33:49 +0000463/// Just like getValue, except that it returns a null pointer
464/// only on error. It always returns a constant (meaning that if the value is
465/// defined, but is not a constant, that is an error). If the specified
466/// constant hasn't been parsed yet, a placeholder is defined and used.
467/// Later, after the real value is parsed, the placeholder is eliminated.
Reid Spencer060d25d2004-06-29 23:29:38 +0000468Constant* BytecodeReader::getConstantValue(unsigned TypeSlot, unsigned Slot) {
469 if (Value *V = getValue(TypeSlot, Slot, false))
470 if (Constant *C = dyn_cast<Constant>(V))
471 return C; // If we already have the value parsed, just return it
Reid Spencer060d25d2004-06-29 23:29:38 +0000472 else
Reid Spencera86037e2004-07-18 00:12:03 +0000473 error("Value for slot " + utostr(Slot) +
474 " is expected to be a constant!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000475
476 const Type *Ty = getType(TypeSlot);
477 std::pair<const Type*, unsigned> Key(Ty, Slot);
478 ConstantRefsType::iterator I = ConstantFwdRefs.lower_bound(Key);
479
480 if (I != ConstantFwdRefs.end() && I->first == Key) {
481 return I->second;
482 } else {
483 // Create a placeholder for the constant reference and
484 // keep track of the fact that we have a forward ref to recycle it
Reid Spencer46b002c2004-07-11 17:28:43 +0000485 Constant *C = new ConstantPlaceHolder(Ty, Slot);
Reid Spencer060d25d2004-06-29 23:29:38 +0000486
487 // Keep track of the fact that we have a forward ref to recycle it
488 ConstantFwdRefs.insert(I, std::make_pair(Key, C));
489 return C;
490 }
491}
492
493//===----------------------------------------------------------------------===//
494// IR Construction Methods
495//===----------------------------------------------------------------------===//
496
Reid Spencer04cde2c2004-07-04 11:33:49 +0000497/// As values are created, they are inserted into the appropriate place
498/// with this method. The ValueTable argument must be one of ModuleValues
499/// or FunctionValues data members of this class.
Reid Spencer46b002c2004-07-11 17:28:43 +0000500unsigned BytecodeReader::insertValue(Value *Val, unsigned type,
501 ValueTable &ValueTab) {
Reid Spencer060d25d2004-06-29 23:29:38 +0000502 assert((!isa<Constant>(Val) || !cast<Constant>(Val)->isNullValue()) ||
Reid Spencer04cde2c2004-07-04 11:33:49 +0000503 !hasImplicitNull(type) &&
504 "Cannot read null values from bytecode!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000505
506 if (ValueTab.size() <= type)
507 ValueTab.resize(type+1);
508
509 if (!ValueTab[type]) ValueTab[type] = new ValueList();
510
511 ValueTab[type]->push_back(Val);
512
513 bool HasOffset = hasImplicitNull(type);
514 return ValueTab[type]->size()-1 + HasOffset;
515}
516
Reid Spencer04cde2c2004-07-04 11:33:49 +0000517/// Insert the arguments of a function as new values in the reader.
Reid Spencer46b002c2004-07-11 17:28:43 +0000518void BytecodeReader::insertArguments(Function* F) {
Reid Spencer060d25d2004-06-29 23:29:38 +0000519 const FunctionType *FT = F->getFunctionType();
520 Function::aiterator AI = F->abegin();
521 for (FunctionType::param_iterator It = FT->param_begin();
522 It != FT->param_end(); ++It, ++AI)
523 insertValue(AI, getTypeSlot(AI->getType()), FunctionValues);
524}
525
526//===----------------------------------------------------------------------===//
527// Bytecode Parsing Methods
528//===----------------------------------------------------------------------===//
529
Reid Spencer04cde2c2004-07-04 11:33:49 +0000530/// This method parses a single instruction. The instruction is
531/// inserted at the end of the \p BB provided. The arguments of
532/// the instruction are provided in the \p Args vector.
Reid Spencer060d25d2004-06-29 23:29:38 +0000533void BytecodeReader::ParseInstruction(std::vector<unsigned> &Oprnds,
Reid Spencer46b002c2004-07-11 17:28:43 +0000534 BasicBlock* BB) {
Reid Spencer060d25d2004-06-29 23:29:38 +0000535 BufPtr SaveAt = At;
536
537 // Clear instruction data
538 Oprnds.clear();
539 unsigned iType = 0;
540 unsigned Opcode = 0;
541 unsigned Op = read_uint();
542
543 // bits Instruction format: Common to all formats
544 // --------------------------
545 // 01-00: Opcode type, fixed to 1.
546 // 07-02: Opcode
547 Opcode = (Op >> 2) & 63;
548 Oprnds.resize((Op >> 0) & 03);
549
550 // Extract the operands
551 switch (Oprnds.size()) {
552 case 1:
553 // bits Instruction format:
554 // --------------------------
555 // 19-08: Resulting type plane
556 // 31-20: Operand #1 (if set to (2^12-1), then zero operands)
557 //
558 iType = (Op >> 8) & 4095;
559 Oprnds[0] = (Op >> 20) & 4095;
560 if (Oprnds[0] == 4095) // Handle special encoding for 0 operands...
561 Oprnds.resize(0);
562 break;
563 case 2:
564 // bits Instruction format:
565 // --------------------------
566 // 15-08: Resulting type plane
567 // 23-16: Operand #1
568 // 31-24: Operand #2
569 //
570 iType = (Op >> 8) & 255;
571 Oprnds[0] = (Op >> 16) & 255;
572 Oprnds[1] = (Op >> 24) & 255;
573 break;
574 case 3:
575 // bits Instruction format:
576 // --------------------------
577 // 13-08: Resulting type plane
578 // 19-14: Operand #1
579 // 25-20: Operand #2
580 // 31-26: Operand #3
581 //
582 iType = (Op >> 8) & 63;
583 Oprnds[0] = (Op >> 14) & 63;
584 Oprnds[1] = (Op >> 20) & 63;
585 Oprnds[2] = (Op >> 26) & 63;
586 break;
587 case 0:
588 At -= 4; // Hrm, try this again...
589 Opcode = read_vbr_uint();
590 Opcode >>= 2;
591 iType = read_vbr_uint();
592
593 unsigned NumOprnds = read_vbr_uint();
594 Oprnds.resize(NumOprnds);
595
596 if (NumOprnds == 0)
Reid Spencer24399722004-07-09 22:21:33 +0000597 error("Zero-argument instruction found; this is invalid.");
Reid Spencer060d25d2004-06-29 23:29:38 +0000598
599 for (unsigned i = 0; i != NumOprnds; ++i)
600 Oprnds[i] = read_vbr_uint();
601 align32();
602 break;
603 }
604
Reid Spencer04cde2c2004-07-04 11:33:49 +0000605 const Type *InstTy = getSanitizedType(iType);
Reid Spencer060d25d2004-06-29 23:29:38 +0000606
Reid Spencer46b002c2004-07-11 17:28:43 +0000607 // We have enough info to inform the handler now.
Reid Spencer04cde2c2004-07-04 11:33:49 +0000608 if (Handler) Handler->handleInstruction(Opcode, InstTy, Oprnds, At-SaveAt);
Reid Spencer060d25d2004-06-29 23:29:38 +0000609
610 // Declare the resulting instruction we'll build.
611 Instruction *Result = 0;
612
613 // Handle binary operators
614 if (Opcode >= Instruction::BinaryOpsBegin &&
615 Opcode < Instruction::BinaryOpsEnd && Oprnds.size() == 2)
616 Result = BinaryOperator::create((Instruction::BinaryOps)Opcode,
617 getValue(iType, Oprnds[0]),
618 getValue(iType, Oprnds[1]));
619
620 switch (Opcode) {
621 default:
Reid Spencer04cde2c2004-07-04 11:33:49 +0000622 if (Result == 0)
Reid Spencer24399722004-07-09 22:21:33 +0000623 error("Illegal instruction read!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000624 break;
625 case Instruction::VAArg:
Reid Spencer04cde2c2004-07-04 11:33:49 +0000626 Result = new VAArgInst(getValue(iType, Oprnds[0]),
Reid Spencer46b002c2004-07-11 17:28:43 +0000627 getSanitizedType(Oprnds[1]));
Reid Spencer060d25d2004-06-29 23:29:38 +0000628 break;
629 case Instruction::VANext:
Reid Spencer04cde2c2004-07-04 11:33:49 +0000630 Result = new VANextInst(getValue(iType, Oprnds[0]),
Reid Spencer46b002c2004-07-11 17:28:43 +0000631 getSanitizedType(Oprnds[1]));
Reid Spencer060d25d2004-06-29 23:29:38 +0000632 break;
633 case Instruction::Cast:
Reid Spencer04cde2c2004-07-04 11:33:49 +0000634 Result = new CastInst(getValue(iType, Oprnds[0]),
Reid Spencer46b002c2004-07-11 17:28:43 +0000635 getSanitizedType(Oprnds[1]));
Reid Spencer060d25d2004-06-29 23:29:38 +0000636 break;
637 case Instruction::Select:
638 Result = new SelectInst(getValue(Type::BoolTyID, Oprnds[0]),
639 getValue(iType, Oprnds[1]),
640 getValue(iType, Oprnds[2]));
641 break;
642 case Instruction::PHI: {
643 if (Oprnds.size() == 0 || (Oprnds.size() & 1))
Reid Spencer24399722004-07-09 22:21:33 +0000644 error("Invalid phi node encountered!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000645
646 PHINode *PN = new PHINode(InstTy);
647 PN->op_reserve(Oprnds.size());
648 for (unsigned i = 0, e = Oprnds.size(); i != e; i += 2)
649 PN->addIncoming(getValue(iType, Oprnds[i]), getBasicBlock(Oprnds[i+1]));
650 Result = PN;
651 break;
652 }
653
654 case Instruction::Shl:
655 case Instruction::Shr:
656 Result = new ShiftInst((Instruction::OtherOps)Opcode,
657 getValue(iType, Oprnds[0]),
658 getValue(Type::UByteTyID, Oprnds[1]));
659 break;
660 case Instruction::Ret:
661 if (Oprnds.size() == 0)
662 Result = new ReturnInst();
663 else if (Oprnds.size() == 1)
664 Result = new ReturnInst(getValue(iType, Oprnds[0]));
665 else
Reid Spencer24399722004-07-09 22:21:33 +0000666 error("Unrecognized instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000667 break;
668
669 case Instruction::Br:
670 if (Oprnds.size() == 1)
671 Result = new BranchInst(getBasicBlock(Oprnds[0]));
672 else if (Oprnds.size() == 3)
673 Result = new BranchInst(getBasicBlock(Oprnds[0]),
Reid Spencer04cde2c2004-07-04 11:33:49 +0000674 getBasicBlock(Oprnds[1]), getValue(Type::BoolTyID , Oprnds[2]));
Reid Spencer060d25d2004-06-29 23:29:38 +0000675 else
Reid Spencer24399722004-07-09 22:21:33 +0000676 error("Invalid number of operands for a 'br' instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000677 break;
678 case Instruction::Switch: {
679 if (Oprnds.size() & 1)
Reid Spencer24399722004-07-09 22:21:33 +0000680 error("Switch statement with odd number of arguments!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000681
682 SwitchInst *I = new SwitchInst(getValue(iType, Oprnds[0]),
683 getBasicBlock(Oprnds[1]));
684 for (unsigned i = 2, e = Oprnds.size(); i != e; i += 2)
685 I->addCase(cast<Constant>(getValue(iType, Oprnds[i])),
686 getBasicBlock(Oprnds[i+1]));
687 Result = I;
688 break;
689 }
690
691 case Instruction::Call: {
692 if (Oprnds.size() == 0)
Reid Spencer24399722004-07-09 22:21:33 +0000693 error("Invalid call instruction encountered!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000694
695 Value *F = getValue(iType, Oprnds[0]);
696
697 // Check to make sure we have a pointer to function type
698 const PointerType *PTy = dyn_cast<PointerType>(F->getType());
Reid Spencer24399722004-07-09 22:21:33 +0000699 if (PTy == 0) error("Call to non function pointer value!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000700 const FunctionType *FTy = dyn_cast<FunctionType>(PTy->getElementType());
Reid Spencer24399722004-07-09 22:21:33 +0000701 if (FTy == 0) error("Call to non function pointer value!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000702
703 std::vector<Value *> Params;
704 if (!FTy->isVarArg()) {
705 FunctionType::param_iterator It = FTy->param_begin();
706
707 for (unsigned i = 1, e = Oprnds.size(); i != e; ++i) {
708 if (It == FTy->param_end())
Reid Spencer24399722004-07-09 22:21:33 +0000709 error("Invalid call instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000710 Params.push_back(getValue(getTypeSlot(*It++), Oprnds[i]));
711 }
712 if (It != FTy->param_end())
Reid Spencer24399722004-07-09 22:21:33 +0000713 error("Invalid call instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000714 } else {
715 Oprnds.erase(Oprnds.begin(), Oprnds.begin()+1);
716
717 unsigned FirstVariableOperand;
718 if (Oprnds.size() < FTy->getNumParams())
Reid Spencer24399722004-07-09 22:21:33 +0000719 error("Call instruction missing operands!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000720
721 // Read all of the fixed arguments
722 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
723 Params.push_back(getValue(getTypeSlot(FTy->getParamType(i)),Oprnds[i]));
724
725 FirstVariableOperand = FTy->getNumParams();
726
727 if ((Oprnds.size()-FirstVariableOperand) & 1) // Must be pairs of type/value
Reid Spencer24399722004-07-09 22:21:33 +0000728 error("Invalid call instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000729
730 for (unsigned i = FirstVariableOperand, e = Oprnds.size();
Reid Spencer04cde2c2004-07-04 11:33:49 +0000731 i != e; i += 2)
Reid Spencer060d25d2004-06-29 23:29:38 +0000732 Params.push_back(getValue(Oprnds[i], Oprnds[i+1]));
733 }
734
735 Result = new CallInst(F, Params);
736 break;
737 }
738 case Instruction::Invoke: {
Reid Spencer04cde2c2004-07-04 11:33:49 +0000739 if (Oprnds.size() < 3)
Reid Spencer24399722004-07-09 22:21:33 +0000740 error("Invalid invoke instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000741 Value *F = getValue(iType, Oprnds[0]);
742
743 // Check to make sure we have a pointer to function type
744 const PointerType *PTy = dyn_cast<PointerType>(F->getType());
Reid Spencer04cde2c2004-07-04 11:33:49 +0000745 if (PTy == 0)
Reid Spencer24399722004-07-09 22:21:33 +0000746 error("Invoke to non function pointer value!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000747 const FunctionType *FTy = dyn_cast<FunctionType>(PTy->getElementType());
Reid Spencer04cde2c2004-07-04 11:33:49 +0000748 if (FTy == 0)
Reid Spencer24399722004-07-09 22:21:33 +0000749 error("Invoke to non function pointer value!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000750
751 std::vector<Value *> Params;
752 BasicBlock *Normal, *Except;
753
754 if (!FTy->isVarArg()) {
755 Normal = getBasicBlock(Oprnds[1]);
756 Except = getBasicBlock(Oprnds[2]);
757
758 FunctionType::param_iterator It = FTy->param_begin();
759 for (unsigned i = 3, e = Oprnds.size(); i != e; ++i) {
760 if (It == FTy->param_end())
Reid Spencer24399722004-07-09 22:21:33 +0000761 error("Invalid invoke instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000762 Params.push_back(getValue(getTypeSlot(*It++), Oprnds[i]));
763 }
764 if (It != FTy->param_end())
Reid Spencer24399722004-07-09 22:21:33 +0000765 error("Invalid invoke instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000766 } else {
767 Oprnds.erase(Oprnds.begin(), Oprnds.begin()+1);
768
769 Normal = getBasicBlock(Oprnds[0]);
770 Except = getBasicBlock(Oprnds[1]);
771
772 unsigned FirstVariableArgument = FTy->getNumParams()+2;
773 for (unsigned i = 2; i != FirstVariableArgument; ++i)
774 Params.push_back(getValue(getTypeSlot(FTy->getParamType(i-2)),
775 Oprnds[i]));
776
777 if (Oprnds.size()-FirstVariableArgument & 1) // Must be type/value pairs
Reid Spencer24399722004-07-09 22:21:33 +0000778 error("Invalid invoke instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000779
780 for (unsigned i = FirstVariableArgument; i < Oprnds.size(); i += 2)
781 Params.push_back(getValue(Oprnds[i], Oprnds[i+1]));
782 }
783
784 Result = new InvokeInst(F, Normal, Except, Params);
785 break;
786 }
787 case Instruction::Malloc:
Reid Spencer04cde2c2004-07-04 11:33:49 +0000788 if (Oprnds.size() > 2)
Reid Spencer24399722004-07-09 22:21:33 +0000789 error("Invalid malloc instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000790 if (!isa<PointerType>(InstTy))
Reid Spencer24399722004-07-09 22:21:33 +0000791 error("Invalid malloc instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000792
793 Result = new MallocInst(cast<PointerType>(InstTy)->getElementType(),
794 Oprnds.size() ? getValue(Type::UIntTyID,
795 Oprnds[0]) : 0);
796 break;
797
798 case Instruction::Alloca:
Reid Spencer04cde2c2004-07-04 11:33:49 +0000799 if (Oprnds.size() > 2)
Reid Spencer24399722004-07-09 22:21:33 +0000800 error("Invalid alloca instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000801 if (!isa<PointerType>(InstTy))
Reid Spencer24399722004-07-09 22:21:33 +0000802 error("Invalid alloca instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000803
804 Result = new AllocaInst(cast<PointerType>(InstTy)->getElementType(),
805 Oprnds.size() ? getValue(Type::UIntTyID,
Reid Spencer04cde2c2004-07-04 11:33:49 +0000806 Oprnds[0]) :0);
Reid Spencer060d25d2004-06-29 23:29:38 +0000807 break;
808 case Instruction::Free:
809 if (!isa<PointerType>(InstTy))
Reid Spencer24399722004-07-09 22:21:33 +0000810 error("Invalid free instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000811 Result = new FreeInst(getValue(iType, Oprnds[0]));
812 break;
813 case Instruction::GetElementPtr: {
814 if (Oprnds.size() == 0 || !isa<PointerType>(InstTy))
Reid Spencer24399722004-07-09 22:21:33 +0000815 error("Invalid getelementptr instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000816
817 std::vector<Value*> Idx;
818
819 const Type *NextTy = InstTy;
820 for (unsigned i = 1, e = Oprnds.size(); i != e; ++i) {
821 const CompositeType *TopTy = dyn_cast_or_null<CompositeType>(NextTy);
Reid Spencer04cde2c2004-07-04 11:33:49 +0000822 if (!TopTy)
Reid Spencer46b002c2004-07-11 17:28:43 +0000823 error("Invalid getelementptr instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000824
825 unsigned ValIdx = Oprnds[i];
826 unsigned IdxTy = 0;
827 if (!hasRestrictedGEPTypes) {
828 // Struct indices are always uints, sequential type indices can be any
829 // of the 32 or 64-bit integer types. The actual choice of type is
830 // encoded in the low two bits of the slot number.
831 if (isa<StructType>(TopTy))
832 IdxTy = Type::UIntTyID;
833 else {
834 switch (ValIdx & 3) {
835 default:
836 case 0: IdxTy = Type::UIntTyID; break;
837 case 1: IdxTy = Type::IntTyID; break;
838 case 2: IdxTy = Type::ULongTyID; break;
839 case 3: IdxTy = Type::LongTyID; break;
840 }
841 ValIdx >>= 2;
842 }
843 } else {
844 IdxTy = isa<StructType>(TopTy) ? Type::UByteTyID : Type::LongTyID;
845 }
846
847 Idx.push_back(getValue(IdxTy, ValIdx));
848
849 // Convert ubyte struct indices into uint struct indices.
850 if (isa<StructType>(TopTy) && hasRestrictedGEPTypes)
851 if (ConstantUInt *C = dyn_cast<ConstantUInt>(Idx.back()))
852 Idx[Idx.size()-1] = ConstantExpr::getCast(C, Type::UIntTy);
853
854 NextTy = GetElementPtrInst::getIndexedType(InstTy, Idx, true);
855 }
856
857 Result = new GetElementPtrInst(getValue(iType, Oprnds[0]), Idx);
858 break;
859 }
860
861 case 62: // volatile load
862 case Instruction::Load:
863 if (Oprnds.size() != 1 || !isa<PointerType>(InstTy))
Reid Spencer24399722004-07-09 22:21:33 +0000864 error("Invalid load instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000865 Result = new LoadInst(getValue(iType, Oprnds[0]), "", Opcode == 62);
866 break;
867
868 case 63: // volatile store
869 case Instruction::Store: {
870 if (!isa<PointerType>(InstTy) || Oprnds.size() != 2)
Reid Spencer24399722004-07-09 22:21:33 +0000871 error("Invalid store instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000872
873 Value *Ptr = getValue(iType, Oprnds[1]);
874 const Type *ValTy = cast<PointerType>(Ptr->getType())->getElementType();
875 Result = new StoreInst(getValue(getTypeSlot(ValTy), Oprnds[0]), Ptr,
876 Opcode == 63);
877 break;
878 }
879 case Instruction::Unwind:
Reid Spencer04cde2c2004-07-04 11:33:49 +0000880 if (Oprnds.size() != 0)
Reid Spencer24399722004-07-09 22:21:33 +0000881 error("Invalid unwind instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000882 Result = new UnwindInst();
883 break;
884 } // end switch(Opcode)
885
886 unsigned TypeSlot;
887 if (Result->getType() == InstTy)
888 TypeSlot = iType;
889 else
890 TypeSlot = getTypeSlot(Result->getType());
891
892 insertValue(Result, TypeSlot, FunctionValues);
893 BB->getInstList().push_back(Result);
894}
895
Reid Spencer04cde2c2004-07-04 11:33:49 +0000896/// Get a particular numbered basic block, which might be a forward reference.
897/// This works together with ParseBasicBlock to handle these forward references
898/// in a clean manner. This function is used when constructing phi, br, switch,
899/// and other instructions that reference basic blocks. Blocks are numbered
900/// sequentially as they appear in the function.
Reid Spencer060d25d2004-06-29 23:29:38 +0000901BasicBlock *BytecodeReader::getBasicBlock(unsigned ID) {
Chris Lattner4ee8ef22003-10-08 22:52:54 +0000902 // Make sure there is room in the table...
903 if (ParsedBasicBlocks.size() <= ID) ParsedBasicBlocks.resize(ID+1);
904
905 // First check to see if this is a backwards reference, i.e., ParseBasicBlock
906 // has already created this block, or if the forward reference has already
907 // been created.
908 if (ParsedBasicBlocks[ID])
909 return ParsedBasicBlocks[ID];
910
911 // Otherwise, the basic block has not yet been created. Do so and add it to
912 // the ParsedBasicBlocks list.
913 return ParsedBasicBlocks[ID] = new BasicBlock();
914}
915
Reid Spencer04cde2c2004-07-04 11:33:49 +0000916/// In LLVM 1.0 bytecode files, we used to output one basicblock at a time.
917/// This method reads in one of the basicblock packets. This method is not used
918/// for bytecode files after LLVM 1.0
919/// @returns The basic block constructed.
Reid Spencer46b002c2004-07-11 17:28:43 +0000920BasicBlock *BytecodeReader::ParseBasicBlock(unsigned BlockNo) {
921 if (Handler) Handler->handleBasicBlockBegin(BlockNo);
Reid Spencer060d25d2004-06-29 23:29:38 +0000922
923 BasicBlock *BB = 0;
924
Chris Lattner4ee8ef22003-10-08 22:52:54 +0000925 if (ParsedBasicBlocks.size() == BlockNo)
926 ParsedBasicBlocks.push_back(BB = new BasicBlock());
927 else if (ParsedBasicBlocks[BlockNo] == 0)
928 BB = ParsedBasicBlocks[BlockNo] = new BasicBlock();
929 else
930 BB = ParsedBasicBlocks[BlockNo];
Chris Lattner00950542001-06-06 20:29:01 +0000931
Reid Spencer060d25d2004-06-29 23:29:38 +0000932 std::vector<unsigned> Operands;
Reid Spencer46b002c2004-07-11 17:28:43 +0000933 while (moreInBlock())
Reid Spencer060d25d2004-06-29 23:29:38 +0000934 ParseInstruction(Operands, BB);
Chris Lattner00950542001-06-06 20:29:01 +0000935
Reid Spencer46b002c2004-07-11 17:28:43 +0000936 if (Handler) Handler->handleBasicBlockEnd(BlockNo);
Misha Brukman12c29d12003-09-22 23:38:23 +0000937 return BB;
Chris Lattner00950542001-06-06 20:29:01 +0000938}
939
Reid Spencer04cde2c2004-07-04 11:33:49 +0000940/// Parse all of the BasicBlock's & Instruction's in the body of a function.
941/// In post 1.0 bytecode files, we no longer emit basic block individually,
942/// in order to avoid per-basic-block overhead.
943/// @returns Rhe number of basic blocks encountered.
Reid Spencer060d25d2004-06-29 23:29:38 +0000944unsigned BytecodeReader::ParseInstructionList(Function* F) {
Chris Lattner8d1dbd22003-12-01 07:05:31 +0000945 unsigned BlockNo = 0;
946 std::vector<unsigned> Args;
947
Reid Spencer46b002c2004-07-11 17:28:43 +0000948 while (moreInBlock()) {
949 if (Handler) Handler->handleBasicBlockBegin(BlockNo);
Chris Lattner8d1dbd22003-12-01 07:05:31 +0000950 BasicBlock *BB;
951 if (ParsedBasicBlocks.size() == BlockNo)
952 ParsedBasicBlocks.push_back(BB = new BasicBlock());
953 else if (ParsedBasicBlocks[BlockNo] == 0)
954 BB = ParsedBasicBlocks[BlockNo] = new BasicBlock();
955 else
956 BB = ParsedBasicBlocks[BlockNo];
957 ++BlockNo;
958 F->getBasicBlockList().push_back(BB);
959
960 // Read instructions into this basic block until we get to a terminator
Reid Spencer46b002c2004-07-11 17:28:43 +0000961 while (moreInBlock() && !BB->getTerminator())
Reid Spencer060d25d2004-06-29 23:29:38 +0000962 ParseInstruction(Args, BB);
Chris Lattner8d1dbd22003-12-01 07:05:31 +0000963
964 if (!BB->getTerminator())
Reid Spencer24399722004-07-09 22:21:33 +0000965 error("Non-terminated basic block found!");
Reid Spencer5c15fe52004-07-05 00:57:50 +0000966
Reid Spencer46b002c2004-07-11 17:28:43 +0000967 if (Handler) Handler->handleBasicBlockEnd(BlockNo-1);
Chris Lattner8d1dbd22003-12-01 07:05:31 +0000968 }
969
970 return BlockNo;
971}
972
Reid Spencer04cde2c2004-07-04 11:33:49 +0000973/// Parse a symbol table. This works for both module level and function
974/// level symbol tables. For function level symbol tables, the CurrentFunction
975/// parameter must be non-zero and the ST parameter must correspond to
976/// CurrentFunction's symbol table. For Module level symbol tables, the
977/// CurrentFunction argument must be zero.
Reid Spencer060d25d2004-06-29 23:29:38 +0000978void BytecodeReader::ParseSymbolTable(Function *CurrentFunction,
Reid Spencer04cde2c2004-07-04 11:33:49 +0000979 SymbolTable *ST) {
980 if (Handler) Handler->handleSymbolTableBegin(CurrentFunction,ST);
Reid Spencer060d25d2004-06-29 23:29:38 +0000981
Chris Lattner39cacce2003-10-10 05:43:47 +0000982 // Allow efficient basic block lookup by number.
983 std::vector<BasicBlock*> BBMap;
984 if (CurrentFunction)
985 for (Function::iterator I = CurrentFunction->begin(),
986 E = CurrentFunction->end(); I != E; ++I)
987 BBMap.push_back(I);
988
Reid Spencer04cde2c2004-07-04 11:33:49 +0000989 /// In LLVM 1.3 we write types separately from values so
990 /// The types are always first in the symbol table. This is
991 /// because Type no longer derives from Value.
Reid Spencer46b002c2004-07-11 17:28:43 +0000992 if (!hasTypeDerivedFromValue) {
Reid Spencer04cde2c2004-07-04 11:33:49 +0000993 // Symtab block header: [num entries]
994 unsigned NumEntries = read_vbr_uint();
Reid Spencer46b002c2004-07-11 17:28:43 +0000995 for (unsigned i = 0; i < NumEntries; ++i) {
Reid Spencer04cde2c2004-07-04 11:33:49 +0000996 // Symtab entry: [def slot #][name]
997 unsigned slot = read_vbr_uint();
998 std::string Name = read_str();
999 const Type* T = getType(slot);
1000 ST->insert(Name, T);
1001 }
1002 }
1003
Reid Spencer46b002c2004-07-11 17:28:43 +00001004 while (moreInBlock()) {
Chris Lattner00950542001-06-06 20:29:01 +00001005 // Symtab block header: [num entries][type id number]
Reid Spencer060d25d2004-06-29 23:29:38 +00001006 unsigned NumEntries = read_vbr_uint();
Reid Spencer04cde2c2004-07-04 11:33:49 +00001007 unsigned Typ = 0;
1008 bool isTypeType = read_typeid(Typ);
Chris Lattner00950542001-06-06 20:29:01 +00001009 const Type *Ty = getType(Typ);
Chris Lattner1d670cc2001-09-07 16:37:43 +00001010
Chris Lattner7dc3a2e2003-10-13 14:57:53 +00001011 for (unsigned i = 0; i != NumEntries; ++i) {
Chris Lattner00950542001-06-06 20:29:01 +00001012 // Symtab entry: [def slot #][name]
Reid Spencer060d25d2004-06-29 23:29:38 +00001013 unsigned slot = read_vbr_uint();
1014 std::string Name = read_str();
Chris Lattner00950542001-06-06 20:29:01 +00001015
Reid Spencer04cde2c2004-07-04 11:33:49 +00001016 // if we're reading a pre 1.3 bytecode file and the type plane
1017 // is the "type type", handle it here
Reid Spencer46b002c2004-07-11 17:28:43 +00001018 if (isTypeType) {
1019 const Type* T = getType(slot);
1020 if (T == 0)
1021 error("Failed type look-up for name '" + Name + "'");
1022 ST->insert(Name, T);
1023 continue; // code below must be short circuited
Chris Lattner39cacce2003-10-10 05:43:47 +00001024 } else {
Reid Spencer46b002c2004-07-11 17:28:43 +00001025 Value *V = 0;
1026 if (Typ == Type::LabelTyID) {
1027 if (slot < BBMap.size())
1028 V = BBMap[slot];
1029 } else {
1030 V = getValue(Typ, slot, false); // Find mapping...
1031 }
1032 if (V == 0)
1033 error("Failed value look-up for name '" + Name + "'");
1034 V->setName(Name, ST);
Chris Lattner39cacce2003-10-10 05:43:47 +00001035 }
Chris Lattner00950542001-06-06 20:29:01 +00001036 }
1037 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001038 checkPastBlockEnd("Symbol Table");
Reid Spencer04cde2c2004-07-04 11:33:49 +00001039 if (Handler) Handler->handleSymbolTableEnd();
Chris Lattner00950542001-06-06 20:29:01 +00001040}
1041
Reid Spencer04cde2c2004-07-04 11:33:49 +00001042/// Read in the types portion of a compaction table.
Reid Spencer46b002c2004-07-11 17:28:43 +00001043void BytecodeReader::ParseCompactionTypes(unsigned NumEntries) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001044 for (unsigned i = 0; i != NumEntries; ++i) {
1045 unsigned TypeSlot = 0;
Reid Spencer46b002c2004-07-11 17:28:43 +00001046 if (read_typeid(TypeSlot))
Reid Spencer24399722004-07-09 22:21:33 +00001047 error("Invalid type in compaction table: type type");
Reid Spencer04cde2c2004-07-04 11:33:49 +00001048 const Type *Typ = getGlobalTableType(TypeSlot);
Chris Lattner45b5dd22004-08-03 23:41:28 +00001049 CompactionTypes.push_back(std::make_pair(Typ, TypeSlot));
Reid Spencer46b002c2004-07-11 17:28:43 +00001050 if (Handler) Handler->handleCompactionTableType(i, TypeSlot, Typ);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001051 }
1052}
1053
1054/// Parse a compaction table.
Reid Spencer060d25d2004-06-29 23:29:38 +00001055void BytecodeReader::ParseCompactionTable() {
1056
Reid Spencer46b002c2004-07-11 17:28:43 +00001057 // Notify handler that we're beginning a compaction table.
Reid Spencer04cde2c2004-07-04 11:33:49 +00001058 if (Handler) Handler->handleCompactionTableBegin();
1059
Reid Spencer46b002c2004-07-11 17:28:43 +00001060 // In LLVM 1.3 Type no longer derives from Value. So,
1061 // we always write them first in the compaction table
1062 // because they can't occupy a "type plane" where the
1063 // Values reside.
1064 if (! hasTypeDerivedFromValue) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001065 unsigned NumEntries = read_vbr_uint();
Reid Spencer46b002c2004-07-11 17:28:43 +00001066 ParseCompactionTypes(NumEntries);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001067 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001068
Reid Spencer46b002c2004-07-11 17:28:43 +00001069 // Compaction tables live in separate blocks so we have to loop
1070 // until we've read the whole thing.
1071 while (moreInBlock()) {
1072 // Read the number of Value* entries in the compaction table
Reid Spencer060d25d2004-06-29 23:29:38 +00001073 unsigned NumEntries = read_vbr_uint();
Reid Spencer04cde2c2004-07-04 11:33:49 +00001074 unsigned Ty = 0;
1075 unsigned isTypeType = false;
Reid Spencer060d25d2004-06-29 23:29:38 +00001076
Reid Spencer46b002c2004-07-11 17:28:43 +00001077 // Decode the type from value read in. Most compaction table
1078 // planes will have one or two entries in them. If that's the
1079 // case then the length is encoded in the bottom two bits and
1080 // the higher bits encode the type. This saves another VBR value.
Reid Spencer060d25d2004-06-29 23:29:38 +00001081 if ((NumEntries & 3) == 3) {
Reid Spencer46b002c2004-07-11 17:28:43 +00001082 // In this case, both low-order bits are set (value 3). This
1083 // is a signal that the typeid follows.
Reid Spencer060d25d2004-06-29 23:29:38 +00001084 NumEntries >>= 2;
Reid Spencer04cde2c2004-07-04 11:33:49 +00001085 isTypeType = read_typeid(Ty);
Reid Spencer060d25d2004-06-29 23:29:38 +00001086 } else {
Reid Spencer46b002c2004-07-11 17:28:43 +00001087 // In this case, the low-order bits specify the number of entries
1088 // and the high order bits specify the type.
Reid Spencer060d25d2004-06-29 23:29:38 +00001089 Ty = NumEntries >> 2;
Reid Spencer04cde2c2004-07-04 11:33:49 +00001090 isTypeType = sanitizeTypeId(Ty);
Reid Spencer060d25d2004-06-29 23:29:38 +00001091 NumEntries &= 3;
1092 }
1093
Reid Spencer04cde2c2004-07-04 11:33:49 +00001094 // if we're reading a pre 1.3 bytecode file and the type plane
1095 // is the "type type", handle it here
Reid Spencer46b002c2004-07-11 17:28:43 +00001096 if (isTypeType) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001097 ParseCompactionTypes(NumEntries);
Reid Spencer060d25d2004-06-29 23:29:38 +00001098 } else {
Reid Spencer46b002c2004-07-11 17:28:43 +00001099 // Make sure we have enough room for the plane
Reid Spencer04cde2c2004-07-04 11:33:49 +00001100 if (Ty >= CompactionValues.size())
Reid Spencer46b002c2004-07-11 17:28:43 +00001101 CompactionValues.resize(Ty+1);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001102
Reid Spencer46b002c2004-07-11 17:28:43 +00001103 // Make sure the plane is empty or we have some kind of error
Reid Spencer04cde2c2004-07-04 11:33:49 +00001104 if (!CompactionValues[Ty].empty())
Reid Spencer46b002c2004-07-11 17:28:43 +00001105 error("Compaction table plane contains multiple entries!");
Reid Spencer04cde2c2004-07-04 11:33:49 +00001106
Reid Spencer46b002c2004-07-11 17:28:43 +00001107 // Notify handler about the plane
1108 if (Handler) Handler->handleCompactionTablePlane(Ty, NumEntries);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001109
Reid Spencer46b002c2004-07-11 17:28:43 +00001110 // Convert the type slot to a type
Reid Spencer060d25d2004-06-29 23:29:38 +00001111 const Type *Typ = getType(Ty);
Reid Spencer46b002c2004-07-11 17:28:43 +00001112
Reid Spencer060d25d2004-06-29 23:29:38 +00001113 // Push the implicit zero
1114 CompactionValues[Ty].push_back(Constant::getNullValue(Typ));
Reid Spencer46b002c2004-07-11 17:28:43 +00001115
1116 // Read in each of the entries, put them in the compaction table
1117 // and notify the handler that we have a new compaction table value.
Reid Spencer060d25d2004-06-29 23:29:38 +00001118 for (unsigned i = 0; i != NumEntries; ++i) {
Reid Spencer46b002c2004-07-11 17:28:43 +00001119 unsigned ValSlot = read_vbr_uint();
1120 Value *V = getGlobalTableValue(Typ, ValSlot);
1121 CompactionValues[Ty].push_back(V);
1122 if (Handler) Handler->handleCompactionTableValue(i, Ty, ValSlot, Typ);
Reid Spencer060d25d2004-06-29 23:29:38 +00001123 }
1124 }
1125 }
Reid Spencer46b002c2004-07-11 17:28:43 +00001126 // Notify handler that the compaction table is done.
Reid Spencer04cde2c2004-07-04 11:33:49 +00001127 if (Handler) Handler->handleCompactionTableEnd();
Reid Spencer060d25d2004-06-29 23:29:38 +00001128}
1129
Reid Spencer46b002c2004-07-11 17:28:43 +00001130// Parse a single type. The typeid is read in first. If its a primitive type
1131// then nothing else needs to be read, we know how to instantiate it. If its
1132// a derived type, then additional data is read to fill out the type
1133// definition.
1134const Type *BytecodeReader::ParseType() {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001135 unsigned PrimType = 0;
Reid Spencer46b002c2004-07-11 17:28:43 +00001136 if (read_typeid(PrimType))
Reid Spencer24399722004-07-09 22:21:33 +00001137 error("Invalid type (type type) in type constants!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001138
1139 const Type *Result = 0;
1140 if ((Result = Type::getPrimitiveType((Type::TypeID)PrimType)))
1141 return Result;
1142
1143 switch (PrimType) {
1144 case Type::FunctionTyID: {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001145 const Type *RetType = readSanitizedType();
Reid Spencer060d25d2004-06-29 23:29:38 +00001146
1147 unsigned NumParams = read_vbr_uint();
1148
1149 std::vector<const Type*> Params;
Reid Spencer04cde2c2004-07-04 11:33:49 +00001150 while (NumParams--)
1151 Params.push_back(readSanitizedType());
Reid Spencer060d25d2004-06-29 23:29:38 +00001152
1153 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1154 if (isVarArg) Params.pop_back();
1155
1156 Result = FunctionType::get(RetType, Params, isVarArg);
1157 break;
1158 }
1159 case Type::ArrayTyID: {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001160 const Type *ElementType = readSanitizedType();
Reid Spencer060d25d2004-06-29 23:29:38 +00001161 unsigned NumElements = read_vbr_uint();
Reid Spencer060d25d2004-06-29 23:29:38 +00001162 Result = ArrayType::get(ElementType, NumElements);
1163 break;
1164 }
1165 case Type::StructTyID: {
1166 std::vector<const Type*> Elements;
Reid Spencer04cde2c2004-07-04 11:33:49 +00001167 unsigned Typ = 0;
Reid Spencer46b002c2004-07-11 17:28:43 +00001168 if (read_typeid(Typ))
Reid Spencer24399722004-07-09 22:21:33 +00001169 error("Invalid element type (type type) for structure!");
1170
Reid Spencer060d25d2004-06-29 23:29:38 +00001171 while (Typ) { // List is terminated by void/0 typeid
1172 Elements.push_back(getType(Typ));
Reid Spencer46b002c2004-07-11 17:28:43 +00001173 if (read_typeid(Typ))
1174 error("Invalid element type (type type) for structure!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001175 }
1176
1177 Result = StructType::get(Elements);
1178 break;
1179 }
1180 case Type::PointerTyID: {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001181 Result = PointerType::get(readSanitizedType());
Reid Spencer060d25d2004-06-29 23:29:38 +00001182 break;
1183 }
1184
1185 case Type::OpaqueTyID: {
1186 Result = OpaqueType::get();
1187 break;
1188 }
1189
1190 default:
Reid Spencer24399722004-07-09 22:21:33 +00001191 error("Don't know how to deserialize primitive type " + utostr(PrimType));
Reid Spencer060d25d2004-06-29 23:29:38 +00001192 break;
1193 }
Reid Spencer46b002c2004-07-11 17:28:43 +00001194 if (Handler) Handler->handleType(Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001195 return Result;
1196}
1197
Reid Spencer46b002c2004-07-11 17:28:43 +00001198// ParseType - We have to use this weird code to handle recursive
Reid Spencer060d25d2004-06-29 23:29:38 +00001199// types. We know that recursive types will only reference the current slab of
1200// values in the type plane, but they can forward reference types before they
1201// have been read. For example, Type #0 might be '{ Ty#1 }' and Type #1 might
1202// be 'Ty#0*'. When reading Type #0, type number one doesn't exist. To fix
1203// this ugly problem, we pessimistically insert an opaque type for each type we
1204// are about to read. This means that forward references will resolve to
1205// something and when we reread the type later, we can replace the opaque type
1206// with a new resolved concrete type.
1207//
Reid Spencer46b002c2004-07-11 17:28:43 +00001208void BytecodeReader::ParseTypes(TypeListTy &Tab, unsigned NumEntries){
Reid Spencer060d25d2004-06-29 23:29:38 +00001209 assert(Tab.size() == 0 && "should not have read type constants in before!");
1210
1211 // Insert a bunch of opaque types to be resolved later...
1212 Tab.reserve(NumEntries);
1213 for (unsigned i = 0; i != NumEntries; ++i)
1214 Tab.push_back(OpaqueType::get());
1215
1216 // Loop through reading all of the types. Forward types will make use of the
1217 // opaque types just inserted.
1218 //
1219 for (unsigned i = 0; i != NumEntries; ++i) {
Reid Spencer46b002c2004-07-11 17:28:43 +00001220 const Type* NewTy = ParseType();
Reid Spencer04cde2c2004-07-04 11:33:49 +00001221 const Type* OldTy = Tab[i].get();
1222 if (NewTy == 0)
Reid Spencer24399722004-07-09 22:21:33 +00001223 error("Couldn't parse type!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001224
1225 // Don't directly push the new type on the Tab. Instead we want to replace
1226 // the opaque type we previously inserted with the new concrete value. This
1227 // approach helps with forward references to types. The refinement from the
1228 // abstract (opaque) type to the new type causes all uses of the abstract
1229 // type to use the concrete type (NewTy). This will also cause the opaque
1230 // type to be deleted.
1231 cast<DerivedType>(const_cast<Type*>(OldTy))->refineAbstractTypeTo(NewTy);
1232
1233 // This should have replaced the old opaque type with the new type in the
1234 // value table... or with a preexisting type that was already in the system.
1235 // Let's just make sure it did.
1236 assert(Tab[i] != OldTy && "refineAbstractType didn't work!");
1237 }
1238}
1239
Reid Spencer04cde2c2004-07-04 11:33:49 +00001240/// Parse a single constant value
Reid Spencer46b002c2004-07-11 17:28:43 +00001241Constant *BytecodeReader::ParseConstantValue(unsigned TypeID) {
Reid Spencer060d25d2004-06-29 23:29:38 +00001242 // We must check for a ConstantExpr before switching by type because
1243 // a ConstantExpr can be of any type, and has no explicit value.
1244 //
1245 // 0 if not expr; numArgs if is expr
1246 unsigned isExprNumArgs = read_vbr_uint();
1247
1248 if (isExprNumArgs) {
1249 // FIXME: Encoding of constant exprs could be much more compact!
1250 std::vector<Constant*> ArgVec;
1251 ArgVec.reserve(isExprNumArgs);
1252 unsigned Opcode = read_vbr_uint();
1253
1254 // Read the slot number and types of each of the arguments
1255 for (unsigned i = 0; i != isExprNumArgs; ++i) {
1256 unsigned ArgValSlot = read_vbr_uint();
Reid Spencer04cde2c2004-07-04 11:33:49 +00001257 unsigned ArgTypeSlot = 0;
Reid Spencer46b002c2004-07-11 17:28:43 +00001258 if (read_typeid(ArgTypeSlot))
1259 error("Invalid argument type (type type) for constant value");
Reid Spencer060d25d2004-06-29 23:29:38 +00001260
1261 // Get the arg value from its slot if it exists, otherwise a placeholder
1262 ArgVec.push_back(getConstantValue(ArgTypeSlot, ArgValSlot));
1263 }
1264
1265 // Construct a ConstantExpr of the appropriate kind
1266 if (isExprNumArgs == 1) { // All one-operand expressions
Reid Spencer46b002c2004-07-11 17:28:43 +00001267 if (Opcode != Instruction::Cast)
1268 error("Only Cast instruction has one argument for ConstantExpr");
1269
Reid Spencer060d25d2004-06-29 23:29:38 +00001270 Constant* Result = ConstantExpr::getCast(ArgVec[0], getType(TypeID));
Reid Spencer04cde2c2004-07-04 11:33:49 +00001271 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001272 return Result;
1273 } else if (Opcode == Instruction::GetElementPtr) { // GetElementPtr
1274 std::vector<Constant*> IdxList(ArgVec.begin()+1, ArgVec.end());
1275
1276 if (hasRestrictedGEPTypes) {
1277 const Type *BaseTy = ArgVec[0]->getType();
1278 generic_gep_type_iterator<std::vector<Constant*>::iterator>
1279 GTI = gep_type_begin(BaseTy, IdxList.begin(), IdxList.end()),
1280 E = gep_type_end(BaseTy, IdxList.begin(), IdxList.end());
1281 for (unsigned i = 0; GTI != E; ++GTI, ++i)
1282 if (isa<StructType>(*GTI)) {
1283 if (IdxList[i]->getType() != Type::UByteTy)
Reid Spencer24399722004-07-09 22:21:33 +00001284 error("Invalid index for getelementptr!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001285 IdxList[i] = ConstantExpr::getCast(IdxList[i], Type::UIntTy);
1286 }
1287 }
1288
1289 Constant* Result = ConstantExpr::getGetElementPtr(ArgVec[0], IdxList);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001290 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001291 return Result;
1292 } else if (Opcode == Instruction::Select) {
Reid Spencer46b002c2004-07-11 17:28:43 +00001293 if (ArgVec.size() != 3)
1294 error("Select instruction must have three arguments.");
Reid Spencer060d25d2004-06-29 23:29:38 +00001295 Constant* Result = ConstantExpr::getSelect(ArgVec[0], ArgVec[1],
Reid Spencer04cde2c2004-07-04 11:33:49 +00001296 ArgVec[2]);
1297 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001298 return Result;
1299 } else { // All other 2-operand expressions
1300 Constant* Result = ConstantExpr::get(Opcode, ArgVec[0], ArgVec[1]);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001301 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001302 return Result;
1303 }
1304 }
1305
1306 // Ok, not an ConstantExpr. We now know how to read the given type...
1307 const Type *Ty = getType(TypeID);
1308 switch (Ty->getTypeID()) {
1309 case Type::BoolTyID: {
1310 unsigned Val = read_vbr_uint();
1311 if (Val != 0 && Val != 1)
Reid Spencer24399722004-07-09 22:21:33 +00001312 error("Invalid boolean value read.");
Reid Spencer060d25d2004-06-29 23:29:38 +00001313 Constant* Result = ConstantBool::get(Val == 1);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001314 if (Handler) Handler->handleConstantValue(Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001315 return Result;
1316 }
1317
1318 case Type::UByteTyID: // Unsigned integer types...
1319 case Type::UShortTyID:
1320 case Type::UIntTyID: {
1321 unsigned Val = read_vbr_uint();
1322 if (!ConstantUInt::isValueValidForType(Ty, Val))
Reid Spencer24399722004-07-09 22:21:33 +00001323 error("Invalid unsigned byte/short/int read.");
Reid Spencer060d25d2004-06-29 23:29:38 +00001324 Constant* Result = ConstantUInt::get(Ty, Val);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001325 if (Handler) Handler->handleConstantValue(Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001326 return Result;
1327 }
1328
1329 case Type::ULongTyID: {
1330 Constant* Result = ConstantUInt::get(Ty, read_vbr_uint64());
Reid Spencer04cde2c2004-07-04 11:33:49 +00001331 if (Handler) Handler->handleConstantValue(Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001332 return Result;
1333 }
1334
1335 case Type::SByteTyID: // Signed integer types...
1336 case Type::ShortTyID:
1337 case Type::IntTyID: {
1338 case Type::LongTyID:
1339 int64_t Val = read_vbr_int64();
1340 if (!ConstantSInt::isValueValidForType(Ty, Val))
Reid Spencer24399722004-07-09 22:21:33 +00001341 error("Invalid signed byte/short/int/long read.");
Reid Spencer060d25d2004-06-29 23:29:38 +00001342 Constant* Result = ConstantSInt::get(Ty, Val);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001343 if (Handler) Handler->handleConstantValue(Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001344 return Result;
1345 }
1346
1347 case Type::FloatTyID: {
Reid Spencer46b002c2004-07-11 17:28:43 +00001348 float Val;
1349 read_float(Val);
1350 Constant* Result = ConstantFP::get(Ty, Val);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001351 if (Handler) Handler->handleConstantValue(Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001352 return Result;
1353 }
1354
1355 case Type::DoubleTyID: {
1356 double Val;
Reid Spencer46b002c2004-07-11 17:28:43 +00001357 read_double(Val);
Reid Spencer060d25d2004-06-29 23:29:38 +00001358 Constant* Result = ConstantFP::get(Ty, Val);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001359 if (Handler) Handler->handleConstantValue(Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001360 return Result;
1361 }
1362
Reid Spencer060d25d2004-06-29 23:29:38 +00001363 case Type::ArrayTyID: {
1364 const ArrayType *AT = cast<ArrayType>(Ty);
1365 unsigned NumElements = AT->getNumElements();
1366 unsigned TypeSlot = getTypeSlot(AT->getElementType());
1367 std::vector<Constant*> Elements;
1368 Elements.reserve(NumElements);
1369 while (NumElements--) // Read all of the elements of the constant.
1370 Elements.push_back(getConstantValue(TypeSlot,
1371 read_vbr_uint()));
1372 Constant* Result = ConstantArray::get(AT, Elements);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001373 if (Handler) Handler->handleConstantArray(AT, Elements, TypeSlot, Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001374 return Result;
1375 }
1376
1377 case Type::StructTyID: {
1378 const StructType *ST = cast<StructType>(Ty);
1379
1380 std::vector<Constant *> Elements;
1381 Elements.reserve(ST->getNumElements());
1382 for (unsigned i = 0; i != ST->getNumElements(); ++i)
1383 Elements.push_back(getConstantValue(ST->getElementType(i),
1384 read_vbr_uint()));
1385
1386 Constant* Result = ConstantStruct::get(ST, Elements);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001387 if (Handler) Handler->handleConstantStruct(ST, Elements, Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001388 return Result;
1389 }
1390
1391 case Type::PointerTyID: { // ConstantPointerRef value...
1392 const PointerType *PT = cast<PointerType>(Ty);
1393 unsigned Slot = read_vbr_uint();
1394
1395 // Check to see if we have already read this global variable...
1396 Value *Val = getValue(TypeID, Slot, false);
Reid Spencer060d25d2004-06-29 23:29:38 +00001397 if (Val) {
Chris Lattnerbcb11cf2004-07-27 02:34:49 +00001398 GlobalValue *GV = dyn_cast<GlobalValue>(Val);
1399 if (!GV) error("GlobalValue not in ValueTable!");
1400 if (Handler) Handler->handleConstantPointer(PT, Slot, GV);
1401 return GV;
Reid Spencer060d25d2004-06-29 23:29:38 +00001402 } else {
Reid Spencer24399722004-07-09 22:21:33 +00001403 error("Forward references are not allowed here.");
Reid Spencer060d25d2004-06-29 23:29:38 +00001404 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001405 }
1406
1407 default:
Reid Spencer24399722004-07-09 22:21:33 +00001408 error("Don't know how to deserialize constant value of type '" +
Reid Spencer060d25d2004-06-29 23:29:38 +00001409 Ty->getDescription());
1410 break;
1411 }
Reid Spencer24399722004-07-09 22:21:33 +00001412 return 0;
Reid Spencer060d25d2004-06-29 23:29:38 +00001413}
1414
Reid Spencer04cde2c2004-07-04 11:33:49 +00001415/// Resolve references for constants. This function resolves the forward
1416/// referenced constants in the ConstantFwdRefs map. It uses the
1417/// replaceAllUsesWith method of Value class to substitute the placeholder
1418/// instance with the actual instance.
Reid Spencer060d25d2004-06-29 23:29:38 +00001419void BytecodeReader::ResolveReferencesToConstant(Constant *NewV, unsigned Slot){
Chris Lattner29b789b2003-11-19 17:27:18 +00001420 ConstantRefsType::iterator I =
1421 ConstantFwdRefs.find(std::make_pair(NewV->getType(), Slot));
1422 if (I == ConstantFwdRefs.end()) return; // Never forward referenced?
Chris Lattner00950542001-06-06 20:29:01 +00001423
Chris Lattner29b789b2003-11-19 17:27:18 +00001424 Value *PH = I->second; // Get the placeholder...
1425 PH->replaceAllUsesWith(NewV);
1426 delete PH; // Delete the old placeholder
1427 ConstantFwdRefs.erase(I); // Remove the map entry for it
Vikram S. Advec1e4a812002-07-14 23:04:18 +00001428}
1429
Reid Spencer04cde2c2004-07-04 11:33:49 +00001430/// Parse the constant strings section.
Reid Spencer060d25d2004-06-29 23:29:38 +00001431void BytecodeReader::ParseStringConstants(unsigned NumEntries, ValueTable &Tab){
1432 for (; NumEntries; --NumEntries) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001433 unsigned Typ = 0;
Reid Spencer46b002c2004-07-11 17:28:43 +00001434 if (read_typeid(Typ))
Reid Spencer24399722004-07-09 22:21:33 +00001435 error("Invalid type (type type) for string constant");
Reid Spencer060d25d2004-06-29 23:29:38 +00001436 const Type *Ty = getType(Typ);
1437 if (!isa<ArrayType>(Ty))
Reid Spencer24399722004-07-09 22:21:33 +00001438 error("String constant data invalid!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001439
1440 const ArrayType *ATy = cast<ArrayType>(Ty);
1441 if (ATy->getElementType() != Type::SByteTy &&
1442 ATy->getElementType() != Type::UByteTy)
Reid Spencer24399722004-07-09 22:21:33 +00001443 error("String constant data invalid!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001444
1445 // Read character data. The type tells us how long the string is.
1446 char Data[ATy->getNumElements()];
1447 read_data(Data, Data+ATy->getNumElements());
Chris Lattner52e20b02003-03-19 20:54:26 +00001448
Reid Spencer060d25d2004-06-29 23:29:38 +00001449 std::vector<Constant*> Elements(ATy->getNumElements());
1450 if (ATy->getElementType() == Type::SByteTy)
1451 for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
1452 Elements[i] = ConstantSInt::get(Type::SByteTy, (signed char)Data[i]);
1453 else
1454 for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
1455 Elements[i] = ConstantUInt::get(Type::UByteTy, (unsigned char)Data[i]);
Misha Brukman12c29d12003-09-22 23:38:23 +00001456
Reid Spencer060d25d2004-06-29 23:29:38 +00001457 // Create the constant, inserting it as needed.
1458 Constant *C = ConstantArray::get(ATy, Elements);
1459 unsigned Slot = insertValue(C, Typ, Tab);
1460 ResolveReferencesToConstant(C, Slot);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001461 if (Handler) Handler->handleConstantString(cast<ConstantArray>(C));
Reid Spencer060d25d2004-06-29 23:29:38 +00001462 }
Misha Brukman12c29d12003-09-22 23:38:23 +00001463}
1464
Reid Spencer04cde2c2004-07-04 11:33:49 +00001465/// Parse the constant pool.
Reid Spencer060d25d2004-06-29 23:29:38 +00001466void BytecodeReader::ParseConstantPool(ValueTable &Tab,
Reid Spencer04cde2c2004-07-04 11:33:49 +00001467 TypeListTy &TypeTab,
Reid Spencer46b002c2004-07-11 17:28:43 +00001468 bool isFunction) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001469 if (Handler) Handler->handleGlobalConstantsBegin();
1470
1471 /// In LLVM 1.3 Type does not derive from Value so the types
1472 /// do not occupy a plane. Consequently, we read the types
1473 /// first in the constant pool.
Reid Spencer46b002c2004-07-11 17:28:43 +00001474 if (isFunction && !hasTypeDerivedFromValue) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001475 unsigned NumEntries = read_vbr_uint();
Reid Spencer46b002c2004-07-11 17:28:43 +00001476 ParseTypes(TypeTab, NumEntries);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001477 }
1478
Reid Spencer46b002c2004-07-11 17:28:43 +00001479 while (moreInBlock()) {
Reid Spencer060d25d2004-06-29 23:29:38 +00001480 unsigned NumEntries = read_vbr_uint();
Reid Spencer04cde2c2004-07-04 11:33:49 +00001481 unsigned Typ = 0;
1482 bool isTypeType = read_typeid(Typ);
1483
1484 /// In LLVM 1.2 and before, Types were written to the
1485 /// bytecode file in the "Type Type" plane (#12).
1486 /// In 1.3 plane 12 is now the label plane. Handle this here.
Reid Spencer46b002c2004-07-11 17:28:43 +00001487 if (isTypeType) {
1488 ParseTypes(TypeTab, NumEntries);
Reid Spencer060d25d2004-06-29 23:29:38 +00001489 } else if (Typ == Type::VoidTyID) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001490 /// Use of Type::VoidTyID is a misnomer. It actually means
1491 /// that the following plane is constant strings
Reid Spencer060d25d2004-06-29 23:29:38 +00001492 assert(&Tab == &ModuleValues && "Cannot read strings in functions!");
1493 ParseStringConstants(NumEntries, Tab);
1494 } else {
1495 for (unsigned i = 0; i < NumEntries; ++i) {
1496 Constant *C = ParseConstantValue(Typ);
1497 assert(C && "ParseConstantValue returned NULL!");
1498 unsigned Slot = insertValue(C, Typ, Tab);
Chris Lattner29b789b2003-11-19 17:27:18 +00001499
Reid Spencer060d25d2004-06-29 23:29:38 +00001500 // If we are reading a function constant table, make sure that we adjust
1501 // the slot number to be the real global constant number.
1502 //
1503 if (&Tab != &ModuleValues && Typ < ModuleValues.size() &&
1504 ModuleValues[Typ])
1505 Slot += ModuleValues[Typ]->size();
1506 ResolveReferencesToConstant(C, Slot);
1507 }
1508 }
1509 }
1510 checkPastBlockEnd("Constant Pool");
Reid Spencer04cde2c2004-07-04 11:33:49 +00001511 if (Handler) Handler->handleGlobalConstantsEnd();
Reid Spencer060d25d2004-06-29 23:29:38 +00001512}
Chris Lattner00950542001-06-06 20:29:01 +00001513
Reid Spencer04cde2c2004-07-04 11:33:49 +00001514/// Parse the contents of a function. Note that this function can be
1515/// called lazily by materializeFunction
1516/// @see materializeFunction
Reid Spencer46b002c2004-07-11 17:28:43 +00001517void BytecodeReader::ParseFunctionBody(Function* F) {
Reid Spencer060d25d2004-06-29 23:29:38 +00001518
1519 unsigned FuncSize = BlockEnd - At;
Chris Lattnere3869c82003-04-16 21:16:05 +00001520 GlobalValue::LinkageTypes Linkage = GlobalValue::ExternalLinkage;
1521
Reid Spencer060d25d2004-06-29 23:29:38 +00001522 unsigned LinkageType = read_vbr_uint();
Chris Lattnerc08912f2004-01-14 16:44:44 +00001523 switch (LinkageType) {
1524 case 0: Linkage = GlobalValue::ExternalLinkage; break;
1525 case 1: Linkage = GlobalValue::WeakLinkage; break;
1526 case 2: Linkage = GlobalValue::AppendingLinkage; break;
1527 case 3: Linkage = GlobalValue::InternalLinkage; break;
1528 case 4: Linkage = GlobalValue::LinkOnceLinkage; break;
Reid Spencer060d25d2004-06-29 23:29:38 +00001529 default:
Reid Spencer24399722004-07-09 22:21:33 +00001530 error("Invalid linkage type for Function.");
Reid Spencer060d25d2004-06-29 23:29:38 +00001531 Linkage = GlobalValue::InternalLinkage;
1532 break;
Chris Lattnere3869c82003-04-16 21:16:05 +00001533 }
Chris Lattnerd23b1d32001-11-26 18:56:10 +00001534
Reid Spencer46b002c2004-07-11 17:28:43 +00001535 F->setLinkage(Linkage);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001536 if (Handler) Handler->handleFunctionBegin(F,FuncSize);
Chris Lattner00950542001-06-06 20:29:01 +00001537
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001538 // Keep track of how many basic blocks we have read in...
1539 unsigned BlockNum = 0;
Chris Lattner89e02532004-01-18 21:08:15 +00001540 bool InsertedArguments = false;
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001541
Reid Spencer060d25d2004-06-29 23:29:38 +00001542 BufPtr MyEnd = BlockEnd;
Reid Spencer46b002c2004-07-11 17:28:43 +00001543 while (At < MyEnd) {
Chris Lattner00950542001-06-06 20:29:01 +00001544 unsigned Type, Size;
Reid Spencer060d25d2004-06-29 23:29:38 +00001545 BufPtr OldAt = At;
1546 read_block(Type, Size);
Chris Lattner00950542001-06-06 20:29:01 +00001547
1548 switch (Type) {
Reid Spencerad89bd62004-07-25 18:07:36 +00001549 case BytecodeFormat::ConstantPoolBlockID:
Chris Lattner89e02532004-01-18 21:08:15 +00001550 if (!InsertedArguments) {
1551 // Insert arguments into the value table before we parse the first basic
1552 // block in the function, but after we potentially read in the
1553 // compaction table.
Reid Spencer04cde2c2004-07-04 11:33:49 +00001554 insertArguments(F);
Chris Lattner89e02532004-01-18 21:08:15 +00001555 InsertedArguments = true;
1556 }
1557
Reid Spencer04cde2c2004-07-04 11:33:49 +00001558 ParseConstantPool(FunctionValues, FunctionTypes, true);
Chris Lattner00950542001-06-06 20:29:01 +00001559 break;
1560
Reid Spencerad89bd62004-07-25 18:07:36 +00001561 case BytecodeFormat::CompactionTableBlockID:
Reid Spencer060d25d2004-06-29 23:29:38 +00001562 ParseCompactionTable();
Chris Lattner89e02532004-01-18 21:08:15 +00001563 break;
1564
Chris Lattner00950542001-06-06 20:29:01 +00001565 case BytecodeFormat::BasicBlock: {
Chris Lattner89e02532004-01-18 21:08:15 +00001566 if (!InsertedArguments) {
1567 // Insert arguments into the value table before we parse the first basic
1568 // block in the function, but after we potentially read in the
1569 // compaction table.
Reid Spencer04cde2c2004-07-04 11:33:49 +00001570 insertArguments(F);
Chris Lattner89e02532004-01-18 21:08:15 +00001571 InsertedArguments = true;
1572 }
1573
Reid Spencer060d25d2004-06-29 23:29:38 +00001574 BasicBlock *BB = ParseBasicBlock(BlockNum++);
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001575 F->getBasicBlockList().push_back(BB);
Chris Lattner00950542001-06-06 20:29:01 +00001576 break;
1577 }
1578
Reid Spencerad89bd62004-07-25 18:07:36 +00001579 case BytecodeFormat::InstructionListBlockID: {
Chris Lattner89e02532004-01-18 21:08:15 +00001580 // Insert arguments into the value table before we parse the instruction
1581 // list for the function, but after we potentially read in the compaction
1582 // table.
1583 if (!InsertedArguments) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001584 insertArguments(F);
Chris Lattner89e02532004-01-18 21:08:15 +00001585 InsertedArguments = true;
1586 }
1587
Reid Spencer060d25d2004-06-29 23:29:38 +00001588 if (BlockNum)
Reid Spencer24399722004-07-09 22:21:33 +00001589 error("Already parsed basic blocks!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001590 BlockNum = ParseInstructionList(F);
Chris Lattner8d1dbd22003-12-01 07:05:31 +00001591 break;
1592 }
1593
Reid Spencerad89bd62004-07-25 18:07:36 +00001594 case BytecodeFormat::SymbolTableBlockID:
Reid Spencer060d25d2004-06-29 23:29:38 +00001595 ParseSymbolTable(F, &F->getSymbolTable());
Chris Lattner00950542001-06-06 20:29:01 +00001596 break;
1597
1598 default:
Reid Spencer060d25d2004-06-29 23:29:38 +00001599 At += Size;
1600 if (OldAt > At)
Reid Spencer24399722004-07-09 22:21:33 +00001601 error("Wrapped around reading bytecode.");
Chris Lattner00950542001-06-06 20:29:01 +00001602 break;
1603 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001604 BlockEnd = MyEnd;
Chris Lattner1d670cc2001-09-07 16:37:43 +00001605
Misha Brukman12c29d12003-09-22 23:38:23 +00001606 // Malformed bc file if read past end of block.
Reid Spencer060d25d2004-06-29 23:29:38 +00001607 align32();
Chris Lattner00950542001-06-06 20:29:01 +00001608 }
1609
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001610 // Make sure there were no references to non-existant basic blocks.
1611 if (BlockNum != ParsedBasicBlocks.size())
Reid Spencer24399722004-07-09 22:21:33 +00001612 error("Illegal basic block operand reference");
Reid Spencer060d25d2004-06-29 23:29:38 +00001613
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001614 ParsedBasicBlocks.clear();
1615
Chris Lattner97330cf2003-10-09 23:10:14 +00001616 // Resolve forward references. Replace any uses of a forward reference value
1617 // with the real value.
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001618
Chris Lattner97330cf2003-10-09 23:10:14 +00001619 // replaceAllUsesWith is very inefficient for instructions which have a LARGE
1620 // number of operands. PHI nodes often have forward references, and can also
1621 // often have a very large number of operands.
Chris Lattner89e02532004-01-18 21:08:15 +00001622 //
1623 // FIXME: REEVALUATE. replaceAllUsesWith is _much_ faster now, and this code
1624 // should be simplified back to using it!
1625 //
Chris Lattner97330cf2003-10-09 23:10:14 +00001626 std::map<Value*, Value*> ForwardRefMapping;
1627 for (std::map<std::pair<unsigned,unsigned>, Value*>::iterator
1628 I = ForwardReferences.begin(), E = ForwardReferences.end();
1629 I != E; ++I)
1630 ForwardRefMapping[I->second] = getValue(I->first.first, I->first.second,
1631 false);
1632
1633 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
1634 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
1635 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1636 if (Argument *A = dyn_cast<Argument>(I->getOperand(i))) {
1637 std::map<Value*, Value*>::iterator It = ForwardRefMapping.find(A);
1638 if (It != ForwardRefMapping.end()) I->setOperand(i, It->second);
1639 }
1640
Chris Lattner8eb10ce2003-10-09 06:05:40 +00001641 while (!ForwardReferences.empty()) {
Chris Lattner35d2ca62003-10-09 22:39:30 +00001642 std::map<std::pair<unsigned,unsigned>, Value*>::iterator I =
1643 ForwardReferences.begin();
Chris Lattner8eb10ce2003-10-09 06:05:40 +00001644 Value *PlaceHolder = I->second;
1645 ForwardReferences.erase(I);
Chris Lattner00950542001-06-06 20:29:01 +00001646
Chris Lattner8eb10ce2003-10-09 06:05:40 +00001647 // Now that all the uses are gone, delete the placeholder...
1648 // If we couldn't find a def (error case), then leak a little
1649 // memory, because otherwise we can't remove all uses!
1650 delete PlaceHolder;
Chris Lattner6e448022003-10-08 21:51:46 +00001651 }
Chris Lattner00950542001-06-06 20:29:01 +00001652
Misha Brukman12c29d12003-09-22 23:38:23 +00001653 // Clear out function-level types...
Reid Spencer060d25d2004-06-29 23:29:38 +00001654 FunctionTypes.clear();
1655 CompactionTypes.clear();
1656 CompactionValues.clear();
1657 freeTable(FunctionValues);
1658
Reid Spencer04cde2c2004-07-04 11:33:49 +00001659 if (Handler) Handler->handleFunctionEnd(F);
Chris Lattner00950542001-06-06 20:29:01 +00001660}
1661
Reid Spencer04cde2c2004-07-04 11:33:49 +00001662/// This function parses LLVM functions lazily. It obtains the type of the
1663/// function and records where the body of the function is in the bytecode
1664/// buffer. The caller can then use the ParseNextFunction and
1665/// ParseAllFunctionBodies to get handler events for the functions.
Reid Spencer060d25d2004-06-29 23:29:38 +00001666void BytecodeReader::ParseFunctionLazily() {
1667 if (FunctionSignatureList.empty())
Reid Spencer24399722004-07-09 22:21:33 +00001668 error("FunctionSignatureList empty!");
Chris Lattner89e02532004-01-18 21:08:15 +00001669
Reid Spencer060d25d2004-06-29 23:29:38 +00001670 Function *Func = FunctionSignatureList.back();
1671 FunctionSignatureList.pop_back();
Chris Lattner24102432004-01-18 22:35:34 +00001672
Reid Spencer060d25d2004-06-29 23:29:38 +00001673 // Save the information for future reading of the function
1674 LazyFunctionLoadMap[Func] = LazyFunctionInfo(BlockStart, BlockEnd);
Chris Lattner89e02532004-01-18 21:08:15 +00001675
Reid Spencer060d25d2004-06-29 23:29:38 +00001676 // Pretend we've `parsed' this function
1677 At = BlockEnd;
1678}
Chris Lattner89e02532004-01-18 21:08:15 +00001679
Reid Spencer04cde2c2004-07-04 11:33:49 +00001680/// The ParserFunction method lazily parses one function. Use this method to
1681/// casue the parser to parse a specific function in the module. Note that
1682/// this will remove the function from what is to be included by
1683/// ParseAllFunctionBodies.
1684/// @see ParseAllFunctionBodies
1685/// @see ParseBytecode
Reid Spencer060d25d2004-06-29 23:29:38 +00001686void BytecodeReader::ParseFunction(Function* Func) {
1687 // Find {start, end} pointers and slot in the map. If not there, we're done.
1688 LazyFunctionMap::iterator Fi = LazyFunctionLoadMap.find(Func);
Chris Lattner89e02532004-01-18 21:08:15 +00001689
Reid Spencer060d25d2004-06-29 23:29:38 +00001690 // Make sure we found it
Reid Spencer46b002c2004-07-11 17:28:43 +00001691 if (Fi == LazyFunctionLoadMap.end()) {
Reid Spencer24399722004-07-09 22:21:33 +00001692 error("Unrecognized function of type " + Func->getType()->getDescription());
Reid Spencer060d25d2004-06-29 23:29:38 +00001693 return;
Chris Lattner89e02532004-01-18 21:08:15 +00001694 }
1695
Reid Spencer060d25d2004-06-29 23:29:38 +00001696 BlockStart = At = Fi->second.Buf;
1697 BlockEnd = Fi->second.EndBuf;
Reid Spencer24399722004-07-09 22:21:33 +00001698 assert(Fi->first == Func && "Found wrong function?");
Reid Spencer060d25d2004-06-29 23:29:38 +00001699
1700 LazyFunctionLoadMap.erase(Fi);
1701
Reid Spencer46b002c2004-07-11 17:28:43 +00001702 this->ParseFunctionBody(Func);
Chris Lattner89e02532004-01-18 21:08:15 +00001703}
1704
Reid Spencer04cde2c2004-07-04 11:33:49 +00001705/// The ParseAllFunctionBodies method parses through all the previously
1706/// unparsed functions in the bytecode file. If you want to completely parse
1707/// a bytecode file, this method should be called after Parsebytecode because
1708/// Parsebytecode only records the locations in the bytecode file of where
1709/// the function definitions are located. This function uses that information
1710/// to materialize the functions.
1711/// @see ParseBytecode
Reid Spencer060d25d2004-06-29 23:29:38 +00001712void BytecodeReader::ParseAllFunctionBodies() {
1713 LazyFunctionMap::iterator Fi = LazyFunctionLoadMap.begin();
1714 LazyFunctionMap::iterator Fe = LazyFunctionLoadMap.end();
Chris Lattner89e02532004-01-18 21:08:15 +00001715
Reid Spencer46b002c2004-07-11 17:28:43 +00001716 while (Fi != Fe) {
Reid Spencer060d25d2004-06-29 23:29:38 +00001717 Function* Func = Fi->first;
1718 BlockStart = At = Fi->second.Buf;
1719 BlockEnd = Fi->second.EndBuf;
1720 this->ParseFunctionBody(Func);
1721 ++Fi;
1722 }
1723}
Chris Lattner89e02532004-01-18 21:08:15 +00001724
Reid Spencer04cde2c2004-07-04 11:33:49 +00001725/// Parse the global type list
Reid Spencer060d25d2004-06-29 23:29:38 +00001726void BytecodeReader::ParseGlobalTypes() {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001727 // Read the number of types
1728 unsigned NumEntries = read_vbr_uint();
Reid Spencer011bed52004-07-09 21:13:53 +00001729
1730 // Ignore the type plane identifier for types if the bc file is pre 1.3
1731 if (hasTypeDerivedFromValue)
1732 read_vbr_uint();
1733
Reid Spencer46b002c2004-07-11 17:28:43 +00001734 ParseTypes(ModuleTypes, NumEntries);
Reid Spencer060d25d2004-06-29 23:29:38 +00001735}
1736
Reid Spencer04cde2c2004-07-04 11:33:49 +00001737/// Parse the Global info (types, global vars, constants)
Reid Spencer060d25d2004-06-29 23:29:38 +00001738void BytecodeReader::ParseModuleGlobalInfo() {
1739
Reid Spencer04cde2c2004-07-04 11:33:49 +00001740 if (Handler) Handler->handleModuleGlobalsBegin();
Chris Lattner00950542001-06-06 20:29:01 +00001741
Chris Lattner70cc3392001-09-10 07:58:01 +00001742 // Read global variables...
Reid Spencer060d25d2004-06-29 23:29:38 +00001743 unsigned VarType = read_vbr_uint();
Chris Lattner70cc3392001-09-10 07:58:01 +00001744 while (VarType != Type::VoidTyID) { // List is terminated by Void
Chris Lattner9dd87702004-04-03 23:43:42 +00001745 // VarType Fields: bit0 = isConstant, bit1 = hasInitializer, bit2,3,4 =
1746 // Linkage, bit4+ = slot#
1747 unsigned SlotNo = VarType >> 5;
Reid Spencer46b002c2004-07-11 17:28:43 +00001748 if (sanitizeTypeId(SlotNo))
Reid Spencer24399722004-07-09 22:21:33 +00001749 error("Invalid type (type type) for global var!");
Chris Lattner9dd87702004-04-03 23:43:42 +00001750 unsigned LinkageID = (VarType >> 2) & 7;
Reid Spencer060d25d2004-06-29 23:29:38 +00001751 bool isConstant = VarType & 1;
1752 bool hasInitializer = VarType & 2;
Chris Lattnere3869c82003-04-16 21:16:05 +00001753 GlobalValue::LinkageTypes Linkage;
1754
Chris Lattnerc08912f2004-01-14 16:44:44 +00001755 switch (LinkageID) {
Chris Lattnerc08912f2004-01-14 16:44:44 +00001756 case 0: Linkage = GlobalValue::ExternalLinkage; break;
1757 case 1: Linkage = GlobalValue::WeakLinkage; break;
1758 case 2: Linkage = GlobalValue::AppendingLinkage; break;
1759 case 3: Linkage = GlobalValue::InternalLinkage; break;
1760 case 4: Linkage = GlobalValue::LinkOnceLinkage; break;
Reid Spencer060d25d2004-06-29 23:29:38 +00001761 default:
Reid Spencer24399722004-07-09 22:21:33 +00001762 error("Unknown linkage type: " + utostr(LinkageID));
Reid Spencer060d25d2004-06-29 23:29:38 +00001763 Linkage = GlobalValue::InternalLinkage;
1764 break;
Chris Lattnere3869c82003-04-16 21:16:05 +00001765 }
1766
1767 const Type *Ty = getType(SlotNo);
Reid Spencer46b002c2004-07-11 17:28:43 +00001768 if (!Ty) {
Reid Spencer24399722004-07-09 22:21:33 +00001769 error("Global has no type! SlotNo=" + utostr(SlotNo));
Reid Spencer060d25d2004-06-29 23:29:38 +00001770 }
1771
Reid Spencer46b002c2004-07-11 17:28:43 +00001772 if (!isa<PointerType>(Ty)) {
Reid Spencer24399722004-07-09 22:21:33 +00001773 error("Global not a pointer type! Ty= " + Ty->getDescription());
Reid Spencer060d25d2004-06-29 23:29:38 +00001774 }
Chris Lattner70cc3392001-09-10 07:58:01 +00001775
Chris Lattner52e20b02003-03-19 20:54:26 +00001776 const Type *ElTy = cast<PointerType>(Ty)->getElementType();
Chris Lattnerd70684f2001-09-18 04:01:05 +00001777
Chris Lattner70cc3392001-09-10 07:58:01 +00001778 // Create the global variable...
Reid Spencer060d25d2004-06-29 23:29:38 +00001779 GlobalVariable *GV = new GlobalVariable(ElTy, isConstant, Linkage,
Chris Lattner52e20b02003-03-19 20:54:26 +00001780 0, "", TheModule);
Chris Lattner29b789b2003-11-19 17:27:18 +00001781 insertValue(GV, SlotNo, ModuleValues);
Chris Lattner05950c32001-10-13 06:47:01 +00001782
Reid Spencer060d25d2004-06-29 23:29:38 +00001783 unsigned initSlot = 0;
1784 if (hasInitializer) {
1785 initSlot = read_vbr_uint();
1786 GlobalInits.push_back(std::make_pair(GV, initSlot));
1787 }
1788
1789 // Notify handler about the global value.
Reid Spencer46b002c2004-07-11 17:28:43 +00001790 if (Handler) Handler->handleGlobalVariable(ElTy, isConstant, Linkage, SlotNo, initSlot);
Reid Spencer060d25d2004-06-29 23:29:38 +00001791
1792 // Get next item
1793 VarType = read_vbr_uint();
Chris Lattner70cc3392001-09-10 07:58:01 +00001794 }
1795
Chris Lattner52e20b02003-03-19 20:54:26 +00001796 // Read the function objects for all of the functions that are coming
Reid Spencer04cde2c2004-07-04 11:33:49 +00001797 unsigned FnSignature = 0;
Reid Spencer46b002c2004-07-11 17:28:43 +00001798 if (read_typeid(FnSignature))
Reid Spencer24399722004-07-09 22:21:33 +00001799 error("Invalid function type (type type) found");
1800
Chris Lattner74734132002-08-17 22:01:27 +00001801 while (FnSignature != Type::VoidTyID) { // List is terminated by Void
1802 const Type *Ty = getType(FnSignature);
Chris Lattner927b1852003-10-09 20:22:47 +00001803 if (!isa<PointerType>(Ty) ||
Reid Spencer060d25d2004-06-29 23:29:38 +00001804 !isa<FunctionType>(cast<PointerType>(Ty)->getElementType())) {
Reid Spencer24399722004-07-09 22:21:33 +00001805 error("Function not a pointer to function type! Ty = " +
Reid Spencer46b002c2004-07-11 17:28:43 +00001806 Ty->getDescription());
Reid Spencer060d25d2004-06-29 23:29:38 +00001807 // FIXME: what should Ty be if handler continues?
1808 }
Chris Lattner8cdc6b72002-10-23 00:51:54 +00001809
Chris Lattner2a7b6ba2003-03-06 17:15:19 +00001810 // We create functions by passing the underlying FunctionType to create...
Reid Spencer060d25d2004-06-29 23:29:38 +00001811 const FunctionType* FTy =
1812 cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
Chris Lattner00950542001-06-06 20:29:01 +00001813
Reid Spencer060d25d2004-06-29 23:29:38 +00001814 // Insert the place hodler
1815 Function* Func = new Function(FTy, GlobalValue::InternalLinkage,
Reid Spencer04cde2c2004-07-04 11:33:49 +00001816 "", TheModule);
Chris Lattner29b789b2003-11-19 17:27:18 +00001817 insertValue(Func, FnSignature, ModuleValues);
Chris Lattner00950542001-06-06 20:29:01 +00001818
Reid Spencer060d25d2004-06-29 23:29:38 +00001819 // Save this for later so we know type of lazily instantiated functions
Chris Lattner29b789b2003-11-19 17:27:18 +00001820 FunctionSignatureList.push_back(Func);
Chris Lattner52e20b02003-03-19 20:54:26 +00001821
Reid Spencer04cde2c2004-07-04 11:33:49 +00001822 if (Handler) Handler->handleFunctionDeclaration(Func);
Reid Spencer060d25d2004-06-29 23:29:38 +00001823
1824 // Get Next function signature
Reid Spencer46b002c2004-07-11 17:28:43 +00001825 if (read_typeid(FnSignature))
Reid Spencer24399722004-07-09 22:21:33 +00001826 error("Invalid function type (type type) found");
Chris Lattner00950542001-06-06 20:29:01 +00001827 }
1828
Chris Lattner74734132002-08-17 22:01:27 +00001829 // Now that the function signature list is set up, reverse it so that we can
1830 // remove elements efficiently from the back of the vector.
1831 std::reverse(FunctionSignatureList.begin(), FunctionSignatureList.end());
Chris Lattner00950542001-06-06 20:29:01 +00001832
Reid Spencerad89bd62004-07-25 18:07:36 +00001833 // If this bytecode format has dependent library information in it ..
1834 if (!hasNoDependentLibraries) {
1835 // Read in the number of dependent library items that follow
1836 unsigned num_dep_libs = read_vbr_uint();
1837 std::string dep_lib;
1838 while( num_dep_libs-- ) {
1839 dep_lib = read_str();
Reid Spencerada16182004-07-25 21:36:26 +00001840 TheModule->addLibrary(dep_lib);
Reid Spencerad89bd62004-07-25 18:07:36 +00001841 }
1842
1843 // Read target triple and place into the module
1844 std::string triple = read_str();
1845 TheModule->setTargetTriple(triple);
1846 }
1847
1848 if (hasInconsistentModuleGlobalInfo)
1849 align32();
1850
Chris Lattner00950542001-06-06 20:29:01 +00001851 // This is for future proofing... in the future extra fields may be added that
1852 // we don't understand, so we transparently ignore them.
1853 //
Reid Spencer060d25d2004-06-29 23:29:38 +00001854 At = BlockEnd;
1855
Reid Spencer04cde2c2004-07-04 11:33:49 +00001856 if (Handler) Handler->handleModuleGlobalsEnd();
Chris Lattner00950542001-06-06 20:29:01 +00001857}
1858
Reid Spencer04cde2c2004-07-04 11:33:49 +00001859/// Parse the version information and decode it by setting flags on the
1860/// Reader that enable backward compatibility of the reader.
Reid Spencer060d25d2004-06-29 23:29:38 +00001861void BytecodeReader::ParseVersionInfo() {
1862 unsigned Version = read_vbr_uint();
Chris Lattner036b8aa2003-03-06 17:55:45 +00001863
1864 // Unpack version number: low four bits are for flags, top bits = version
Chris Lattnerd445c6b2003-08-24 13:47:36 +00001865 Module::Endianness Endianness;
1866 Module::PointerSize PointerSize;
1867 Endianness = (Version & 1) ? Module::BigEndian : Module::LittleEndian;
1868 PointerSize = (Version & 2) ? Module::Pointer64 : Module::Pointer32;
1869
1870 bool hasNoEndianness = Version & 4;
1871 bool hasNoPointerSize = Version & 8;
1872
1873 RevisionNum = Version >> 4;
Chris Lattnere3869c82003-04-16 21:16:05 +00001874
1875 // Default values for the current bytecode version
Chris Lattner44d0eeb2004-01-15 17:55:01 +00001876 hasInconsistentModuleGlobalInfo = false;
Chris Lattner80b97342004-01-17 23:25:43 +00001877 hasExplicitPrimitiveZeros = false;
Chris Lattner5fa428f2004-04-05 01:27:26 +00001878 hasRestrictedGEPTypes = false;
Reid Spencer04cde2c2004-07-04 11:33:49 +00001879 hasTypeDerivedFromValue = false;
Reid Spencerad89bd62004-07-25 18:07:36 +00001880 hasLongBlockHeaders = false;
Reid Spencerad89bd62004-07-25 18:07:36 +00001881 has32BitTypes = false;
1882 hasNoDependentLibraries = false;
Chris Lattner036b8aa2003-03-06 17:55:45 +00001883
1884 switch (RevisionNum) {
Chris Lattnerc08912f2004-01-14 16:44:44 +00001885 case 0: // LLVM 1.0, 1.1 release version
Chris Lattner9e893e82004-01-14 23:35:21 +00001886 // Base LLVM 1.0 bytecode format.
Chris Lattner44d0eeb2004-01-15 17:55:01 +00001887 hasInconsistentModuleGlobalInfo = true;
Chris Lattner80b97342004-01-17 23:25:43 +00001888 hasExplicitPrimitiveZeros = true;
Reid Spencer04cde2c2004-07-04 11:33:49 +00001889
Reid Spencerad89bd62004-07-25 18:07:36 +00001890
Chris Lattner80b97342004-01-17 23:25:43 +00001891 // FALL THROUGH
Chris Lattnerc08912f2004-01-14 16:44:44 +00001892 case 1: // LLVM 1.2 release version
Chris Lattner9e893e82004-01-14 23:35:21 +00001893 // LLVM 1.2 added explicit support for emitting strings efficiently.
Chris Lattner44d0eeb2004-01-15 17:55:01 +00001894
1895 // Also, it fixed the problem where the size of the ModuleGlobalInfo block
1896 // included the size for the alignment at the end, where the rest of the
1897 // blocks did not.
Chris Lattner5fa428f2004-04-05 01:27:26 +00001898
1899 // LLVM 1.2 and before required that GEP indices be ubyte constants for
1900 // structures and longs for sequential types.
1901 hasRestrictedGEPTypes = true;
1902
Reid Spencer04cde2c2004-07-04 11:33:49 +00001903 // LLVM 1.2 and before had the Type class derive from Value class. This
1904 // changed in release 1.3 and consequently LLVM 1.3 bytecode files are
1905 // written differently because Types can no longer be part of the
1906 // type planes for Values.
1907 hasTypeDerivedFromValue = true;
1908
Chris Lattner5fa428f2004-04-05 01:27:26 +00001909 // FALL THROUGH
Reid Spencerad89bd62004-07-25 18:07:36 +00001910
1911 case 2: /// 1.2.5 (mid-release) version
1912
1913 /// LLVM 1.2 and earlier had two-word block headers. This is a bit wasteful,
1914 /// especially for small files where the 8 bytes per block is a large fraction
1915 /// of the total block size. In LLVM 1.3, the block type and length are
1916 /// compressed into a single 32-bit unsigned integer. 27 bits for length, 5
1917 /// bits for block type.
1918 hasLongBlockHeaders = true;
1919
Reid Spencerad89bd62004-07-25 18:07:36 +00001920 /// LLVM 1.2 and earlier wrote type slot numbers as vbr_uint32. In LLVM 1.3
1921 /// this has been reduced to vbr_uint24. It shouldn't make much difference
1922 /// since we haven't run into a module with > 24 million types, but for safety
1923 /// the 24-bit restriction has been enforced in 1.3 to free some bits in
1924 /// various places and to ensure consistency.
1925 has32BitTypes = true;
1926
1927 /// LLVM 1.2 and earlier did not provide a target triple nor a list of
1928 /// libraries on which the bytecode is dependent. LLVM 1.3 provides these
1929 /// features, for use in future versions of LLVM.
1930 hasNoDependentLibraries = true;
1931
1932 // FALL THROUGH
1933 case 3: // LLVM 1.3 release version
Chris Lattnerc08912f2004-01-14 16:44:44 +00001934 break;
1935
Chris Lattner036b8aa2003-03-06 17:55:45 +00001936 default:
Reid Spencer24399722004-07-09 22:21:33 +00001937 error("Unknown bytecode version number: " + itostr(RevisionNum));
Chris Lattner036b8aa2003-03-06 17:55:45 +00001938 }
1939
Chris Lattnerd445c6b2003-08-24 13:47:36 +00001940 if (hasNoEndianness) Endianness = Module::AnyEndianness;
1941 if (hasNoPointerSize) PointerSize = Module::AnyPointerSize;
Chris Lattner76e38962003-04-22 18:15:10 +00001942
Brian Gaekefe2102b2004-07-14 20:33:13 +00001943 TheModule->setEndianness(Endianness);
1944 TheModule->setPointerSize(PointerSize);
1945
Reid Spencer46b002c2004-07-11 17:28:43 +00001946 if (Handler) Handler->handleVersionInfo(RevisionNum, Endianness, PointerSize);
Chris Lattner036b8aa2003-03-06 17:55:45 +00001947}
1948
Reid Spencer04cde2c2004-07-04 11:33:49 +00001949/// Parse a whole module.
Reid Spencer060d25d2004-06-29 23:29:38 +00001950void BytecodeReader::ParseModule() {
Chris Lattner00950542001-06-06 20:29:01 +00001951 unsigned Type, Size;
Chris Lattner00950542001-06-06 20:29:01 +00001952
Reid Spencer060d25d2004-06-29 23:29:38 +00001953 FunctionSignatureList.clear(); // Just in case...
Chris Lattner00950542001-06-06 20:29:01 +00001954
1955 // Read into instance variables...
Reid Spencer060d25d2004-06-29 23:29:38 +00001956 ParseVersionInfo();
Reid Spencerad89bd62004-07-25 18:07:36 +00001957 align32();
Chris Lattner00950542001-06-06 20:29:01 +00001958
Reid Spencer060d25d2004-06-29 23:29:38 +00001959 bool SeenModuleGlobalInfo = false;
1960 bool SeenGlobalTypePlane = false;
1961 BufPtr MyEnd = BlockEnd;
1962 while (At < MyEnd) {
1963 BufPtr OldAt = At;
1964 read_block(Type, Size);
1965
Chris Lattner00950542001-06-06 20:29:01 +00001966 switch (Type) {
Reid Spencer060d25d2004-06-29 23:29:38 +00001967
Reid Spencerad89bd62004-07-25 18:07:36 +00001968 case BytecodeFormat::GlobalTypePlaneBlockID:
Reid Spencer46b002c2004-07-11 17:28:43 +00001969 if (SeenGlobalTypePlane)
Reid Spencer24399722004-07-09 22:21:33 +00001970 error("Two GlobalTypePlane Blocks Encountered!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001971
1972 ParseGlobalTypes();
1973 SeenGlobalTypePlane = true;
Chris Lattner52e20b02003-03-19 20:54:26 +00001974 break;
1975
Reid Spencerad89bd62004-07-25 18:07:36 +00001976 case BytecodeFormat::ModuleGlobalInfoBlockID:
Reid Spencer46b002c2004-07-11 17:28:43 +00001977 if (SeenModuleGlobalInfo)
Reid Spencer24399722004-07-09 22:21:33 +00001978 error("Two ModuleGlobalInfo Blocks Encountered!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001979 ParseModuleGlobalInfo();
1980 SeenModuleGlobalInfo = true;
Chris Lattner52e20b02003-03-19 20:54:26 +00001981 break;
1982
Reid Spencerad89bd62004-07-25 18:07:36 +00001983 case BytecodeFormat::ConstantPoolBlockID:
Reid Spencer04cde2c2004-07-04 11:33:49 +00001984 ParseConstantPool(ModuleValues, ModuleTypes,false);
Chris Lattner00950542001-06-06 20:29:01 +00001985 break;
1986
Reid Spencerad89bd62004-07-25 18:07:36 +00001987 case BytecodeFormat::FunctionBlockID:
Reid Spencer060d25d2004-06-29 23:29:38 +00001988 ParseFunctionLazily();
Chris Lattner00950542001-06-06 20:29:01 +00001989 break;
Chris Lattner00950542001-06-06 20:29:01 +00001990
Reid Spencerad89bd62004-07-25 18:07:36 +00001991 case BytecodeFormat::SymbolTableBlockID:
Reid Spencer060d25d2004-06-29 23:29:38 +00001992 ParseSymbolTable(0, &TheModule->getSymbolTable());
Chris Lattner00950542001-06-06 20:29:01 +00001993 break;
Reid Spencer060d25d2004-06-29 23:29:38 +00001994
Chris Lattner00950542001-06-06 20:29:01 +00001995 default:
Reid Spencer060d25d2004-06-29 23:29:38 +00001996 At += Size;
1997 if (OldAt > At) {
Reid Spencer46b002c2004-07-11 17:28:43 +00001998 error("Unexpected Block of Type #" + utostr(Type) + " encountered!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001999 }
Chris Lattner00950542001-06-06 20:29:01 +00002000 break;
2001 }
Reid Spencer060d25d2004-06-29 23:29:38 +00002002 BlockEnd = MyEnd;
2003 align32();
Chris Lattner00950542001-06-06 20:29:01 +00002004 }
2005
Chris Lattner52e20b02003-03-19 20:54:26 +00002006 // After the module constant pool has been read, we can safely initialize
2007 // global variables...
2008 while (!GlobalInits.empty()) {
2009 GlobalVariable *GV = GlobalInits.back().first;
2010 unsigned Slot = GlobalInits.back().second;
2011 GlobalInits.pop_back();
2012
2013 // Look up the initializer value...
Chris Lattner29b789b2003-11-19 17:27:18 +00002014 // FIXME: Preserve this type ID!
Reid Spencer060d25d2004-06-29 23:29:38 +00002015
2016 const llvm::PointerType* GVType = GV->getType();
2017 unsigned TypeSlot = getTypeSlot(GVType->getElementType());
Chris Lattner93361992004-01-15 18:45:25 +00002018 if (Constant *CV = getConstantValue(TypeSlot, Slot)) {
Misha Brukman12c29d12003-09-22 23:38:23 +00002019 if (GV->hasInitializer())
Reid Spencer24399722004-07-09 22:21:33 +00002020 error("Global *already* has an initializer?!");
Reid Spencer04cde2c2004-07-04 11:33:49 +00002021 if (Handler) Handler->handleGlobalInitializer(GV,CV);
Chris Lattner93361992004-01-15 18:45:25 +00002022 GV->setInitializer(CV);
Chris Lattner52e20b02003-03-19 20:54:26 +00002023 } else
Reid Spencer24399722004-07-09 22:21:33 +00002024 error("Cannot find initializer value.");
Chris Lattner52e20b02003-03-19 20:54:26 +00002025 }
2026
Reid Spencer060d25d2004-06-29 23:29:38 +00002027 /// Make sure we pulled them all out. If we didn't then there's a declaration
2028 /// but a missing body. That's not allowed.
Misha Brukman12c29d12003-09-22 23:38:23 +00002029 if (!FunctionSignatureList.empty())
Reid Spencer24399722004-07-09 22:21:33 +00002030 error("Function declared, but bytecode stream ended before definition");
Chris Lattner00950542001-06-06 20:29:01 +00002031}
2032
Reid Spencer04cde2c2004-07-04 11:33:49 +00002033/// This function completely parses a bytecode buffer given by the \p Buf
2034/// and \p Length parameters.
Reid Spencer46b002c2004-07-11 17:28:43 +00002035void BytecodeReader::ParseBytecode(BufPtr Buf, unsigned Length,
2036 const std::string &ModuleID,
2037 bool processFunctions) {
Misha Brukmane0dd0d42003-09-23 16:15:29 +00002038
Reid Spencer060d25d2004-06-29 23:29:38 +00002039 try {
2040 At = MemStart = BlockStart = Buf;
2041 MemEnd = BlockEnd = Buf + Length;
Misha Brukmane0dd0d42003-09-23 16:15:29 +00002042
Reid Spencer060d25d2004-06-29 23:29:38 +00002043 // Create the module
2044 TheModule = new Module(ModuleID);
Chris Lattner00950542001-06-06 20:29:01 +00002045
Reid Spencer04cde2c2004-07-04 11:33:49 +00002046 if (Handler) Handler->handleStart(TheModule, Length);
Reid Spencer060d25d2004-06-29 23:29:38 +00002047
2048 // Read and check signature...
2049 unsigned Sig = read_uint();
2050 if (Sig != ('l' | ('l' << 8) | ('v' << 16) | ('m' << 24))) {
Reid Spencer24399722004-07-09 22:21:33 +00002051 error("Invalid bytecode signature: " + utostr(Sig));
Reid Spencer060d25d2004-06-29 23:29:38 +00002052 }
2053
Reid Spencer060d25d2004-06-29 23:29:38 +00002054 // Tell the handler we're starting a module
Reid Spencer04cde2c2004-07-04 11:33:49 +00002055 if (Handler) Handler->handleModuleBegin(ModuleID);
Reid Spencer060d25d2004-06-29 23:29:38 +00002056
Reid Spencerad89bd62004-07-25 18:07:36 +00002057 // Get the module block and size and verify. This is handled specially
2058 // because the module block/size is always written in long format. Other
2059 // blocks are written in short format so the read_block method is used.
Reid Spencer060d25d2004-06-29 23:29:38 +00002060 unsigned Type, Size;
Reid Spencerad89bd62004-07-25 18:07:36 +00002061 Type = read_uint();
2062 Size = read_uint();
2063 if (Type != BytecodeFormat::ModuleBlockID) {
Reid Spencer24399722004-07-09 22:21:33 +00002064 error("Expected Module Block! Type:" + utostr(Type) + ", Size:"
Reid Spencer46b002c2004-07-11 17:28:43 +00002065 + utostr(Size));
Reid Spencer060d25d2004-06-29 23:29:38 +00002066 }
Reid Spencer46b002c2004-07-11 17:28:43 +00002067 if (At + Size != MemEnd) {
Reid Spencer24399722004-07-09 22:21:33 +00002068 error("Invalid Top Level Block Length! Type:" + utostr(Type)
Reid Spencer46b002c2004-07-11 17:28:43 +00002069 + ", Size:" + utostr(Size));
Reid Spencer060d25d2004-06-29 23:29:38 +00002070 }
2071
2072 // Parse the module contents
2073 this->ParseModule();
2074
Reid Spencer060d25d2004-06-29 23:29:38 +00002075 // Check for missing functions
Reid Spencer46b002c2004-07-11 17:28:43 +00002076 if (hasFunctions())
Reid Spencer24399722004-07-09 22:21:33 +00002077 error("Function expected, but bytecode stream ended!");
Reid Spencer060d25d2004-06-29 23:29:38 +00002078
Reid Spencer5c15fe52004-07-05 00:57:50 +00002079 // Process all the function bodies now, if requested
Reid Spencer46b002c2004-07-11 17:28:43 +00002080 if (processFunctions)
Reid Spencer5c15fe52004-07-05 00:57:50 +00002081 ParseAllFunctionBodies();
2082
2083 // Tell the handler we're done with the module
2084 if (Handler)
2085 Handler->handleModuleEnd(ModuleID);
2086
2087 // Tell the handler we're finished the parse
Reid Spencer04cde2c2004-07-04 11:33:49 +00002088 if (Handler) Handler->handleFinish();
Reid Spencer060d25d2004-06-29 23:29:38 +00002089
Reid Spencer46b002c2004-07-11 17:28:43 +00002090 } catch (std::string& errstr) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00002091 if (Handler) Handler->handleError(errstr);
Reid Spencer060d25d2004-06-29 23:29:38 +00002092 freeState();
Chris Lattner2a7b6ba2003-03-06 17:15:19 +00002093 delete TheModule;
2094 TheModule = 0;
Chris Lattnerb0b7c0d2003-09-26 14:44:52 +00002095 throw;
Reid Spencer060d25d2004-06-29 23:29:38 +00002096 } catch (...) {
2097 std::string msg("Unknown Exception Occurred");
Reid Spencer04cde2c2004-07-04 11:33:49 +00002098 if (Handler) Handler->handleError(msg);
Reid Spencer060d25d2004-06-29 23:29:38 +00002099 freeState();
2100 delete TheModule;
2101 TheModule = 0;
2102 throw msg;
Chris Lattner2a7b6ba2003-03-06 17:15:19 +00002103 }
Chris Lattner00950542001-06-06 20:29:01 +00002104}
Reid Spencer060d25d2004-06-29 23:29:38 +00002105
2106//===----------------------------------------------------------------------===//
2107//=== Default Implementations of Handler Methods
2108//===----------------------------------------------------------------------===//
2109
2110BytecodeHandler::~BytecodeHandler() {}
Reid Spencer060d25d2004-06-29 23:29:38 +00002111
2112// vim: sw=2