blob: 18780208e2b28d181dcf874581308fd9eb31626b [file] [log] [blame]
Chris Lattnerd6b65252001-10-24 01:15:12 +00001//===- Reader.cpp - Code to read bytecode files ---------------------------===//
John Criswellb576c942003-10-20 19:43:21 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
Chris Lattner00950542001-06-06 20:29:01 +00009//
10// This library implements the functionality defined in llvm/Bytecode/Reader.h
11//
12// Note that this library should be as fast as possible, reentrant, and
13// threadsafe!!
14//
Chris Lattner00950542001-06-06 20:29:01 +000015// TODO: Allow passing in an option to ignore the symbol table
16//
Chris Lattnerd6b65252001-10-24 01:15:12 +000017//===----------------------------------------------------------------------===//
Chris Lattner00950542001-06-06 20:29:01 +000018
Reid Spencer060d25d2004-06-29 23:29:38 +000019#include "Reader.h"
20#include "llvm/Bytecode/BytecodeHandler.h"
21#include "llvm/BasicBlock.h"
22#include "llvm/Constants.h"
Reid Spencer04cde2c2004-07-04 11:33:49 +000023#include "llvm/Instructions.h"
24#include "llvm/SymbolTable.h"
Chris Lattner00950542001-06-06 20:29:01 +000025#include "llvm/Bytecode/Format.h"
Reid Spencer060d25d2004-06-29 23:29:38 +000026#include "llvm/Support/GetElementPtrTypeIterator.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000027#include "llvm/ADT/StringExtras.h"
Reid Spencer060d25d2004-06-29 23:29:38 +000028#include <sstream>
Alkis Evlogimenos20aa4742004-09-03 18:19:51 +000029#include <algorithm>
Chris Lattner29b789b2003-11-19 17:27:18 +000030using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000031
Reid Spencer46b002c2004-07-11 17:28:43 +000032namespace {
33
Reid Spencer060d25d2004-06-29 23:29:38 +000034/// @brief A class for maintaining the slot number definition
Reid Spencer46b002c2004-07-11 17:28:43 +000035/// as a placeholder for the actual definition for forward constants defs.
36class ConstantPlaceHolder : public ConstantExpr {
Reid Spencer060d25d2004-06-29 23:29:38 +000037 unsigned ID;
Reid Spencer46b002c2004-07-11 17:28:43 +000038 ConstantPlaceHolder(); // DO NOT IMPLEMENT
39 void operator=(const ConstantPlaceHolder &); // DO NOT IMPLEMENT
Reid Spencer060d25d2004-06-29 23:29:38 +000040public:
Reid Spencer46b002c2004-07-11 17:28:43 +000041 ConstantPlaceHolder(const Type *Ty, unsigned id)
42 : ConstantExpr(Instruction::UserOp1, Constant::getNullValue(Ty), Ty),
43 ID(id) {}
Reid Spencer060d25d2004-06-29 23:29:38 +000044 unsigned getID() { return ID; }
45};
Chris Lattner9e460f22003-10-04 20:00:03 +000046
Reid Spencer46b002c2004-07-11 17:28:43 +000047}
Reid Spencer060d25d2004-06-29 23:29:38 +000048
Reid Spencer24399722004-07-09 22:21:33 +000049// Provide some details on error
50inline void BytecodeReader::error(std::string err) {
51 err += " (Vers=" ;
52 err += itostr(RevisionNum) ;
53 err += ", Pos=" ;
54 err += itostr(At-MemStart);
55 err += ")";
56 throw err;
57}
58
Reid Spencer060d25d2004-06-29 23:29:38 +000059//===----------------------------------------------------------------------===//
60// Bytecode Reading Methods
61//===----------------------------------------------------------------------===//
62
Reid Spencer04cde2c2004-07-04 11:33:49 +000063/// Determine if the current block being read contains any more data.
Reid Spencer060d25d2004-06-29 23:29:38 +000064inline bool BytecodeReader::moreInBlock() {
65 return At < BlockEnd;
Chris Lattner00950542001-06-06 20:29:01 +000066}
67
Reid Spencer04cde2c2004-07-04 11:33:49 +000068/// Throw an error if we've read past the end of the current block
Reid Spencer060d25d2004-06-29 23:29:38 +000069inline void BytecodeReader::checkPastBlockEnd(const char * block_name) {
Reid Spencer46b002c2004-07-11 17:28:43 +000070 if (At > BlockEnd)
Reid Spencer24399722004-07-09 22:21:33 +000071 error(std::string("Attempt to read past the end of ") + block_name + " 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...
Reid Spencer2da5c3d2004-09-15 17:06:42 +0000350 TypeListTy::iterator I = std::find(FunctionTypes.begin(), FunctionTypes.end(), Ty);
Reid Spencer060d25d2004-06-29 23:29:38 +0000351
352 if (I != FunctionTypes.end())
Reid Spencer46b002c2004-07-11 17:28:43 +0000353 return Type::FirstDerivedTyID + ModuleTypes.size() +
354 (&*I - &FunctionTypes[0]);
Reid Spencer060d25d2004-06-29 23:29:38 +0000355
356 // Check the module level types now...
Reid Spencer2da5c3d2004-09-15 17:06:42 +0000357 I = std::find(ModuleTypes.begin(), ModuleTypes.end(), Ty);
Reid Spencer060d25d2004-06-29 23:29:38 +0000358 if (I == ModuleTypes.end())
Reid Spencer24399722004-07-09 22:21:33 +0000359 error("Didn't find type in ModuleTypes.");
Reid Spencer060d25d2004-06-29 23:29:38 +0000360 return Type::FirstDerivedTyID + (&*I - &ModuleTypes[0]);
Chris Lattner80b97342004-01-17 23:25:43 +0000361}
362
Reid Spencer04cde2c2004-07-04 11:33:49 +0000363/// This is just like getType, but when a compaction table is in use, it is
364/// ignored. It also ignores function level types.
365/// @see getType
Reid Spencer060d25d2004-06-29 23:29:38 +0000366const Type *BytecodeReader::getGlobalTableType(unsigned Slot) {
367 if (Slot < Type::FirstDerivedTyID) {
368 const Type *Ty = Type::getPrimitiveType((Type::TypeID)Slot);
Reid Spencer46b002c2004-07-11 17:28:43 +0000369 if (!Ty)
Reid Spencer24399722004-07-09 22:21:33 +0000370 error("Not a primitive type ID?");
Reid Spencer060d25d2004-06-29 23:29:38 +0000371 return Ty;
372 }
373 Slot -= Type::FirstDerivedTyID;
374 if (Slot >= ModuleTypes.size())
Reid Spencer24399722004-07-09 22:21:33 +0000375 error("Illegal compaction table type reference!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000376 return ModuleTypes[Slot];
Chris Lattner52e20b02003-03-19 20:54:26 +0000377}
378
Reid Spencer04cde2c2004-07-04 11:33:49 +0000379/// This is just like getTypeSlot, but when a compaction table is in use, it
380/// is ignored. It also ignores function level types.
Reid Spencer060d25d2004-06-29 23:29:38 +0000381unsigned BytecodeReader::getGlobalTableTypeSlot(const Type *Ty) {
382 if (Ty->isPrimitiveType())
383 return Ty->getTypeID();
Reid Spencer2da5c3d2004-09-15 17:06:42 +0000384 TypeListTy::iterator I = std::find(ModuleTypes.begin(),
Reid Spencer04cde2c2004-07-04 11:33:49 +0000385 ModuleTypes.end(), Ty);
Reid Spencer060d25d2004-06-29 23:29:38 +0000386 if (I == ModuleTypes.end())
Reid Spencer24399722004-07-09 22:21:33 +0000387 error("Didn't find type in ModuleTypes.");
Reid Spencer060d25d2004-06-29 23:29:38 +0000388 return Type::FirstDerivedTyID + (&*I - &ModuleTypes[0]);
389}
390
Reid Spencer04cde2c2004-07-04 11:33:49 +0000391/// Retrieve a value of a given type and slot number, possibly creating
392/// it if it doesn't already exist.
Reid Spencer060d25d2004-06-29 23:29:38 +0000393Value * BytecodeReader::getValue(unsigned type, unsigned oNum, bool Create) {
Chris Lattner4ee8ef22003-10-08 22:52:54 +0000394 assert(type != Type::LabelTyID && "getValue() cannot get blocks!");
Chris Lattner00950542001-06-06 20:29:01 +0000395 unsigned Num = oNum;
Chris Lattner00950542001-06-06 20:29:01 +0000396
Chris Lattner89e02532004-01-18 21:08:15 +0000397 // If there is a compaction table active, it defines the low-level numbers.
398 // If not, the module values define the low-level numbers.
Reid Spencer060d25d2004-06-29 23:29:38 +0000399 if (CompactionValues.size() > type && !CompactionValues[type].empty()) {
400 if (Num < CompactionValues[type].size())
401 return CompactionValues[type][Num];
402 Num -= CompactionValues[type].size();
Chris Lattner89e02532004-01-18 21:08:15 +0000403 } else {
Reid Spencer060d25d2004-06-29 23:29:38 +0000404 // By default, the global type id is the type id passed in
Chris Lattner52f86d62004-01-20 00:54:06 +0000405 unsigned GlobalTyID = type;
Reid Spencer060d25d2004-06-29 23:29:38 +0000406
Chris Lattner45b5dd22004-08-03 23:41:28 +0000407 // If the type plane was compactified, figure out the global type ID by
408 // adding the derived type ids and the distance.
409 if (!CompactionTypes.empty() && type >= Type::FirstDerivedTyID)
410 GlobalTyID = CompactionTypes[type-Type::FirstDerivedTyID].second;
Chris Lattner00950542001-06-06 20:29:01 +0000411
Reid Spencer060d25d2004-06-29 23:29:38 +0000412 if (hasImplicitNull(GlobalTyID)) {
Chris Lattner89e02532004-01-18 21:08:15 +0000413 if (Num == 0)
Reid Spencer04cde2c2004-07-04 11:33:49 +0000414 return Constant::getNullValue(getType(type));
Chris Lattner89e02532004-01-18 21:08:15 +0000415 --Num;
416 }
417
Chris Lattner52f86d62004-01-20 00:54:06 +0000418 if (GlobalTyID < ModuleValues.size() && ModuleValues[GlobalTyID]) {
419 if (Num < ModuleValues[GlobalTyID]->size())
Reid Spencer04cde2c2004-07-04 11:33:49 +0000420 return ModuleValues[GlobalTyID]->getOperand(Num);
Chris Lattner52f86d62004-01-20 00:54:06 +0000421 Num -= ModuleValues[GlobalTyID]->size();
Chris Lattner89e02532004-01-18 21:08:15 +0000422 }
Chris Lattner52e20b02003-03-19 20:54:26 +0000423 }
424
Reid Spencer060d25d2004-06-29 23:29:38 +0000425 if (FunctionValues.size() > type &&
426 FunctionValues[type] &&
427 Num < FunctionValues[type]->size())
428 return FunctionValues[type]->getOperand(Num);
Chris Lattner00950542001-06-06 20:29:01 +0000429
Chris Lattner74734132002-08-17 22:01:27 +0000430 if (!Create) return 0; // Do not create a placeholder?
Chris Lattner00950542001-06-06 20:29:01 +0000431
Reid Spencer551ccae2004-09-01 22:55:40 +0000432 // Did we already create a place holder?
Chris Lattner8eb10ce2003-10-09 06:05:40 +0000433 std::pair<unsigned,unsigned> KeyValue(type, oNum);
Reid Spencer060d25d2004-06-29 23:29:38 +0000434 ForwardReferenceMap::iterator I = ForwardReferences.lower_bound(KeyValue);
Chris Lattner8eb10ce2003-10-09 06:05:40 +0000435 if (I != ForwardReferences.end() && I->first == KeyValue)
436 return I->second; // We have already created this placeholder
437
Reid Spencer551ccae2004-09-01 22:55:40 +0000438 // If the type exists (it should)
439 if (const Type* Ty = getType(type)) {
440 // Create the place holder
441 Value *Val = new Argument(Ty);
442 ForwardReferences.insert(I, std::make_pair(KeyValue, Val));
443 return Val;
444 }
445 throw "Can't create placeholder for value of type slot #" + utostr(type);
Chris Lattner00950542001-06-06 20:29:01 +0000446}
447
Reid Spencer04cde2c2004-07-04 11:33:49 +0000448/// This is just like getValue, but when a compaction table is in use, it
449/// is ignored. Also, no forward references or other fancy features are
450/// supported.
Chris Lattner2c6c14d2004-08-04 00:19:23 +0000451Value* BytecodeReader::getGlobalTableValue(unsigned TyID, unsigned SlotNo) {
452 if (SlotNo == 0)
453 return Constant::getNullValue(getType(TyID));
454
455 if (!CompactionTypes.empty() && TyID >= Type::FirstDerivedTyID) {
456 TyID -= Type::FirstDerivedTyID;
457 if (TyID >= CompactionTypes.size())
458 error("Type ID out of range for compaction table!");
459 TyID = CompactionTypes[TyID].second;
Reid Spencer060d25d2004-06-29 23:29:38 +0000460 }
461
Chris Lattner2c6c14d2004-08-04 00:19:23 +0000462 --SlotNo;
463
Reid Spencer060d25d2004-06-29 23:29:38 +0000464 if (TyID >= ModuleValues.size() || ModuleValues[TyID] == 0 ||
465 SlotNo >= ModuleValues[TyID]->size()) {
Chris Lattner2c6c14d2004-08-04 00:19:23 +0000466 if (TyID >= ModuleValues.size() || ModuleValues[TyID] == 0)
467 error("Corrupt compaction table entry!"
468 + utostr(TyID) + ", " + utostr(SlotNo) + ": "
469 + utostr(ModuleValues.size()));
470 else
471 error("Corrupt compaction table entry!"
472 + utostr(TyID) + ", " + utostr(SlotNo) + ": "
473 + utostr(ModuleValues.size()) + ", "
Reid Spencer9a7e0c52004-08-04 22:56:46 +0000474 + utohexstr(reinterpret_cast<uint64_t>(((void*)ModuleValues[TyID])))
475 + ", "
Chris Lattner2c6c14d2004-08-04 00:19:23 +0000476 + utostr(ModuleValues[TyID]->size()));
Reid Spencer060d25d2004-06-29 23:29:38 +0000477 }
478 return ModuleValues[TyID]->getOperand(SlotNo);
479}
480
Reid Spencer04cde2c2004-07-04 11:33:49 +0000481/// Just like getValue, except that it returns a null pointer
482/// only on error. It always returns a constant (meaning that if the value is
483/// defined, but is not a constant, that is an error). If the specified
484/// constant hasn't been parsed yet, a placeholder is defined and used.
485/// Later, after the real value is parsed, the placeholder is eliminated.
Reid Spencer060d25d2004-06-29 23:29:38 +0000486Constant* BytecodeReader::getConstantValue(unsigned TypeSlot, unsigned Slot) {
487 if (Value *V = getValue(TypeSlot, Slot, false))
488 if (Constant *C = dyn_cast<Constant>(V))
489 return C; // If we already have the value parsed, just return it
Reid Spencer060d25d2004-06-29 23:29:38 +0000490 else
Reid Spencera86037e2004-07-18 00:12:03 +0000491 error("Value for slot " + utostr(Slot) +
492 " is expected to be a constant!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000493
494 const Type *Ty = getType(TypeSlot);
495 std::pair<const Type*, unsigned> Key(Ty, Slot);
496 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
Reid Spencer46b002c2004-07-11 17:28:43 +0000503 Constant *C = new ConstantPlaceHolder(Ty, Slot);
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
550/// the instruction are provided in the \p Args 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
631 // Handle binary operators
632 if (Opcode >= Instruction::BinaryOpsBegin &&
633 Opcode < Instruction::BinaryOpsEnd && Oprnds.size() == 2)
634 Result = BinaryOperator::create((Instruction::BinaryOps)Opcode,
635 getValue(iType, Oprnds[0]),
636 getValue(iType, Oprnds[1]));
637
638 switch (Opcode) {
639 default:
Reid Spencer04cde2c2004-07-04 11:33:49 +0000640 if (Result == 0)
Reid Spencer24399722004-07-09 22:21:33 +0000641 error("Illegal instruction read!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000642 break;
643 case Instruction::VAArg:
Reid Spencer04cde2c2004-07-04 11:33:49 +0000644 Result = new VAArgInst(getValue(iType, Oprnds[0]),
Reid Spencer46b002c2004-07-11 17:28:43 +0000645 getSanitizedType(Oprnds[1]));
Reid Spencer060d25d2004-06-29 23:29:38 +0000646 break;
647 case Instruction::VANext:
Reid Spencer04cde2c2004-07-04 11:33:49 +0000648 Result = new VANextInst(getValue(iType, Oprnds[0]),
Reid Spencer46b002c2004-07-11 17:28:43 +0000649 getSanitizedType(Oprnds[1]));
Reid Spencer060d25d2004-06-29 23:29:38 +0000650 break;
651 case Instruction::Cast:
Reid Spencer04cde2c2004-07-04 11:33:49 +0000652 Result = new CastInst(getValue(iType, Oprnds[0]),
Reid Spencer46b002c2004-07-11 17:28:43 +0000653 getSanitizedType(Oprnds[1]));
Reid Spencer060d25d2004-06-29 23:29:38 +0000654 break;
655 case Instruction::Select:
656 Result = new SelectInst(getValue(Type::BoolTyID, Oprnds[0]),
657 getValue(iType, Oprnds[1]),
658 getValue(iType, Oprnds[2]));
659 break;
660 case Instruction::PHI: {
661 if (Oprnds.size() == 0 || (Oprnds.size() & 1))
Reid Spencer24399722004-07-09 22:21:33 +0000662 error("Invalid phi node encountered!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000663
664 PHINode *PN = new PHINode(InstTy);
665 PN->op_reserve(Oprnds.size());
666 for (unsigned i = 0, e = Oprnds.size(); i != e; i += 2)
667 PN->addIncoming(getValue(iType, Oprnds[i]), getBasicBlock(Oprnds[i+1]));
668 Result = PN;
669 break;
670 }
671
672 case Instruction::Shl:
673 case Instruction::Shr:
674 Result = new ShiftInst((Instruction::OtherOps)Opcode,
675 getValue(iType, Oprnds[0]),
676 getValue(Type::UByteTyID, Oprnds[1]));
677 break;
678 case Instruction::Ret:
679 if (Oprnds.size() == 0)
680 Result = new ReturnInst();
681 else if (Oprnds.size() == 1)
682 Result = new ReturnInst(getValue(iType, Oprnds[0]));
683 else
Reid Spencer24399722004-07-09 22:21:33 +0000684 error("Unrecognized instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000685 break;
686
687 case Instruction::Br:
688 if (Oprnds.size() == 1)
689 Result = new BranchInst(getBasicBlock(Oprnds[0]));
690 else if (Oprnds.size() == 3)
691 Result = new BranchInst(getBasicBlock(Oprnds[0]),
Reid Spencer04cde2c2004-07-04 11:33:49 +0000692 getBasicBlock(Oprnds[1]), getValue(Type::BoolTyID , Oprnds[2]));
Reid Spencer060d25d2004-06-29 23:29:38 +0000693 else
Reid Spencer24399722004-07-09 22:21:33 +0000694 error("Invalid number of operands for a 'br' instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000695 break;
696 case Instruction::Switch: {
697 if (Oprnds.size() & 1)
Reid Spencer24399722004-07-09 22:21:33 +0000698 error("Switch statement with odd number of arguments!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000699
700 SwitchInst *I = new SwitchInst(getValue(iType, Oprnds[0]),
701 getBasicBlock(Oprnds[1]));
702 for (unsigned i = 2, e = Oprnds.size(); i != e; i += 2)
703 I->addCase(cast<Constant>(getValue(iType, Oprnds[i])),
704 getBasicBlock(Oprnds[i+1]));
705 Result = I;
706 break;
707 }
708
709 case Instruction::Call: {
710 if (Oprnds.size() == 0)
Reid Spencer24399722004-07-09 22:21:33 +0000711 error("Invalid call instruction encountered!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000712
713 Value *F = getValue(iType, Oprnds[0]);
714
715 // Check to make sure we have a pointer to function type
716 const PointerType *PTy = dyn_cast<PointerType>(F->getType());
Reid Spencer24399722004-07-09 22:21:33 +0000717 if (PTy == 0) error("Call to non function pointer value!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000718 const FunctionType *FTy = dyn_cast<FunctionType>(PTy->getElementType());
Reid Spencer24399722004-07-09 22:21:33 +0000719 if (FTy == 0) error("Call to non function pointer value!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000720
721 std::vector<Value *> Params;
722 if (!FTy->isVarArg()) {
723 FunctionType::param_iterator It = FTy->param_begin();
724
725 for (unsigned i = 1, e = Oprnds.size(); i != e; ++i) {
726 if (It == FTy->param_end())
Reid Spencer24399722004-07-09 22:21:33 +0000727 error("Invalid call instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000728 Params.push_back(getValue(getTypeSlot(*It++), Oprnds[i]));
729 }
730 if (It != FTy->param_end())
Reid Spencer24399722004-07-09 22:21:33 +0000731 error("Invalid call instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000732 } else {
733 Oprnds.erase(Oprnds.begin(), Oprnds.begin()+1);
734
735 unsigned FirstVariableOperand;
736 if (Oprnds.size() < FTy->getNumParams())
Reid Spencer24399722004-07-09 22:21:33 +0000737 error("Call instruction missing operands!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000738
739 // Read all of the fixed arguments
740 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
741 Params.push_back(getValue(getTypeSlot(FTy->getParamType(i)),Oprnds[i]));
742
743 FirstVariableOperand = FTy->getNumParams();
744
745 if ((Oprnds.size()-FirstVariableOperand) & 1) // Must be pairs of type/value
Reid Spencer24399722004-07-09 22:21:33 +0000746 error("Invalid call instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000747
748 for (unsigned i = FirstVariableOperand, e = Oprnds.size();
Reid Spencer04cde2c2004-07-04 11:33:49 +0000749 i != e; i += 2)
Reid Spencer060d25d2004-06-29 23:29:38 +0000750 Params.push_back(getValue(Oprnds[i], Oprnds[i+1]));
751 }
752
753 Result = new CallInst(F, Params);
754 break;
755 }
756 case Instruction::Invoke: {
Reid Spencer04cde2c2004-07-04 11:33:49 +0000757 if (Oprnds.size() < 3)
Reid Spencer24399722004-07-09 22:21:33 +0000758 error("Invalid invoke instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000759 Value *F = getValue(iType, Oprnds[0]);
760
761 // Check to make sure we have a pointer to function type
762 const PointerType *PTy = dyn_cast<PointerType>(F->getType());
Reid Spencer04cde2c2004-07-04 11:33:49 +0000763 if (PTy == 0)
Reid Spencer24399722004-07-09 22:21:33 +0000764 error("Invoke to non function pointer value!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000765 const FunctionType *FTy = dyn_cast<FunctionType>(PTy->getElementType());
Reid Spencer04cde2c2004-07-04 11:33:49 +0000766 if (FTy == 0)
Reid Spencer24399722004-07-09 22:21:33 +0000767 error("Invoke to non function pointer value!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000768
769 std::vector<Value *> Params;
770 BasicBlock *Normal, *Except;
771
772 if (!FTy->isVarArg()) {
773 Normal = getBasicBlock(Oprnds[1]);
774 Except = getBasicBlock(Oprnds[2]);
775
776 FunctionType::param_iterator It = FTy->param_begin();
777 for (unsigned i = 3, e = Oprnds.size(); i != e; ++i) {
778 if (It == FTy->param_end())
Reid Spencer24399722004-07-09 22:21:33 +0000779 error("Invalid invoke instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000780 Params.push_back(getValue(getTypeSlot(*It++), Oprnds[i]));
781 }
782 if (It != FTy->param_end())
Reid Spencer24399722004-07-09 22:21:33 +0000783 error("Invalid invoke instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000784 } else {
785 Oprnds.erase(Oprnds.begin(), Oprnds.begin()+1);
786
787 Normal = getBasicBlock(Oprnds[0]);
788 Except = getBasicBlock(Oprnds[1]);
789
790 unsigned FirstVariableArgument = FTy->getNumParams()+2;
791 for (unsigned i = 2; i != FirstVariableArgument; ++i)
792 Params.push_back(getValue(getTypeSlot(FTy->getParamType(i-2)),
793 Oprnds[i]));
794
795 if (Oprnds.size()-FirstVariableArgument & 1) // Must be type/value pairs
Reid Spencer24399722004-07-09 22:21:33 +0000796 error("Invalid invoke instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000797
798 for (unsigned i = FirstVariableArgument; i < Oprnds.size(); i += 2)
799 Params.push_back(getValue(Oprnds[i], Oprnds[i+1]));
800 }
801
802 Result = new InvokeInst(F, Normal, Except, Params);
803 break;
804 }
805 case Instruction::Malloc:
Reid Spencer04cde2c2004-07-04 11:33:49 +0000806 if (Oprnds.size() > 2)
Reid Spencer24399722004-07-09 22:21:33 +0000807 error("Invalid malloc instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000808 if (!isa<PointerType>(InstTy))
Reid Spencer24399722004-07-09 22:21:33 +0000809 error("Invalid malloc instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000810
811 Result = new MallocInst(cast<PointerType>(InstTy)->getElementType(),
812 Oprnds.size() ? getValue(Type::UIntTyID,
813 Oprnds[0]) : 0);
814 break;
815
816 case Instruction::Alloca:
Reid Spencer04cde2c2004-07-04 11:33:49 +0000817 if (Oprnds.size() > 2)
Reid Spencer24399722004-07-09 22:21:33 +0000818 error("Invalid alloca instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000819 if (!isa<PointerType>(InstTy))
Reid Spencer24399722004-07-09 22:21:33 +0000820 error("Invalid alloca instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000821
822 Result = new AllocaInst(cast<PointerType>(InstTy)->getElementType(),
823 Oprnds.size() ? getValue(Type::UIntTyID,
Reid Spencer04cde2c2004-07-04 11:33:49 +0000824 Oprnds[0]) :0);
Reid Spencer060d25d2004-06-29 23:29:38 +0000825 break;
826 case Instruction::Free:
827 if (!isa<PointerType>(InstTy))
Reid Spencer24399722004-07-09 22:21:33 +0000828 error("Invalid free instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000829 Result = new FreeInst(getValue(iType, Oprnds[0]));
830 break;
831 case Instruction::GetElementPtr: {
832 if (Oprnds.size() == 0 || !isa<PointerType>(InstTy))
Reid Spencer24399722004-07-09 22:21:33 +0000833 error("Invalid getelementptr instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000834
835 std::vector<Value*> Idx;
836
837 const Type *NextTy = InstTy;
838 for (unsigned i = 1, e = Oprnds.size(); i != e; ++i) {
839 const CompositeType *TopTy = dyn_cast_or_null<CompositeType>(NextTy);
Reid Spencer04cde2c2004-07-04 11:33:49 +0000840 if (!TopTy)
Reid Spencer46b002c2004-07-11 17:28:43 +0000841 error("Invalid getelementptr instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000842
843 unsigned ValIdx = Oprnds[i];
844 unsigned IdxTy = 0;
845 if (!hasRestrictedGEPTypes) {
846 // Struct indices are always uints, sequential type indices can be any
847 // of the 32 or 64-bit integer types. The actual choice of type is
848 // encoded in the low two bits of the slot number.
849 if (isa<StructType>(TopTy))
850 IdxTy = Type::UIntTyID;
851 else {
852 switch (ValIdx & 3) {
853 default:
854 case 0: IdxTy = Type::UIntTyID; break;
855 case 1: IdxTy = Type::IntTyID; break;
856 case 2: IdxTy = Type::ULongTyID; break;
857 case 3: IdxTy = Type::LongTyID; break;
858 }
859 ValIdx >>= 2;
860 }
861 } else {
862 IdxTy = isa<StructType>(TopTy) ? Type::UByteTyID : Type::LongTyID;
863 }
864
865 Idx.push_back(getValue(IdxTy, ValIdx));
866
867 // Convert ubyte struct indices into uint struct indices.
868 if (isa<StructType>(TopTy) && hasRestrictedGEPTypes)
869 if (ConstantUInt *C = dyn_cast<ConstantUInt>(Idx.back()))
870 Idx[Idx.size()-1] = ConstantExpr::getCast(C, Type::UIntTy);
871
872 NextTy = GetElementPtrInst::getIndexedType(InstTy, Idx, true);
873 }
874
875 Result = new GetElementPtrInst(getValue(iType, Oprnds[0]), Idx);
876 break;
877 }
878
879 case 62: // volatile load
880 case Instruction::Load:
881 if (Oprnds.size() != 1 || !isa<PointerType>(InstTy))
Reid Spencer24399722004-07-09 22:21:33 +0000882 error("Invalid load instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000883 Result = new LoadInst(getValue(iType, Oprnds[0]), "", Opcode == 62);
884 break;
885
886 case 63: // volatile store
887 case Instruction::Store: {
888 if (!isa<PointerType>(InstTy) || Oprnds.size() != 2)
Reid Spencer24399722004-07-09 22:21:33 +0000889 error("Invalid store instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000890
891 Value *Ptr = getValue(iType, Oprnds[1]);
892 const Type *ValTy = cast<PointerType>(Ptr->getType())->getElementType();
893 Result = new StoreInst(getValue(getTypeSlot(ValTy), Oprnds[0]), Ptr,
894 Opcode == 63);
895 break;
896 }
897 case Instruction::Unwind:
Reid Spencer04cde2c2004-07-04 11:33:49 +0000898 if (Oprnds.size() != 0)
Reid Spencer24399722004-07-09 22:21:33 +0000899 error("Invalid unwind instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000900 Result = new UnwindInst();
901 break;
902 } // end switch(Opcode)
903
904 unsigned TypeSlot;
905 if (Result->getType() == InstTy)
906 TypeSlot = iType;
907 else
908 TypeSlot = getTypeSlot(Result->getType());
909
910 insertValue(Result, TypeSlot, FunctionValues);
911 BB->getInstList().push_back(Result);
912}
913
Reid Spencer04cde2c2004-07-04 11:33:49 +0000914/// Get a particular numbered basic block, which might be a forward reference.
915/// This works together with ParseBasicBlock to handle these forward references
916/// in a clean manner. This function is used when constructing phi, br, switch,
917/// and other instructions that reference basic blocks. Blocks are numbered
918/// sequentially as they appear in the function.
Reid Spencer060d25d2004-06-29 23:29:38 +0000919BasicBlock *BytecodeReader::getBasicBlock(unsigned ID) {
Chris Lattner4ee8ef22003-10-08 22:52:54 +0000920 // Make sure there is room in the table...
921 if (ParsedBasicBlocks.size() <= ID) ParsedBasicBlocks.resize(ID+1);
922
923 // First check to see if this is a backwards reference, i.e., ParseBasicBlock
924 // has already created this block, or if the forward reference has already
925 // been created.
926 if (ParsedBasicBlocks[ID])
927 return ParsedBasicBlocks[ID];
928
929 // Otherwise, the basic block has not yet been created. Do so and add it to
930 // the ParsedBasicBlocks list.
931 return ParsedBasicBlocks[ID] = new BasicBlock();
932}
933
Reid Spencer04cde2c2004-07-04 11:33:49 +0000934/// In LLVM 1.0 bytecode files, we used to output one basicblock at a time.
935/// This method reads in one of the basicblock packets. This method is not used
936/// for bytecode files after LLVM 1.0
937/// @returns The basic block constructed.
Reid Spencer46b002c2004-07-11 17:28:43 +0000938BasicBlock *BytecodeReader::ParseBasicBlock(unsigned BlockNo) {
939 if (Handler) Handler->handleBasicBlockBegin(BlockNo);
Reid Spencer060d25d2004-06-29 23:29:38 +0000940
941 BasicBlock *BB = 0;
942
Chris Lattner4ee8ef22003-10-08 22:52:54 +0000943 if (ParsedBasicBlocks.size() == BlockNo)
944 ParsedBasicBlocks.push_back(BB = new BasicBlock());
945 else if (ParsedBasicBlocks[BlockNo] == 0)
946 BB = ParsedBasicBlocks[BlockNo] = new BasicBlock();
947 else
948 BB = ParsedBasicBlocks[BlockNo];
Chris Lattner00950542001-06-06 20:29:01 +0000949
Reid Spencer060d25d2004-06-29 23:29:38 +0000950 std::vector<unsigned> Operands;
Reid Spencer46b002c2004-07-11 17:28:43 +0000951 while (moreInBlock())
Reid Spencer060d25d2004-06-29 23:29:38 +0000952 ParseInstruction(Operands, BB);
Chris Lattner00950542001-06-06 20:29:01 +0000953
Reid Spencer46b002c2004-07-11 17:28:43 +0000954 if (Handler) Handler->handleBasicBlockEnd(BlockNo);
Misha Brukman12c29d12003-09-22 23:38:23 +0000955 return BB;
Chris Lattner00950542001-06-06 20:29:01 +0000956}
957
Reid Spencer04cde2c2004-07-04 11:33:49 +0000958/// Parse all of the BasicBlock's & Instruction's in the body of a function.
959/// In post 1.0 bytecode files, we no longer emit basic block individually,
960/// in order to avoid per-basic-block overhead.
961/// @returns Rhe number of basic blocks encountered.
Reid Spencer060d25d2004-06-29 23:29:38 +0000962unsigned BytecodeReader::ParseInstructionList(Function* F) {
Chris Lattner8d1dbd22003-12-01 07:05:31 +0000963 unsigned BlockNo = 0;
964 std::vector<unsigned> Args;
965
Reid Spencer46b002c2004-07-11 17:28:43 +0000966 while (moreInBlock()) {
967 if (Handler) Handler->handleBasicBlockBegin(BlockNo);
Chris Lattner8d1dbd22003-12-01 07:05:31 +0000968 BasicBlock *BB;
969 if (ParsedBasicBlocks.size() == BlockNo)
970 ParsedBasicBlocks.push_back(BB = new BasicBlock());
971 else if (ParsedBasicBlocks[BlockNo] == 0)
972 BB = ParsedBasicBlocks[BlockNo] = new BasicBlock();
973 else
974 BB = ParsedBasicBlocks[BlockNo];
975 ++BlockNo;
976 F->getBasicBlockList().push_back(BB);
977
978 // Read instructions into this basic block until we get to a terminator
Reid Spencer46b002c2004-07-11 17:28:43 +0000979 while (moreInBlock() && !BB->getTerminator())
Reid Spencer060d25d2004-06-29 23:29:38 +0000980 ParseInstruction(Args, BB);
Chris Lattner8d1dbd22003-12-01 07:05:31 +0000981
982 if (!BB->getTerminator())
Reid Spencer24399722004-07-09 22:21:33 +0000983 error("Non-terminated basic block found!");
Reid Spencer5c15fe52004-07-05 00:57:50 +0000984
Reid Spencer46b002c2004-07-11 17:28:43 +0000985 if (Handler) Handler->handleBasicBlockEnd(BlockNo-1);
Chris Lattner8d1dbd22003-12-01 07:05:31 +0000986 }
987
988 return BlockNo;
989}
990
Reid Spencer04cde2c2004-07-04 11:33:49 +0000991/// Parse a symbol table. This works for both module level and function
992/// level symbol tables. For function level symbol tables, the CurrentFunction
993/// parameter must be non-zero and the ST parameter must correspond to
994/// CurrentFunction's symbol table. For Module level symbol tables, the
995/// CurrentFunction argument must be zero.
Reid Spencer060d25d2004-06-29 23:29:38 +0000996void BytecodeReader::ParseSymbolTable(Function *CurrentFunction,
Reid Spencer04cde2c2004-07-04 11:33:49 +0000997 SymbolTable *ST) {
998 if (Handler) Handler->handleSymbolTableBegin(CurrentFunction,ST);
Reid Spencer060d25d2004-06-29 23:29:38 +0000999
Chris Lattner39cacce2003-10-10 05:43:47 +00001000 // Allow efficient basic block lookup by number.
1001 std::vector<BasicBlock*> BBMap;
1002 if (CurrentFunction)
1003 for (Function::iterator I = CurrentFunction->begin(),
1004 E = CurrentFunction->end(); I != E; ++I)
1005 BBMap.push_back(I);
1006
Reid Spencer04cde2c2004-07-04 11:33:49 +00001007 /// In LLVM 1.3 we write types separately from values so
1008 /// The types are always first in the symbol table. This is
1009 /// because Type no longer derives from Value.
Reid Spencer46b002c2004-07-11 17:28:43 +00001010 if (!hasTypeDerivedFromValue) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001011 // Symtab block header: [num entries]
1012 unsigned NumEntries = read_vbr_uint();
Reid Spencer46b002c2004-07-11 17:28:43 +00001013 for (unsigned i = 0; i < NumEntries; ++i) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001014 // Symtab entry: [def slot #][name]
1015 unsigned slot = read_vbr_uint();
1016 std::string Name = read_str();
1017 const Type* T = getType(slot);
1018 ST->insert(Name, T);
1019 }
1020 }
1021
Reid Spencer46b002c2004-07-11 17:28:43 +00001022 while (moreInBlock()) {
Chris Lattner00950542001-06-06 20:29:01 +00001023 // Symtab block header: [num entries][type id number]
Reid Spencer060d25d2004-06-29 23:29:38 +00001024 unsigned NumEntries = read_vbr_uint();
Reid Spencer04cde2c2004-07-04 11:33:49 +00001025 unsigned Typ = 0;
1026 bool isTypeType = read_typeid(Typ);
Chris Lattner00950542001-06-06 20:29:01 +00001027 const Type *Ty = getType(Typ);
Chris Lattner1d670cc2001-09-07 16:37:43 +00001028
Chris Lattner7dc3a2e2003-10-13 14:57:53 +00001029 for (unsigned i = 0; i != NumEntries; ++i) {
Chris Lattner00950542001-06-06 20:29:01 +00001030 // Symtab entry: [def slot #][name]
Reid Spencer060d25d2004-06-29 23:29:38 +00001031 unsigned slot = read_vbr_uint();
1032 std::string Name = read_str();
Chris Lattner00950542001-06-06 20:29:01 +00001033
Reid Spencer04cde2c2004-07-04 11:33:49 +00001034 // if we're reading a pre 1.3 bytecode file and the type plane
1035 // is the "type type", handle it here
Reid Spencer46b002c2004-07-11 17:28:43 +00001036 if (isTypeType) {
1037 const Type* T = getType(slot);
1038 if (T == 0)
1039 error("Failed type look-up for name '" + Name + "'");
1040 ST->insert(Name, T);
1041 continue; // code below must be short circuited
Chris Lattner39cacce2003-10-10 05:43:47 +00001042 } else {
Reid Spencer46b002c2004-07-11 17:28:43 +00001043 Value *V = 0;
1044 if (Typ == Type::LabelTyID) {
1045 if (slot < BBMap.size())
1046 V = BBMap[slot];
1047 } else {
1048 V = getValue(Typ, slot, false); // Find mapping...
1049 }
1050 if (V == 0)
1051 error("Failed value look-up for name '" + Name + "'");
1052 V->setName(Name, ST);
Chris Lattner39cacce2003-10-10 05:43:47 +00001053 }
Chris Lattner00950542001-06-06 20:29:01 +00001054 }
1055 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001056 checkPastBlockEnd("Symbol Table");
Reid Spencer04cde2c2004-07-04 11:33:49 +00001057 if (Handler) Handler->handleSymbolTableEnd();
Chris Lattner00950542001-06-06 20:29:01 +00001058}
1059
Reid Spencer04cde2c2004-07-04 11:33:49 +00001060/// Read in the types portion of a compaction table.
Reid Spencer46b002c2004-07-11 17:28:43 +00001061void BytecodeReader::ParseCompactionTypes(unsigned NumEntries) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001062 for (unsigned i = 0; i != NumEntries; ++i) {
1063 unsigned TypeSlot = 0;
Reid Spencer46b002c2004-07-11 17:28:43 +00001064 if (read_typeid(TypeSlot))
Reid Spencer24399722004-07-09 22:21:33 +00001065 error("Invalid type in compaction table: type type");
Reid Spencer04cde2c2004-07-04 11:33:49 +00001066 const Type *Typ = getGlobalTableType(TypeSlot);
Chris Lattner45b5dd22004-08-03 23:41:28 +00001067 CompactionTypes.push_back(std::make_pair(Typ, TypeSlot));
Reid Spencer46b002c2004-07-11 17:28:43 +00001068 if (Handler) Handler->handleCompactionTableType(i, TypeSlot, Typ);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001069 }
1070}
1071
1072/// Parse a compaction table.
Reid Spencer060d25d2004-06-29 23:29:38 +00001073void BytecodeReader::ParseCompactionTable() {
1074
Reid Spencer46b002c2004-07-11 17:28:43 +00001075 // Notify handler that we're beginning a compaction table.
Reid Spencer04cde2c2004-07-04 11:33:49 +00001076 if (Handler) Handler->handleCompactionTableBegin();
1077
Reid Spencer46b002c2004-07-11 17:28:43 +00001078 // In LLVM 1.3 Type no longer derives from Value. So,
1079 // we always write them first in the compaction table
1080 // because they can't occupy a "type plane" where the
1081 // Values reside.
1082 if (! hasTypeDerivedFromValue) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001083 unsigned NumEntries = read_vbr_uint();
Reid Spencer46b002c2004-07-11 17:28:43 +00001084 ParseCompactionTypes(NumEntries);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001085 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001086
Reid Spencer46b002c2004-07-11 17:28:43 +00001087 // Compaction tables live in separate blocks so we have to loop
1088 // until we've read the whole thing.
1089 while (moreInBlock()) {
1090 // Read the number of Value* entries in the compaction table
Reid Spencer060d25d2004-06-29 23:29:38 +00001091 unsigned NumEntries = read_vbr_uint();
Reid Spencer04cde2c2004-07-04 11:33:49 +00001092 unsigned Ty = 0;
1093 unsigned isTypeType = false;
Reid Spencer060d25d2004-06-29 23:29:38 +00001094
Reid Spencer46b002c2004-07-11 17:28:43 +00001095 // Decode the type from value read in. Most compaction table
1096 // planes will have one or two entries in them. If that's the
1097 // case then the length is encoded in the bottom two bits and
1098 // the higher bits encode the type. This saves another VBR value.
Reid Spencer060d25d2004-06-29 23:29:38 +00001099 if ((NumEntries & 3) == 3) {
Reid Spencer46b002c2004-07-11 17:28:43 +00001100 // In this case, both low-order bits are set (value 3). This
1101 // is a signal that the typeid follows.
Reid Spencer060d25d2004-06-29 23:29:38 +00001102 NumEntries >>= 2;
Reid Spencer04cde2c2004-07-04 11:33:49 +00001103 isTypeType = read_typeid(Ty);
Reid Spencer060d25d2004-06-29 23:29:38 +00001104 } else {
Reid Spencer46b002c2004-07-11 17:28:43 +00001105 // In this case, the low-order bits specify the number of entries
1106 // and the high order bits specify the type.
Reid Spencer060d25d2004-06-29 23:29:38 +00001107 Ty = NumEntries >> 2;
Reid Spencer04cde2c2004-07-04 11:33:49 +00001108 isTypeType = sanitizeTypeId(Ty);
Reid Spencer060d25d2004-06-29 23:29:38 +00001109 NumEntries &= 3;
1110 }
1111
Reid Spencer04cde2c2004-07-04 11:33:49 +00001112 // if we're reading a pre 1.3 bytecode file and the type plane
1113 // is the "type type", handle it here
Reid Spencer46b002c2004-07-11 17:28:43 +00001114 if (isTypeType) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001115 ParseCompactionTypes(NumEntries);
Reid Spencer060d25d2004-06-29 23:29:38 +00001116 } else {
Chris Lattner2c6c14d2004-08-04 00:19:23 +00001117 // Make sure we have enough room for the plane.
Reid Spencer04cde2c2004-07-04 11:33:49 +00001118 if (Ty >= CompactionValues.size())
Reid Spencer46b002c2004-07-11 17:28:43 +00001119 CompactionValues.resize(Ty+1);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001120
Chris Lattner2c6c14d2004-08-04 00:19:23 +00001121 // Make sure the plane is empty or we have some kind of error.
Reid Spencer04cde2c2004-07-04 11:33:49 +00001122 if (!CompactionValues[Ty].empty())
Reid Spencer46b002c2004-07-11 17:28:43 +00001123 error("Compaction table plane contains multiple entries!");
Reid Spencer04cde2c2004-07-04 11:33:49 +00001124
Chris Lattner2c6c14d2004-08-04 00:19:23 +00001125 // Notify handler about the plane.
Reid Spencer46b002c2004-07-11 17:28:43 +00001126 if (Handler) Handler->handleCompactionTablePlane(Ty, NumEntries);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001127
Chris Lattner2c6c14d2004-08-04 00:19:23 +00001128 // Push the implicit zero.
1129 CompactionValues[Ty].push_back(Constant::getNullValue(getType(Ty)));
Reid Spencer46b002c2004-07-11 17:28:43 +00001130
1131 // Read in each of the entries, put them in the compaction table
1132 // and notify the handler that we have a new compaction table value.
Reid Spencer060d25d2004-06-29 23:29:38 +00001133 for (unsigned i = 0; i != NumEntries; ++i) {
Reid Spencer46b002c2004-07-11 17:28:43 +00001134 unsigned ValSlot = read_vbr_uint();
Chris Lattner2c6c14d2004-08-04 00:19:23 +00001135 Value *V = getGlobalTableValue(Ty, ValSlot);
Reid Spencer46b002c2004-07-11 17:28:43 +00001136 CompactionValues[Ty].push_back(V);
Chris Lattner2c6c14d2004-08-04 00:19:23 +00001137 if (Handler) Handler->handleCompactionTableValue(i, Ty, ValSlot);
Reid Spencer060d25d2004-06-29 23:29:38 +00001138 }
1139 }
1140 }
Reid Spencer46b002c2004-07-11 17:28:43 +00001141 // Notify handler that the compaction table is done.
Reid Spencer04cde2c2004-07-04 11:33:49 +00001142 if (Handler) Handler->handleCompactionTableEnd();
Reid Spencer060d25d2004-06-29 23:29:38 +00001143}
1144
Reid Spencer46b002c2004-07-11 17:28:43 +00001145// Parse a single type. The typeid is read in first. If its a primitive type
1146// then nothing else needs to be read, we know how to instantiate it. If its
1147// a derived type, then additional data is read to fill out the type
1148// definition.
1149const Type *BytecodeReader::ParseType() {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001150 unsigned PrimType = 0;
Reid Spencer46b002c2004-07-11 17:28:43 +00001151 if (read_typeid(PrimType))
Reid Spencer24399722004-07-09 22:21:33 +00001152 error("Invalid type (type type) in type constants!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001153
1154 const Type *Result = 0;
1155 if ((Result = Type::getPrimitiveType((Type::TypeID)PrimType)))
1156 return Result;
1157
1158 switch (PrimType) {
1159 case Type::FunctionTyID: {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001160 const Type *RetType = readSanitizedType();
Reid Spencer060d25d2004-06-29 23:29:38 +00001161
1162 unsigned NumParams = read_vbr_uint();
1163
1164 std::vector<const Type*> Params;
Reid Spencer04cde2c2004-07-04 11:33:49 +00001165 while (NumParams--)
1166 Params.push_back(readSanitizedType());
Reid Spencer060d25d2004-06-29 23:29:38 +00001167
1168 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1169 if (isVarArg) Params.pop_back();
1170
1171 Result = FunctionType::get(RetType, Params, isVarArg);
1172 break;
1173 }
1174 case Type::ArrayTyID: {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001175 const Type *ElementType = readSanitizedType();
Reid Spencer060d25d2004-06-29 23:29:38 +00001176 unsigned NumElements = read_vbr_uint();
Reid Spencer060d25d2004-06-29 23:29:38 +00001177 Result = ArrayType::get(ElementType, NumElements);
1178 break;
1179 }
Brian Gaeke715c90b2004-08-20 06:00:58 +00001180 case Type::PackedTyID: {
1181 const Type *ElementType = readSanitizedType();
1182 unsigned NumElements = read_vbr_uint();
1183 Result = PackedType::get(ElementType, NumElements);
1184 break;
1185 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001186 case Type::StructTyID: {
1187 std::vector<const Type*> Elements;
Reid Spencer04cde2c2004-07-04 11:33:49 +00001188 unsigned Typ = 0;
Reid Spencer46b002c2004-07-11 17:28:43 +00001189 if (read_typeid(Typ))
Reid Spencer24399722004-07-09 22:21:33 +00001190 error("Invalid element type (type type) for structure!");
1191
Reid Spencer060d25d2004-06-29 23:29:38 +00001192 while (Typ) { // List is terminated by void/0 typeid
1193 Elements.push_back(getType(Typ));
Reid Spencer46b002c2004-07-11 17:28:43 +00001194 if (read_typeid(Typ))
1195 error("Invalid element type (type type) for structure!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001196 }
1197
1198 Result = StructType::get(Elements);
1199 break;
1200 }
1201 case Type::PointerTyID: {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001202 Result = PointerType::get(readSanitizedType());
Reid Spencer060d25d2004-06-29 23:29:38 +00001203 break;
1204 }
1205
1206 case Type::OpaqueTyID: {
1207 Result = OpaqueType::get();
1208 break;
1209 }
1210
1211 default:
Reid Spencer24399722004-07-09 22:21:33 +00001212 error("Don't know how to deserialize primitive type " + utostr(PrimType));
Reid Spencer060d25d2004-06-29 23:29:38 +00001213 break;
1214 }
Reid Spencer46b002c2004-07-11 17:28:43 +00001215 if (Handler) Handler->handleType(Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001216 return Result;
1217}
1218
Reid Spencer5b472d92004-08-21 20:49:23 +00001219// ParseTypes - We have to use this weird code to handle recursive
Reid Spencer060d25d2004-06-29 23:29:38 +00001220// types. We know that recursive types will only reference the current slab of
1221// values in the type plane, but they can forward reference types before they
1222// have been read. For example, Type #0 might be '{ Ty#1 }' and Type #1 might
1223// be 'Ty#0*'. When reading Type #0, type number one doesn't exist. To fix
1224// this ugly problem, we pessimistically insert an opaque type for each type we
1225// are about to read. This means that forward references will resolve to
1226// something and when we reread the type later, we can replace the opaque type
1227// with a new resolved concrete type.
1228//
Reid Spencer46b002c2004-07-11 17:28:43 +00001229void BytecodeReader::ParseTypes(TypeListTy &Tab, unsigned NumEntries){
Reid Spencer060d25d2004-06-29 23:29:38 +00001230 assert(Tab.size() == 0 && "should not have read type constants in before!");
1231
1232 // Insert a bunch of opaque types to be resolved later...
1233 Tab.reserve(NumEntries);
1234 for (unsigned i = 0; i != NumEntries; ++i)
1235 Tab.push_back(OpaqueType::get());
1236
Reid Spencer5b472d92004-08-21 20:49:23 +00001237 if (Handler)
1238 Handler->handleTypeList(NumEntries);
1239
Reid Spencer060d25d2004-06-29 23:29:38 +00001240 // Loop through reading all of the types. Forward types will make use of the
1241 // opaque types just inserted.
1242 //
1243 for (unsigned i = 0; i != NumEntries; ++i) {
Reid Spencer46b002c2004-07-11 17:28:43 +00001244 const Type* NewTy = ParseType();
Reid Spencer04cde2c2004-07-04 11:33:49 +00001245 const Type* OldTy = Tab[i].get();
1246 if (NewTy == 0)
Reid Spencer24399722004-07-09 22:21:33 +00001247 error("Couldn't parse type!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001248
1249 // Don't directly push the new type on the Tab. Instead we want to replace
1250 // the opaque type we previously inserted with the new concrete value. This
1251 // approach helps with forward references to types. The refinement from the
1252 // abstract (opaque) type to the new type causes all uses of the abstract
1253 // type to use the concrete type (NewTy). This will also cause the opaque
1254 // type to be deleted.
1255 cast<DerivedType>(const_cast<Type*>(OldTy))->refineAbstractTypeTo(NewTy);
1256
1257 // This should have replaced the old opaque type with the new type in the
1258 // value table... or with a preexisting type that was already in the system.
1259 // Let's just make sure it did.
1260 assert(Tab[i] != OldTy && "refineAbstractType didn't work!");
1261 }
1262}
1263
Reid Spencer04cde2c2004-07-04 11:33:49 +00001264/// Parse a single constant value
Reid Spencer46b002c2004-07-11 17:28:43 +00001265Constant *BytecodeReader::ParseConstantValue(unsigned TypeID) {
Reid Spencer060d25d2004-06-29 23:29:38 +00001266 // We must check for a ConstantExpr before switching by type because
1267 // a ConstantExpr can be of any type, and has no explicit value.
1268 //
1269 // 0 if not expr; numArgs if is expr
1270 unsigned isExprNumArgs = read_vbr_uint();
1271
1272 if (isExprNumArgs) {
1273 // FIXME: Encoding of constant exprs could be much more compact!
1274 std::vector<Constant*> ArgVec;
1275 ArgVec.reserve(isExprNumArgs);
1276 unsigned Opcode = read_vbr_uint();
1277
1278 // Read the slot number and types of each of the arguments
1279 for (unsigned i = 0; i != isExprNumArgs; ++i) {
1280 unsigned ArgValSlot = read_vbr_uint();
Reid Spencer04cde2c2004-07-04 11:33:49 +00001281 unsigned ArgTypeSlot = 0;
Reid Spencer46b002c2004-07-11 17:28:43 +00001282 if (read_typeid(ArgTypeSlot))
1283 error("Invalid argument type (type type) for constant value");
Reid Spencer060d25d2004-06-29 23:29:38 +00001284
1285 // Get the arg value from its slot if it exists, otherwise a placeholder
1286 ArgVec.push_back(getConstantValue(ArgTypeSlot, ArgValSlot));
1287 }
1288
1289 // Construct a ConstantExpr of the appropriate kind
1290 if (isExprNumArgs == 1) { // All one-operand expressions
Reid Spencer46b002c2004-07-11 17:28:43 +00001291 if (Opcode != Instruction::Cast)
1292 error("Only Cast instruction has one argument for ConstantExpr");
1293
Reid Spencer060d25d2004-06-29 23:29:38 +00001294 Constant* Result = ConstantExpr::getCast(ArgVec[0], getType(TypeID));
Reid Spencer04cde2c2004-07-04 11:33:49 +00001295 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001296 return Result;
1297 } else if (Opcode == Instruction::GetElementPtr) { // GetElementPtr
1298 std::vector<Constant*> IdxList(ArgVec.begin()+1, ArgVec.end());
1299
1300 if (hasRestrictedGEPTypes) {
1301 const Type *BaseTy = ArgVec[0]->getType();
1302 generic_gep_type_iterator<std::vector<Constant*>::iterator>
1303 GTI = gep_type_begin(BaseTy, IdxList.begin(), IdxList.end()),
1304 E = gep_type_end(BaseTy, IdxList.begin(), IdxList.end());
1305 for (unsigned i = 0; GTI != E; ++GTI, ++i)
1306 if (isa<StructType>(*GTI)) {
1307 if (IdxList[i]->getType() != Type::UByteTy)
Reid Spencer24399722004-07-09 22:21:33 +00001308 error("Invalid index for getelementptr!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001309 IdxList[i] = ConstantExpr::getCast(IdxList[i], Type::UIntTy);
1310 }
1311 }
1312
1313 Constant* Result = ConstantExpr::getGetElementPtr(ArgVec[0], IdxList);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001314 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001315 return Result;
1316 } else if (Opcode == Instruction::Select) {
Reid Spencer46b002c2004-07-11 17:28:43 +00001317 if (ArgVec.size() != 3)
1318 error("Select instruction must have three arguments.");
Reid Spencer060d25d2004-06-29 23:29:38 +00001319 Constant* Result = ConstantExpr::getSelect(ArgVec[0], ArgVec[1],
Reid Spencer04cde2c2004-07-04 11:33:49 +00001320 ArgVec[2]);
1321 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001322 return Result;
1323 } else { // All other 2-operand expressions
1324 Constant* Result = ConstantExpr::get(Opcode, ArgVec[0], ArgVec[1]);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001325 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001326 return Result;
1327 }
1328 }
1329
1330 // Ok, not an ConstantExpr. We now know how to read the given type...
1331 const Type *Ty = getType(TypeID);
1332 switch (Ty->getTypeID()) {
1333 case Type::BoolTyID: {
1334 unsigned Val = read_vbr_uint();
1335 if (Val != 0 && Val != 1)
Reid Spencer24399722004-07-09 22:21:33 +00001336 error("Invalid boolean value read.");
Reid Spencer060d25d2004-06-29 23:29:38 +00001337 Constant* Result = ConstantBool::get(Val == 1);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001338 if (Handler) Handler->handleConstantValue(Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001339 return Result;
1340 }
1341
1342 case Type::UByteTyID: // Unsigned integer types...
1343 case Type::UShortTyID:
1344 case Type::UIntTyID: {
1345 unsigned Val = read_vbr_uint();
1346 if (!ConstantUInt::isValueValidForType(Ty, Val))
Reid Spencer24399722004-07-09 22:21:33 +00001347 error("Invalid unsigned byte/short/int read.");
Reid Spencer060d25d2004-06-29 23:29:38 +00001348 Constant* Result = ConstantUInt::get(Ty, Val);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001349 if (Handler) Handler->handleConstantValue(Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001350 return Result;
1351 }
1352
1353 case Type::ULongTyID: {
1354 Constant* Result = ConstantUInt::get(Ty, read_vbr_uint64());
Reid Spencer04cde2c2004-07-04 11:33:49 +00001355 if (Handler) Handler->handleConstantValue(Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001356 return Result;
1357 }
1358
1359 case Type::SByteTyID: // Signed integer types...
1360 case Type::ShortTyID:
1361 case Type::IntTyID: {
1362 case Type::LongTyID:
1363 int64_t Val = read_vbr_int64();
1364 if (!ConstantSInt::isValueValidForType(Ty, Val))
Reid Spencer24399722004-07-09 22:21:33 +00001365 error("Invalid signed byte/short/int/long read.");
Reid Spencer060d25d2004-06-29 23:29:38 +00001366 Constant* Result = ConstantSInt::get(Ty, Val);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001367 if (Handler) Handler->handleConstantValue(Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001368 return Result;
1369 }
1370
1371 case Type::FloatTyID: {
Reid Spencer46b002c2004-07-11 17:28:43 +00001372 float Val;
1373 read_float(Val);
1374 Constant* Result = ConstantFP::get(Ty, Val);
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::DoubleTyID: {
1380 double Val;
Reid Spencer46b002c2004-07-11 17:28:43 +00001381 read_double(Val);
Reid Spencer060d25d2004-06-29 23:29:38 +00001382 Constant* Result = ConstantFP::get(Ty, Val);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001383 if (Handler) Handler->handleConstantValue(Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001384 return Result;
1385 }
1386
Reid Spencer060d25d2004-06-29 23:29:38 +00001387 case Type::ArrayTyID: {
1388 const ArrayType *AT = cast<ArrayType>(Ty);
1389 unsigned NumElements = AT->getNumElements();
1390 unsigned TypeSlot = getTypeSlot(AT->getElementType());
1391 std::vector<Constant*> Elements;
1392 Elements.reserve(NumElements);
1393 while (NumElements--) // Read all of the elements of the constant.
1394 Elements.push_back(getConstantValue(TypeSlot,
1395 read_vbr_uint()));
1396 Constant* Result = ConstantArray::get(AT, Elements);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001397 if (Handler) Handler->handleConstantArray(AT, Elements, TypeSlot, Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001398 return Result;
1399 }
1400
1401 case Type::StructTyID: {
1402 const StructType *ST = cast<StructType>(Ty);
1403
1404 std::vector<Constant *> Elements;
1405 Elements.reserve(ST->getNumElements());
1406 for (unsigned i = 0; i != ST->getNumElements(); ++i)
1407 Elements.push_back(getConstantValue(ST->getElementType(i),
1408 read_vbr_uint()));
1409
1410 Constant* Result = ConstantStruct::get(ST, Elements);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001411 if (Handler) Handler->handleConstantStruct(ST, Elements, Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001412 return Result;
1413 }
1414
Brian Gaeke715c90b2004-08-20 06:00:58 +00001415 case Type::PackedTyID: {
1416 const PackedType *PT = cast<PackedType>(Ty);
1417 unsigned NumElements = PT->getNumElements();
1418 unsigned TypeSlot = getTypeSlot(PT->getElementType());
1419 std::vector<Constant*> Elements;
1420 Elements.reserve(NumElements);
1421 while (NumElements--) // Read all of the elements of the constant.
1422 Elements.push_back(getConstantValue(TypeSlot,
1423 read_vbr_uint()));
1424 Constant* Result = ConstantPacked::get(PT, Elements);
1425 if (Handler) Handler->handleConstantPacked(PT, Elements, TypeSlot, Result);
1426 return Result;
1427 }
1428
Reid Spencer060d25d2004-06-29 23:29:38 +00001429 case Type::PointerTyID: { // ConstantPointerRef value...
1430 const PointerType *PT = cast<PointerType>(Ty);
1431 unsigned Slot = read_vbr_uint();
1432
1433 // Check to see if we have already read this global variable...
1434 Value *Val = getValue(TypeID, Slot, false);
Reid Spencer060d25d2004-06-29 23:29:38 +00001435 if (Val) {
Chris Lattnerbcb11cf2004-07-27 02:34:49 +00001436 GlobalValue *GV = dyn_cast<GlobalValue>(Val);
1437 if (!GV) error("GlobalValue not in ValueTable!");
1438 if (Handler) Handler->handleConstantPointer(PT, Slot, GV);
1439 return GV;
Reid Spencer060d25d2004-06-29 23:29:38 +00001440 } else {
Reid Spencer24399722004-07-09 22:21:33 +00001441 error("Forward references are not allowed here.");
Reid Spencer060d25d2004-06-29 23:29:38 +00001442 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001443 }
1444
1445 default:
Reid Spencer24399722004-07-09 22:21:33 +00001446 error("Don't know how to deserialize constant value of type '" +
Reid Spencer060d25d2004-06-29 23:29:38 +00001447 Ty->getDescription());
1448 break;
1449 }
Reid Spencer24399722004-07-09 22:21:33 +00001450 return 0;
Reid Spencer060d25d2004-06-29 23:29:38 +00001451}
1452
Reid Spencer04cde2c2004-07-04 11:33:49 +00001453/// Resolve references for constants. This function resolves the forward
1454/// referenced constants in the ConstantFwdRefs map. It uses the
1455/// replaceAllUsesWith method of Value class to substitute the placeholder
1456/// instance with the actual instance.
Reid Spencer060d25d2004-06-29 23:29:38 +00001457void BytecodeReader::ResolveReferencesToConstant(Constant *NewV, unsigned Slot){
Chris Lattner29b789b2003-11-19 17:27:18 +00001458 ConstantRefsType::iterator I =
1459 ConstantFwdRefs.find(std::make_pair(NewV->getType(), Slot));
1460 if (I == ConstantFwdRefs.end()) return; // Never forward referenced?
Chris Lattner00950542001-06-06 20:29:01 +00001461
Chris Lattner29b789b2003-11-19 17:27:18 +00001462 Value *PH = I->second; // Get the placeholder...
1463 PH->replaceAllUsesWith(NewV);
1464 delete PH; // Delete the old placeholder
1465 ConstantFwdRefs.erase(I); // Remove the map entry for it
Vikram S. Advec1e4a812002-07-14 23:04:18 +00001466}
1467
Reid Spencer04cde2c2004-07-04 11:33:49 +00001468/// Parse the constant strings section.
Reid Spencer060d25d2004-06-29 23:29:38 +00001469void BytecodeReader::ParseStringConstants(unsigned NumEntries, ValueTable &Tab){
1470 for (; NumEntries; --NumEntries) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001471 unsigned Typ = 0;
Reid Spencer46b002c2004-07-11 17:28:43 +00001472 if (read_typeid(Typ))
Reid Spencer24399722004-07-09 22:21:33 +00001473 error("Invalid type (type type) for string constant");
Reid Spencer060d25d2004-06-29 23:29:38 +00001474 const Type *Ty = getType(Typ);
1475 if (!isa<ArrayType>(Ty))
Reid Spencer24399722004-07-09 22:21:33 +00001476 error("String constant data invalid!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001477
1478 const ArrayType *ATy = cast<ArrayType>(Ty);
1479 if (ATy->getElementType() != Type::SByteTy &&
1480 ATy->getElementType() != Type::UByteTy)
Reid Spencer24399722004-07-09 22:21:33 +00001481 error("String constant data invalid!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001482
1483 // Read character data. The type tells us how long the string is.
1484 char Data[ATy->getNumElements()];
1485 read_data(Data, Data+ATy->getNumElements());
Chris Lattner52e20b02003-03-19 20:54:26 +00001486
Reid Spencer060d25d2004-06-29 23:29:38 +00001487 std::vector<Constant*> Elements(ATy->getNumElements());
1488 if (ATy->getElementType() == Type::SByteTy)
1489 for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
1490 Elements[i] = ConstantSInt::get(Type::SByteTy, (signed char)Data[i]);
1491 else
1492 for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
1493 Elements[i] = ConstantUInt::get(Type::UByteTy, (unsigned char)Data[i]);
Misha Brukman12c29d12003-09-22 23:38:23 +00001494
Reid Spencer060d25d2004-06-29 23:29:38 +00001495 // Create the constant, inserting it as needed.
1496 Constant *C = ConstantArray::get(ATy, Elements);
1497 unsigned Slot = insertValue(C, Typ, Tab);
1498 ResolveReferencesToConstant(C, Slot);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001499 if (Handler) Handler->handleConstantString(cast<ConstantArray>(C));
Reid Spencer060d25d2004-06-29 23:29:38 +00001500 }
Misha Brukman12c29d12003-09-22 23:38:23 +00001501}
1502
Reid Spencer04cde2c2004-07-04 11:33:49 +00001503/// Parse the constant pool.
Reid Spencer060d25d2004-06-29 23:29:38 +00001504void BytecodeReader::ParseConstantPool(ValueTable &Tab,
Reid Spencer04cde2c2004-07-04 11:33:49 +00001505 TypeListTy &TypeTab,
Reid Spencer46b002c2004-07-11 17:28:43 +00001506 bool isFunction) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001507 if (Handler) Handler->handleGlobalConstantsBegin();
1508
1509 /// In LLVM 1.3 Type does not derive from Value so the types
1510 /// do not occupy a plane. Consequently, we read the types
1511 /// first in the constant pool.
Reid Spencer46b002c2004-07-11 17:28:43 +00001512 if (isFunction && !hasTypeDerivedFromValue) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001513 unsigned NumEntries = read_vbr_uint();
Reid Spencer46b002c2004-07-11 17:28:43 +00001514 ParseTypes(TypeTab, NumEntries);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001515 }
1516
Reid Spencer46b002c2004-07-11 17:28:43 +00001517 while (moreInBlock()) {
Reid Spencer060d25d2004-06-29 23:29:38 +00001518 unsigned NumEntries = read_vbr_uint();
Reid Spencer04cde2c2004-07-04 11:33:49 +00001519 unsigned Typ = 0;
1520 bool isTypeType = read_typeid(Typ);
1521
1522 /// In LLVM 1.2 and before, Types were written to the
1523 /// bytecode file in the "Type Type" plane (#12).
1524 /// In 1.3 plane 12 is now the label plane. Handle this here.
Reid Spencer46b002c2004-07-11 17:28:43 +00001525 if (isTypeType) {
1526 ParseTypes(TypeTab, NumEntries);
Reid Spencer060d25d2004-06-29 23:29:38 +00001527 } else if (Typ == Type::VoidTyID) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001528 /// Use of Type::VoidTyID is a misnomer. It actually means
1529 /// that the following plane is constant strings
Reid Spencer060d25d2004-06-29 23:29:38 +00001530 assert(&Tab == &ModuleValues && "Cannot read strings in functions!");
1531 ParseStringConstants(NumEntries, Tab);
1532 } else {
1533 for (unsigned i = 0; i < NumEntries; ++i) {
1534 Constant *C = ParseConstantValue(Typ);
1535 assert(C && "ParseConstantValue returned NULL!");
1536 unsigned Slot = insertValue(C, Typ, Tab);
Chris Lattner29b789b2003-11-19 17:27:18 +00001537
Reid Spencer060d25d2004-06-29 23:29:38 +00001538 // If we are reading a function constant table, make sure that we adjust
1539 // the slot number to be the real global constant number.
1540 //
1541 if (&Tab != &ModuleValues && Typ < ModuleValues.size() &&
1542 ModuleValues[Typ])
1543 Slot += ModuleValues[Typ]->size();
1544 ResolveReferencesToConstant(C, Slot);
1545 }
1546 }
1547 }
1548 checkPastBlockEnd("Constant Pool");
Reid Spencer04cde2c2004-07-04 11:33:49 +00001549 if (Handler) Handler->handleGlobalConstantsEnd();
Reid Spencer060d25d2004-06-29 23:29:38 +00001550}
Chris Lattner00950542001-06-06 20:29:01 +00001551
Reid Spencer04cde2c2004-07-04 11:33:49 +00001552/// Parse the contents of a function. Note that this function can be
1553/// called lazily by materializeFunction
1554/// @see materializeFunction
Reid Spencer46b002c2004-07-11 17:28:43 +00001555void BytecodeReader::ParseFunctionBody(Function* F) {
Reid Spencer060d25d2004-06-29 23:29:38 +00001556
1557 unsigned FuncSize = BlockEnd - At;
Chris Lattnere3869c82003-04-16 21:16:05 +00001558 GlobalValue::LinkageTypes Linkage = GlobalValue::ExternalLinkage;
1559
Reid Spencer060d25d2004-06-29 23:29:38 +00001560 unsigned LinkageType = read_vbr_uint();
Chris Lattnerc08912f2004-01-14 16:44:44 +00001561 switch (LinkageType) {
1562 case 0: Linkage = GlobalValue::ExternalLinkage; break;
1563 case 1: Linkage = GlobalValue::WeakLinkage; break;
1564 case 2: Linkage = GlobalValue::AppendingLinkage; break;
1565 case 3: Linkage = GlobalValue::InternalLinkage; break;
1566 case 4: Linkage = GlobalValue::LinkOnceLinkage; break;
Reid Spencer060d25d2004-06-29 23:29:38 +00001567 default:
Reid Spencer24399722004-07-09 22:21:33 +00001568 error("Invalid linkage type for Function.");
Reid Spencer060d25d2004-06-29 23:29:38 +00001569 Linkage = GlobalValue::InternalLinkage;
1570 break;
Chris Lattnere3869c82003-04-16 21:16:05 +00001571 }
Chris Lattnerd23b1d32001-11-26 18:56:10 +00001572
Reid Spencer46b002c2004-07-11 17:28:43 +00001573 F->setLinkage(Linkage);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001574 if (Handler) Handler->handleFunctionBegin(F,FuncSize);
Chris Lattner00950542001-06-06 20:29:01 +00001575
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001576 // Keep track of how many basic blocks we have read in...
1577 unsigned BlockNum = 0;
Chris Lattner89e02532004-01-18 21:08:15 +00001578 bool InsertedArguments = false;
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001579
Reid Spencer060d25d2004-06-29 23:29:38 +00001580 BufPtr MyEnd = BlockEnd;
Reid Spencer46b002c2004-07-11 17:28:43 +00001581 while (At < MyEnd) {
Chris Lattner00950542001-06-06 20:29:01 +00001582 unsigned Type, Size;
Reid Spencer060d25d2004-06-29 23:29:38 +00001583 BufPtr OldAt = At;
1584 read_block(Type, Size);
Chris Lattner00950542001-06-06 20:29:01 +00001585
1586 switch (Type) {
Reid Spencerad89bd62004-07-25 18:07:36 +00001587 case BytecodeFormat::ConstantPoolBlockID:
Chris Lattner89e02532004-01-18 21:08:15 +00001588 if (!InsertedArguments) {
1589 // Insert arguments into the value table before we parse the first basic
1590 // block in the function, but after we potentially read in the
1591 // compaction table.
Reid Spencer04cde2c2004-07-04 11:33:49 +00001592 insertArguments(F);
Chris Lattner89e02532004-01-18 21:08:15 +00001593 InsertedArguments = true;
1594 }
1595
Reid Spencer04cde2c2004-07-04 11:33:49 +00001596 ParseConstantPool(FunctionValues, FunctionTypes, true);
Chris Lattner00950542001-06-06 20:29:01 +00001597 break;
1598
Reid Spencerad89bd62004-07-25 18:07:36 +00001599 case BytecodeFormat::CompactionTableBlockID:
Reid Spencer060d25d2004-06-29 23:29:38 +00001600 ParseCompactionTable();
Chris Lattner89e02532004-01-18 21:08:15 +00001601 break;
1602
Chris Lattner00950542001-06-06 20:29:01 +00001603 case BytecodeFormat::BasicBlock: {
Chris Lattner89e02532004-01-18 21:08:15 +00001604 if (!InsertedArguments) {
1605 // Insert arguments into the value table before we parse the first basic
1606 // block in the function, but after we potentially read in the
1607 // compaction table.
Reid Spencer04cde2c2004-07-04 11:33:49 +00001608 insertArguments(F);
Chris Lattner89e02532004-01-18 21:08:15 +00001609 InsertedArguments = true;
1610 }
1611
Reid Spencer060d25d2004-06-29 23:29:38 +00001612 BasicBlock *BB = ParseBasicBlock(BlockNum++);
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001613 F->getBasicBlockList().push_back(BB);
Chris Lattner00950542001-06-06 20:29:01 +00001614 break;
1615 }
1616
Reid Spencerad89bd62004-07-25 18:07:36 +00001617 case BytecodeFormat::InstructionListBlockID: {
Chris Lattner89e02532004-01-18 21:08:15 +00001618 // Insert arguments into the value table before we parse the instruction
1619 // list for the function, but after we potentially read in the compaction
1620 // table.
1621 if (!InsertedArguments) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001622 insertArguments(F);
Chris Lattner89e02532004-01-18 21:08:15 +00001623 InsertedArguments = true;
1624 }
1625
Reid Spencer060d25d2004-06-29 23:29:38 +00001626 if (BlockNum)
Reid Spencer24399722004-07-09 22:21:33 +00001627 error("Already parsed basic blocks!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001628 BlockNum = ParseInstructionList(F);
Chris Lattner8d1dbd22003-12-01 07:05:31 +00001629 break;
1630 }
1631
Reid Spencerad89bd62004-07-25 18:07:36 +00001632 case BytecodeFormat::SymbolTableBlockID:
Reid Spencer060d25d2004-06-29 23:29:38 +00001633 ParseSymbolTable(F, &F->getSymbolTable());
Chris Lattner00950542001-06-06 20:29:01 +00001634 break;
1635
1636 default:
Reid Spencer060d25d2004-06-29 23:29:38 +00001637 At += Size;
1638 if (OldAt > At)
Reid Spencer24399722004-07-09 22:21:33 +00001639 error("Wrapped around reading bytecode.");
Chris Lattner00950542001-06-06 20:29:01 +00001640 break;
1641 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001642 BlockEnd = MyEnd;
Chris Lattner1d670cc2001-09-07 16:37:43 +00001643
Misha Brukman12c29d12003-09-22 23:38:23 +00001644 // Malformed bc file if read past end of block.
Reid Spencer060d25d2004-06-29 23:29:38 +00001645 align32();
Chris Lattner00950542001-06-06 20:29:01 +00001646 }
1647
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001648 // Make sure there were no references to non-existant basic blocks.
1649 if (BlockNum != ParsedBasicBlocks.size())
Reid Spencer24399722004-07-09 22:21:33 +00001650 error("Illegal basic block operand reference");
Reid Spencer060d25d2004-06-29 23:29:38 +00001651
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001652 ParsedBasicBlocks.clear();
1653
Chris Lattner97330cf2003-10-09 23:10:14 +00001654 // Resolve forward references. Replace any uses of a forward reference value
1655 // with the real value.
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001656
Chris Lattner97330cf2003-10-09 23:10:14 +00001657 // replaceAllUsesWith is very inefficient for instructions which have a LARGE
1658 // number of operands. PHI nodes often have forward references, and can also
1659 // often have a very large number of operands.
Chris Lattner89e02532004-01-18 21:08:15 +00001660 //
1661 // FIXME: REEVALUATE. replaceAllUsesWith is _much_ faster now, and this code
1662 // should be simplified back to using it!
1663 //
Chris Lattner97330cf2003-10-09 23:10:14 +00001664 std::map<Value*, Value*> ForwardRefMapping;
1665 for (std::map<std::pair<unsigned,unsigned>, Value*>::iterator
1666 I = ForwardReferences.begin(), E = ForwardReferences.end();
1667 I != E; ++I)
1668 ForwardRefMapping[I->second] = getValue(I->first.first, I->first.second,
1669 false);
1670
1671 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
1672 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
1673 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
Reid Spencer5b472d92004-08-21 20:49:23 +00001674 if (Value* V = I->getOperand(i))
1675 if (Argument *A = dyn_cast<Argument>(V)) {
1676 std::map<Value*, Value*>::iterator It = ForwardRefMapping.find(A);
1677 if (It != ForwardRefMapping.end()) I->setOperand(i, It->second);
1678 }
Chris Lattner97330cf2003-10-09 23:10:14 +00001679
Chris Lattner8eb10ce2003-10-09 06:05:40 +00001680 while (!ForwardReferences.empty()) {
Chris Lattner35d2ca62003-10-09 22:39:30 +00001681 std::map<std::pair<unsigned,unsigned>, Value*>::iterator I =
1682 ForwardReferences.begin();
Chris Lattner8eb10ce2003-10-09 06:05:40 +00001683 Value *PlaceHolder = I->second;
1684 ForwardReferences.erase(I);
Chris Lattner00950542001-06-06 20:29:01 +00001685
Chris Lattner8eb10ce2003-10-09 06:05:40 +00001686 // Now that all the uses are gone, delete the placeholder...
1687 // If we couldn't find a def (error case), then leak a little
1688 // memory, because otherwise we can't remove all uses!
1689 delete PlaceHolder;
Chris Lattner6e448022003-10-08 21:51:46 +00001690 }
Chris Lattner00950542001-06-06 20:29:01 +00001691
Misha Brukman12c29d12003-09-22 23:38:23 +00001692 // Clear out function-level types...
Reid Spencer060d25d2004-06-29 23:29:38 +00001693 FunctionTypes.clear();
1694 CompactionTypes.clear();
1695 CompactionValues.clear();
1696 freeTable(FunctionValues);
1697
Reid Spencer04cde2c2004-07-04 11:33:49 +00001698 if (Handler) Handler->handleFunctionEnd(F);
Chris Lattner00950542001-06-06 20:29:01 +00001699}
1700
Reid Spencer04cde2c2004-07-04 11:33:49 +00001701/// This function parses LLVM functions lazily. It obtains the type of the
1702/// function and records where the body of the function is in the bytecode
1703/// buffer. The caller can then use the ParseNextFunction and
1704/// ParseAllFunctionBodies to get handler events for the functions.
Reid Spencer060d25d2004-06-29 23:29:38 +00001705void BytecodeReader::ParseFunctionLazily() {
1706 if (FunctionSignatureList.empty())
Reid Spencer24399722004-07-09 22:21:33 +00001707 error("FunctionSignatureList empty!");
Chris Lattner89e02532004-01-18 21:08:15 +00001708
Reid Spencer060d25d2004-06-29 23:29:38 +00001709 Function *Func = FunctionSignatureList.back();
1710 FunctionSignatureList.pop_back();
Chris Lattner24102432004-01-18 22:35:34 +00001711
Reid Spencer060d25d2004-06-29 23:29:38 +00001712 // Save the information for future reading of the function
1713 LazyFunctionLoadMap[Func] = LazyFunctionInfo(BlockStart, BlockEnd);
Chris Lattner89e02532004-01-18 21:08:15 +00001714
Reid Spencer060d25d2004-06-29 23:29:38 +00001715 // Pretend we've `parsed' this function
1716 At = BlockEnd;
1717}
Chris Lattner89e02532004-01-18 21:08:15 +00001718
Reid Spencer04cde2c2004-07-04 11:33:49 +00001719/// The ParserFunction method lazily parses one function. Use this method to
1720/// casue the parser to parse a specific function in the module. Note that
1721/// this will remove the function from what is to be included by
1722/// ParseAllFunctionBodies.
1723/// @see ParseAllFunctionBodies
1724/// @see ParseBytecode
Reid Spencer060d25d2004-06-29 23:29:38 +00001725void BytecodeReader::ParseFunction(Function* Func) {
1726 // Find {start, end} pointers and slot in the map. If not there, we're done.
1727 LazyFunctionMap::iterator Fi = LazyFunctionLoadMap.find(Func);
Chris Lattner89e02532004-01-18 21:08:15 +00001728
Reid Spencer060d25d2004-06-29 23:29:38 +00001729 // Make sure we found it
Reid Spencer46b002c2004-07-11 17:28:43 +00001730 if (Fi == LazyFunctionLoadMap.end()) {
Reid Spencer24399722004-07-09 22:21:33 +00001731 error("Unrecognized function of type " + Func->getType()->getDescription());
Reid Spencer060d25d2004-06-29 23:29:38 +00001732 return;
Chris Lattner89e02532004-01-18 21:08:15 +00001733 }
1734
Reid Spencer060d25d2004-06-29 23:29:38 +00001735 BlockStart = At = Fi->second.Buf;
1736 BlockEnd = Fi->second.EndBuf;
Reid Spencer24399722004-07-09 22:21:33 +00001737 assert(Fi->first == Func && "Found wrong function?");
Reid Spencer060d25d2004-06-29 23:29:38 +00001738
1739 LazyFunctionLoadMap.erase(Fi);
1740
Reid Spencer46b002c2004-07-11 17:28:43 +00001741 this->ParseFunctionBody(Func);
Chris Lattner89e02532004-01-18 21:08:15 +00001742}
1743
Reid Spencer04cde2c2004-07-04 11:33:49 +00001744/// The ParseAllFunctionBodies method parses through all the previously
1745/// unparsed functions in the bytecode file. If you want to completely parse
1746/// a bytecode file, this method should be called after Parsebytecode because
1747/// Parsebytecode only records the locations in the bytecode file of where
1748/// the function definitions are located. This function uses that information
1749/// to materialize the functions.
1750/// @see ParseBytecode
Reid Spencer060d25d2004-06-29 23:29:38 +00001751void BytecodeReader::ParseAllFunctionBodies() {
1752 LazyFunctionMap::iterator Fi = LazyFunctionLoadMap.begin();
1753 LazyFunctionMap::iterator Fe = LazyFunctionLoadMap.end();
Chris Lattner89e02532004-01-18 21:08:15 +00001754
Reid Spencer46b002c2004-07-11 17:28:43 +00001755 while (Fi != Fe) {
Reid Spencer060d25d2004-06-29 23:29:38 +00001756 Function* Func = Fi->first;
1757 BlockStart = At = Fi->second.Buf;
1758 BlockEnd = Fi->second.EndBuf;
1759 this->ParseFunctionBody(Func);
1760 ++Fi;
1761 }
1762}
Chris Lattner89e02532004-01-18 21:08:15 +00001763
Reid Spencer04cde2c2004-07-04 11:33:49 +00001764/// Parse the global type list
Reid Spencer060d25d2004-06-29 23:29:38 +00001765void BytecodeReader::ParseGlobalTypes() {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001766 // Read the number of types
1767 unsigned NumEntries = read_vbr_uint();
Reid Spencer011bed52004-07-09 21:13:53 +00001768
1769 // Ignore the type plane identifier for types if the bc file is pre 1.3
1770 if (hasTypeDerivedFromValue)
1771 read_vbr_uint();
1772
Reid Spencer46b002c2004-07-11 17:28:43 +00001773 ParseTypes(ModuleTypes, NumEntries);
Reid Spencer060d25d2004-06-29 23:29:38 +00001774}
1775
Reid Spencer04cde2c2004-07-04 11:33:49 +00001776/// Parse the Global info (types, global vars, constants)
Reid Spencer060d25d2004-06-29 23:29:38 +00001777void BytecodeReader::ParseModuleGlobalInfo() {
1778
Reid Spencer04cde2c2004-07-04 11:33:49 +00001779 if (Handler) Handler->handleModuleGlobalsBegin();
Chris Lattner00950542001-06-06 20:29:01 +00001780
Chris Lattner70cc3392001-09-10 07:58:01 +00001781 // Read global variables...
Reid Spencer060d25d2004-06-29 23:29:38 +00001782 unsigned VarType = read_vbr_uint();
Chris Lattner70cc3392001-09-10 07:58:01 +00001783 while (VarType != Type::VoidTyID) { // List is terminated by Void
Chris Lattner9dd87702004-04-03 23:43:42 +00001784 // VarType Fields: bit0 = isConstant, bit1 = hasInitializer, bit2,3,4 =
1785 // Linkage, bit4+ = slot#
1786 unsigned SlotNo = VarType >> 5;
Reid Spencer46b002c2004-07-11 17:28:43 +00001787 if (sanitizeTypeId(SlotNo))
Reid Spencer24399722004-07-09 22:21:33 +00001788 error("Invalid type (type type) for global var!");
Chris Lattner9dd87702004-04-03 23:43:42 +00001789 unsigned LinkageID = (VarType >> 2) & 7;
Reid Spencer060d25d2004-06-29 23:29:38 +00001790 bool isConstant = VarType & 1;
1791 bool hasInitializer = VarType & 2;
Chris Lattnere3869c82003-04-16 21:16:05 +00001792 GlobalValue::LinkageTypes Linkage;
1793
Chris Lattnerc08912f2004-01-14 16:44:44 +00001794 switch (LinkageID) {
Chris Lattnerc08912f2004-01-14 16:44:44 +00001795 case 0: Linkage = GlobalValue::ExternalLinkage; break;
1796 case 1: Linkage = GlobalValue::WeakLinkage; break;
1797 case 2: Linkage = GlobalValue::AppendingLinkage; break;
1798 case 3: Linkage = GlobalValue::InternalLinkage; break;
1799 case 4: Linkage = GlobalValue::LinkOnceLinkage; break;
Reid Spencer060d25d2004-06-29 23:29:38 +00001800 default:
Reid Spencer24399722004-07-09 22:21:33 +00001801 error("Unknown linkage type: " + utostr(LinkageID));
Reid Spencer060d25d2004-06-29 23:29:38 +00001802 Linkage = GlobalValue::InternalLinkage;
1803 break;
Chris Lattnere3869c82003-04-16 21:16:05 +00001804 }
1805
1806 const Type *Ty = getType(SlotNo);
Reid Spencer46b002c2004-07-11 17:28:43 +00001807 if (!Ty) {
Reid Spencer24399722004-07-09 22:21:33 +00001808 error("Global has no type! SlotNo=" + utostr(SlotNo));
Reid Spencer060d25d2004-06-29 23:29:38 +00001809 }
1810
Reid Spencer46b002c2004-07-11 17:28:43 +00001811 if (!isa<PointerType>(Ty)) {
Reid Spencer24399722004-07-09 22:21:33 +00001812 error("Global not a pointer type! Ty= " + Ty->getDescription());
Reid Spencer060d25d2004-06-29 23:29:38 +00001813 }
Chris Lattner70cc3392001-09-10 07:58:01 +00001814
Chris Lattner52e20b02003-03-19 20:54:26 +00001815 const Type *ElTy = cast<PointerType>(Ty)->getElementType();
Chris Lattnerd70684f2001-09-18 04:01:05 +00001816
Chris Lattner70cc3392001-09-10 07:58:01 +00001817 // Create the global variable...
Reid Spencer060d25d2004-06-29 23:29:38 +00001818 GlobalVariable *GV = new GlobalVariable(ElTy, isConstant, Linkage,
Chris Lattner52e20b02003-03-19 20:54:26 +00001819 0, "", TheModule);
Chris Lattner29b789b2003-11-19 17:27:18 +00001820 insertValue(GV, SlotNo, ModuleValues);
Chris Lattner05950c32001-10-13 06:47:01 +00001821
Reid Spencer060d25d2004-06-29 23:29:38 +00001822 unsigned initSlot = 0;
1823 if (hasInitializer) {
1824 initSlot = read_vbr_uint();
1825 GlobalInits.push_back(std::make_pair(GV, initSlot));
1826 }
1827
1828 // Notify handler about the global value.
Reid Spencer46b002c2004-07-11 17:28:43 +00001829 if (Handler) Handler->handleGlobalVariable(ElTy, isConstant, Linkage, SlotNo, initSlot);
Reid Spencer060d25d2004-06-29 23:29:38 +00001830
1831 // Get next item
1832 VarType = read_vbr_uint();
Chris Lattner70cc3392001-09-10 07:58:01 +00001833 }
1834
Chris Lattner52e20b02003-03-19 20:54:26 +00001835 // Read the function objects for all of the functions that are coming
Reid Spencer04cde2c2004-07-04 11:33:49 +00001836 unsigned FnSignature = 0;
Reid Spencer46b002c2004-07-11 17:28:43 +00001837 if (read_typeid(FnSignature))
Reid Spencer24399722004-07-09 22:21:33 +00001838 error("Invalid function type (type type) found");
1839
Chris Lattner74734132002-08-17 22:01:27 +00001840 while (FnSignature != Type::VoidTyID) { // List is terminated by Void
1841 const Type *Ty = getType(FnSignature);
Chris Lattner927b1852003-10-09 20:22:47 +00001842 if (!isa<PointerType>(Ty) ||
Reid Spencer060d25d2004-06-29 23:29:38 +00001843 !isa<FunctionType>(cast<PointerType>(Ty)->getElementType())) {
Reid Spencer24399722004-07-09 22:21:33 +00001844 error("Function not a pointer to function type! Ty = " +
Reid Spencer46b002c2004-07-11 17:28:43 +00001845 Ty->getDescription());
Reid Spencer060d25d2004-06-29 23:29:38 +00001846 // FIXME: what should Ty be if handler continues?
1847 }
Chris Lattner8cdc6b72002-10-23 00:51:54 +00001848
Chris Lattner2a7b6ba2003-03-06 17:15:19 +00001849 // We create functions by passing the underlying FunctionType to create...
Reid Spencer060d25d2004-06-29 23:29:38 +00001850 const FunctionType* FTy =
1851 cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
Chris Lattner00950542001-06-06 20:29:01 +00001852
Reid Spencer060d25d2004-06-29 23:29:38 +00001853 // Insert the place hodler
1854 Function* Func = new Function(FTy, GlobalValue::InternalLinkage,
Reid Spencer04cde2c2004-07-04 11:33:49 +00001855 "", TheModule);
Chris Lattner29b789b2003-11-19 17:27:18 +00001856 insertValue(Func, FnSignature, ModuleValues);
Chris Lattner00950542001-06-06 20:29:01 +00001857
Reid Spencer060d25d2004-06-29 23:29:38 +00001858 // Save this for later so we know type of lazily instantiated functions
Chris Lattner29b789b2003-11-19 17:27:18 +00001859 FunctionSignatureList.push_back(Func);
Chris Lattner52e20b02003-03-19 20:54:26 +00001860
Reid Spencer04cde2c2004-07-04 11:33:49 +00001861 if (Handler) Handler->handleFunctionDeclaration(Func);
Reid Spencer060d25d2004-06-29 23:29:38 +00001862
1863 // Get Next function signature
Reid Spencer46b002c2004-07-11 17:28:43 +00001864 if (read_typeid(FnSignature))
Reid Spencer24399722004-07-09 22:21:33 +00001865 error("Invalid function type (type type) found");
Chris Lattner00950542001-06-06 20:29:01 +00001866 }
1867
Chris Lattner74734132002-08-17 22:01:27 +00001868 // Now that the function signature list is set up, reverse it so that we can
1869 // remove elements efficiently from the back of the vector.
1870 std::reverse(FunctionSignatureList.begin(), FunctionSignatureList.end());
Chris Lattner00950542001-06-06 20:29:01 +00001871
Reid Spencerad89bd62004-07-25 18:07:36 +00001872 // If this bytecode format has dependent library information in it ..
1873 if (!hasNoDependentLibraries) {
1874 // Read in the number of dependent library items that follow
1875 unsigned num_dep_libs = read_vbr_uint();
1876 std::string dep_lib;
1877 while( num_dep_libs-- ) {
1878 dep_lib = read_str();
Reid Spencerada16182004-07-25 21:36:26 +00001879 TheModule->addLibrary(dep_lib);
Reid Spencer5b472d92004-08-21 20:49:23 +00001880 if (Handler)
1881 Handler->handleDependentLibrary(dep_lib);
Reid Spencerad89bd62004-07-25 18:07:36 +00001882 }
1883
Reid Spencer5b472d92004-08-21 20:49:23 +00001884
Reid Spencerad89bd62004-07-25 18:07:36 +00001885 // Read target triple and place into the module
1886 std::string triple = read_str();
1887 TheModule->setTargetTriple(triple);
Reid Spencer5b472d92004-08-21 20:49:23 +00001888 if (Handler)
1889 Handler->handleTargetTriple(triple);
Reid Spencerad89bd62004-07-25 18:07:36 +00001890 }
1891
1892 if (hasInconsistentModuleGlobalInfo)
1893 align32();
1894
Chris Lattner00950542001-06-06 20:29:01 +00001895 // This is for future proofing... in the future extra fields may be added that
1896 // we don't understand, so we transparently ignore them.
1897 //
Reid Spencer060d25d2004-06-29 23:29:38 +00001898 At = BlockEnd;
1899
Reid Spencer04cde2c2004-07-04 11:33:49 +00001900 if (Handler) Handler->handleModuleGlobalsEnd();
Chris Lattner00950542001-06-06 20:29:01 +00001901}
1902
Reid Spencer04cde2c2004-07-04 11:33:49 +00001903/// Parse the version information and decode it by setting flags on the
1904/// Reader that enable backward compatibility of the reader.
Reid Spencer060d25d2004-06-29 23:29:38 +00001905void BytecodeReader::ParseVersionInfo() {
1906 unsigned Version = read_vbr_uint();
Chris Lattner036b8aa2003-03-06 17:55:45 +00001907
1908 // Unpack version number: low four bits are for flags, top bits = version
Chris Lattnerd445c6b2003-08-24 13:47:36 +00001909 Module::Endianness Endianness;
1910 Module::PointerSize PointerSize;
1911 Endianness = (Version & 1) ? Module::BigEndian : Module::LittleEndian;
1912 PointerSize = (Version & 2) ? Module::Pointer64 : Module::Pointer32;
1913
1914 bool hasNoEndianness = Version & 4;
1915 bool hasNoPointerSize = Version & 8;
1916
1917 RevisionNum = Version >> 4;
Chris Lattnere3869c82003-04-16 21:16:05 +00001918
1919 // Default values for the current bytecode version
Chris Lattner44d0eeb2004-01-15 17:55:01 +00001920 hasInconsistentModuleGlobalInfo = false;
Chris Lattner80b97342004-01-17 23:25:43 +00001921 hasExplicitPrimitiveZeros = false;
Chris Lattner5fa428f2004-04-05 01:27:26 +00001922 hasRestrictedGEPTypes = false;
Reid Spencer04cde2c2004-07-04 11:33:49 +00001923 hasTypeDerivedFromValue = false;
Reid Spencerad89bd62004-07-25 18:07:36 +00001924 hasLongBlockHeaders = false;
Reid Spencerad89bd62004-07-25 18:07:36 +00001925 has32BitTypes = false;
1926 hasNoDependentLibraries = false;
Reid Spencer38d54be2004-08-17 07:45:14 +00001927 hasAlignment = false;
Reid Spencer5b472d92004-08-21 20:49:23 +00001928 hasInconsistentBBSlotNums = false;
1929 hasVBRByteTypes = false;
1930 hasUnnecessaryModuleBlockId = false;
Chris Lattner036b8aa2003-03-06 17:55:45 +00001931
1932 switch (RevisionNum) {
Reid Spencer5b472d92004-08-21 20:49:23 +00001933 case 0: // LLVM 1.0, 1.1 (Released)
Chris Lattner9e893e82004-01-14 23:35:21 +00001934 // Base LLVM 1.0 bytecode format.
Chris Lattner44d0eeb2004-01-15 17:55:01 +00001935 hasInconsistentModuleGlobalInfo = true;
Chris Lattner80b97342004-01-17 23:25:43 +00001936 hasExplicitPrimitiveZeros = true;
Reid Spencer04cde2c2004-07-04 11:33:49 +00001937
Chris Lattner80b97342004-01-17 23:25:43 +00001938 // FALL THROUGH
Reid Spencer5b472d92004-08-21 20:49:23 +00001939
1940 case 1: // LLVM 1.2 (Released)
Chris Lattner9e893e82004-01-14 23:35:21 +00001941 // LLVM 1.2 added explicit support for emitting strings efficiently.
Chris Lattner44d0eeb2004-01-15 17:55:01 +00001942
1943 // Also, it fixed the problem where the size of the ModuleGlobalInfo block
1944 // included the size for the alignment at the end, where the rest of the
1945 // blocks did not.
Chris Lattner5fa428f2004-04-05 01:27:26 +00001946
1947 // LLVM 1.2 and before required that GEP indices be ubyte constants for
1948 // structures and longs for sequential types.
1949 hasRestrictedGEPTypes = true;
1950
Reid Spencer04cde2c2004-07-04 11:33:49 +00001951 // LLVM 1.2 and before had the Type class derive from Value class. This
1952 // changed in release 1.3 and consequently LLVM 1.3 bytecode files are
1953 // written differently because Types can no longer be part of the
1954 // type planes for Values.
1955 hasTypeDerivedFromValue = true;
1956
Chris Lattner5fa428f2004-04-05 01:27:26 +00001957 // FALL THROUGH
Reid Spencerad89bd62004-07-25 18:07:36 +00001958
Reid Spencer5b472d92004-08-21 20:49:23 +00001959 case 2: // 1.2.5 (Not Released)
Reid Spencerad89bd62004-07-25 18:07:36 +00001960
Reid Spencer5b472d92004-08-21 20:49:23 +00001961 // LLVM 1.2 and earlier had two-word block headers. This is a bit wasteful,
1962 // especially for small files where the 8 bytes per block is a large fraction
1963 // of the total block size. In LLVM 1.3, the block type and length are
1964 // compressed into a single 32-bit unsigned integer. 27 bits for length, 5
1965 // bits for block type.
Reid Spencerad89bd62004-07-25 18:07:36 +00001966 hasLongBlockHeaders = true;
1967
Reid Spencer5b472d92004-08-21 20:49:23 +00001968 // LLVM 1.2 and earlier wrote type slot numbers as vbr_uint32. In LLVM 1.3
1969 // this has been reduced to vbr_uint24. It shouldn't make much difference
1970 // since we haven't run into a module with > 24 million types, but for safety
1971 // the 24-bit restriction has been enforced in 1.3 to free some bits in
1972 // various places and to ensure consistency.
Reid Spencerad89bd62004-07-25 18:07:36 +00001973 has32BitTypes = true;
1974
Reid Spencer5b472d92004-08-21 20:49:23 +00001975 // LLVM 1.2 and earlier did not provide a target triple nor a list of
1976 // libraries on which the bytecode is dependent. LLVM 1.3 provides these
1977 // features, for use in future versions of LLVM.
Reid Spencerad89bd62004-07-25 18:07:36 +00001978 hasNoDependentLibraries = true;
1979
1980 // FALL THROUGH
Reid Spencer5b472d92004-08-21 20:49:23 +00001981
1982 case 3: // LLVM 1.3 (Released)
1983 // LLVM 1.3 and earlier caused alignment bytes to be written on some block
1984 // boundaries and at the end of some strings. In extreme cases (e.g. lots
1985 // of GEP references to a constant array), this can increase the file size
1986 // by 30% or more. In version 1.4 alignment is done away with completely.
Reid Spencer38d54be2004-08-17 07:45:14 +00001987 hasAlignment = true;
1988
1989 // FALL THROUGH
Reid Spencer5b472d92004-08-21 20:49:23 +00001990
1991 case 4: // 1.3.1 (Not Released)
1992 // In version 4, basic blocks have a minimum index of 0 whereas all the
1993 // other primitives have a minimum index of 1 (because 0 is the "null"
1994 // value. In version 5, we made this consistent.
1995 hasInconsistentBBSlotNums = true;
Chris Lattnerc08912f2004-01-14 16:44:44 +00001996
Reid Spencer5b472d92004-08-21 20:49:23 +00001997 // In version 4, the types SByte and UByte were encoded as vbr_uint so that
1998 // signed values > 63 and unsigned values >127 would be encoded as two
1999 // bytes. In version 5, they are encoded directly in a single byte.
2000 hasVBRByteTypes = true;
2001
2002 // In version 4, modules begin with a "Module Block" which encodes a 4-byte
2003 // integer value 0x01 to identify the module block. This is unnecessary and
2004 // removed in version 5.
2005 hasUnnecessaryModuleBlockId = true;
2006
2007 // FALL THROUGH
2008
2009 case 5: // LLVM 1.4 (Released)
2010 break;
Chris Lattner036b8aa2003-03-06 17:55:45 +00002011 default:
Reid Spencer24399722004-07-09 22:21:33 +00002012 error("Unknown bytecode version number: " + itostr(RevisionNum));
Chris Lattner036b8aa2003-03-06 17:55:45 +00002013 }
2014
Chris Lattnerd445c6b2003-08-24 13:47:36 +00002015 if (hasNoEndianness) Endianness = Module::AnyEndianness;
2016 if (hasNoPointerSize) PointerSize = Module::AnyPointerSize;
Chris Lattner76e38962003-04-22 18:15:10 +00002017
Brian Gaekefe2102b2004-07-14 20:33:13 +00002018 TheModule->setEndianness(Endianness);
2019 TheModule->setPointerSize(PointerSize);
2020
Reid Spencer46b002c2004-07-11 17:28:43 +00002021 if (Handler) Handler->handleVersionInfo(RevisionNum, Endianness, PointerSize);
Chris Lattner036b8aa2003-03-06 17:55:45 +00002022}
2023
Reid Spencer04cde2c2004-07-04 11:33:49 +00002024/// Parse a whole module.
Reid Spencer060d25d2004-06-29 23:29:38 +00002025void BytecodeReader::ParseModule() {
Chris Lattner00950542001-06-06 20:29:01 +00002026 unsigned Type, Size;
Chris Lattner00950542001-06-06 20:29:01 +00002027
Reid Spencer060d25d2004-06-29 23:29:38 +00002028 FunctionSignatureList.clear(); // Just in case...
Chris Lattner00950542001-06-06 20:29:01 +00002029
2030 // Read into instance variables...
Reid Spencer060d25d2004-06-29 23:29:38 +00002031 ParseVersionInfo();
Reid Spencerad89bd62004-07-25 18:07:36 +00002032 align32();
Chris Lattner00950542001-06-06 20:29:01 +00002033
Reid Spencer060d25d2004-06-29 23:29:38 +00002034 bool SeenModuleGlobalInfo = false;
2035 bool SeenGlobalTypePlane = false;
2036 BufPtr MyEnd = BlockEnd;
2037 while (At < MyEnd) {
2038 BufPtr OldAt = At;
2039 read_block(Type, Size);
2040
Chris Lattner00950542001-06-06 20:29:01 +00002041 switch (Type) {
Reid Spencer060d25d2004-06-29 23:29:38 +00002042
Reid Spencerad89bd62004-07-25 18:07:36 +00002043 case BytecodeFormat::GlobalTypePlaneBlockID:
Reid Spencer46b002c2004-07-11 17:28:43 +00002044 if (SeenGlobalTypePlane)
Reid Spencer24399722004-07-09 22:21:33 +00002045 error("Two GlobalTypePlane Blocks Encountered!");
Reid Spencer060d25d2004-06-29 23:29:38 +00002046
Reid Spencer5b472d92004-08-21 20:49:23 +00002047 if (Size > 0)
2048 ParseGlobalTypes();
Reid Spencer060d25d2004-06-29 23:29:38 +00002049 SeenGlobalTypePlane = true;
Chris Lattner52e20b02003-03-19 20:54:26 +00002050 break;
2051
Reid Spencerad89bd62004-07-25 18:07:36 +00002052 case BytecodeFormat::ModuleGlobalInfoBlockID:
Reid Spencer46b002c2004-07-11 17:28:43 +00002053 if (SeenModuleGlobalInfo)
Reid Spencer24399722004-07-09 22:21:33 +00002054 error("Two ModuleGlobalInfo Blocks Encountered!");
Reid Spencer060d25d2004-06-29 23:29:38 +00002055 ParseModuleGlobalInfo();
2056 SeenModuleGlobalInfo = true;
Chris Lattner52e20b02003-03-19 20:54:26 +00002057 break;
2058
Reid Spencerad89bd62004-07-25 18:07:36 +00002059 case BytecodeFormat::ConstantPoolBlockID:
Reid Spencer04cde2c2004-07-04 11:33:49 +00002060 ParseConstantPool(ModuleValues, ModuleTypes,false);
Chris Lattner00950542001-06-06 20:29:01 +00002061 break;
2062
Reid Spencerad89bd62004-07-25 18:07:36 +00002063 case BytecodeFormat::FunctionBlockID:
Reid Spencer060d25d2004-06-29 23:29:38 +00002064 ParseFunctionLazily();
Chris Lattner00950542001-06-06 20:29:01 +00002065 break;
Chris Lattner00950542001-06-06 20:29:01 +00002066
Reid Spencerad89bd62004-07-25 18:07:36 +00002067 case BytecodeFormat::SymbolTableBlockID:
Reid Spencer060d25d2004-06-29 23:29:38 +00002068 ParseSymbolTable(0, &TheModule->getSymbolTable());
Chris Lattner00950542001-06-06 20:29:01 +00002069 break;
Reid Spencer060d25d2004-06-29 23:29:38 +00002070
Chris Lattner00950542001-06-06 20:29:01 +00002071 default:
Reid Spencer060d25d2004-06-29 23:29:38 +00002072 At += Size;
2073 if (OldAt > At) {
Reid Spencer46b002c2004-07-11 17:28:43 +00002074 error("Unexpected Block of Type #" + utostr(Type) + " encountered!");
Reid Spencer060d25d2004-06-29 23:29:38 +00002075 }
Chris Lattner00950542001-06-06 20:29:01 +00002076 break;
2077 }
Reid Spencer060d25d2004-06-29 23:29:38 +00002078 BlockEnd = MyEnd;
2079 align32();
Chris Lattner00950542001-06-06 20:29:01 +00002080 }
2081
Chris Lattner52e20b02003-03-19 20:54:26 +00002082 // After the module constant pool has been read, we can safely initialize
2083 // global variables...
2084 while (!GlobalInits.empty()) {
2085 GlobalVariable *GV = GlobalInits.back().first;
2086 unsigned Slot = GlobalInits.back().second;
2087 GlobalInits.pop_back();
2088
2089 // Look up the initializer value...
Chris Lattner29b789b2003-11-19 17:27:18 +00002090 // FIXME: Preserve this type ID!
Reid Spencer060d25d2004-06-29 23:29:38 +00002091
2092 const llvm::PointerType* GVType = GV->getType();
2093 unsigned TypeSlot = getTypeSlot(GVType->getElementType());
Chris Lattner93361992004-01-15 18:45:25 +00002094 if (Constant *CV = getConstantValue(TypeSlot, Slot)) {
Misha Brukman12c29d12003-09-22 23:38:23 +00002095 if (GV->hasInitializer())
Reid Spencer24399722004-07-09 22:21:33 +00002096 error("Global *already* has an initializer?!");
Reid Spencer04cde2c2004-07-04 11:33:49 +00002097 if (Handler) Handler->handleGlobalInitializer(GV,CV);
Chris Lattner93361992004-01-15 18:45:25 +00002098 GV->setInitializer(CV);
Chris Lattner52e20b02003-03-19 20:54:26 +00002099 } else
Reid Spencer24399722004-07-09 22:21:33 +00002100 error("Cannot find initializer value.");
Chris Lattner52e20b02003-03-19 20:54:26 +00002101 }
2102
Reid Spencer060d25d2004-06-29 23:29:38 +00002103 /// Make sure we pulled them all out. If we didn't then there's a declaration
2104 /// but a missing body. That's not allowed.
Misha Brukman12c29d12003-09-22 23:38:23 +00002105 if (!FunctionSignatureList.empty())
Reid Spencer24399722004-07-09 22:21:33 +00002106 error("Function declared, but bytecode stream ended before definition");
Chris Lattner00950542001-06-06 20:29:01 +00002107}
2108
Reid Spencer04cde2c2004-07-04 11:33:49 +00002109/// This function completely parses a bytecode buffer given by the \p Buf
2110/// and \p Length parameters.
Reid Spencer46b002c2004-07-11 17:28:43 +00002111void BytecodeReader::ParseBytecode(BufPtr Buf, unsigned Length,
Reid Spencer5b472d92004-08-21 20:49:23 +00002112 const std::string &ModuleID) {
Misha Brukmane0dd0d42003-09-23 16:15:29 +00002113
Reid Spencer060d25d2004-06-29 23:29:38 +00002114 try {
2115 At = MemStart = BlockStart = Buf;
2116 MemEnd = BlockEnd = Buf + Length;
Misha Brukmane0dd0d42003-09-23 16:15:29 +00002117
Reid Spencer060d25d2004-06-29 23:29:38 +00002118 // Create the module
2119 TheModule = new Module(ModuleID);
Chris Lattner00950542001-06-06 20:29:01 +00002120
Reid Spencer04cde2c2004-07-04 11:33:49 +00002121 if (Handler) Handler->handleStart(TheModule, Length);
Reid Spencer060d25d2004-06-29 23:29:38 +00002122
2123 // Read and check signature...
2124 unsigned Sig = read_uint();
2125 if (Sig != ('l' | ('l' << 8) | ('v' << 16) | ('m' << 24))) {
Reid Spencer24399722004-07-09 22:21:33 +00002126 error("Invalid bytecode signature: " + utostr(Sig));
Reid Spencer060d25d2004-06-29 23:29:38 +00002127 }
2128
Reid Spencer060d25d2004-06-29 23:29:38 +00002129 // Tell the handler we're starting a module
Reid Spencer04cde2c2004-07-04 11:33:49 +00002130 if (Handler) Handler->handleModuleBegin(ModuleID);
Reid Spencer060d25d2004-06-29 23:29:38 +00002131
Reid Spencerad89bd62004-07-25 18:07:36 +00002132 // Get the module block and size and verify. This is handled specially
2133 // because the module block/size is always written in long format. Other
2134 // blocks are written in short format so the read_block method is used.
Reid Spencer060d25d2004-06-29 23:29:38 +00002135 unsigned Type, Size;
Reid Spencerad89bd62004-07-25 18:07:36 +00002136 Type = read_uint();
2137 Size = read_uint();
2138 if (Type != BytecodeFormat::ModuleBlockID) {
Reid Spencer24399722004-07-09 22:21:33 +00002139 error("Expected Module Block! Type:" + utostr(Type) + ", Size:"
Reid Spencer46b002c2004-07-11 17:28:43 +00002140 + utostr(Size));
Reid Spencer060d25d2004-06-29 23:29:38 +00002141 }
Reid Spencer46b002c2004-07-11 17:28:43 +00002142 if (At + Size != MemEnd) {
Reid Spencer24399722004-07-09 22:21:33 +00002143 error("Invalid Top Level Block Length! Type:" + utostr(Type)
Reid Spencer46b002c2004-07-11 17:28:43 +00002144 + ", Size:" + utostr(Size));
Reid Spencer060d25d2004-06-29 23:29:38 +00002145 }
2146
2147 // Parse the module contents
2148 this->ParseModule();
2149
Reid Spencer060d25d2004-06-29 23:29:38 +00002150 // Check for missing functions
Reid Spencer46b002c2004-07-11 17:28:43 +00002151 if (hasFunctions())
Reid Spencer24399722004-07-09 22:21:33 +00002152 error("Function expected, but bytecode stream ended!");
Reid Spencer060d25d2004-06-29 23:29:38 +00002153
Reid Spencer5c15fe52004-07-05 00:57:50 +00002154 // Tell the handler we're done with the module
2155 if (Handler)
2156 Handler->handleModuleEnd(ModuleID);
2157
2158 // Tell the handler we're finished the parse
Reid Spencer04cde2c2004-07-04 11:33:49 +00002159 if (Handler) Handler->handleFinish();
Reid Spencer060d25d2004-06-29 23:29:38 +00002160
Reid Spencer46b002c2004-07-11 17:28:43 +00002161 } catch (std::string& errstr) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00002162 if (Handler) Handler->handleError(errstr);
Reid Spencer060d25d2004-06-29 23:29:38 +00002163 freeState();
Chris Lattner2a7b6ba2003-03-06 17:15:19 +00002164 delete TheModule;
2165 TheModule = 0;
Chris Lattnerb0b7c0d2003-09-26 14:44:52 +00002166 throw;
Reid Spencer060d25d2004-06-29 23:29:38 +00002167 } catch (...) {
2168 std::string msg("Unknown Exception Occurred");
Reid Spencer04cde2c2004-07-04 11:33:49 +00002169 if (Handler) Handler->handleError(msg);
Reid Spencer060d25d2004-06-29 23:29:38 +00002170 freeState();
2171 delete TheModule;
2172 TheModule = 0;
2173 throw msg;
Chris Lattner2a7b6ba2003-03-06 17:15:19 +00002174 }
Chris Lattner00950542001-06-06 20:29:01 +00002175}
Reid Spencer060d25d2004-06-29 23:29:38 +00002176
2177//===----------------------------------------------------------------------===//
2178//=== Default Implementations of Handler Methods
2179//===----------------------------------------------------------------------===//
2180
2181BytecodeHandler::~BytecodeHandler() {}
Reid Spencer060d25d2004-06-29 23:29:38 +00002182
2183// vim: sw=2