blob: e9b18e0ceaaa49fc6b75043f90f664b25449caf3 [file] [log] [blame]
Chris Lattnerd6b65252001-10-24 01:15:12 +00001//===- Reader.cpp - Code to read bytecode files ---------------------------===//
John Criswellb576c942003-10-20 19:43:21 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
Chris Lattner00950542001-06-06 20:29:01 +00009//
10// This library implements the functionality defined in llvm/Bytecode/Reader.h
11//
12// Note that this library should be as fast as possible, reentrant, and
13// threadsafe!!
14//
Chris Lattner00950542001-06-06 20:29:01 +000015// TODO: Allow passing in an option to ignore the symbol table
16//
Chris Lattnerd6b65252001-10-24 01:15:12 +000017//===----------------------------------------------------------------------===//
Chris Lattner00950542001-06-06 20:29:01 +000018
Reid Spencer060d25d2004-06-29 23:29:38 +000019#include "Reader.h"
20#include "llvm/Bytecode/BytecodeHandler.h"
21#include "llvm/BasicBlock.h"
Jeff Cohene1337212004-12-20 03:23:46 +000022#include "llvm/Config/alloca.h"
Reid Spencer060d25d2004-06-29 23:29:38 +000023#include "llvm/Constants.h"
Reid Spencer04cde2c2004-07-04 11:33:49 +000024#include "llvm/Instructions.h"
25#include "llvm/SymbolTable.h"
Chris Lattner00950542001-06-06 20:29:01 +000026#include "llvm/Bytecode/Format.h"
Reid Spencer060d25d2004-06-29 23:29:38 +000027#include "llvm/Support/GetElementPtrTypeIterator.h"
Reid Spencer17f52c52004-11-06 23:17:23 +000028#include "llvm/Support/Compressor.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000029#include "llvm/ADT/StringExtras.h"
Reid Spencer060d25d2004-06-29 23:29:38 +000030#include <sstream>
Alkis Evlogimenos20aa4742004-09-03 18:19:51 +000031#include <algorithm>
Chris Lattner29b789b2003-11-19 17:27:18 +000032using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000033
Reid Spencer46b002c2004-07-11 17:28:43 +000034namespace {
35
Reid Spencer060d25d2004-06-29 23:29:38 +000036/// @brief A class for maintaining the slot number definition
Reid Spencer46b002c2004-07-11 17:28:43 +000037/// as a placeholder for the actual definition for forward constants defs.
38class ConstantPlaceHolder : public ConstantExpr {
Reid Spencer46b002c2004-07-11 17:28:43 +000039 ConstantPlaceHolder(); // DO NOT IMPLEMENT
40 void operator=(const ConstantPlaceHolder &); // DO NOT IMPLEMENT
Reid Spencer060d25d2004-06-29 23:29:38 +000041public:
Chris Lattner389bd042004-12-09 06:19:44 +000042 ConstantPlaceHolder(const Type *Ty)
43 : ConstantExpr(Instruction::UserOp1, Constant::getNullValue(Ty), Ty) {}
Reid Spencer060d25d2004-06-29 23:29:38 +000044};
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)
Chris Lattnera79e7cc2004-10-16 18:18:16 +000070 error(std::string("Attempt to read past the end of ") + block_name +
71 " block.");
Reid Spencer060d25d2004-06-29 23:29:38 +000072}
Chris Lattner36392bc2003-10-08 21:18:57 +000073
Reid Spencer04cde2c2004-07-04 11:33:49 +000074/// Align the buffer position to a 32 bit boundary
Reid Spencer060d25d2004-06-29 23:29:38 +000075inline void BytecodeReader::align32() {
Reid Spencer38d54be2004-08-17 07:45:14 +000076 if (hasAlignment) {
77 BufPtr Save = At;
78 At = (const unsigned char *)((unsigned long)(At+3) & (~3UL));
79 if (At > Save)
80 if (Handler) Handler->handleAlignment(At - Save);
81 if (At > BlockEnd)
82 error("Ran out of data while aligning!");
83 }
Reid Spencer060d25d2004-06-29 23:29:38 +000084}
85
Reid Spencer04cde2c2004-07-04 11:33:49 +000086/// Read a whole unsigned integer
Reid Spencer060d25d2004-06-29 23:29:38 +000087inline unsigned BytecodeReader::read_uint() {
88 if (At+4 > BlockEnd)
Reid Spencer24399722004-07-09 22:21:33 +000089 error("Ran out of data reading uint!");
Reid Spencer060d25d2004-06-29 23:29:38 +000090 At += 4;
91 return At[-4] | (At[-3] << 8) | (At[-2] << 16) | (At[-1] << 24);
92}
93
Reid Spencer04cde2c2004-07-04 11:33:49 +000094/// Read a variable-bit-rate encoded unsigned integer
Reid Spencer060d25d2004-06-29 23:29:38 +000095inline unsigned BytecodeReader::read_vbr_uint() {
96 unsigned Shift = 0;
97 unsigned Result = 0;
98 BufPtr Save = At;
99
100 do {
101 if (At == BlockEnd)
Reid Spencer24399722004-07-09 22:21:33 +0000102 error("Ran out of data reading vbr_uint!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000103 Result |= (unsigned)((*At++) & 0x7F) << Shift;
104 Shift += 7;
105 } while (At[-1] & 0x80);
Reid Spencer04cde2c2004-07-04 11:33:49 +0000106 if (Handler) Handler->handleVBR32(At-Save);
Reid Spencer060d25d2004-06-29 23:29:38 +0000107 return Result;
108}
109
Reid Spencer04cde2c2004-07-04 11:33:49 +0000110/// Read a variable-bit-rate encoded unsigned 64-bit integer.
Reid Spencer060d25d2004-06-29 23:29:38 +0000111inline uint64_t BytecodeReader::read_vbr_uint64() {
112 unsigned Shift = 0;
113 uint64_t Result = 0;
114 BufPtr Save = At;
115
116 do {
117 if (At == BlockEnd)
Reid Spencer24399722004-07-09 22:21:33 +0000118 error("Ran out of data reading vbr_uint64!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000119 Result |= (uint64_t)((*At++) & 0x7F) << Shift;
120 Shift += 7;
121 } while (At[-1] & 0x80);
Reid Spencer04cde2c2004-07-04 11:33:49 +0000122 if (Handler) Handler->handleVBR64(At-Save);
Reid Spencer060d25d2004-06-29 23:29:38 +0000123 return Result;
124}
125
Reid Spencer04cde2c2004-07-04 11:33:49 +0000126/// Read a variable-bit-rate encoded signed 64-bit integer.
Reid Spencer060d25d2004-06-29 23:29:38 +0000127inline int64_t BytecodeReader::read_vbr_int64() {
128 uint64_t R = read_vbr_uint64();
129 if (R & 1) {
130 if (R != 1)
131 return -(int64_t)(R >> 1);
132 else // There is no such thing as -0 with integers. "-0" really means
133 // 0x8000000000000000.
134 return 1LL << 63;
135 } else
136 return (int64_t)(R >> 1);
137}
138
Reid Spencer04cde2c2004-07-04 11:33:49 +0000139/// Read a pascal-style string (length followed by text)
Reid Spencer060d25d2004-06-29 23:29:38 +0000140inline std::string BytecodeReader::read_str() {
141 unsigned Size = read_vbr_uint();
142 const unsigned char *OldAt = At;
143 At += Size;
144 if (At > BlockEnd) // Size invalid?
Reid Spencer24399722004-07-09 22:21:33 +0000145 error("Ran out of data reading a string!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000146 return std::string((char*)OldAt, Size);
147}
148
Reid Spencer04cde2c2004-07-04 11:33:49 +0000149/// Read an arbitrary block of data
Reid Spencer060d25d2004-06-29 23:29:38 +0000150inline void BytecodeReader::read_data(void *Ptr, void *End) {
151 unsigned char *Start = (unsigned char *)Ptr;
152 unsigned Amount = (unsigned char *)End - Start;
153 if (At+Amount > BlockEnd)
Reid Spencer24399722004-07-09 22:21:33 +0000154 error("Ran out of data!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000155 std::copy(At, At+Amount, Start);
156 At += Amount;
157}
158
Reid Spencer46b002c2004-07-11 17:28:43 +0000159/// Read a float value in little-endian order
160inline void BytecodeReader::read_float(float& FloatVal) {
Reid Spencerada16182004-07-25 21:36:26 +0000161 /// FIXME: This isn't optimal, it has size problems on some platforms
162 /// where FP is not IEEE.
163 union {
164 float f;
165 uint32_t i;
166 } FloatUnion;
167 FloatUnion.i = At[0] | (At[1] << 8) | (At[2] << 16) | (At[3] << 24);
168 At+=sizeof(uint32_t);
169 FloatVal = FloatUnion.f;
Reid Spencer46b002c2004-07-11 17:28:43 +0000170}
171
172/// Read a double value in little-endian order
173inline void BytecodeReader::read_double(double& DoubleVal) {
Reid Spencerada16182004-07-25 21:36:26 +0000174 /// FIXME: This isn't optimal, it has size problems on some platforms
175 /// where FP is not IEEE.
176 union {
177 double d;
178 uint64_t i;
179 } DoubleUnion;
Chris Lattner1d785162004-07-25 23:15:44 +0000180 DoubleUnion.i = (uint64_t(At[0]) << 0) | (uint64_t(At[1]) << 8) |
181 (uint64_t(At[2]) << 16) | (uint64_t(At[3]) << 24) |
Reid Spencerada16182004-07-25 21:36:26 +0000182 (uint64_t(At[4]) << 32) | (uint64_t(At[5]) << 40) |
183 (uint64_t(At[6]) << 48) | (uint64_t(At[7]) << 56);
184 At+=sizeof(uint64_t);
185 DoubleVal = DoubleUnion.d;
Reid Spencer46b002c2004-07-11 17:28:43 +0000186}
187
Reid Spencer04cde2c2004-07-04 11:33:49 +0000188/// Read a block header and obtain its type and size
Reid Spencer060d25d2004-06-29 23:29:38 +0000189inline void BytecodeReader::read_block(unsigned &Type, unsigned &Size) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000190 if ( hasLongBlockHeaders ) {
191 Type = read_uint();
192 Size = read_uint();
193 switch (Type) {
194 case BytecodeFormat::Reserved_DoNotUse :
195 error("Reserved_DoNotUse used as Module Type?");
Reid Spencer5b472d92004-08-21 20:49:23 +0000196 Type = BytecodeFormat::ModuleBlockID; break;
Reid Spencerad89bd62004-07-25 18:07:36 +0000197 case BytecodeFormat::Module:
198 Type = BytecodeFormat::ModuleBlockID; break;
199 case BytecodeFormat::Function:
200 Type = BytecodeFormat::FunctionBlockID; break;
201 case BytecodeFormat::ConstantPool:
202 Type = BytecodeFormat::ConstantPoolBlockID; break;
203 case BytecodeFormat::SymbolTable:
204 Type = BytecodeFormat::SymbolTableBlockID; break;
205 case BytecodeFormat::ModuleGlobalInfo:
206 Type = BytecodeFormat::ModuleGlobalInfoBlockID; break;
207 case BytecodeFormat::GlobalTypePlane:
208 Type = BytecodeFormat::GlobalTypePlaneBlockID; break;
209 case BytecodeFormat::InstructionList:
210 Type = BytecodeFormat::InstructionListBlockID; break;
211 case BytecodeFormat::CompactionTable:
212 Type = BytecodeFormat::CompactionTableBlockID; break;
213 case BytecodeFormat::BasicBlock:
214 /// This block type isn't used after version 1.1. However, we have to
215 /// still allow the value in case this is an old bc format file.
216 /// We just let its value creep thru.
217 break;
218 default:
Reid Spencer5b472d92004-08-21 20:49:23 +0000219 error("Invalid block id found: " + utostr(Type));
Reid Spencerad89bd62004-07-25 18:07:36 +0000220 break;
221 }
222 } else {
223 Size = read_uint();
224 Type = Size & 0x1F; // mask low order five bits
225 Size >>= 5; // get rid of five low order bits, leaving high 27
226 }
Reid Spencer060d25d2004-06-29 23:29:38 +0000227 BlockStart = At;
Reid Spencer46b002c2004-07-11 17:28:43 +0000228 if (At + Size > BlockEnd)
Reid Spencer24399722004-07-09 22:21:33 +0000229 error("Attempt to size a block past end of memory");
Reid Spencer060d25d2004-06-29 23:29:38 +0000230 BlockEnd = At + Size;
Reid Spencer46b002c2004-07-11 17:28:43 +0000231 if (Handler) Handler->handleBlock(Type, BlockStart, Size);
Reid Spencer04cde2c2004-07-04 11:33:49 +0000232}
233
234
235/// In LLVM 1.2 and before, Types were derived from Value and so they were
236/// written as part of the type planes along with any other Value. In LLVM
237/// 1.3 this changed so that Type does not derive from Value. Consequently,
238/// the BytecodeReader's containers for Values can't contain Types because
239/// there's no inheritance relationship. This means that the "Type Type"
240/// plane is defunct along with the Type::TypeTyID TypeID. In LLVM 1.3
241/// whenever a bytecode construct must have both types and values together,
242/// the types are always read/written first and then the Values. Furthermore
243/// since Type::TypeTyID no longer exists, its value (12) now corresponds to
244/// Type::LabelTyID. In order to overcome this we must "sanitize" all the
245/// type TypeIDs we encounter. For LLVM 1.3 bytecode files, there's no change.
246/// For LLVM 1.2 and before, this function will decrement the type id by
247/// one to account for the missing Type::TypeTyID enumerator if the value is
248/// larger than 12 (Type::LabelTyID). If the value is exactly 12, then this
249/// function returns true, otherwise false. This helps detect situations
250/// where the pre 1.3 bytecode is indicating that what follows is a type.
251/// @returns true iff type id corresponds to pre 1.3 "type type"
Reid Spencer46b002c2004-07-11 17:28:43 +0000252inline bool BytecodeReader::sanitizeTypeId(unsigned &TypeId) {
253 if (hasTypeDerivedFromValue) { /// do nothing if 1.3 or later
254 if (TypeId == Type::LabelTyID) {
Reid Spencer04cde2c2004-07-04 11:33:49 +0000255 TypeId = Type::VoidTyID; // sanitize it
256 return true; // indicate we got TypeTyID in pre 1.3 bytecode
Reid Spencer46b002c2004-07-11 17:28:43 +0000257 } else if (TypeId > Type::LabelTyID)
Reid Spencer04cde2c2004-07-04 11:33:49 +0000258 --TypeId; // shift all planes down because type type plane is missing
259 }
260 return false;
261}
262
263/// Reads a vbr uint to read in a type id and does the necessary
264/// conversion on it by calling sanitizeTypeId.
265/// @returns true iff \p TypeId read corresponds to a pre 1.3 "type type"
266/// @see sanitizeTypeId
267inline bool BytecodeReader::read_typeid(unsigned &TypeId) {
268 TypeId = read_vbr_uint();
Reid Spencerad89bd62004-07-25 18:07:36 +0000269 if ( !has32BitTypes )
270 if ( TypeId == 0x00FFFFFF )
271 TypeId = read_vbr_uint();
Reid Spencer04cde2c2004-07-04 11:33:49 +0000272 return sanitizeTypeId(TypeId);
Reid Spencer060d25d2004-06-29 23:29:38 +0000273}
274
275//===----------------------------------------------------------------------===//
276// IR Lookup Methods
277//===----------------------------------------------------------------------===//
278
Reid Spencer04cde2c2004-07-04 11:33:49 +0000279/// Determine if a type id has an implicit null value
Reid Spencer46b002c2004-07-11 17:28:43 +0000280inline bool BytecodeReader::hasImplicitNull(unsigned TyID) {
Reid Spencer060d25d2004-06-29 23:29:38 +0000281 if (!hasExplicitPrimitiveZeros)
Reid Spencer04cde2c2004-07-04 11:33:49 +0000282 return TyID != Type::LabelTyID && TyID != Type::VoidTyID;
Reid Spencer060d25d2004-06-29 23:29:38 +0000283 return TyID >= Type::FirstDerivedTyID;
284}
285
Reid Spencer04cde2c2004-07-04 11:33:49 +0000286/// Obtain a type given a typeid and account for things like compaction tables,
287/// function level vs module level, and the offsetting for the primitive types.
Reid Spencer060d25d2004-06-29 23:29:38 +0000288const Type *BytecodeReader::getType(unsigned ID) {
Chris Lattner89e02532004-01-18 21:08:15 +0000289 if (ID < Type::FirstDerivedTyID)
Chris Lattnerf70c22b2004-06-17 18:19:28 +0000290 if (const Type *T = Type::getPrimitiveType((Type::TypeID)ID))
Chris Lattner927b1852003-10-09 20:22:47 +0000291 return T; // Asked for a primitive type...
Chris Lattner36392bc2003-10-08 21:18:57 +0000292
293 // Otherwise, derived types need offset...
Chris Lattner89e02532004-01-18 21:08:15 +0000294 ID -= Type::FirstDerivedTyID;
295
Reid Spencer060d25d2004-06-29 23:29:38 +0000296 if (!CompactionTypes.empty()) {
297 if (ID >= CompactionTypes.size())
Reid Spencer24399722004-07-09 22:21:33 +0000298 error("Type ID out of range for compaction table!");
Chris Lattner45b5dd22004-08-03 23:41:28 +0000299 return CompactionTypes[ID].first;
Chris Lattner89e02532004-01-18 21:08:15 +0000300 }
Chris Lattner36392bc2003-10-08 21:18:57 +0000301
302 // Is it a module-level type?
Reid Spencer46b002c2004-07-11 17:28:43 +0000303 if (ID < ModuleTypes.size())
304 return ModuleTypes[ID].get();
Chris Lattner36392bc2003-10-08 21:18:57 +0000305
Reid Spencer46b002c2004-07-11 17:28:43 +0000306 // Nope, is it a function-level type?
307 ID -= ModuleTypes.size();
308 if (ID < FunctionTypes.size())
309 return FunctionTypes[ID].get();
Chris Lattner36392bc2003-10-08 21:18:57 +0000310
Reid Spencer46b002c2004-07-11 17:28:43 +0000311 error("Illegal type reference!");
312 return Type::VoidTy;
Chris Lattner00950542001-06-06 20:29:01 +0000313}
314
Reid Spencer04cde2c2004-07-04 11:33:49 +0000315/// Get a sanitized type id. This just makes sure that the \p ID
316/// is both sanitized and not the "type type" of pre-1.3 bytecode.
317/// @see sanitizeTypeId
318inline const Type* BytecodeReader::getSanitizedType(unsigned& ID) {
Reid Spencer46b002c2004-07-11 17:28:43 +0000319 if (sanitizeTypeId(ID))
Reid Spencer24399722004-07-09 22:21:33 +0000320 error("Invalid type id encountered");
Reid Spencer04cde2c2004-07-04 11:33:49 +0000321 return getType(ID);
322}
323
324/// This method just saves some coding. It uses read_typeid to read
Reid Spencer24399722004-07-09 22:21:33 +0000325/// in a sanitized type id, errors that its not the type type, and
Reid Spencer04cde2c2004-07-04 11:33:49 +0000326/// then calls getType to return the type value.
327inline const Type* BytecodeReader::readSanitizedType() {
328 unsigned ID;
Reid Spencer46b002c2004-07-11 17:28:43 +0000329 if (read_typeid(ID))
330 error("Invalid type id encountered");
Reid Spencer04cde2c2004-07-04 11:33:49 +0000331 return getType(ID);
332}
333
334/// Get the slot number associated with a type accounting for primitive
335/// types, compaction tables, and function level vs module level.
Reid Spencer060d25d2004-06-29 23:29:38 +0000336unsigned BytecodeReader::getTypeSlot(const Type *Ty) {
337 if (Ty->isPrimitiveType())
338 return Ty->getTypeID();
339
340 // Scan the compaction table for the type if needed.
341 if (!CompactionTypes.empty()) {
Chris Lattner45b5dd22004-08-03 23:41:28 +0000342 for (unsigned i = 0, e = CompactionTypes.size(); i != e; ++i)
343 if (CompactionTypes[i].first == Ty)
344 return Type::FirstDerivedTyID + i;
Reid Spencer060d25d2004-06-29 23:29:38 +0000345
Chris Lattner45b5dd22004-08-03 23:41:28 +0000346 error("Couldn't find type specified in compaction table!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000347 }
348
349 // Check the function level types first...
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000350 TypeListTy::iterator I = std::find(FunctionTypes.begin(),
351 FunctionTypes.end(), Ty);
Reid Spencer060d25d2004-06-29 23:29:38 +0000352
353 if (I != FunctionTypes.end())
Reid Spencer46b002c2004-07-11 17:28:43 +0000354 return Type::FirstDerivedTyID + ModuleTypes.size() +
355 (&*I - &FunctionTypes[0]);
Reid Spencer060d25d2004-06-29 23:29:38 +0000356
357 // Check the module level types now...
Reid Spencer2da5c3d2004-09-15 17:06:42 +0000358 I = std::find(ModuleTypes.begin(), ModuleTypes.end(), Ty);
Reid Spencer060d25d2004-06-29 23:29:38 +0000359 if (I == ModuleTypes.end())
Reid Spencer24399722004-07-09 22:21:33 +0000360 error("Didn't find type in ModuleTypes.");
Reid Spencer060d25d2004-06-29 23:29:38 +0000361 return Type::FirstDerivedTyID + (&*I - &ModuleTypes[0]);
Chris Lattner80b97342004-01-17 23:25:43 +0000362}
363
Reid Spencer04cde2c2004-07-04 11:33:49 +0000364/// This is just like getType, but when a compaction table is in use, it is
365/// ignored. It also ignores function level types.
366/// @see getType
Reid Spencer060d25d2004-06-29 23:29:38 +0000367const Type *BytecodeReader::getGlobalTableType(unsigned Slot) {
368 if (Slot < Type::FirstDerivedTyID) {
369 const Type *Ty = Type::getPrimitiveType((Type::TypeID)Slot);
Reid Spencer46b002c2004-07-11 17:28:43 +0000370 if (!Ty)
Reid Spencer24399722004-07-09 22:21:33 +0000371 error("Not a primitive type ID?");
Reid Spencer060d25d2004-06-29 23:29:38 +0000372 return Ty;
373 }
374 Slot -= Type::FirstDerivedTyID;
375 if (Slot >= ModuleTypes.size())
Reid Spencer24399722004-07-09 22:21:33 +0000376 error("Illegal compaction table type reference!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000377 return ModuleTypes[Slot];
Chris Lattner52e20b02003-03-19 20:54:26 +0000378}
379
Reid Spencer04cde2c2004-07-04 11:33:49 +0000380/// This is just like getTypeSlot, but when a compaction table is in use, it
381/// is ignored. It also ignores function level types.
Reid Spencer060d25d2004-06-29 23:29:38 +0000382unsigned BytecodeReader::getGlobalTableTypeSlot(const Type *Ty) {
383 if (Ty->isPrimitiveType())
384 return Ty->getTypeID();
Reid Spencer2da5c3d2004-09-15 17:06:42 +0000385 TypeListTy::iterator I = std::find(ModuleTypes.begin(),
Reid Spencer04cde2c2004-07-04 11:33:49 +0000386 ModuleTypes.end(), Ty);
Reid Spencer060d25d2004-06-29 23:29:38 +0000387 if (I == ModuleTypes.end())
Reid Spencer24399722004-07-09 22:21:33 +0000388 error("Didn't find type in ModuleTypes.");
Reid Spencer060d25d2004-06-29 23:29:38 +0000389 return Type::FirstDerivedTyID + (&*I - &ModuleTypes[0]);
390}
391
Reid Spencer04cde2c2004-07-04 11:33:49 +0000392/// Retrieve a value of a given type and slot number, possibly creating
393/// it if it doesn't already exist.
Reid Spencer060d25d2004-06-29 23:29:38 +0000394Value * BytecodeReader::getValue(unsigned type, unsigned oNum, bool Create) {
Chris Lattner4ee8ef22003-10-08 22:52:54 +0000395 assert(type != Type::LabelTyID && "getValue() cannot get blocks!");
Chris Lattner00950542001-06-06 20:29:01 +0000396 unsigned Num = oNum;
Chris Lattner00950542001-06-06 20:29:01 +0000397
Chris Lattner89e02532004-01-18 21:08:15 +0000398 // If there is a compaction table active, it defines the low-level numbers.
399 // If not, the module values define the low-level numbers.
Reid Spencer060d25d2004-06-29 23:29:38 +0000400 if (CompactionValues.size() > type && !CompactionValues[type].empty()) {
401 if (Num < CompactionValues[type].size())
402 return CompactionValues[type][Num];
403 Num -= CompactionValues[type].size();
Chris Lattner89e02532004-01-18 21:08:15 +0000404 } else {
Reid Spencer060d25d2004-06-29 23:29:38 +0000405 // By default, the global type id is the type id passed in
Chris Lattner52f86d62004-01-20 00:54:06 +0000406 unsigned GlobalTyID = type;
Reid Spencer060d25d2004-06-29 23:29:38 +0000407
Chris Lattner45b5dd22004-08-03 23:41:28 +0000408 // If the type plane was compactified, figure out the global type ID by
409 // adding the derived type ids and the distance.
410 if (!CompactionTypes.empty() && type >= Type::FirstDerivedTyID)
411 GlobalTyID = CompactionTypes[type-Type::FirstDerivedTyID].second;
Chris Lattner00950542001-06-06 20:29:01 +0000412
Reid Spencer060d25d2004-06-29 23:29:38 +0000413 if (hasImplicitNull(GlobalTyID)) {
Chris Lattner89e02532004-01-18 21:08:15 +0000414 if (Num == 0)
Reid Spencer04cde2c2004-07-04 11:33:49 +0000415 return Constant::getNullValue(getType(type));
Chris Lattner89e02532004-01-18 21:08:15 +0000416 --Num;
417 }
418
Chris Lattner52f86d62004-01-20 00:54:06 +0000419 if (GlobalTyID < ModuleValues.size() && ModuleValues[GlobalTyID]) {
420 if (Num < ModuleValues[GlobalTyID]->size())
Reid Spencer04cde2c2004-07-04 11:33:49 +0000421 return ModuleValues[GlobalTyID]->getOperand(Num);
Chris Lattner52f86d62004-01-20 00:54:06 +0000422 Num -= ModuleValues[GlobalTyID]->size();
Chris Lattner89e02532004-01-18 21:08:15 +0000423 }
Chris Lattner52e20b02003-03-19 20:54:26 +0000424 }
425
Reid Spencer060d25d2004-06-29 23:29:38 +0000426 if (FunctionValues.size() > type &&
427 FunctionValues[type] &&
428 Num < FunctionValues[type]->size())
429 return FunctionValues[type]->getOperand(Num);
Chris Lattner00950542001-06-06 20:29:01 +0000430
Chris Lattner74734132002-08-17 22:01:27 +0000431 if (!Create) return 0; // Do not create a placeholder?
Chris Lattner00950542001-06-06 20:29:01 +0000432
Reid Spencer551ccae2004-09-01 22:55:40 +0000433 // Did we already create a place holder?
Chris Lattner8eb10ce2003-10-09 06:05:40 +0000434 std::pair<unsigned,unsigned> KeyValue(type, oNum);
Reid Spencer060d25d2004-06-29 23:29:38 +0000435 ForwardReferenceMap::iterator I = ForwardReferences.lower_bound(KeyValue);
Chris Lattner8eb10ce2003-10-09 06:05:40 +0000436 if (I != ForwardReferences.end() && I->first == KeyValue)
437 return I->second; // We have already created this placeholder
438
Reid Spencer551ccae2004-09-01 22:55:40 +0000439 // If the type exists (it should)
440 if (const Type* Ty = getType(type)) {
441 // Create the place holder
442 Value *Val = new Argument(Ty);
443 ForwardReferences.insert(I, std::make_pair(KeyValue, Val));
444 return Val;
445 }
446 throw "Can't create placeholder for value of type slot #" + utostr(type);
Chris Lattner00950542001-06-06 20:29:01 +0000447}
448
Reid Spencer04cde2c2004-07-04 11:33:49 +0000449/// This is just like getValue, but when a compaction table is in use, it
450/// is ignored. Also, no forward references or other fancy features are
451/// supported.
Chris Lattner2c6c14d2004-08-04 00:19:23 +0000452Value* BytecodeReader::getGlobalTableValue(unsigned TyID, unsigned SlotNo) {
453 if (SlotNo == 0)
454 return Constant::getNullValue(getType(TyID));
455
456 if (!CompactionTypes.empty() && TyID >= Type::FirstDerivedTyID) {
457 TyID -= Type::FirstDerivedTyID;
458 if (TyID >= CompactionTypes.size())
459 error("Type ID out of range for compaction table!");
460 TyID = CompactionTypes[TyID].second;
Reid Spencer060d25d2004-06-29 23:29:38 +0000461 }
462
Chris Lattner2c6c14d2004-08-04 00:19:23 +0000463 --SlotNo;
464
Reid Spencer060d25d2004-06-29 23:29:38 +0000465 if (TyID >= ModuleValues.size() || ModuleValues[TyID] == 0 ||
466 SlotNo >= ModuleValues[TyID]->size()) {
Chris Lattner2c6c14d2004-08-04 00:19:23 +0000467 if (TyID >= ModuleValues.size() || ModuleValues[TyID] == 0)
468 error("Corrupt compaction table entry!"
469 + utostr(TyID) + ", " + utostr(SlotNo) + ": "
470 + utostr(ModuleValues.size()));
471 else
472 error("Corrupt compaction table entry!"
473 + utostr(TyID) + ", " + utostr(SlotNo) + ": "
474 + utostr(ModuleValues.size()) + ", "
Reid Spencer9a7e0c52004-08-04 22:56:46 +0000475 + utohexstr(reinterpret_cast<uint64_t>(((void*)ModuleValues[TyID])))
476 + ", "
Chris Lattner2c6c14d2004-08-04 00:19:23 +0000477 + utostr(ModuleValues[TyID]->size()));
Reid Spencer060d25d2004-06-29 23:29:38 +0000478 }
479 return ModuleValues[TyID]->getOperand(SlotNo);
480}
481
Reid Spencer04cde2c2004-07-04 11:33:49 +0000482/// Just like getValue, except that it returns a null pointer
483/// only on error. It always returns a constant (meaning that if the value is
484/// defined, but is not a constant, that is an error). If the specified
485/// constant hasn't been parsed yet, a placeholder is defined and used.
486/// Later, after the real value is parsed, the placeholder is eliminated.
Reid Spencer060d25d2004-06-29 23:29:38 +0000487Constant* BytecodeReader::getConstantValue(unsigned TypeSlot, unsigned Slot) {
488 if (Value *V = getValue(TypeSlot, Slot, false))
489 if (Constant *C = dyn_cast<Constant>(V))
490 return C; // If we already have the value parsed, just return it
Reid Spencer060d25d2004-06-29 23:29:38 +0000491 else
Reid Spencera86037e2004-07-18 00:12:03 +0000492 error("Value for slot " + utostr(Slot) +
493 " is expected to be a constant!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000494
Chris Lattner389bd042004-12-09 06:19:44 +0000495 std::pair<unsigned, unsigned> Key(TypeSlot, Slot);
Reid Spencer060d25d2004-06-29 23:29:38 +0000496 ConstantRefsType::iterator I = ConstantFwdRefs.lower_bound(Key);
497
498 if (I != ConstantFwdRefs.end() && I->first == Key) {
499 return I->second;
500 } else {
501 // Create a placeholder for the constant reference and
502 // keep track of the fact that we have a forward ref to recycle it
Chris Lattner389bd042004-12-09 06:19:44 +0000503 Constant *C = new ConstantPlaceHolder(getType(TypeSlot));
Reid Spencer060d25d2004-06-29 23:29:38 +0000504
505 // Keep track of the fact that we have a forward ref to recycle it
506 ConstantFwdRefs.insert(I, std::make_pair(Key, C));
507 return C;
508 }
509}
510
511//===----------------------------------------------------------------------===//
512// IR Construction Methods
513//===----------------------------------------------------------------------===//
514
Reid Spencer04cde2c2004-07-04 11:33:49 +0000515/// As values are created, they are inserted into the appropriate place
516/// with this method. The ValueTable argument must be one of ModuleValues
517/// or FunctionValues data members of this class.
Reid Spencer46b002c2004-07-11 17:28:43 +0000518unsigned BytecodeReader::insertValue(Value *Val, unsigned type,
519 ValueTable &ValueTab) {
Reid Spencer060d25d2004-06-29 23:29:38 +0000520 assert((!isa<Constant>(Val) || !cast<Constant>(Val)->isNullValue()) ||
Reid Spencer04cde2c2004-07-04 11:33:49 +0000521 !hasImplicitNull(type) &&
522 "Cannot read null values from bytecode!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000523
524 if (ValueTab.size() <= type)
525 ValueTab.resize(type+1);
526
527 if (!ValueTab[type]) ValueTab[type] = new ValueList();
528
529 ValueTab[type]->push_back(Val);
530
531 bool HasOffset = hasImplicitNull(type);
532 return ValueTab[type]->size()-1 + HasOffset;
533}
534
Reid Spencer04cde2c2004-07-04 11:33:49 +0000535/// Insert the arguments of a function as new values in the reader.
Reid Spencer46b002c2004-07-11 17:28:43 +0000536void BytecodeReader::insertArguments(Function* F) {
Reid Spencer060d25d2004-06-29 23:29:38 +0000537 const FunctionType *FT = F->getFunctionType();
538 Function::aiterator AI = F->abegin();
539 for (FunctionType::param_iterator It = FT->param_begin();
540 It != FT->param_end(); ++It, ++AI)
541 insertValue(AI, getTypeSlot(AI->getType()), FunctionValues);
542}
543
544//===----------------------------------------------------------------------===//
545// Bytecode Parsing Methods
546//===----------------------------------------------------------------------===//
547
Reid Spencer04cde2c2004-07-04 11:33:49 +0000548/// This method parses a single instruction. The instruction is
549/// inserted at the end of the \p BB provided. The arguments of
Misha Brukman44666b12004-09-28 16:57:46 +0000550/// the instruction are provided in the \p Oprnds vector.
Reid Spencer060d25d2004-06-29 23:29:38 +0000551void BytecodeReader::ParseInstruction(std::vector<unsigned> &Oprnds,
Reid Spencer46b002c2004-07-11 17:28:43 +0000552 BasicBlock* BB) {
Reid Spencer060d25d2004-06-29 23:29:38 +0000553 BufPtr SaveAt = At;
554
555 // Clear instruction data
556 Oprnds.clear();
557 unsigned iType = 0;
558 unsigned Opcode = 0;
559 unsigned Op = read_uint();
560
561 // bits Instruction format: Common to all formats
562 // --------------------------
563 // 01-00: Opcode type, fixed to 1.
564 // 07-02: Opcode
565 Opcode = (Op >> 2) & 63;
566 Oprnds.resize((Op >> 0) & 03);
567
568 // Extract the operands
569 switch (Oprnds.size()) {
570 case 1:
571 // bits Instruction format:
572 // --------------------------
573 // 19-08: Resulting type plane
574 // 31-20: Operand #1 (if set to (2^12-1), then zero operands)
575 //
576 iType = (Op >> 8) & 4095;
577 Oprnds[0] = (Op >> 20) & 4095;
578 if (Oprnds[0] == 4095) // Handle special encoding for 0 operands...
579 Oprnds.resize(0);
580 break;
581 case 2:
582 // bits Instruction format:
583 // --------------------------
584 // 15-08: Resulting type plane
585 // 23-16: Operand #1
586 // 31-24: Operand #2
587 //
588 iType = (Op >> 8) & 255;
589 Oprnds[0] = (Op >> 16) & 255;
590 Oprnds[1] = (Op >> 24) & 255;
591 break;
592 case 3:
593 // bits Instruction format:
594 // --------------------------
595 // 13-08: Resulting type plane
596 // 19-14: Operand #1
597 // 25-20: Operand #2
598 // 31-26: Operand #3
599 //
600 iType = (Op >> 8) & 63;
601 Oprnds[0] = (Op >> 14) & 63;
602 Oprnds[1] = (Op >> 20) & 63;
603 Oprnds[2] = (Op >> 26) & 63;
604 break;
605 case 0:
606 At -= 4; // Hrm, try this again...
607 Opcode = read_vbr_uint();
608 Opcode >>= 2;
609 iType = read_vbr_uint();
610
611 unsigned NumOprnds = read_vbr_uint();
612 Oprnds.resize(NumOprnds);
613
614 if (NumOprnds == 0)
Reid Spencer24399722004-07-09 22:21:33 +0000615 error("Zero-argument instruction found; this is invalid.");
Reid Spencer060d25d2004-06-29 23:29:38 +0000616
617 for (unsigned i = 0; i != NumOprnds; ++i)
618 Oprnds[i] = read_vbr_uint();
619 align32();
620 break;
621 }
622
Reid Spencer04cde2c2004-07-04 11:33:49 +0000623 const Type *InstTy = getSanitizedType(iType);
Reid Spencer060d25d2004-06-29 23:29:38 +0000624
Reid Spencer46b002c2004-07-11 17:28:43 +0000625 // We have enough info to inform the handler now.
Reid Spencer04cde2c2004-07-04 11:33:49 +0000626 if (Handler) Handler->handleInstruction(Opcode, InstTy, Oprnds, At-SaveAt);
Reid Spencer060d25d2004-06-29 23:29:38 +0000627
628 // Declare the resulting instruction we'll build.
629 Instruction *Result = 0;
630
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000631 // If this is a bytecode format that did not include the unreachable
632 // instruction, bump up all opcodes numbers to make space.
633 if (hasNoUnreachableInst) {
634 if (Opcode >= Instruction::Unreachable &&
635 Opcode < 62) {
636 ++Opcode;
637 }
638 }
639
Reid Spencer060d25d2004-06-29 23:29:38 +0000640 // Handle binary operators
641 if (Opcode >= Instruction::BinaryOpsBegin &&
642 Opcode < Instruction::BinaryOpsEnd && Oprnds.size() == 2)
643 Result = BinaryOperator::create((Instruction::BinaryOps)Opcode,
644 getValue(iType, Oprnds[0]),
645 getValue(iType, Oprnds[1]));
646
647 switch (Opcode) {
648 default:
Reid Spencer04cde2c2004-07-04 11:33:49 +0000649 if (Result == 0)
Reid Spencer24399722004-07-09 22:21:33 +0000650 error("Illegal instruction read!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000651 break;
652 case Instruction::VAArg:
Reid Spencer04cde2c2004-07-04 11:33:49 +0000653 Result = new VAArgInst(getValue(iType, Oprnds[0]),
Reid Spencer46b002c2004-07-11 17:28:43 +0000654 getSanitizedType(Oprnds[1]));
Reid Spencer060d25d2004-06-29 23:29:38 +0000655 break;
656 case Instruction::VANext:
Reid Spencer04cde2c2004-07-04 11:33:49 +0000657 Result = new VANextInst(getValue(iType, Oprnds[0]),
Reid Spencer46b002c2004-07-11 17:28:43 +0000658 getSanitizedType(Oprnds[1]));
Reid Spencer060d25d2004-06-29 23:29:38 +0000659 break;
660 case Instruction::Cast:
Reid Spencer04cde2c2004-07-04 11:33:49 +0000661 Result = new CastInst(getValue(iType, Oprnds[0]),
Reid Spencer46b002c2004-07-11 17:28:43 +0000662 getSanitizedType(Oprnds[1]));
Reid Spencer060d25d2004-06-29 23:29:38 +0000663 break;
664 case Instruction::Select:
665 Result = new SelectInst(getValue(Type::BoolTyID, Oprnds[0]),
666 getValue(iType, Oprnds[1]),
667 getValue(iType, Oprnds[2]));
668 break;
669 case Instruction::PHI: {
670 if (Oprnds.size() == 0 || (Oprnds.size() & 1))
Reid Spencer24399722004-07-09 22:21:33 +0000671 error("Invalid phi node encountered!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000672
673 PHINode *PN = new PHINode(InstTy);
674 PN->op_reserve(Oprnds.size());
675 for (unsigned i = 0, e = Oprnds.size(); i != e; i += 2)
676 PN->addIncoming(getValue(iType, Oprnds[i]), getBasicBlock(Oprnds[i+1]));
677 Result = PN;
678 break;
679 }
680
681 case Instruction::Shl:
682 case Instruction::Shr:
683 Result = new ShiftInst((Instruction::OtherOps)Opcode,
684 getValue(iType, Oprnds[0]),
685 getValue(Type::UByteTyID, Oprnds[1]));
686 break;
687 case Instruction::Ret:
688 if (Oprnds.size() == 0)
689 Result = new ReturnInst();
690 else if (Oprnds.size() == 1)
691 Result = new ReturnInst(getValue(iType, Oprnds[0]));
692 else
Reid Spencer24399722004-07-09 22:21:33 +0000693 error("Unrecognized instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000694 break;
695
696 case Instruction::Br:
697 if (Oprnds.size() == 1)
698 Result = new BranchInst(getBasicBlock(Oprnds[0]));
699 else if (Oprnds.size() == 3)
700 Result = new BranchInst(getBasicBlock(Oprnds[0]),
Reid Spencer04cde2c2004-07-04 11:33:49 +0000701 getBasicBlock(Oprnds[1]), getValue(Type::BoolTyID , Oprnds[2]));
Reid Spencer060d25d2004-06-29 23:29:38 +0000702 else
Reid Spencer24399722004-07-09 22:21:33 +0000703 error("Invalid number of operands for a 'br' instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000704 break;
705 case Instruction::Switch: {
706 if (Oprnds.size() & 1)
Reid Spencer24399722004-07-09 22:21:33 +0000707 error("Switch statement with odd number of arguments!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000708
709 SwitchInst *I = new SwitchInst(getValue(iType, Oprnds[0]),
710 getBasicBlock(Oprnds[1]));
711 for (unsigned i = 2, e = Oprnds.size(); i != e; i += 2)
712 I->addCase(cast<Constant>(getValue(iType, Oprnds[i])),
713 getBasicBlock(Oprnds[i+1]));
714 Result = I;
715 break;
716 }
717
718 case Instruction::Call: {
719 if (Oprnds.size() == 0)
Reid Spencer24399722004-07-09 22:21:33 +0000720 error("Invalid call instruction encountered!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000721
722 Value *F = getValue(iType, Oprnds[0]);
723
724 // Check to make sure we have a pointer to function type
725 const PointerType *PTy = dyn_cast<PointerType>(F->getType());
Reid Spencer24399722004-07-09 22:21:33 +0000726 if (PTy == 0) error("Call to non function pointer value!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000727 const FunctionType *FTy = dyn_cast<FunctionType>(PTy->getElementType());
Reid Spencer24399722004-07-09 22:21:33 +0000728 if (FTy == 0) error("Call to non function pointer value!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000729
730 std::vector<Value *> Params;
731 if (!FTy->isVarArg()) {
732 FunctionType::param_iterator It = FTy->param_begin();
733
734 for (unsigned i = 1, e = Oprnds.size(); i != e; ++i) {
735 if (It == FTy->param_end())
Reid Spencer24399722004-07-09 22:21:33 +0000736 error("Invalid call instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000737 Params.push_back(getValue(getTypeSlot(*It++), Oprnds[i]));
738 }
739 if (It != FTy->param_end())
Reid Spencer24399722004-07-09 22:21:33 +0000740 error("Invalid call instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000741 } else {
742 Oprnds.erase(Oprnds.begin(), Oprnds.begin()+1);
743
744 unsigned FirstVariableOperand;
745 if (Oprnds.size() < FTy->getNumParams())
Reid Spencer24399722004-07-09 22:21:33 +0000746 error("Call instruction missing operands!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000747
748 // Read all of the fixed arguments
749 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
750 Params.push_back(getValue(getTypeSlot(FTy->getParamType(i)),Oprnds[i]));
751
752 FirstVariableOperand = FTy->getNumParams();
753
Chris Lattner4a242b32004-10-14 01:39:18 +0000754 if ((Oprnds.size()-FirstVariableOperand) & 1)
755 error("Invalid call instruction!"); // Must be pairs of type/value
Reid Spencer060d25d2004-06-29 23:29:38 +0000756
757 for (unsigned i = FirstVariableOperand, e = Oprnds.size();
Reid Spencer04cde2c2004-07-04 11:33:49 +0000758 i != e; i += 2)
Reid Spencer060d25d2004-06-29 23:29:38 +0000759 Params.push_back(getValue(Oprnds[i], Oprnds[i+1]));
760 }
761
762 Result = new CallInst(F, Params);
763 break;
764 }
765 case Instruction::Invoke: {
Reid Spencer04cde2c2004-07-04 11:33:49 +0000766 if (Oprnds.size() < 3)
Reid Spencer24399722004-07-09 22:21:33 +0000767 error("Invalid invoke instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000768 Value *F = getValue(iType, Oprnds[0]);
769
770 // Check to make sure we have a pointer to function type
771 const PointerType *PTy = dyn_cast<PointerType>(F->getType());
Reid Spencer04cde2c2004-07-04 11:33:49 +0000772 if (PTy == 0)
Reid Spencer24399722004-07-09 22:21:33 +0000773 error("Invoke to non function pointer value!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000774 const FunctionType *FTy = dyn_cast<FunctionType>(PTy->getElementType());
Reid Spencer04cde2c2004-07-04 11:33:49 +0000775 if (FTy == 0)
Reid Spencer24399722004-07-09 22:21:33 +0000776 error("Invoke to non function pointer value!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000777
778 std::vector<Value *> Params;
779 BasicBlock *Normal, *Except;
780
781 if (!FTy->isVarArg()) {
782 Normal = getBasicBlock(Oprnds[1]);
783 Except = getBasicBlock(Oprnds[2]);
784
785 FunctionType::param_iterator It = FTy->param_begin();
786 for (unsigned i = 3, e = Oprnds.size(); i != e; ++i) {
787 if (It == FTy->param_end())
Reid Spencer24399722004-07-09 22:21:33 +0000788 error("Invalid invoke instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000789 Params.push_back(getValue(getTypeSlot(*It++), Oprnds[i]));
790 }
791 if (It != FTy->param_end())
Reid Spencer24399722004-07-09 22:21:33 +0000792 error("Invalid invoke instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000793 } else {
794 Oprnds.erase(Oprnds.begin(), Oprnds.begin()+1);
795
796 Normal = getBasicBlock(Oprnds[0]);
797 Except = getBasicBlock(Oprnds[1]);
798
799 unsigned FirstVariableArgument = FTy->getNumParams()+2;
800 for (unsigned i = 2; i != FirstVariableArgument; ++i)
801 Params.push_back(getValue(getTypeSlot(FTy->getParamType(i-2)),
802 Oprnds[i]));
803
804 if (Oprnds.size()-FirstVariableArgument & 1) // Must be type/value pairs
Reid Spencer24399722004-07-09 22:21:33 +0000805 error("Invalid invoke instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000806
807 for (unsigned i = FirstVariableArgument; i < Oprnds.size(); i += 2)
808 Params.push_back(getValue(Oprnds[i], Oprnds[i+1]));
809 }
810
811 Result = new InvokeInst(F, Normal, Except, Params);
812 break;
813 }
814 case Instruction::Malloc:
Reid Spencer04cde2c2004-07-04 11:33:49 +0000815 if (Oprnds.size() > 2)
Reid Spencer24399722004-07-09 22:21:33 +0000816 error("Invalid malloc instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000817 if (!isa<PointerType>(InstTy))
Reid Spencer24399722004-07-09 22:21:33 +0000818 error("Invalid malloc instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000819
820 Result = new MallocInst(cast<PointerType>(InstTy)->getElementType(),
821 Oprnds.size() ? getValue(Type::UIntTyID,
822 Oprnds[0]) : 0);
823 break;
824
825 case Instruction::Alloca:
Reid Spencer04cde2c2004-07-04 11:33:49 +0000826 if (Oprnds.size() > 2)
Reid Spencer24399722004-07-09 22:21:33 +0000827 error("Invalid alloca instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000828 if (!isa<PointerType>(InstTy))
Reid Spencer24399722004-07-09 22:21:33 +0000829 error("Invalid alloca instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000830
831 Result = new AllocaInst(cast<PointerType>(InstTy)->getElementType(),
832 Oprnds.size() ? getValue(Type::UIntTyID,
Reid Spencer04cde2c2004-07-04 11:33:49 +0000833 Oprnds[0]) :0);
Reid Spencer060d25d2004-06-29 23:29:38 +0000834 break;
835 case Instruction::Free:
836 if (!isa<PointerType>(InstTy))
Reid Spencer24399722004-07-09 22:21:33 +0000837 error("Invalid free instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000838 Result = new FreeInst(getValue(iType, Oprnds[0]));
839 break;
840 case Instruction::GetElementPtr: {
841 if (Oprnds.size() == 0 || !isa<PointerType>(InstTy))
Reid Spencer24399722004-07-09 22:21:33 +0000842 error("Invalid getelementptr instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000843
844 std::vector<Value*> Idx;
845
846 const Type *NextTy = InstTy;
847 for (unsigned i = 1, e = Oprnds.size(); i != e; ++i) {
848 const CompositeType *TopTy = dyn_cast_or_null<CompositeType>(NextTy);
Reid Spencer04cde2c2004-07-04 11:33:49 +0000849 if (!TopTy)
Reid Spencer46b002c2004-07-11 17:28:43 +0000850 error("Invalid getelementptr instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000851
852 unsigned ValIdx = Oprnds[i];
853 unsigned IdxTy = 0;
854 if (!hasRestrictedGEPTypes) {
855 // Struct indices are always uints, sequential type indices can be any
856 // of the 32 or 64-bit integer types. The actual choice of type is
857 // encoded in the low two bits of the slot number.
858 if (isa<StructType>(TopTy))
859 IdxTy = Type::UIntTyID;
860 else {
861 switch (ValIdx & 3) {
862 default:
863 case 0: IdxTy = Type::UIntTyID; break;
864 case 1: IdxTy = Type::IntTyID; break;
865 case 2: IdxTy = Type::ULongTyID; break;
866 case 3: IdxTy = Type::LongTyID; break;
867 }
868 ValIdx >>= 2;
869 }
870 } else {
871 IdxTy = isa<StructType>(TopTy) ? Type::UByteTyID : Type::LongTyID;
872 }
873
874 Idx.push_back(getValue(IdxTy, ValIdx));
875
876 // Convert ubyte struct indices into uint struct indices.
877 if (isa<StructType>(TopTy) && hasRestrictedGEPTypes)
878 if (ConstantUInt *C = dyn_cast<ConstantUInt>(Idx.back()))
879 Idx[Idx.size()-1] = ConstantExpr::getCast(C, Type::UIntTy);
880
881 NextTy = GetElementPtrInst::getIndexedType(InstTy, Idx, true);
882 }
883
884 Result = new GetElementPtrInst(getValue(iType, Oprnds[0]), Idx);
885 break;
886 }
887
888 case 62: // volatile load
889 case Instruction::Load:
890 if (Oprnds.size() != 1 || !isa<PointerType>(InstTy))
Reid Spencer24399722004-07-09 22:21:33 +0000891 error("Invalid load instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000892 Result = new LoadInst(getValue(iType, Oprnds[0]), "", Opcode == 62);
893 break;
894
895 case 63: // volatile store
896 case Instruction::Store: {
897 if (!isa<PointerType>(InstTy) || Oprnds.size() != 2)
Reid Spencer24399722004-07-09 22:21:33 +0000898 error("Invalid store instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000899
900 Value *Ptr = getValue(iType, Oprnds[1]);
901 const Type *ValTy = cast<PointerType>(Ptr->getType())->getElementType();
902 Result = new StoreInst(getValue(getTypeSlot(ValTy), Oprnds[0]), Ptr,
903 Opcode == 63);
904 break;
905 }
906 case Instruction::Unwind:
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000907 if (Oprnds.size() != 0) error("Invalid unwind instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000908 Result = new UnwindInst();
909 break;
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000910 case Instruction::Unreachable:
911 if (Oprnds.size() != 0) error("Invalid unreachable instruction!");
912 Result = new UnreachableInst();
913 break;
Reid Spencer060d25d2004-06-29 23:29:38 +0000914 } // end switch(Opcode)
915
916 unsigned TypeSlot;
917 if (Result->getType() == InstTy)
918 TypeSlot = iType;
919 else
920 TypeSlot = getTypeSlot(Result->getType());
921
922 insertValue(Result, TypeSlot, FunctionValues);
923 BB->getInstList().push_back(Result);
924}
925
Reid Spencer04cde2c2004-07-04 11:33:49 +0000926/// Get a particular numbered basic block, which might be a forward reference.
927/// This works together with ParseBasicBlock to handle these forward references
Chris Lattner4a242b32004-10-14 01:39:18 +0000928/// in a clean manner. This function is used when constructing phi, br, switch,
929/// and other instructions that reference basic blocks. Blocks are numbered
Reid Spencer04cde2c2004-07-04 11:33:49 +0000930/// sequentially as they appear in the function.
Reid Spencer060d25d2004-06-29 23:29:38 +0000931BasicBlock *BytecodeReader::getBasicBlock(unsigned ID) {
Chris Lattner4ee8ef22003-10-08 22:52:54 +0000932 // Make sure there is room in the table...
933 if (ParsedBasicBlocks.size() <= ID) ParsedBasicBlocks.resize(ID+1);
934
935 // First check to see if this is a backwards reference, i.e., ParseBasicBlock
936 // has already created this block, or if the forward reference has already
937 // been created.
938 if (ParsedBasicBlocks[ID])
939 return ParsedBasicBlocks[ID];
940
941 // Otherwise, the basic block has not yet been created. Do so and add it to
942 // the ParsedBasicBlocks list.
943 return ParsedBasicBlocks[ID] = new BasicBlock();
944}
945
Reid Spencer04cde2c2004-07-04 11:33:49 +0000946/// In LLVM 1.0 bytecode files, we used to output one basicblock at a time.
947/// This method reads in one of the basicblock packets. This method is not used
948/// for bytecode files after LLVM 1.0
949/// @returns The basic block constructed.
Reid Spencer46b002c2004-07-11 17:28:43 +0000950BasicBlock *BytecodeReader::ParseBasicBlock(unsigned BlockNo) {
951 if (Handler) Handler->handleBasicBlockBegin(BlockNo);
Reid Spencer060d25d2004-06-29 23:29:38 +0000952
953 BasicBlock *BB = 0;
954
Chris Lattner4ee8ef22003-10-08 22:52:54 +0000955 if (ParsedBasicBlocks.size() == BlockNo)
956 ParsedBasicBlocks.push_back(BB = new BasicBlock());
957 else if (ParsedBasicBlocks[BlockNo] == 0)
958 BB = ParsedBasicBlocks[BlockNo] = new BasicBlock();
959 else
960 BB = ParsedBasicBlocks[BlockNo];
Chris Lattner00950542001-06-06 20:29:01 +0000961
Reid Spencer060d25d2004-06-29 23:29:38 +0000962 std::vector<unsigned> Operands;
Reid Spencer46b002c2004-07-11 17:28:43 +0000963 while (moreInBlock())
Reid Spencer060d25d2004-06-29 23:29:38 +0000964 ParseInstruction(Operands, BB);
Chris Lattner00950542001-06-06 20:29:01 +0000965
Reid Spencer46b002c2004-07-11 17:28:43 +0000966 if (Handler) Handler->handleBasicBlockEnd(BlockNo);
Misha Brukman12c29d12003-09-22 23:38:23 +0000967 return BB;
Chris Lattner00950542001-06-06 20:29:01 +0000968}
969
Reid Spencer04cde2c2004-07-04 11:33:49 +0000970/// Parse all of the BasicBlock's & Instruction's in the body of a function.
971/// In post 1.0 bytecode files, we no longer emit basic block individually,
972/// in order to avoid per-basic-block overhead.
973/// @returns Rhe number of basic blocks encountered.
Reid Spencer060d25d2004-06-29 23:29:38 +0000974unsigned BytecodeReader::ParseInstructionList(Function* F) {
Chris Lattner8d1dbd22003-12-01 07:05:31 +0000975 unsigned BlockNo = 0;
976 std::vector<unsigned> Args;
977
Reid Spencer46b002c2004-07-11 17:28:43 +0000978 while (moreInBlock()) {
979 if (Handler) Handler->handleBasicBlockBegin(BlockNo);
Chris Lattner8d1dbd22003-12-01 07:05:31 +0000980 BasicBlock *BB;
981 if (ParsedBasicBlocks.size() == BlockNo)
982 ParsedBasicBlocks.push_back(BB = new BasicBlock());
983 else if (ParsedBasicBlocks[BlockNo] == 0)
984 BB = ParsedBasicBlocks[BlockNo] = new BasicBlock();
985 else
986 BB = ParsedBasicBlocks[BlockNo];
987 ++BlockNo;
988 F->getBasicBlockList().push_back(BB);
989
990 // Read instructions into this basic block until we get to a terminator
Reid Spencer46b002c2004-07-11 17:28:43 +0000991 while (moreInBlock() && !BB->getTerminator())
Reid Spencer060d25d2004-06-29 23:29:38 +0000992 ParseInstruction(Args, BB);
Chris Lattner8d1dbd22003-12-01 07:05:31 +0000993
994 if (!BB->getTerminator())
Reid Spencer24399722004-07-09 22:21:33 +0000995 error("Non-terminated basic block found!");
Reid Spencer5c15fe52004-07-05 00:57:50 +0000996
Reid Spencer46b002c2004-07-11 17:28:43 +0000997 if (Handler) Handler->handleBasicBlockEnd(BlockNo-1);
Chris Lattner8d1dbd22003-12-01 07:05:31 +0000998 }
999
1000 return BlockNo;
1001}
1002
Reid Spencer04cde2c2004-07-04 11:33:49 +00001003/// Parse a symbol table. This works for both module level and function
1004/// level symbol tables. For function level symbol tables, the CurrentFunction
1005/// parameter must be non-zero and the ST parameter must correspond to
1006/// CurrentFunction's symbol table. For Module level symbol tables, the
1007/// CurrentFunction argument must be zero.
Reid Spencer060d25d2004-06-29 23:29:38 +00001008void BytecodeReader::ParseSymbolTable(Function *CurrentFunction,
Reid Spencer04cde2c2004-07-04 11:33:49 +00001009 SymbolTable *ST) {
1010 if (Handler) Handler->handleSymbolTableBegin(CurrentFunction,ST);
Reid Spencer060d25d2004-06-29 23:29:38 +00001011
Chris Lattner39cacce2003-10-10 05:43:47 +00001012 // Allow efficient basic block lookup by number.
1013 std::vector<BasicBlock*> BBMap;
1014 if (CurrentFunction)
1015 for (Function::iterator I = CurrentFunction->begin(),
1016 E = CurrentFunction->end(); I != E; ++I)
1017 BBMap.push_back(I);
1018
Reid Spencer04cde2c2004-07-04 11:33:49 +00001019 /// In LLVM 1.3 we write types separately from values so
1020 /// The types are always first in the symbol table. This is
1021 /// because Type no longer derives from Value.
Reid Spencer46b002c2004-07-11 17:28:43 +00001022 if (!hasTypeDerivedFromValue) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001023 // Symtab block header: [num entries]
1024 unsigned NumEntries = read_vbr_uint();
Reid Spencer46b002c2004-07-11 17:28:43 +00001025 for (unsigned i = 0; i < NumEntries; ++i) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001026 // Symtab entry: [def slot #][name]
1027 unsigned slot = read_vbr_uint();
1028 std::string Name = read_str();
1029 const Type* T = getType(slot);
1030 ST->insert(Name, T);
1031 }
1032 }
1033
Reid Spencer46b002c2004-07-11 17:28:43 +00001034 while (moreInBlock()) {
Chris Lattner00950542001-06-06 20:29:01 +00001035 // Symtab block header: [num entries][type id number]
Reid Spencer060d25d2004-06-29 23:29:38 +00001036 unsigned NumEntries = read_vbr_uint();
Reid Spencer04cde2c2004-07-04 11:33:49 +00001037 unsigned Typ = 0;
1038 bool isTypeType = read_typeid(Typ);
Chris Lattner00950542001-06-06 20:29:01 +00001039 const Type *Ty = getType(Typ);
Chris Lattner1d670cc2001-09-07 16:37:43 +00001040
Chris Lattner7dc3a2e2003-10-13 14:57:53 +00001041 for (unsigned i = 0; i != NumEntries; ++i) {
Chris Lattner00950542001-06-06 20:29:01 +00001042 // Symtab entry: [def slot #][name]
Reid Spencer060d25d2004-06-29 23:29:38 +00001043 unsigned slot = read_vbr_uint();
1044 std::string Name = read_str();
Chris Lattner00950542001-06-06 20:29:01 +00001045
Reid Spencer04cde2c2004-07-04 11:33:49 +00001046 // if we're reading a pre 1.3 bytecode file and the type plane
1047 // is the "type type", handle it here
Reid Spencer46b002c2004-07-11 17:28:43 +00001048 if (isTypeType) {
1049 const Type* T = getType(slot);
1050 if (T == 0)
1051 error("Failed type look-up for name '" + Name + "'");
1052 ST->insert(Name, T);
1053 continue; // code below must be short circuited
Chris Lattner39cacce2003-10-10 05:43:47 +00001054 } else {
Reid Spencer46b002c2004-07-11 17:28:43 +00001055 Value *V = 0;
1056 if (Typ == Type::LabelTyID) {
1057 if (slot < BBMap.size())
1058 V = BBMap[slot];
1059 } else {
1060 V = getValue(Typ, slot, false); // Find mapping...
1061 }
1062 if (V == 0)
1063 error("Failed value look-up for name '" + Name + "'");
1064 V->setName(Name, ST);
Chris Lattner39cacce2003-10-10 05:43:47 +00001065 }
Chris Lattner00950542001-06-06 20:29:01 +00001066 }
1067 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001068 checkPastBlockEnd("Symbol Table");
Reid Spencer04cde2c2004-07-04 11:33:49 +00001069 if (Handler) Handler->handleSymbolTableEnd();
Chris Lattner00950542001-06-06 20:29:01 +00001070}
1071
Reid Spencer04cde2c2004-07-04 11:33:49 +00001072/// Read in the types portion of a compaction table.
Reid Spencer46b002c2004-07-11 17:28:43 +00001073void BytecodeReader::ParseCompactionTypes(unsigned NumEntries) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001074 for (unsigned i = 0; i != NumEntries; ++i) {
1075 unsigned TypeSlot = 0;
Reid Spencer46b002c2004-07-11 17:28:43 +00001076 if (read_typeid(TypeSlot))
Reid Spencer24399722004-07-09 22:21:33 +00001077 error("Invalid type in compaction table: type type");
Reid Spencer04cde2c2004-07-04 11:33:49 +00001078 const Type *Typ = getGlobalTableType(TypeSlot);
Chris Lattner45b5dd22004-08-03 23:41:28 +00001079 CompactionTypes.push_back(std::make_pair(Typ, TypeSlot));
Reid Spencer46b002c2004-07-11 17:28:43 +00001080 if (Handler) Handler->handleCompactionTableType(i, TypeSlot, Typ);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001081 }
1082}
1083
1084/// Parse a compaction table.
Reid Spencer060d25d2004-06-29 23:29:38 +00001085void BytecodeReader::ParseCompactionTable() {
1086
Reid Spencer46b002c2004-07-11 17:28:43 +00001087 // Notify handler that we're beginning a compaction table.
Reid Spencer04cde2c2004-07-04 11:33:49 +00001088 if (Handler) Handler->handleCompactionTableBegin();
1089
Reid Spencer46b002c2004-07-11 17:28:43 +00001090 // In LLVM 1.3 Type no longer derives from Value. So,
1091 // we always write them first in the compaction table
1092 // because they can't occupy a "type plane" where the
1093 // Values reside.
1094 if (! hasTypeDerivedFromValue) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001095 unsigned NumEntries = read_vbr_uint();
Reid Spencer46b002c2004-07-11 17:28:43 +00001096 ParseCompactionTypes(NumEntries);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001097 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001098
Reid Spencer46b002c2004-07-11 17:28:43 +00001099 // Compaction tables live in separate blocks so we have to loop
1100 // until we've read the whole thing.
1101 while (moreInBlock()) {
1102 // Read the number of Value* entries in the compaction table
Reid Spencer060d25d2004-06-29 23:29:38 +00001103 unsigned NumEntries = read_vbr_uint();
Reid Spencer04cde2c2004-07-04 11:33:49 +00001104 unsigned Ty = 0;
1105 unsigned isTypeType = false;
Reid Spencer060d25d2004-06-29 23:29:38 +00001106
Reid Spencer46b002c2004-07-11 17:28:43 +00001107 // Decode the type from value read in. Most compaction table
1108 // planes will have one or two entries in them. If that's the
1109 // case then the length is encoded in the bottom two bits and
1110 // the higher bits encode the type. This saves another VBR value.
Reid Spencer060d25d2004-06-29 23:29:38 +00001111 if ((NumEntries & 3) == 3) {
Reid Spencer46b002c2004-07-11 17:28:43 +00001112 // In this case, both low-order bits are set (value 3). This
1113 // is a signal that the typeid follows.
Reid Spencer060d25d2004-06-29 23:29:38 +00001114 NumEntries >>= 2;
Reid Spencer04cde2c2004-07-04 11:33:49 +00001115 isTypeType = read_typeid(Ty);
Reid Spencer060d25d2004-06-29 23:29:38 +00001116 } else {
Reid Spencer46b002c2004-07-11 17:28:43 +00001117 // In this case, the low-order bits specify the number of entries
1118 // and the high order bits specify the type.
Reid Spencer060d25d2004-06-29 23:29:38 +00001119 Ty = NumEntries >> 2;
Reid Spencer04cde2c2004-07-04 11:33:49 +00001120 isTypeType = sanitizeTypeId(Ty);
Reid Spencer060d25d2004-06-29 23:29:38 +00001121 NumEntries &= 3;
1122 }
1123
Reid Spencer04cde2c2004-07-04 11:33:49 +00001124 // if we're reading a pre 1.3 bytecode file and the type plane
1125 // is the "type type", handle it here
Reid Spencer46b002c2004-07-11 17:28:43 +00001126 if (isTypeType) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001127 ParseCompactionTypes(NumEntries);
Reid Spencer060d25d2004-06-29 23:29:38 +00001128 } else {
Chris Lattner2c6c14d2004-08-04 00:19:23 +00001129 // Make sure we have enough room for the plane.
Reid Spencer04cde2c2004-07-04 11:33:49 +00001130 if (Ty >= CompactionValues.size())
Reid Spencer46b002c2004-07-11 17:28:43 +00001131 CompactionValues.resize(Ty+1);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001132
Chris Lattner2c6c14d2004-08-04 00:19:23 +00001133 // Make sure the plane is empty or we have some kind of error.
Reid Spencer04cde2c2004-07-04 11:33:49 +00001134 if (!CompactionValues[Ty].empty())
Reid Spencer46b002c2004-07-11 17:28:43 +00001135 error("Compaction table plane contains multiple entries!");
Reid Spencer04cde2c2004-07-04 11:33:49 +00001136
Chris Lattner2c6c14d2004-08-04 00:19:23 +00001137 // Notify handler about the plane.
Reid Spencer46b002c2004-07-11 17:28:43 +00001138 if (Handler) Handler->handleCompactionTablePlane(Ty, NumEntries);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001139
Chris Lattner2c6c14d2004-08-04 00:19:23 +00001140 // Push the implicit zero.
1141 CompactionValues[Ty].push_back(Constant::getNullValue(getType(Ty)));
Reid Spencer46b002c2004-07-11 17:28:43 +00001142
1143 // Read in each of the entries, put them in the compaction table
1144 // and notify the handler that we have a new compaction table value.
Reid Spencer060d25d2004-06-29 23:29:38 +00001145 for (unsigned i = 0; i != NumEntries; ++i) {
Reid Spencer46b002c2004-07-11 17:28:43 +00001146 unsigned ValSlot = read_vbr_uint();
Chris Lattner2c6c14d2004-08-04 00:19:23 +00001147 Value *V = getGlobalTableValue(Ty, ValSlot);
Reid Spencer46b002c2004-07-11 17:28:43 +00001148 CompactionValues[Ty].push_back(V);
Chris Lattner2c6c14d2004-08-04 00:19:23 +00001149 if (Handler) Handler->handleCompactionTableValue(i, Ty, ValSlot);
Reid Spencer060d25d2004-06-29 23:29:38 +00001150 }
1151 }
1152 }
Reid Spencer46b002c2004-07-11 17:28:43 +00001153 // Notify handler that the compaction table is done.
Reid Spencer04cde2c2004-07-04 11:33:49 +00001154 if (Handler) Handler->handleCompactionTableEnd();
Reid Spencer060d25d2004-06-29 23:29:38 +00001155}
1156
Reid Spencer46b002c2004-07-11 17:28:43 +00001157// Parse a single type. The typeid is read in first. If its a primitive type
1158// then nothing else needs to be read, we know how to instantiate it. If its
1159// a derived type, then additional data is read to fill out the type
1160// definition.
1161const Type *BytecodeReader::ParseType() {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001162 unsigned PrimType = 0;
Reid Spencer46b002c2004-07-11 17:28:43 +00001163 if (read_typeid(PrimType))
Reid Spencer24399722004-07-09 22:21:33 +00001164 error("Invalid type (type type) in type constants!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001165
1166 const Type *Result = 0;
1167 if ((Result = Type::getPrimitiveType((Type::TypeID)PrimType)))
1168 return Result;
1169
1170 switch (PrimType) {
1171 case Type::FunctionTyID: {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001172 const Type *RetType = readSanitizedType();
Reid Spencer060d25d2004-06-29 23:29:38 +00001173
1174 unsigned NumParams = read_vbr_uint();
1175
1176 std::vector<const Type*> Params;
Reid Spencer04cde2c2004-07-04 11:33:49 +00001177 while (NumParams--)
1178 Params.push_back(readSanitizedType());
Reid Spencer060d25d2004-06-29 23:29:38 +00001179
1180 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1181 if (isVarArg) Params.pop_back();
1182
1183 Result = FunctionType::get(RetType, Params, isVarArg);
1184 break;
1185 }
1186 case Type::ArrayTyID: {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001187 const Type *ElementType = readSanitizedType();
Reid Spencer060d25d2004-06-29 23:29:38 +00001188 unsigned NumElements = read_vbr_uint();
Reid Spencer060d25d2004-06-29 23:29:38 +00001189 Result = ArrayType::get(ElementType, NumElements);
1190 break;
1191 }
Brian Gaeke715c90b2004-08-20 06:00:58 +00001192 case Type::PackedTyID: {
1193 const Type *ElementType = readSanitizedType();
1194 unsigned NumElements = read_vbr_uint();
1195 Result = PackedType::get(ElementType, NumElements);
1196 break;
1197 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001198 case Type::StructTyID: {
1199 std::vector<const Type*> Elements;
Reid Spencer04cde2c2004-07-04 11:33:49 +00001200 unsigned Typ = 0;
Reid Spencer46b002c2004-07-11 17:28:43 +00001201 if (read_typeid(Typ))
Reid Spencer24399722004-07-09 22:21:33 +00001202 error("Invalid element type (type type) for structure!");
1203
Reid Spencer060d25d2004-06-29 23:29:38 +00001204 while (Typ) { // List is terminated by void/0 typeid
1205 Elements.push_back(getType(Typ));
Reid Spencer46b002c2004-07-11 17:28:43 +00001206 if (read_typeid(Typ))
1207 error("Invalid element type (type type) for structure!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001208 }
1209
1210 Result = StructType::get(Elements);
1211 break;
1212 }
1213 case Type::PointerTyID: {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001214 Result = PointerType::get(readSanitizedType());
Reid Spencer060d25d2004-06-29 23:29:38 +00001215 break;
1216 }
1217
1218 case Type::OpaqueTyID: {
1219 Result = OpaqueType::get();
1220 break;
1221 }
1222
1223 default:
Reid Spencer24399722004-07-09 22:21:33 +00001224 error("Don't know how to deserialize primitive type " + utostr(PrimType));
Reid Spencer060d25d2004-06-29 23:29:38 +00001225 break;
1226 }
Reid Spencer46b002c2004-07-11 17:28:43 +00001227 if (Handler) Handler->handleType(Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001228 return Result;
1229}
1230
Reid Spencer5b472d92004-08-21 20:49:23 +00001231// ParseTypes - We have to use this weird code to handle recursive
Reid Spencer060d25d2004-06-29 23:29:38 +00001232// types. We know that recursive types will only reference the current slab of
1233// values in the type plane, but they can forward reference types before they
1234// have been read. For example, Type #0 might be '{ Ty#1 }' and Type #1 might
1235// be 'Ty#0*'. When reading Type #0, type number one doesn't exist. To fix
1236// this ugly problem, we pessimistically insert an opaque type for each type we
1237// are about to read. This means that forward references will resolve to
1238// something and when we reread the type later, we can replace the opaque type
1239// with a new resolved concrete type.
1240//
Reid Spencer46b002c2004-07-11 17:28:43 +00001241void BytecodeReader::ParseTypes(TypeListTy &Tab, unsigned NumEntries){
Reid Spencer060d25d2004-06-29 23:29:38 +00001242 assert(Tab.size() == 0 && "should not have read type constants in before!");
1243
1244 // Insert a bunch of opaque types to be resolved later...
1245 Tab.reserve(NumEntries);
1246 for (unsigned i = 0; i != NumEntries; ++i)
1247 Tab.push_back(OpaqueType::get());
1248
Reid Spencer5b472d92004-08-21 20:49:23 +00001249 if (Handler)
1250 Handler->handleTypeList(NumEntries);
1251
Reid Spencer060d25d2004-06-29 23:29:38 +00001252 // Loop through reading all of the types. Forward types will make use of the
1253 // opaque types just inserted.
1254 //
1255 for (unsigned i = 0; i != NumEntries; ++i) {
Reid Spencer46b002c2004-07-11 17:28:43 +00001256 const Type* NewTy = ParseType();
Reid Spencer04cde2c2004-07-04 11:33:49 +00001257 const Type* OldTy = Tab[i].get();
1258 if (NewTy == 0)
Reid Spencer24399722004-07-09 22:21:33 +00001259 error("Couldn't parse type!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001260
1261 // Don't directly push the new type on the Tab. Instead we want to replace
1262 // the opaque type we previously inserted with the new concrete value. This
1263 // approach helps with forward references to types. The refinement from the
1264 // abstract (opaque) type to the new type causes all uses of the abstract
1265 // type to use the concrete type (NewTy). This will also cause the opaque
1266 // type to be deleted.
1267 cast<DerivedType>(const_cast<Type*>(OldTy))->refineAbstractTypeTo(NewTy);
1268
1269 // This should have replaced the old opaque type with the new type in the
1270 // value table... or with a preexisting type that was already in the system.
1271 // Let's just make sure it did.
1272 assert(Tab[i] != OldTy && "refineAbstractType didn't work!");
1273 }
1274}
1275
Reid Spencer04cde2c2004-07-04 11:33:49 +00001276/// Parse a single constant value
Reid Spencer46b002c2004-07-11 17:28:43 +00001277Constant *BytecodeReader::ParseConstantValue(unsigned TypeID) {
Reid Spencer060d25d2004-06-29 23:29:38 +00001278 // We must check for a ConstantExpr before switching by type because
1279 // a ConstantExpr can be of any type, and has no explicit value.
1280 //
1281 // 0 if not expr; numArgs if is expr
1282 unsigned isExprNumArgs = read_vbr_uint();
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001283
Reid Spencer060d25d2004-06-29 23:29:38 +00001284 if (isExprNumArgs) {
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001285 // 'undef' is encoded with 'exprnumargs' == 1.
1286 if (!hasNoUndefValue)
1287 if (--isExprNumArgs == 0)
1288 return UndefValue::get(getType(TypeID));
1289
Reid Spencer060d25d2004-06-29 23:29:38 +00001290 // FIXME: Encoding of constant exprs could be much more compact!
1291 std::vector<Constant*> ArgVec;
1292 ArgVec.reserve(isExprNumArgs);
1293 unsigned Opcode = read_vbr_uint();
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001294
1295 // Bytecode files before LLVM 1.4 need have a missing terminator inst.
1296 if (hasNoUnreachableInst) Opcode++;
Reid Spencer060d25d2004-06-29 23:29:38 +00001297
1298 // Read the slot number and types of each of the arguments
1299 for (unsigned i = 0; i != isExprNumArgs; ++i) {
1300 unsigned ArgValSlot = read_vbr_uint();
Reid Spencer04cde2c2004-07-04 11:33:49 +00001301 unsigned ArgTypeSlot = 0;
Reid Spencer46b002c2004-07-11 17:28:43 +00001302 if (read_typeid(ArgTypeSlot))
1303 error("Invalid argument type (type type) for constant value");
Reid Spencer060d25d2004-06-29 23:29:38 +00001304
1305 // Get the arg value from its slot if it exists, otherwise a placeholder
1306 ArgVec.push_back(getConstantValue(ArgTypeSlot, ArgValSlot));
1307 }
1308
1309 // Construct a ConstantExpr of the appropriate kind
1310 if (isExprNumArgs == 1) { // All one-operand expressions
Reid Spencer46b002c2004-07-11 17:28:43 +00001311 if (Opcode != Instruction::Cast)
Chris Lattner02dce162004-12-04 05:28:27 +00001312 error("Only cast instruction has one argument for ConstantExpr");
Reid Spencer46b002c2004-07-11 17:28:43 +00001313
Reid Spencer060d25d2004-06-29 23:29:38 +00001314 Constant* Result = ConstantExpr::getCast(ArgVec[0], getType(TypeID));
Reid Spencer04cde2c2004-07-04 11:33:49 +00001315 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001316 return Result;
1317 } else if (Opcode == Instruction::GetElementPtr) { // GetElementPtr
1318 std::vector<Constant*> IdxList(ArgVec.begin()+1, ArgVec.end());
1319
1320 if (hasRestrictedGEPTypes) {
1321 const Type *BaseTy = ArgVec[0]->getType();
1322 generic_gep_type_iterator<std::vector<Constant*>::iterator>
1323 GTI = gep_type_begin(BaseTy, IdxList.begin(), IdxList.end()),
1324 E = gep_type_end(BaseTy, IdxList.begin(), IdxList.end());
1325 for (unsigned i = 0; GTI != E; ++GTI, ++i)
1326 if (isa<StructType>(*GTI)) {
1327 if (IdxList[i]->getType() != Type::UByteTy)
Reid Spencer24399722004-07-09 22:21:33 +00001328 error("Invalid index for getelementptr!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001329 IdxList[i] = ConstantExpr::getCast(IdxList[i], Type::UIntTy);
1330 }
1331 }
1332
1333 Constant* Result = ConstantExpr::getGetElementPtr(ArgVec[0], IdxList);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001334 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001335 return Result;
1336 } else if (Opcode == Instruction::Select) {
Reid Spencer46b002c2004-07-11 17:28:43 +00001337 if (ArgVec.size() != 3)
1338 error("Select instruction must have three arguments.");
Reid Spencer060d25d2004-06-29 23:29:38 +00001339 Constant* Result = ConstantExpr::getSelect(ArgVec[0], ArgVec[1],
Reid Spencer04cde2c2004-07-04 11:33:49 +00001340 ArgVec[2]);
1341 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001342 return Result;
1343 } else { // All other 2-operand expressions
1344 Constant* Result = ConstantExpr::get(Opcode, ArgVec[0], ArgVec[1]);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001345 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001346 return Result;
1347 }
1348 }
1349
1350 // Ok, not an ConstantExpr. We now know how to read the given type...
1351 const Type *Ty = getType(TypeID);
1352 switch (Ty->getTypeID()) {
1353 case Type::BoolTyID: {
1354 unsigned Val = read_vbr_uint();
1355 if (Val != 0 && Val != 1)
Reid Spencer24399722004-07-09 22:21:33 +00001356 error("Invalid boolean value read.");
Reid Spencer060d25d2004-06-29 23:29:38 +00001357 Constant* Result = ConstantBool::get(Val == 1);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001358 if (Handler) Handler->handleConstantValue(Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001359 return Result;
1360 }
1361
1362 case Type::UByteTyID: // Unsigned integer types...
1363 case Type::UShortTyID:
1364 case Type::UIntTyID: {
1365 unsigned Val = read_vbr_uint();
1366 if (!ConstantUInt::isValueValidForType(Ty, Val))
Reid Spencer24399722004-07-09 22:21:33 +00001367 error("Invalid unsigned byte/short/int read.");
Reid Spencer060d25d2004-06-29 23:29:38 +00001368 Constant* Result = ConstantUInt::get(Ty, Val);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001369 if (Handler) Handler->handleConstantValue(Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001370 return Result;
1371 }
1372
1373 case Type::ULongTyID: {
1374 Constant* Result = ConstantUInt::get(Ty, read_vbr_uint64());
Reid Spencer04cde2c2004-07-04 11:33:49 +00001375 if (Handler) Handler->handleConstantValue(Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001376 return Result;
1377 }
1378
1379 case Type::SByteTyID: // Signed integer types...
1380 case Type::ShortTyID:
1381 case Type::IntTyID: {
1382 case Type::LongTyID:
1383 int64_t Val = read_vbr_int64();
1384 if (!ConstantSInt::isValueValidForType(Ty, Val))
Reid Spencer24399722004-07-09 22:21:33 +00001385 error("Invalid signed byte/short/int/long read.");
Reid Spencer060d25d2004-06-29 23:29:38 +00001386 Constant* Result = ConstantSInt::get(Ty, Val);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001387 if (Handler) Handler->handleConstantValue(Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001388 return Result;
1389 }
1390
1391 case Type::FloatTyID: {
Reid Spencer46b002c2004-07-11 17:28:43 +00001392 float Val;
1393 read_float(Val);
1394 Constant* Result = ConstantFP::get(Ty, Val);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001395 if (Handler) Handler->handleConstantValue(Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001396 return Result;
1397 }
1398
1399 case Type::DoubleTyID: {
1400 double Val;
Reid Spencer46b002c2004-07-11 17:28:43 +00001401 read_double(Val);
Reid Spencer060d25d2004-06-29 23:29:38 +00001402 Constant* Result = ConstantFP::get(Ty, Val);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001403 if (Handler) Handler->handleConstantValue(Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001404 return Result;
1405 }
1406
Reid Spencer060d25d2004-06-29 23:29:38 +00001407 case Type::ArrayTyID: {
1408 const ArrayType *AT = cast<ArrayType>(Ty);
1409 unsigned NumElements = AT->getNumElements();
1410 unsigned TypeSlot = getTypeSlot(AT->getElementType());
1411 std::vector<Constant*> Elements;
1412 Elements.reserve(NumElements);
1413 while (NumElements--) // Read all of the elements of the constant.
1414 Elements.push_back(getConstantValue(TypeSlot,
1415 read_vbr_uint()));
1416 Constant* Result = ConstantArray::get(AT, Elements);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001417 if (Handler) Handler->handleConstantArray(AT, Elements, TypeSlot, Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001418 return Result;
1419 }
1420
1421 case Type::StructTyID: {
1422 const StructType *ST = cast<StructType>(Ty);
1423
1424 std::vector<Constant *> Elements;
1425 Elements.reserve(ST->getNumElements());
1426 for (unsigned i = 0; i != ST->getNumElements(); ++i)
1427 Elements.push_back(getConstantValue(ST->getElementType(i),
1428 read_vbr_uint()));
1429
1430 Constant* Result = ConstantStruct::get(ST, Elements);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001431 if (Handler) Handler->handleConstantStruct(ST, Elements, Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001432 return Result;
1433 }
1434
Brian Gaeke715c90b2004-08-20 06:00:58 +00001435 case Type::PackedTyID: {
1436 const PackedType *PT = cast<PackedType>(Ty);
1437 unsigned NumElements = PT->getNumElements();
1438 unsigned TypeSlot = getTypeSlot(PT->getElementType());
1439 std::vector<Constant*> Elements;
1440 Elements.reserve(NumElements);
1441 while (NumElements--) // Read all of the elements of the constant.
1442 Elements.push_back(getConstantValue(TypeSlot,
1443 read_vbr_uint()));
1444 Constant* Result = ConstantPacked::get(PT, Elements);
1445 if (Handler) Handler->handleConstantPacked(PT, Elements, TypeSlot, Result);
1446 return Result;
1447 }
1448
Chris Lattner638c3812004-11-19 16:24:05 +00001449 case Type::PointerTyID: { // ConstantPointerRef value (backwards compat).
Reid Spencer060d25d2004-06-29 23:29:38 +00001450 const PointerType *PT = cast<PointerType>(Ty);
1451 unsigned Slot = read_vbr_uint();
1452
1453 // Check to see if we have already read this global variable...
1454 Value *Val = getValue(TypeID, Slot, false);
Reid Spencer060d25d2004-06-29 23:29:38 +00001455 if (Val) {
Chris Lattnerbcb11cf2004-07-27 02:34:49 +00001456 GlobalValue *GV = dyn_cast<GlobalValue>(Val);
1457 if (!GV) error("GlobalValue not in ValueTable!");
1458 if (Handler) Handler->handleConstantPointer(PT, Slot, GV);
1459 return GV;
Reid Spencer060d25d2004-06-29 23:29:38 +00001460 } else {
Reid Spencer24399722004-07-09 22:21:33 +00001461 error("Forward references are not allowed here.");
Reid Spencer060d25d2004-06-29 23:29:38 +00001462 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001463 }
1464
1465 default:
Reid Spencer24399722004-07-09 22:21:33 +00001466 error("Don't know how to deserialize constant value of type '" +
Reid Spencer060d25d2004-06-29 23:29:38 +00001467 Ty->getDescription());
1468 break;
1469 }
Reid Spencer24399722004-07-09 22:21:33 +00001470 return 0;
Reid Spencer060d25d2004-06-29 23:29:38 +00001471}
1472
Reid Spencer04cde2c2004-07-04 11:33:49 +00001473/// Resolve references for constants. This function resolves the forward
1474/// referenced constants in the ConstantFwdRefs map. It uses the
1475/// replaceAllUsesWith method of Value class to substitute the placeholder
1476/// instance with the actual instance.
Chris Lattner389bd042004-12-09 06:19:44 +00001477void BytecodeReader::ResolveReferencesToConstant(Constant *NewV, unsigned Typ,
1478 unsigned Slot) {
Chris Lattner29b789b2003-11-19 17:27:18 +00001479 ConstantRefsType::iterator I =
Chris Lattner389bd042004-12-09 06:19:44 +00001480 ConstantFwdRefs.find(std::make_pair(Typ, Slot));
Chris Lattner29b789b2003-11-19 17:27:18 +00001481 if (I == ConstantFwdRefs.end()) return; // Never forward referenced?
Chris Lattner00950542001-06-06 20:29:01 +00001482
Chris Lattner29b789b2003-11-19 17:27:18 +00001483 Value *PH = I->second; // Get the placeholder...
1484 PH->replaceAllUsesWith(NewV);
1485 delete PH; // Delete the old placeholder
1486 ConstantFwdRefs.erase(I); // Remove the map entry for it
Vikram S. Advec1e4a812002-07-14 23:04:18 +00001487}
1488
Reid Spencer04cde2c2004-07-04 11:33:49 +00001489/// Parse the constant strings section.
Reid Spencer060d25d2004-06-29 23:29:38 +00001490void BytecodeReader::ParseStringConstants(unsigned NumEntries, ValueTable &Tab){
1491 for (; NumEntries; --NumEntries) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001492 unsigned Typ = 0;
Reid Spencer46b002c2004-07-11 17:28:43 +00001493 if (read_typeid(Typ))
Reid Spencer24399722004-07-09 22:21:33 +00001494 error("Invalid type (type type) for string constant");
Reid Spencer060d25d2004-06-29 23:29:38 +00001495 const Type *Ty = getType(Typ);
1496 if (!isa<ArrayType>(Ty))
Reid Spencer24399722004-07-09 22:21:33 +00001497 error("String constant data invalid!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001498
1499 const ArrayType *ATy = cast<ArrayType>(Ty);
1500 if (ATy->getElementType() != Type::SByteTy &&
1501 ATy->getElementType() != Type::UByteTy)
Reid Spencer24399722004-07-09 22:21:33 +00001502 error("String constant data invalid!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001503
1504 // Read character data. The type tells us how long the string is.
Jeff Cohene1337212004-12-20 03:23:46 +00001505 char *Data = reinterpret_cast<char *>(alloca(ATy->getNumElements()));
Reid Spencer060d25d2004-06-29 23:29:38 +00001506 read_data(Data, Data+ATy->getNumElements());
Chris Lattner52e20b02003-03-19 20:54:26 +00001507
Reid Spencer060d25d2004-06-29 23:29:38 +00001508 std::vector<Constant*> Elements(ATy->getNumElements());
1509 if (ATy->getElementType() == Type::SByteTy)
1510 for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
1511 Elements[i] = ConstantSInt::get(Type::SByteTy, (signed char)Data[i]);
1512 else
1513 for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
1514 Elements[i] = ConstantUInt::get(Type::UByteTy, (unsigned char)Data[i]);
Misha Brukman12c29d12003-09-22 23:38:23 +00001515
Reid Spencer060d25d2004-06-29 23:29:38 +00001516 // Create the constant, inserting it as needed.
1517 Constant *C = ConstantArray::get(ATy, Elements);
1518 unsigned Slot = insertValue(C, Typ, Tab);
Chris Lattner389bd042004-12-09 06:19:44 +00001519 ResolveReferencesToConstant(C, Typ, Slot);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001520 if (Handler) Handler->handleConstantString(cast<ConstantArray>(C));
Reid Spencer060d25d2004-06-29 23:29:38 +00001521 }
Misha Brukman12c29d12003-09-22 23:38:23 +00001522}
1523
Reid Spencer04cde2c2004-07-04 11:33:49 +00001524/// Parse the constant pool.
Reid Spencer060d25d2004-06-29 23:29:38 +00001525void BytecodeReader::ParseConstantPool(ValueTable &Tab,
Reid Spencer04cde2c2004-07-04 11:33:49 +00001526 TypeListTy &TypeTab,
Reid Spencer46b002c2004-07-11 17:28:43 +00001527 bool isFunction) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001528 if (Handler) Handler->handleGlobalConstantsBegin();
1529
1530 /// In LLVM 1.3 Type does not derive from Value so the types
1531 /// do not occupy a plane. Consequently, we read the types
1532 /// first in the constant pool.
Reid Spencer46b002c2004-07-11 17:28:43 +00001533 if (isFunction && !hasTypeDerivedFromValue) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001534 unsigned NumEntries = read_vbr_uint();
Reid Spencer46b002c2004-07-11 17:28:43 +00001535 ParseTypes(TypeTab, NumEntries);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001536 }
1537
Reid Spencer46b002c2004-07-11 17:28:43 +00001538 while (moreInBlock()) {
Reid Spencer060d25d2004-06-29 23:29:38 +00001539 unsigned NumEntries = read_vbr_uint();
Reid Spencer04cde2c2004-07-04 11:33:49 +00001540 unsigned Typ = 0;
1541 bool isTypeType = read_typeid(Typ);
1542
1543 /// In LLVM 1.2 and before, Types were written to the
1544 /// bytecode file in the "Type Type" plane (#12).
1545 /// In 1.3 plane 12 is now the label plane. Handle this here.
Reid Spencer46b002c2004-07-11 17:28:43 +00001546 if (isTypeType) {
1547 ParseTypes(TypeTab, NumEntries);
Reid Spencer060d25d2004-06-29 23:29:38 +00001548 } else if (Typ == Type::VoidTyID) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001549 /// Use of Type::VoidTyID is a misnomer. It actually means
1550 /// that the following plane is constant strings
Reid Spencer060d25d2004-06-29 23:29:38 +00001551 assert(&Tab == &ModuleValues && "Cannot read strings in functions!");
1552 ParseStringConstants(NumEntries, Tab);
1553 } else {
1554 for (unsigned i = 0; i < NumEntries; ++i) {
1555 Constant *C = ParseConstantValue(Typ);
1556 assert(C && "ParseConstantValue returned NULL!");
1557 unsigned Slot = insertValue(C, Typ, Tab);
Chris Lattner29b789b2003-11-19 17:27:18 +00001558
Reid Spencer060d25d2004-06-29 23:29:38 +00001559 // If we are reading a function constant table, make sure that we adjust
1560 // the slot number to be the real global constant number.
1561 //
1562 if (&Tab != &ModuleValues && Typ < ModuleValues.size() &&
1563 ModuleValues[Typ])
1564 Slot += ModuleValues[Typ]->size();
Chris Lattner389bd042004-12-09 06:19:44 +00001565 ResolveReferencesToConstant(C, Typ, Slot);
Reid Spencer060d25d2004-06-29 23:29:38 +00001566 }
1567 }
1568 }
Chris Lattner02dce162004-12-04 05:28:27 +00001569
1570 // After we have finished parsing the constant pool, we had better not have
1571 // any dangling references left.
Reid Spencer3c391272004-12-04 22:19:53 +00001572 if (!ConstantFwdRefs.empty()) {
Reid Spencer3c391272004-12-04 22:19:53 +00001573 ConstantRefsType::const_iterator I = ConstantFwdRefs.begin();
Reid Spencer3c391272004-12-04 22:19:53 +00001574 Constant* missingConst = I->second;
1575 error(utostr(ConstantFwdRefs.size()) +
1576 " unresolved constant reference exist. First one is '" +
1577 missingConst->getName() + "' of type '" +
Chris Lattner389bd042004-12-09 06:19:44 +00001578 missingConst->getType()->getDescription() + "'.");
Reid Spencer3c391272004-12-04 22:19:53 +00001579 }
Chris Lattner02dce162004-12-04 05:28:27 +00001580
Reid Spencer060d25d2004-06-29 23:29:38 +00001581 checkPastBlockEnd("Constant Pool");
Reid Spencer04cde2c2004-07-04 11:33:49 +00001582 if (Handler) Handler->handleGlobalConstantsEnd();
Reid Spencer060d25d2004-06-29 23:29:38 +00001583}
Chris Lattner00950542001-06-06 20:29:01 +00001584
Reid Spencer04cde2c2004-07-04 11:33:49 +00001585/// Parse the contents of a function. Note that this function can be
1586/// called lazily by materializeFunction
1587/// @see materializeFunction
Reid Spencer46b002c2004-07-11 17:28:43 +00001588void BytecodeReader::ParseFunctionBody(Function* F) {
Reid Spencer060d25d2004-06-29 23:29:38 +00001589
1590 unsigned FuncSize = BlockEnd - At;
Chris Lattnere3869c82003-04-16 21:16:05 +00001591 GlobalValue::LinkageTypes Linkage = GlobalValue::ExternalLinkage;
1592
Reid Spencer060d25d2004-06-29 23:29:38 +00001593 unsigned LinkageType = read_vbr_uint();
Chris Lattnerc08912f2004-01-14 16:44:44 +00001594 switch (LinkageType) {
1595 case 0: Linkage = GlobalValue::ExternalLinkage; break;
1596 case 1: Linkage = GlobalValue::WeakLinkage; break;
1597 case 2: Linkage = GlobalValue::AppendingLinkage; break;
1598 case 3: Linkage = GlobalValue::InternalLinkage; break;
1599 case 4: Linkage = GlobalValue::LinkOnceLinkage; break;
Reid Spencer060d25d2004-06-29 23:29:38 +00001600 default:
Reid Spencer24399722004-07-09 22:21:33 +00001601 error("Invalid linkage type for Function.");
Reid Spencer060d25d2004-06-29 23:29:38 +00001602 Linkage = GlobalValue::InternalLinkage;
1603 break;
Chris Lattnere3869c82003-04-16 21:16:05 +00001604 }
Chris Lattnerd23b1d32001-11-26 18:56:10 +00001605
Reid Spencer46b002c2004-07-11 17:28:43 +00001606 F->setLinkage(Linkage);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001607 if (Handler) Handler->handleFunctionBegin(F,FuncSize);
Chris Lattner00950542001-06-06 20:29:01 +00001608
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001609 // Keep track of how many basic blocks we have read in...
1610 unsigned BlockNum = 0;
Chris Lattner89e02532004-01-18 21:08:15 +00001611 bool InsertedArguments = false;
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001612
Reid Spencer060d25d2004-06-29 23:29:38 +00001613 BufPtr MyEnd = BlockEnd;
Reid Spencer46b002c2004-07-11 17:28:43 +00001614 while (At < MyEnd) {
Chris Lattner00950542001-06-06 20:29:01 +00001615 unsigned Type, Size;
Reid Spencer060d25d2004-06-29 23:29:38 +00001616 BufPtr OldAt = At;
1617 read_block(Type, Size);
Chris Lattner00950542001-06-06 20:29:01 +00001618
1619 switch (Type) {
Reid Spencerad89bd62004-07-25 18:07:36 +00001620 case BytecodeFormat::ConstantPoolBlockID:
Chris Lattner89e02532004-01-18 21:08:15 +00001621 if (!InsertedArguments) {
1622 // Insert arguments into the value table before we parse the first basic
1623 // block in the function, but after we potentially read in the
1624 // compaction table.
Reid Spencer04cde2c2004-07-04 11:33:49 +00001625 insertArguments(F);
Chris Lattner89e02532004-01-18 21:08:15 +00001626 InsertedArguments = true;
1627 }
1628
Reid Spencer04cde2c2004-07-04 11:33:49 +00001629 ParseConstantPool(FunctionValues, FunctionTypes, true);
Chris Lattner00950542001-06-06 20:29:01 +00001630 break;
1631
Reid Spencerad89bd62004-07-25 18:07:36 +00001632 case BytecodeFormat::CompactionTableBlockID:
Reid Spencer060d25d2004-06-29 23:29:38 +00001633 ParseCompactionTable();
Chris Lattner89e02532004-01-18 21:08:15 +00001634 break;
1635
Chris Lattner00950542001-06-06 20:29:01 +00001636 case BytecodeFormat::BasicBlock: {
Chris Lattner89e02532004-01-18 21:08:15 +00001637 if (!InsertedArguments) {
1638 // Insert arguments into the value table before we parse the first basic
1639 // block in the function, but after we potentially read in the
1640 // compaction table.
Reid Spencer04cde2c2004-07-04 11:33:49 +00001641 insertArguments(F);
Chris Lattner89e02532004-01-18 21:08:15 +00001642 InsertedArguments = true;
1643 }
1644
Reid Spencer060d25d2004-06-29 23:29:38 +00001645 BasicBlock *BB = ParseBasicBlock(BlockNum++);
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001646 F->getBasicBlockList().push_back(BB);
Chris Lattner00950542001-06-06 20:29:01 +00001647 break;
1648 }
1649
Reid Spencerad89bd62004-07-25 18:07:36 +00001650 case BytecodeFormat::InstructionListBlockID: {
Chris Lattner89e02532004-01-18 21:08:15 +00001651 // Insert arguments into the value table before we parse the instruction
1652 // list for the function, but after we potentially read in the compaction
1653 // table.
1654 if (!InsertedArguments) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001655 insertArguments(F);
Chris Lattner89e02532004-01-18 21:08:15 +00001656 InsertedArguments = true;
1657 }
1658
Reid Spencer060d25d2004-06-29 23:29:38 +00001659 if (BlockNum)
Reid Spencer24399722004-07-09 22:21:33 +00001660 error("Already parsed basic blocks!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001661 BlockNum = ParseInstructionList(F);
Chris Lattner8d1dbd22003-12-01 07:05:31 +00001662 break;
1663 }
1664
Reid Spencerad89bd62004-07-25 18:07:36 +00001665 case BytecodeFormat::SymbolTableBlockID:
Reid Spencer060d25d2004-06-29 23:29:38 +00001666 ParseSymbolTable(F, &F->getSymbolTable());
Chris Lattner00950542001-06-06 20:29:01 +00001667 break;
1668
1669 default:
Reid Spencer060d25d2004-06-29 23:29:38 +00001670 At += Size;
1671 if (OldAt > At)
Reid Spencer24399722004-07-09 22:21:33 +00001672 error("Wrapped around reading bytecode.");
Chris Lattner00950542001-06-06 20:29:01 +00001673 break;
1674 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001675 BlockEnd = MyEnd;
Chris Lattner1d670cc2001-09-07 16:37:43 +00001676
Misha Brukman12c29d12003-09-22 23:38:23 +00001677 // Malformed bc file if read past end of block.
Reid Spencer060d25d2004-06-29 23:29:38 +00001678 align32();
Chris Lattner00950542001-06-06 20:29:01 +00001679 }
1680
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001681 // Make sure there were no references to non-existant basic blocks.
1682 if (BlockNum != ParsedBasicBlocks.size())
Reid Spencer24399722004-07-09 22:21:33 +00001683 error("Illegal basic block operand reference");
Reid Spencer060d25d2004-06-29 23:29:38 +00001684
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001685 ParsedBasicBlocks.clear();
1686
Chris Lattner97330cf2003-10-09 23:10:14 +00001687 // Resolve forward references. Replace any uses of a forward reference value
1688 // with the real value.
Chris Lattner8eb10ce2003-10-09 06:05:40 +00001689 while (!ForwardReferences.empty()) {
Chris Lattnerc4d69162004-12-09 04:51:50 +00001690 std::map<std::pair<unsigned,unsigned>, Value*>::iterator
1691 I = ForwardReferences.begin();
1692 Value *V = getValue(I->first.first, I->first.second, false);
Chris Lattner8eb10ce2003-10-09 06:05:40 +00001693 Value *PlaceHolder = I->second;
Chris Lattnerc4d69162004-12-09 04:51:50 +00001694 PlaceHolder->replaceAllUsesWith(V);
Chris Lattner8eb10ce2003-10-09 06:05:40 +00001695 ForwardReferences.erase(I);
Chris Lattner8eb10ce2003-10-09 06:05:40 +00001696 delete PlaceHolder;
Chris Lattner6e448022003-10-08 21:51:46 +00001697 }
Chris Lattner00950542001-06-06 20:29:01 +00001698
Misha Brukman12c29d12003-09-22 23:38:23 +00001699 // Clear out function-level types...
Reid Spencer060d25d2004-06-29 23:29:38 +00001700 FunctionTypes.clear();
1701 CompactionTypes.clear();
1702 CompactionValues.clear();
1703 freeTable(FunctionValues);
1704
Reid Spencer04cde2c2004-07-04 11:33:49 +00001705 if (Handler) Handler->handleFunctionEnd(F);
Chris Lattner00950542001-06-06 20:29:01 +00001706}
1707
Reid Spencer04cde2c2004-07-04 11:33:49 +00001708/// This function parses LLVM functions lazily. It obtains the type of the
1709/// function and records where the body of the function is in the bytecode
1710/// buffer. The caller can then use the ParseNextFunction and
1711/// ParseAllFunctionBodies to get handler events for the functions.
Reid Spencer060d25d2004-06-29 23:29:38 +00001712void BytecodeReader::ParseFunctionLazily() {
1713 if (FunctionSignatureList.empty())
Reid Spencer24399722004-07-09 22:21:33 +00001714 error("FunctionSignatureList empty!");
Chris Lattner89e02532004-01-18 21:08:15 +00001715
Reid Spencer060d25d2004-06-29 23:29:38 +00001716 Function *Func = FunctionSignatureList.back();
1717 FunctionSignatureList.pop_back();
Chris Lattner24102432004-01-18 22:35:34 +00001718
Reid Spencer060d25d2004-06-29 23:29:38 +00001719 // Save the information for future reading of the function
1720 LazyFunctionLoadMap[Func] = LazyFunctionInfo(BlockStart, BlockEnd);
Chris Lattner89e02532004-01-18 21:08:15 +00001721
Misha Brukmana3e6ad62004-11-14 21:02:55 +00001722 // This function has a body but it's not loaded so it appears `External'.
1723 // Mark it as a `Ghost' instead to notify the users that it has a body.
1724 Func->setLinkage(GlobalValue::GhostLinkage);
1725
Reid Spencer060d25d2004-06-29 23:29:38 +00001726 // Pretend we've `parsed' this function
1727 At = BlockEnd;
1728}
Chris Lattner89e02532004-01-18 21:08:15 +00001729
Reid Spencer04cde2c2004-07-04 11:33:49 +00001730/// The ParserFunction method lazily parses one function. Use this method to
1731/// casue the parser to parse a specific function in the module. Note that
1732/// this will remove the function from what is to be included by
1733/// ParseAllFunctionBodies.
1734/// @see ParseAllFunctionBodies
1735/// @see ParseBytecode
Reid Spencer060d25d2004-06-29 23:29:38 +00001736void BytecodeReader::ParseFunction(Function* Func) {
1737 // Find {start, end} pointers and slot in the map. If not there, we're done.
1738 LazyFunctionMap::iterator Fi = LazyFunctionLoadMap.find(Func);
Chris Lattner89e02532004-01-18 21:08:15 +00001739
Reid Spencer060d25d2004-06-29 23:29:38 +00001740 // Make sure we found it
Reid Spencer46b002c2004-07-11 17:28:43 +00001741 if (Fi == LazyFunctionLoadMap.end()) {
Reid Spencer24399722004-07-09 22:21:33 +00001742 error("Unrecognized function of type " + Func->getType()->getDescription());
Reid Spencer060d25d2004-06-29 23:29:38 +00001743 return;
Chris Lattner89e02532004-01-18 21:08:15 +00001744 }
1745
Reid Spencer060d25d2004-06-29 23:29:38 +00001746 BlockStart = At = Fi->second.Buf;
1747 BlockEnd = Fi->second.EndBuf;
Reid Spencer24399722004-07-09 22:21:33 +00001748 assert(Fi->first == Func && "Found wrong function?");
Reid Spencer060d25d2004-06-29 23:29:38 +00001749
1750 LazyFunctionLoadMap.erase(Fi);
1751
Reid Spencer46b002c2004-07-11 17:28:43 +00001752 this->ParseFunctionBody(Func);
Chris Lattner89e02532004-01-18 21:08:15 +00001753}
1754
Reid Spencer04cde2c2004-07-04 11:33:49 +00001755/// The ParseAllFunctionBodies method parses through all the previously
1756/// unparsed functions in the bytecode file. If you want to completely parse
1757/// a bytecode file, this method should be called after Parsebytecode because
1758/// Parsebytecode only records the locations in the bytecode file of where
1759/// the function definitions are located. This function uses that information
1760/// to materialize the functions.
1761/// @see ParseBytecode
Reid Spencer060d25d2004-06-29 23:29:38 +00001762void BytecodeReader::ParseAllFunctionBodies() {
1763 LazyFunctionMap::iterator Fi = LazyFunctionLoadMap.begin();
1764 LazyFunctionMap::iterator Fe = LazyFunctionLoadMap.end();
Chris Lattner89e02532004-01-18 21:08:15 +00001765
Reid Spencer46b002c2004-07-11 17:28:43 +00001766 while (Fi != Fe) {
Reid Spencer060d25d2004-06-29 23:29:38 +00001767 Function* Func = Fi->first;
1768 BlockStart = At = Fi->second.Buf;
1769 BlockEnd = Fi->second.EndBuf;
1770 this->ParseFunctionBody(Func);
1771 ++Fi;
1772 }
1773}
Chris Lattner89e02532004-01-18 21:08:15 +00001774
Reid Spencer04cde2c2004-07-04 11:33:49 +00001775/// Parse the global type list
Reid Spencer060d25d2004-06-29 23:29:38 +00001776void BytecodeReader::ParseGlobalTypes() {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001777 // Read the number of types
1778 unsigned NumEntries = read_vbr_uint();
Reid Spencer011bed52004-07-09 21:13:53 +00001779
1780 // Ignore the type plane identifier for types if the bc file is pre 1.3
1781 if (hasTypeDerivedFromValue)
1782 read_vbr_uint();
1783
Reid Spencer46b002c2004-07-11 17:28:43 +00001784 ParseTypes(ModuleTypes, NumEntries);
Reid Spencer060d25d2004-06-29 23:29:38 +00001785}
1786
Reid Spencer04cde2c2004-07-04 11:33:49 +00001787/// Parse the Global info (types, global vars, constants)
Reid Spencer060d25d2004-06-29 23:29:38 +00001788void BytecodeReader::ParseModuleGlobalInfo() {
1789
Reid Spencer04cde2c2004-07-04 11:33:49 +00001790 if (Handler) Handler->handleModuleGlobalsBegin();
Chris Lattner00950542001-06-06 20:29:01 +00001791
Chris Lattner70cc3392001-09-10 07:58:01 +00001792 // Read global variables...
Reid Spencer060d25d2004-06-29 23:29:38 +00001793 unsigned VarType = read_vbr_uint();
Chris Lattner70cc3392001-09-10 07:58:01 +00001794 while (VarType != Type::VoidTyID) { // List is terminated by Void
Chris Lattner9dd87702004-04-03 23:43:42 +00001795 // VarType Fields: bit0 = isConstant, bit1 = hasInitializer, bit2,3,4 =
1796 // Linkage, bit4+ = slot#
1797 unsigned SlotNo = VarType >> 5;
Reid Spencer46b002c2004-07-11 17:28:43 +00001798 if (sanitizeTypeId(SlotNo))
Reid Spencer24399722004-07-09 22:21:33 +00001799 error("Invalid type (type type) for global var!");
Chris Lattner9dd87702004-04-03 23:43:42 +00001800 unsigned LinkageID = (VarType >> 2) & 7;
Reid Spencer060d25d2004-06-29 23:29:38 +00001801 bool isConstant = VarType & 1;
1802 bool hasInitializer = VarType & 2;
Chris Lattnere3869c82003-04-16 21:16:05 +00001803 GlobalValue::LinkageTypes Linkage;
1804
Chris Lattnerc08912f2004-01-14 16:44:44 +00001805 switch (LinkageID) {
Chris Lattnerc08912f2004-01-14 16:44:44 +00001806 case 0: Linkage = GlobalValue::ExternalLinkage; break;
1807 case 1: Linkage = GlobalValue::WeakLinkage; break;
1808 case 2: Linkage = GlobalValue::AppendingLinkage; break;
1809 case 3: Linkage = GlobalValue::InternalLinkage; break;
1810 case 4: Linkage = GlobalValue::LinkOnceLinkage; break;
Reid Spencer060d25d2004-06-29 23:29:38 +00001811 default:
Reid Spencer24399722004-07-09 22:21:33 +00001812 error("Unknown linkage type: " + utostr(LinkageID));
Reid Spencer060d25d2004-06-29 23:29:38 +00001813 Linkage = GlobalValue::InternalLinkage;
1814 break;
Chris Lattnere3869c82003-04-16 21:16:05 +00001815 }
1816
1817 const Type *Ty = getType(SlotNo);
Reid Spencer46b002c2004-07-11 17:28:43 +00001818 if (!Ty) {
Reid Spencer24399722004-07-09 22:21:33 +00001819 error("Global has no type! SlotNo=" + utostr(SlotNo));
Reid Spencer060d25d2004-06-29 23:29:38 +00001820 }
1821
Reid Spencer46b002c2004-07-11 17:28:43 +00001822 if (!isa<PointerType>(Ty)) {
Reid Spencer24399722004-07-09 22:21:33 +00001823 error("Global not a pointer type! Ty= " + Ty->getDescription());
Reid Spencer060d25d2004-06-29 23:29:38 +00001824 }
Chris Lattner70cc3392001-09-10 07:58:01 +00001825
Chris Lattner52e20b02003-03-19 20:54:26 +00001826 const Type *ElTy = cast<PointerType>(Ty)->getElementType();
Chris Lattnerd70684f2001-09-18 04:01:05 +00001827
Chris Lattner70cc3392001-09-10 07:58:01 +00001828 // Create the global variable...
Reid Spencer060d25d2004-06-29 23:29:38 +00001829 GlobalVariable *GV = new GlobalVariable(ElTy, isConstant, Linkage,
Chris Lattner52e20b02003-03-19 20:54:26 +00001830 0, "", TheModule);
Chris Lattner29b789b2003-11-19 17:27:18 +00001831 insertValue(GV, SlotNo, ModuleValues);
Chris Lattner05950c32001-10-13 06:47:01 +00001832
Reid Spencer060d25d2004-06-29 23:29:38 +00001833 unsigned initSlot = 0;
1834 if (hasInitializer) {
1835 initSlot = read_vbr_uint();
1836 GlobalInits.push_back(std::make_pair(GV, initSlot));
1837 }
1838
1839 // Notify handler about the global value.
Chris Lattner4a242b32004-10-14 01:39:18 +00001840 if (Handler)
1841 Handler->handleGlobalVariable(ElTy, isConstant, Linkage, SlotNo,initSlot);
Reid Spencer060d25d2004-06-29 23:29:38 +00001842
1843 // Get next item
1844 VarType = read_vbr_uint();
Chris Lattner70cc3392001-09-10 07:58:01 +00001845 }
1846
Chris Lattner52e20b02003-03-19 20:54:26 +00001847 // Read the function objects for all of the functions that are coming
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001848 unsigned FnSignature = read_vbr_uint();
Reid Spencer24399722004-07-09 22:21:33 +00001849
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001850 if (hasNoFlagsForFunctions)
1851 FnSignature = (FnSignature << 5) + 1;
1852
1853 // List is terminated by VoidTy.
1854 while ((FnSignature >> 5) != Type::VoidTyID) {
1855 const Type *Ty = getType(FnSignature >> 5);
Chris Lattner927b1852003-10-09 20:22:47 +00001856 if (!isa<PointerType>(Ty) ||
Reid Spencer060d25d2004-06-29 23:29:38 +00001857 !isa<FunctionType>(cast<PointerType>(Ty)->getElementType())) {
Reid Spencer24399722004-07-09 22:21:33 +00001858 error("Function not a pointer to function type! Ty = " +
Reid Spencer46b002c2004-07-11 17:28:43 +00001859 Ty->getDescription());
Reid Spencer060d25d2004-06-29 23:29:38 +00001860 }
Chris Lattner8cdc6b72002-10-23 00:51:54 +00001861
Chris Lattner2a7b6ba2003-03-06 17:15:19 +00001862 // We create functions by passing the underlying FunctionType to create...
Reid Spencer060d25d2004-06-29 23:29:38 +00001863 const FunctionType* FTy =
1864 cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
Chris Lattner00950542001-06-06 20:29:01 +00001865
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001866
Chris Lattner18549c22004-11-15 21:43:03 +00001867 // Insert the place holder.
1868 Function* Func = new Function(FTy, GlobalValue::ExternalLinkage,
Reid Spencer04cde2c2004-07-04 11:33:49 +00001869 "", TheModule);
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001870 insertValue(Func, FnSignature >> 5, ModuleValues);
1871
1872 // Flags are not used yet.
Chris Lattner97fbc502004-11-15 22:38:52 +00001873 unsigned Flags = FnSignature & 31;
Chris Lattner00950542001-06-06 20:29:01 +00001874
Chris Lattner97fbc502004-11-15 22:38:52 +00001875 // Save this for later so we know type of lazily instantiated functions.
1876 // Note that known-external functions do not have FunctionInfo blocks, so we
1877 // do not add them to the FunctionSignatureList.
1878 if ((Flags & (1 << 4)) == 0)
1879 FunctionSignatureList.push_back(Func);
Chris Lattner52e20b02003-03-19 20:54:26 +00001880
Reid Spencer04cde2c2004-07-04 11:33:49 +00001881 if (Handler) Handler->handleFunctionDeclaration(Func);
Reid Spencer060d25d2004-06-29 23:29:38 +00001882
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001883 // Get the next function signature.
1884 FnSignature = read_vbr_uint();
1885 if (hasNoFlagsForFunctions)
1886 FnSignature = (FnSignature << 5) + 1;
Chris Lattner00950542001-06-06 20:29:01 +00001887 }
1888
Chris Lattner74734132002-08-17 22:01:27 +00001889 // Now that the function signature list is set up, reverse it so that we can
1890 // remove elements efficiently from the back of the vector.
1891 std::reverse(FunctionSignatureList.begin(), FunctionSignatureList.end());
Chris Lattner00950542001-06-06 20:29:01 +00001892
Reid Spencerad89bd62004-07-25 18:07:36 +00001893 // If this bytecode format has dependent library information in it ..
1894 if (!hasNoDependentLibraries) {
1895 // Read in the number of dependent library items that follow
1896 unsigned num_dep_libs = read_vbr_uint();
1897 std::string dep_lib;
1898 while( num_dep_libs-- ) {
1899 dep_lib = read_str();
Reid Spencerada16182004-07-25 21:36:26 +00001900 TheModule->addLibrary(dep_lib);
Reid Spencer5b472d92004-08-21 20:49:23 +00001901 if (Handler)
1902 Handler->handleDependentLibrary(dep_lib);
Reid Spencerad89bd62004-07-25 18:07:36 +00001903 }
1904
Reid Spencer5b472d92004-08-21 20:49:23 +00001905
Reid Spencerad89bd62004-07-25 18:07:36 +00001906 // Read target triple and place into the module
1907 std::string triple = read_str();
1908 TheModule->setTargetTriple(triple);
Reid Spencer5b472d92004-08-21 20:49:23 +00001909 if (Handler)
1910 Handler->handleTargetTriple(triple);
Reid Spencerad89bd62004-07-25 18:07:36 +00001911 }
1912
1913 if (hasInconsistentModuleGlobalInfo)
1914 align32();
1915
Chris Lattner00950542001-06-06 20:29:01 +00001916 // This is for future proofing... in the future extra fields may be added that
1917 // we don't understand, so we transparently ignore them.
1918 //
Reid Spencer060d25d2004-06-29 23:29:38 +00001919 At = BlockEnd;
1920
Reid Spencer04cde2c2004-07-04 11:33:49 +00001921 if (Handler) Handler->handleModuleGlobalsEnd();
Chris Lattner00950542001-06-06 20:29:01 +00001922}
1923
Reid Spencer04cde2c2004-07-04 11:33:49 +00001924/// Parse the version information and decode it by setting flags on the
1925/// Reader that enable backward compatibility of the reader.
Reid Spencer060d25d2004-06-29 23:29:38 +00001926void BytecodeReader::ParseVersionInfo() {
1927 unsigned Version = read_vbr_uint();
Chris Lattner036b8aa2003-03-06 17:55:45 +00001928
1929 // Unpack version number: low four bits are for flags, top bits = version
Chris Lattnerd445c6b2003-08-24 13:47:36 +00001930 Module::Endianness Endianness;
1931 Module::PointerSize PointerSize;
1932 Endianness = (Version & 1) ? Module::BigEndian : Module::LittleEndian;
1933 PointerSize = (Version & 2) ? Module::Pointer64 : Module::Pointer32;
1934
1935 bool hasNoEndianness = Version & 4;
1936 bool hasNoPointerSize = Version & 8;
1937
1938 RevisionNum = Version >> 4;
Chris Lattnere3869c82003-04-16 21:16:05 +00001939
1940 // Default values for the current bytecode version
Chris Lattner44d0eeb2004-01-15 17:55:01 +00001941 hasInconsistentModuleGlobalInfo = false;
Chris Lattner80b97342004-01-17 23:25:43 +00001942 hasExplicitPrimitiveZeros = false;
Chris Lattner5fa428f2004-04-05 01:27:26 +00001943 hasRestrictedGEPTypes = false;
Reid Spencer04cde2c2004-07-04 11:33:49 +00001944 hasTypeDerivedFromValue = false;
Reid Spencerad89bd62004-07-25 18:07:36 +00001945 hasLongBlockHeaders = false;
Reid Spencerad89bd62004-07-25 18:07:36 +00001946 has32BitTypes = false;
1947 hasNoDependentLibraries = false;
Reid Spencer38d54be2004-08-17 07:45:14 +00001948 hasAlignment = false;
Reid Spencer5b472d92004-08-21 20:49:23 +00001949 hasInconsistentBBSlotNums = false;
1950 hasVBRByteTypes = false;
1951 hasUnnecessaryModuleBlockId = false;
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001952 hasNoUndefValue = false;
1953 hasNoFlagsForFunctions = false;
1954 hasNoUnreachableInst = false;
Chris Lattner036b8aa2003-03-06 17:55:45 +00001955
1956 switch (RevisionNum) {
Reid Spencer5b472d92004-08-21 20:49:23 +00001957 case 0: // LLVM 1.0, 1.1 (Released)
Chris Lattner9e893e82004-01-14 23:35:21 +00001958 // Base LLVM 1.0 bytecode format.
Chris Lattner44d0eeb2004-01-15 17:55:01 +00001959 hasInconsistentModuleGlobalInfo = true;
Chris Lattner80b97342004-01-17 23:25:43 +00001960 hasExplicitPrimitiveZeros = true;
Reid Spencer04cde2c2004-07-04 11:33:49 +00001961
Chris Lattner80b97342004-01-17 23:25:43 +00001962 // FALL THROUGH
Reid Spencer5b472d92004-08-21 20:49:23 +00001963
1964 case 1: // LLVM 1.2 (Released)
Chris Lattner9e893e82004-01-14 23:35:21 +00001965 // LLVM 1.2 added explicit support for emitting strings efficiently.
Chris Lattner44d0eeb2004-01-15 17:55:01 +00001966
1967 // Also, it fixed the problem where the size of the ModuleGlobalInfo block
1968 // included the size for the alignment at the end, where the rest of the
1969 // blocks did not.
Chris Lattner5fa428f2004-04-05 01:27:26 +00001970
1971 // LLVM 1.2 and before required that GEP indices be ubyte constants for
1972 // structures and longs for sequential types.
1973 hasRestrictedGEPTypes = true;
1974
Reid Spencer04cde2c2004-07-04 11:33:49 +00001975 // LLVM 1.2 and before had the Type class derive from Value class. This
1976 // changed in release 1.3 and consequently LLVM 1.3 bytecode files are
1977 // written differently because Types can no longer be part of the
1978 // type planes for Values.
1979 hasTypeDerivedFromValue = true;
1980
Chris Lattner5fa428f2004-04-05 01:27:26 +00001981 // FALL THROUGH
Reid Spencerad89bd62004-07-25 18:07:36 +00001982
Reid Spencer5b472d92004-08-21 20:49:23 +00001983 case 2: // 1.2.5 (Not Released)
Reid Spencerad89bd62004-07-25 18:07:36 +00001984
Reid Spencer5b472d92004-08-21 20:49:23 +00001985 // LLVM 1.2 and earlier had two-word block headers. This is a bit wasteful,
Chris Lattner4a242b32004-10-14 01:39:18 +00001986 // especially for small files where the 8 bytes per block is a large
1987 // fraction of the total block size. In LLVM 1.3, the block type and length
1988 // are compressed into a single 32-bit unsigned integer. 27 bits for length,
1989 // 5 bits for block type.
Reid Spencerad89bd62004-07-25 18:07:36 +00001990 hasLongBlockHeaders = true;
1991
Reid Spencer5b472d92004-08-21 20:49:23 +00001992 // LLVM 1.2 and earlier wrote type slot numbers as vbr_uint32. In LLVM 1.3
Chris Lattner4a242b32004-10-14 01:39:18 +00001993 // this has been reduced to vbr_uint24. It shouldn't make much difference
1994 // since we haven't run into a module with > 24 million types, but for
1995 // safety the 24-bit restriction has been enforced in 1.3 to free some bits
1996 // in various places and to ensure consistency.
Reid Spencerad89bd62004-07-25 18:07:36 +00001997 has32BitTypes = true;
1998
Reid Spencer5b472d92004-08-21 20:49:23 +00001999 // LLVM 1.2 and earlier did not provide a target triple nor a list of
2000 // libraries on which the bytecode is dependent. LLVM 1.3 provides these
2001 // features, for use in future versions of LLVM.
Reid Spencerad89bd62004-07-25 18:07:36 +00002002 hasNoDependentLibraries = true;
2003
2004 // FALL THROUGH
Reid Spencer5b472d92004-08-21 20:49:23 +00002005
2006 case 3: // LLVM 1.3 (Released)
2007 // LLVM 1.3 and earlier caused alignment bytes to be written on some block
2008 // boundaries and at the end of some strings. In extreme cases (e.g. lots
2009 // of GEP references to a constant array), this can increase the file size
2010 // by 30% or more. In version 1.4 alignment is done away with completely.
Reid Spencer38d54be2004-08-17 07:45:14 +00002011 hasAlignment = true;
2012
2013 // FALL THROUGH
Reid Spencer5b472d92004-08-21 20:49:23 +00002014
2015 case 4: // 1.3.1 (Not Released)
Chris Lattnera79e7cc2004-10-16 18:18:16 +00002016 // In version 4, we did not support the 'undef' constant.
2017 hasNoUndefValue = true;
2018
2019 // In version 4 and above, we did not include space for flags for functions
2020 // in the module info block.
2021 hasNoFlagsForFunctions = true;
2022
2023 // In version 4 and above, we did not include the 'unreachable' instruction
2024 // in the opcode numbering in the bytecode file.
2025 hasNoUnreachableInst = true;
Chris Lattner2e7ec122004-10-16 18:56:02 +00002026 break;
Chris Lattnera79e7cc2004-10-16 18:18:16 +00002027
2028 // FALL THROUGH
2029
2030 case 5: // 1.x.x (Not Released)
Chris Lattnera79e7cc2004-10-16 18:18:16 +00002031 break;
Chris Lattner2e7ec122004-10-16 18:56:02 +00002032 // FIXME: NONE of this is implemented yet!
Chris Lattnera79e7cc2004-10-16 18:18:16 +00002033
2034 // In version 5, basic blocks have a minimum index of 0 whereas all the
Reid Spencer5b472d92004-08-21 20:49:23 +00002035 // other primitives have a minimum index of 1 (because 0 is the "null"
2036 // value. In version 5, we made this consistent.
2037 hasInconsistentBBSlotNums = true;
Chris Lattnerc08912f2004-01-14 16:44:44 +00002038
Chris Lattnera79e7cc2004-10-16 18:18:16 +00002039 // In version 5, the types SByte and UByte were encoded as vbr_uint so that
Reid Spencer5b472d92004-08-21 20:49:23 +00002040 // signed values > 63 and unsigned values >127 would be encoded as two
2041 // bytes. In version 5, they are encoded directly in a single byte.
2042 hasVBRByteTypes = true;
2043
Chris Lattnera79e7cc2004-10-16 18:18:16 +00002044 // In version 5, modules begin with a "Module Block" which encodes a 4-byte
Reid Spencer5b472d92004-08-21 20:49:23 +00002045 // integer value 0x01 to identify the module block. This is unnecessary and
2046 // removed in version 5.
2047 hasUnnecessaryModuleBlockId = true;
2048
Chris Lattner036b8aa2003-03-06 17:55:45 +00002049 default:
Reid Spencer24399722004-07-09 22:21:33 +00002050 error("Unknown bytecode version number: " + itostr(RevisionNum));
Chris Lattner036b8aa2003-03-06 17:55:45 +00002051 }
2052
Chris Lattnerd445c6b2003-08-24 13:47:36 +00002053 if (hasNoEndianness) Endianness = Module::AnyEndianness;
2054 if (hasNoPointerSize) PointerSize = Module::AnyPointerSize;
Chris Lattner76e38962003-04-22 18:15:10 +00002055
Brian Gaekefe2102b2004-07-14 20:33:13 +00002056 TheModule->setEndianness(Endianness);
2057 TheModule->setPointerSize(PointerSize);
2058
Reid Spencer46b002c2004-07-11 17:28:43 +00002059 if (Handler) Handler->handleVersionInfo(RevisionNum, Endianness, PointerSize);
Chris Lattner036b8aa2003-03-06 17:55:45 +00002060}
2061
Reid Spencer04cde2c2004-07-04 11:33:49 +00002062/// Parse a whole module.
Reid Spencer060d25d2004-06-29 23:29:38 +00002063void BytecodeReader::ParseModule() {
Chris Lattner00950542001-06-06 20:29:01 +00002064 unsigned Type, Size;
Chris Lattner00950542001-06-06 20:29:01 +00002065
Reid Spencer060d25d2004-06-29 23:29:38 +00002066 FunctionSignatureList.clear(); // Just in case...
Chris Lattner00950542001-06-06 20:29:01 +00002067
2068 // Read into instance variables...
Reid Spencer060d25d2004-06-29 23:29:38 +00002069 ParseVersionInfo();
Reid Spencerad89bd62004-07-25 18:07:36 +00002070 align32();
Chris Lattner00950542001-06-06 20:29:01 +00002071
Reid Spencer060d25d2004-06-29 23:29:38 +00002072 bool SeenModuleGlobalInfo = false;
2073 bool SeenGlobalTypePlane = false;
2074 BufPtr MyEnd = BlockEnd;
2075 while (At < MyEnd) {
2076 BufPtr OldAt = At;
2077 read_block(Type, Size);
2078
Chris Lattner00950542001-06-06 20:29:01 +00002079 switch (Type) {
Reid Spencer060d25d2004-06-29 23:29:38 +00002080
Reid Spencerad89bd62004-07-25 18:07:36 +00002081 case BytecodeFormat::GlobalTypePlaneBlockID:
Reid Spencer46b002c2004-07-11 17:28:43 +00002082 if (SeenGlobalTypePlane)
Reid Spencer24399722004-07-09 22:21:33 +00002083 error("Two GlobalTypePlane Blocks Encountered!");
Reid Spencer060d25d2004-06-29 23:29:38 +00002084
Reid Spencer5b472d92004-08-21 20:49:23 +00002085 if (Size > 0)
2086 ParseGlobalTypes();
Reid Spencer060d25d2004-06-29 23:29:38 +00002087 SeenGlobalTypePlane = true;
Chris Lattner52e20b02003-03-19 20:54:26 +00002088 break;
2089
Reid Spencerad89bd62004-07-25 18:07:36 +00002090 case BytecodeFormat::ModuleGlobalInfoBlockID:
Reid Spencer46b002c2004-07-11 17:28:43 +00002091 if (SeenModuleGlobalInfo)
Reid Spencer24399722004-07-09 22:21:33 +00002092 error("Two ModuleGlobalInfo Blocks Encountered!");
Reid Spencer060d25d2004-06-29 23:29:38 +00002093 ParseModuleGlobalInfo();
2094 SeenModuleGlobalInfo = true;
Chris Lattner52e20b02003-03-19 20:54:26 +00002095 break;
2096
Reid Spencerad89bd62004-07-25 18:07:36 +00002097 case BytecodeFormat::ConstantPoolBlockID:
Reid Spencer04cde2c2004-07-04 11:33:49 +00002098 ParseConstantPool(ModuleValues, ModuleTypes,false);
Chris Lattner00950542001-06-06 20:29:01 +00002099 break;
2100
Reid Spencerad89bd62004-07-25 18:07:36 +00002101 case BytecodeFormat::FunctionBlockID:
Reid Spencer060d25d2004-06-29 23:29:38 +00002102 ParseFunctionLazily();
Chris Lattner00950542001-06-06 20:29:01 +00002103 break;
Chris Lattner00950542001-06-06 20:29:01 +00002104
Reid Spencerad89bd62004-07-25 18:07:36 +00002105 case BytecodeFormat::SymbolTableBlockID:
Reid Spencer060d25d2004-06-29 23:29:38 +00002106 ParseSymbolTable(0, &TheModule->getSymbolTable());
Chris Lattner00950542001-06-06 20:29:01 +00002107 break;
Reid Spencer060d25d2004-06-29 23:29:38 +00002108
Chris Lattner00950542001-06-06 20:29:01 +00002109 default:
Reid Spencer060d25d2004-06-29 23:29:38 +00002110 At += Size;
2111 if (OldAt > At) {
Reid Spencer46b002c2004-07-11 17:28:43 +00002112 error("Unexpected Block of Type #" + utostr(Type) + " encountered!");
Reid Spencer060d25d2004-06-29 23:29:38 +00002113 }
Chris Lattner00950542001-06-06 20:29:01 +00002114 break;
2115 }
Reid Spencer060d25d2004-06-29 23:29:38 +00002116 BlockEnd = MyEnd;
2117 align32();
Chris Lattner00950542001-06-06 20:29:01 +00002118 }
2119
Chris Lattner52e20b02003-03-19 20:54:26 +00002120 // After the module constant pool has been read, we can safely initialize
2121 // global variables...
2122 while (!GlobalInits.empty()) {
2123 GlobalVariable *GV = GlobalInits.back().first;
2124 unsigned Slot = GlobalInits.back().second;
2125 GlobalInits.pop_back();
2126
2127 // Look up the initializer value...
Chris Lattner29b789b2003-11-19 17:27:18 +00002128 // FIXME: Preserve this type ID!
Reid Spencer060d25d2004-06-29 23:29:38 +00002129
2130 const llvm::PointerType* GVType = GV->getType();
2131 unsigned TypeSlot = getTypeSlot(GVType->getElementType());
Chris Lattner93361992004-01-15 18:45:25 +00002132 if (Constant *CV = getConstantValue(TypeSlot, Slot)) {
Misha Brukman12c29d12003-09-22 23:38:23 +00002133 if (GV->hasInitializer())
Reid Spencer24399722004-07-09 22:21:33 +00002134 error("Global *already* has an initializer?!");
Reid Spencer04cde2c2004-07-04 11:33:49 +00002135 if (Handler) Handler->handleGlobalInitializer(GV,CV);
Chris Lattner93361992004-01-15 18:45:25 +00002136 GV->setInitializer(CV);
Chris Lattner52e20b02003-03-19 20:54:26 +00002137 } else
Reid Spencer24399722004-07-09 22:21:33 +00002138 error("Cannot find initializer value.");
Chris Lattner52e20b02003-03-19 20:54:26 +00002139 }
2140
Reid Spencer060d25d2004-06-29 23:29:38 +00002141 /// Make sure we pulled them all out. If we didn't then there's a declaration
2142 /// but a missing body. That's not allowed.
Misha Brukman12c29d12003-09-22 23:38:23 +00002143 if (!FunctionSignatureList.empty())
Reid Spencer24399722004-07-09 22:21:33 +00002144 error("Function declared, but bytecode stream ended before definition");
Chris Lattner00950542001-06-06 20:29:01 +00002145}
2146
Reid Spencer04cde2c2004-07-04 11:33:49 +00002147/// This function completely parses a bytecode buffer given by the \p Buf
2148/// and \p Length parameters.
Reid Spencer46b002c2004-07-11 17:28:43 +00002149void BytecodeReader::ParseBytecode(BufPtr Buf, unsigned Length,
Reid Spencer5b472d92004-08-21 20:49:23 +00002150 const std::string &ModuleID) {
Misha Brukmane0dd0d42003-09-23 16:15:29 +00002151
Reid Spencer060d25d2004-06-29 23:29:38 +00002152 try {
Chris Lattner3af4b4f2004-11-30 16:58:18 +00002153 RevisionNum = 0;
Reid Spencer060d25d2004-06-29 23:29:38 +00002154 At = MemStart = BlockStart = Buf;
2155 MemEnd = BlockEnd = Buf + Length;
Misha Brukmane0dd0d42003-09-23 16:15:29 +00002156
Reid Spencer060d25d2004-06-29 23:29:38 +00002157 // Create the module
2158 TheModule = new Module(ModuleID);
Chris Lattner00950542001-06-06 20:29:01 +00002159
Reid Spencer04cde2c2004-07-04 11:33:49 +00002160 if (Handler) Handler->handleStart(TheModule, Length);
Reid Spencer060d25d2004-06-29 23:29:38 +00002161
Reid Spencerf0c977c2004-11-07 18:20:55 +00002162 // Read the four bytes of the signature.
2163 unsigned Sig = read_uint();
Reid Spencer17f52c52004-11-06 23:17:23 +00002164
Reid Spencerf0c977c2004-11-07 18:20:55 +00002165 // If this is a compressed file
2166 if (Sig == ('l' | ('l' << 8) | ('v' << 16) | ('c' << 24))) {
Reid Spencer17f52c52004-11-06 23:17:23 +00002167
Reid Spencerf0c977c2004-11-07 18:20:55 +00002168 // Invoke the decompression of the bytecode. Note that we have to skip the
2169 // file's magic number which is not part of the compressed block. Hence,
Reid Spencer61aaf2e2004-11-14 21:59:21 +00002170 // the Buf+4 and Length-4. The result goes into decompressedBlock, a data
2171 // member for retention until BytecodeReader is destructed.
2172 unsigned decompressedLength = Compressor::decompressToNewBuffer(
2173 (char*)Buf+4,Length-4,decompressedBlock);
Reid Spencerf0c977c2004-11-07 18:20:55 +00002174
2175 // We must adjust the buffer pointers used by the bytecode reader to point
Reid Spencer61aaf2e2004-11-14 21:59:21 +00002176 // into the new decompressed block. After decompression, the
2177 // decompressedBlock will point to a contiguous memory area that has
Reid Spencerf0c977c2004-11-07 18:20:55 +00002178 // the decompressed data.
Reid Spencer61aaf2e2004-11-14 21:59:21 +00002179 At = MemStart = BlockStart = Buf = (BufPtr) decompressedBlock;
Reid Spencerf0c977c2004-11-07 18:20:55 +00002180 MemEnd = BlockEnd = Buf + decompressedLength;
Reid Spencer17f52c52004-11-06 23:17:23 +00002181
Reid Spencerf0c977c2004-11-07 18:20:55 +00002182 // else if this isn't a regular (uncompressed) bytecode file, then its
2183 // and error, generate that now.
2184 } else if (Sig != ('l' | ('l' << 8) | ('v' << 16) | ('m' << 24))) {
2185 error("Invalid bytecode signature: " + utohexstr(Sig));
Reid Spencer060d25d2004-06-29 23:29:38 +00002186 }
2187
Reid Spencer060d25d2004-06-29 23:29:38 +00002188 // Tell the handler we're starting a module
Reid Spencer04cde2c2004-07-04 11:33:49 +00002189 if (Handler) Handler->handleModuleBegin(ModuleID);
Reid Spencer060d25d2004-06-29 23:29:38 +00002190
Reid Spencerad89bd62004-07-25 18:07:36 +00002191 // Get the module block and size and verify. This is handled specially
2192 // because the module block/size is always written in long format. Other
2193 // blocks are written in short format so the read_block method is used.
Reid Spencer060d25d2004-06-29 23:29:38 +00002194 unsigned Type, Size;
Reid Spencerad89bd62004-07-25 18:07:36 +00002195 Type = read_uint();
2196 Size = read_uint();
2197 if (Type != BytecodeFormat::ModuleBlockID) {
Reid Spencer24399722004-07-09 22:21:33 +00002198 error("Expected Module Block! Type:" + utostr(Type) + ", Size:"
Reid Spencer46b002c2004-07-11 17:28:43 +00002199 + utostr(Size));
Reid Spencer060d25d2004-06-29 23:29:38 +00002200 }
Chris Lattner56bc8942004-09-27 16:59:06 +00002201
2202 // It looks like the darwin ranlib program is broken, and adds trailing
2203 // garbage to the end of some bytecode files. This hack allows the bc
2204 // reader to ignore trailing garbage on bytecode files.
2205 if (At + Size < MemEnd)
2206 MemEnd = BlockEnd = At+Size;
2207
2208 if (At + Size != MemEnd)
Reid Spencer24399722004-07-09 22:21:33 +00002209 error("Invalid Top Level Block Length! Type:" + utostr(Type)
Reid Spencer46b002c2004-07-11 17:28:43 +00002210 + ", Size:" + utostr(Size));
Reid Spencer060d25d2004-06-29 23:29:38 +00002211
2212 // Parse the module contents
2213 this->ParseModule();
2214
Reid Spencer060d25d2004-06-29 23:29:38 +00002215 // Check for missing functions
Reid Spencer46b002c2004-07-11 17:28:43 +00002216 if (hasFunctions())
Reid Spencer24399722004-07-09 22:21:33 +00002217 error("Function expected, but bytecode stream ended!");
Reid Spencer060d25d2004-06-29 23:29:38 +00002218
Reid Spencer5c15fe52004-07-05 00:57:50 +00002219 // Tell the handler we're done with the module
2220 if (Handler)
2221 Handler->handleModuleEnd(ModuleID);
2222
2223 // Tell the handler we're finished the parse
Reid Spencer04cde2c2004-07-04 11:33:49 +00002224 if (Handler) Handler->handleFinish();
Reid Spencer060d25d2004-06-29 23:29:38 +00002225
Reid Spencer46b002c2004-07-11 17:28:43 +00002226 } catch (std::string& errstr) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00002227 if (Handler) Handler->handleError(errstr);
Reid Spencer060d25d2004-06-29 23:29:38 +00002228 freeState();
Chris Lattner2a7b6ba2003-03-06 17:15:19 +00002229 delete TheModule;
2230 TheModule = 0;
Chris Lattner3bdad692004-11-15 21:55:33 +00002231 if (decompressedBlock != 0 ) {
Reid Spencer61aaf2e2004-11-14 21:59:21 +00002232 ::free(decompressedBlock);
Chris Lattner3bdad692004-11-15 21:55:33 +00002233 decompressedBlock = 0;
2234 }
Chris Lattnerb0b7c0d2003-09-26 14:44:52 +00002235 throw;
Reid Spencer060d25d2004-06-29 23:29:38 +00002236 } catch (...) {
2237 std::string msg("Unknown Exception Occurred");
Reid Spencer04cde2c2004-07-04 11:33:49 +00002238 if (Handler) Handler->handleError(msg);
Reid Spencer060d25d2004-06-29 23:29:38 +00002239 freeState();
2240 delete TheModule;
2241 TheModule = 0;
Chris Lattner3bdad692004-11-15 21:55:33 +00002242 if (decompressedBlock != 0) {
Reid Spencer61aaf2e2004-11-14 21:59:21 +00002243 ::free(decompressedBlock);
Chris Lattner3bdad692004-11-15 21:55:33 +00002244 decompressedBlock = 0;
2245 }
Reid Spencer060d25d2004-06-29 23:29:38 +00002246 throw msg;
Chris Lattner2a7b6ba2003-03-06 17:15:19 +00002247 }
Chris Lattner00950542001-06-06 20:29:01 +00002248}
Reid Spencer060d25d2004-06-29 23:29:38 +00002249
2250//===----------------------------------------------------------------------===//
2251//=== Default Implementations of Handler Methods
2252//===----------------------------------------------------------------------===//
2253
2254BytecodeHandler::~BytecodeHandler() {}
Reid Spencer060d25d2004-06-29 23:29:38 +00002255
2256// vim: sw=2