blob: b1e4bf639cc6340db98287668fcc80ac4a85f2d1 [file] [log] [blame]
Chris Lattnerd6b65252001-10-24 01:15:12 +00001//===- Reader.cpp - Code to read bytecode files ---------------------------===//
Misha Brukman8a96c532005-04-21 21:44:41 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// 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.
Misha Brukman8a96c532005-04-21 21:44:41 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner00950542001-06-06 20:29:01 +00009//
10// This library implements the functionality defined in llvm/Bytecode/Reader.h
11//
Misha Brukman8a96c532005-04-21 21:44:41 +000012// Note that this library should be as fast as possible, reentrant, and
Chris Lattner00950542001-06-06 20:29:01 +000013// 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"
Chris Lattnerdee199f2005-05-06 22:34:01 +000022#include "llvm/CallingConv.h"
Reid Spencer060d25d2004-06-29 23:29:38 +000023#include "llvm/Constants.h"
Chris Lattner3bc5a602006-01-25 23:08:15 +000024#include "llvm/InlineAsm.h"
Reid Spencer04cde2c2004-07-04 11:33:49 +000025#include "llvm/Instructions.h"
26#include "llvm/SymbolTable.h"
Reid Spencer78d033e2007-01-06 07:24:44 +000027#include "llvm/TypeSymbolTable.h"
Chris Lattner00950542001-06-06 20:29:01 +000028#include "llvm/Bytecode/Format.h"
Chris Lattnerdee199f2005-05-06 22:34:01 +000029#include "llvm/Config/alloca.h"
Reid Spencer060d25d2004-06-29 23:29:38 +000030#include "llvm/Support/GetElementPtrTypeIterator.h"
Reid Spencer17f52c52004-11-06 23:17:23 +000031#include "llvm/Support/Compressor.h"
Jim Laskeycb6682f2005-08-17 19:34:49 +000032#include "llvm/Support/MathExtras.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000033#include "llvm/ADT/StringExtras.h"
Reid Spencer060d25d2004-06-29 23:29:38 +000034#include <sstream>
Alkis Evlogimenos20aa4742004-09-03 18:19:51 +000035#include <algorithm>
Chris Lattner29b789b2003-11-19 17:27:18 +000036using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000037
Reid Spencer46b002c2004-07-11 17:28:43 +000038namespace {
Chris Lattnercad28bd2005-01-29 00:36:19 +000039 /// @brief A class for maintaining the slot number definition
40 /// as a placeholder for the actual definition for forward constants defs.
41 class ConstantPlaceHolder : public ConstantExpr {
42 ConstantPlaceHolder(); // DO NOT IMPLEMENT
43 void operator=(const ConstantPlaceHolder &); // DO NOT IMPLEMENT
44 public:
Chris Lattner61323322005-01-31 01:11:13 +000045 Use Op;
Misha Brukman8a96c532005-04-21 21:44:41 +000046 ConstantPlaceHolder(const Type *Ty)
Chris Lattner61323322005-01-31 01:11:13 +000047 : ConstantExpr(Ty, Instruction::UserOp1, &Op, 1),
Reid Spencer88cfda22006-12-31 05:44:24 +000048 Op(UndefValue::get(Type::Int32Ty), this) {
Chris Lattner61323322005-01-31 01:11:13 +000049 }
Chris Lattnercad28bd2005-01-29 00:36:19 +000050 };
Reid Spencer46b002c2004-07-11 17:28:43 +000051}
Reid Spencer060d25d2004-06-29 23:29:38 +000052
Reid Spencer24399722004-07-09 22:21:33 +000053// Provide some details on error
Reid Spencer233fe722006-08-22 16:09:19 +000054inline void BytecodeReader::error(const std::string& err) {
55 ErrorMsg = err + " (Vers=" + itostr(RevisionNum) + ", Pos="
56 + itostr(At-MemStart) + ")";
57 longjmp(context,1);
Reid Spencer24399722004-07-09 22:21:33 +000058}
59
Reid Spencer060d25d2004-06-29 23:29:38 +000060//===----------------------------------------------------------------------===//
61// Bytecode Reading Methods
62//===----------------------------------------------------------------------===//
63
Reid Spencer04cde2c2004-07-04 11:33:49 +000064/// Determine if the current block being read contains any more data.
Reid Spencer060d25d2004-06-29 23:29:38 +000065inline bool BytecodeReader::moreInBlock() {
66 return At < BlockEnd;
Chris Lattner00950542001-06-06 20:29:01 +000067}
68
Reid Spencer04cde2c2004-07-04 11:33:49 +000069/// Throw an error if we've read past the end of the current block
Reid Spencer060d25d2004-06-29 23:29:38 +000070inline void BytecodeReader::checkPastBlockEnd(const char * block_name) {
Reid Spencer46b002c2004-07-11 17:28:43 +000071 if (At > BlockEnd)
Chris Lattnera79e7cc2004-10-16 18:18:16 +000072 error(std::string("Attempt to read past the end of ") + block_name +
73 " block.");
Reid Spencer060d25d2004-06-29 23:29:38 +000074}
Chris Lattner36392bc2003-10-08 21:18:57 +000075
Reid Spencer04cde2c2004-07-04 11:33:49 +000076/// Read a whole unsigned integer
Reid Spencer060d25d2004-06-29 23:29:38 +000077inline unsigned BytecodeReader::read_uint() {
Misha Brukman8a96c532005-04-21 21:44:41 +000078 if (At+4 > BlockEnd)
Reid Spencer24399722004-07-09 22:21:33 +000079 error("Ran out of data reading uint!");
Reid Spencer060d25d2004-06-29 23:29:38 +000080 At += 4;
81 return At[-4] | (At[-3] << 8) | (At[-2] << 16) | (At[-1] << 24);
82}
83
Reid Spencer04cde2c2004-07-04 11:33:49 +000084/// Read a variable-bit-rate encoded unsigned integer
Reid Spencer060d25d2004-06-29 23:29:38 +000085inline unsigned BytecodeReader::read_vbr_uint() {
86 unsigned Shift = 0;
87 unsigned Result = 0;
88 BufPtr Save = At;
Misha Brukman8a96c532005-04-21 21:44:41 +000089
Reid Spencer060d25d2004-06-29 23:29:38 +000090 do {
Misha Brukman8a96c532005-04-21 21:44:41 +000091 if (At == BlockEnd)
Reid Spencer24399722004-07-09 22:21:33 +000092 error("Ran out of data reading vbr_uint!");
Reid Spencer060d25d2004-06-29 23:29:38 +000093 Result |= (unsigned)((*At++) & 0x7F) << Shift;
94 Shift += 7;
95 } while (At[-1] & 0x80);
Reid Spencer04cde2c2004-07-04 11:33:49 +000096 if (Handler) Handler->handleVBR32(At-Save);
Reid Spencer060d25d2004-06-29 23:29:38 +000097 return Result;
98}
99
Reid Spencer04cde2c2004-07-04 11:33:49 +0000100/// Read a variable-bit-rate encoded unsigned 64-bit integer.
Reid Spencer060d25d2004-06-29 23:29:38 +0000101inline uint64_t BytecodeReader::read_vbr_uint64() {
102 unsigned Shift = 0;
103 uint64_t Result = 0;
104 BufPtr Save = At;
Misha Brukman8a96c532005-04-21 21:44:41 +0000105
Reid Spencer060d25d2004-06-29 23:29:38 +0000106 do {
Misha Brukman8a96c532005-04-21 21:44:41 +0000107 if (At == BlockEnd)
Reid Spencer24399722004-07-09 22:21:33 +0000108 error("Ran out of data reading vbr_uint64!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000109 Result |= (uint64_t)((*At++) & 0x7F) << Shift;
110 Shift += 7;
111 } while (At[-1] & 0x80);
Reid Spencer04cde2c2004-07-04 11:33:49 +0000112 if (Handler) Handler->handleVBR64(At-Save);
Reid Spencer060d25d2004-06-29 23:29:38 +0000113 return Result;
114}
115
Reid Spencer04cde2c2004-07-04 11:33:49 +0000116/// Read a variable-bit-rate encoded signed 64-bit integer.
Reid Spencer060d25d2004-06-29 23:29:38 +0000117inline int64_t BytecodeReader::read_vbr_int64() {
118 uint64_t R = read_vbr_uint64();
119 if (R & 1) {
120 if (R != 1)
121 return -(int64_t)(R >> 1);
122 else // There is no such thing as -0 with integers. "-0" really means
123 // 0x8000000000000000.
124 return 1LL << 63;
125 } else
126 return (int64_t)(R >> 1);
127}
128
Reid Spencer04cde2c2004-07-04 11:33:49 +0000129/// Read a pascal-style string (length followed by text)
Reid Spencer060d25d2004-06-29 23:29:38 +0000130inline std::string BytecodeReader::read_str() {
131 unsigned Size = read_vbr_uint();
132 const unsigned char *OldAt = At;
133 At += Size;
134 if (At > BlockEnd) // Size invalid?
Reid Spencer24399722004-07-09 22:21:33 +0000135 error("Ran out of data reading a string!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000136 return std::string((char*)OldAt, Size);
137}
138
Reid Spencer04cde2c2004-07-04 11:33:49 +0000139/// Read an arbitrary block of data
Reid Spencer060d25d2004-06-29 23:29:38 +0000140inline void BytecodeReader::read_data(void *Ptr, void *End) {
141 unsigned char *Start = (unsigned char *)Ptr;
142 unsigned Amount = (unsigned char *)End - Start;
Misha Brukman8a96c532005-04-21 21:44:41 +0000143 if (At+Amount > BlockEnd)
Reid Spencer24399722004-07-09 22:21:33 +0000144 error("Ran out of data!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000145 std::copy(At, At+Amount, Start);
146 At += Amount;
147}
148
Reid Spencer46b002c2004-07-11 17:28:43 +0000149/// Read a float value in little-endian order
150inline void BytecodeReader::read_float(float& FloatVal) {
Reid Spencerada16182004-07-25 21:36:26 +0000151 /// FIXME: This isn't optimal, it has size problems on some platforms
152 /// where FP is not IEEE.
Jim Laskeycb6682f2005-08-17 19:34:49 +0000153 FloatVal = BitsToFloat(At[0] | (At[1] << 8) | (At[2] << 16) | (At[3] << 24));
Reid Spencerada16182004-07-25 21:36:26 +0000154 At+=sizeof(uint32_t);
Reid Spencer46b002c2004-07-11 17:28:43 +0000155}
156
157/// Read a double value in little-endian order
158inline void BytecodeReader::read_double(double& DoubleVal) {
Reid Spencerada16182004-07-25 21:36:26 +0000159 /// FIXME: This isn't optimal, it has size problems on some platforms
160 /// where FP is not IEEE.
Jim Laskeycb6682f2005-08-17 19:34:49 +0000161 DoubleVal = BitsToDouble((uint64_t(At[0]) << 0) | (uint64_t(At[1]) << 8) |
162 (uint64_t(At[2]) << 16) | (uint64_t(At[3]) << 24) |
163 (uint64_t(At[4]) << 32) | (uint64_t(At[5]) << 40) |
164 (uint64_t(At[6]) << 48) | (uint64_t(At[7]) << 56));
Reid Spencerada16182004-07-25 21:36:26 +0000165 At+=sizeof(uint64_t);
Reid Spencer46b002c2004-07-11 17:28:43 +0000166}
167
Reid Spencer04cde2c2004-07-04 11:33:49 +0000168/// Read a block header and obtain its type and size
Reid Spencer060d25d2004-06-29 23:29:38 +0000169inline void BytecodeReader::read_block(unsigned &Type, unsigned &Size) {
Reid Spencerd798a512006-11-14 04:47:22 +0000170 Size = read_uint(); // Read the header
171 Type = Size & 0x1F; // mask low order five bits to get type
172 Size >>= 5; // high order 27 bits is the size
Reid Spencer060d25d2004-06-29 23:29:38 +0000173 BlockStart = At;
Reid Spencer46b002c2004-07-11 17:28:43 +0000174 if (At + Size > BlockEnd)
Reid Spencer24399722004-07-09 22:21:33 +0000175 error("Attempt to size a block past end of memory");
Reid Spencer060d25d2004-06-29 23:29:38 +0000176 BlockEnd = At + Size;
Reid Spencer46b002c2004-07-11 17:28:43 +0000177 if (Handler) Handler->handleBlock(Type, BlockStart, Size);
Reid Spencer04cde2c2004-07-04 11:33:49 +0000178}
179
Reid Spencer060d25d2004-06-29 23:29:38 +0000180//===----------------------------------------------------------------------===//
181// IR Lookup Methods
182//===----------------------------------------------------------------------===//
183
Reid Spencer04cde2c2004-07-04 11:33:49 +0000184/// Determine if a type id has an implicit null value
Reid Spencer46b002c2004-07-11 17:28:43 +0000185inline bool BytecodeReader::hasImplicitNull(unsigned TyID) {
Reid Spencerd798a512006-11-14 04:47:22 +0000186 return TyID != Type::LabelTyID && TyID != Type::VoidTyID;
Reid Spencer060d25d2004-06-29 23:29:38 +0000187}
188
Reid Spencer04cde2c2004-07-04 11:33:49 +0000189/// Obtain a type given a typeid and account for things like compaction tables,
190/// function level vs module level, and the offsetting for the primitive types.
Reid Spencer060d25d2004-06-29 23:29:38 +0000191const Type *BytecodeReader::getType(unsigned ID) {
Chris Lattner89e02532004-01-18 21:08:15 +0000192 if (ID < Type::FirstDerivedTyID)
Chris Lattnerf70c22b2004-06-17 18:19:28 +0000193 if (const Type *T = Type::getPrimitiveType((Type::TypeID)ID))
Chris Lattner927b1852003-10-09 20:22:47 +0000194 return T; // Asked for a primitive type...
Chris Lattner36392bc2003-10-08 21:18:57 +0000195
196 // Otherwise, derived types need offset...
Chris Lattner89e02532004-01-18 21:08:15 +0000197 ID -= Type::FirstDerivedTyID;
198
Reid Spencer060d25d2004-06-29 23:29:38 +0000199 if (!CompactionTypes.empty()) {
200 if (ID >= CompactionTypes.size())
Reid Spencer24399722004-07-09 22:21:33 +0000201 error("Type ID out of range for compaction table!");
Chris Lattner45b5dd22004-08-03 23:41:28 +0000202 return CompactionTypes[ID].first;
Chris Lattner89e02532004-01-18 21:08:15 +0000203 }
Chris Lattner36392bc2003-10-08 21:18:57 +0000204
205 // Is it a module-level type?
Reid Spencer46b002c2004-07-11 17:28:43 +0000206 if (ID < ModuleTypes.size())
207 return ModuleTypes[ID].get();
Chris Lattner36392bc2003-10-08 21:18:57 +0000208
Reid Spencer46b002c2004-07-11 17:28:43 +0000209 // Nope, is it a function-level type?
210 ID -= ModuleTypes.size();
211 if (ID < FunctionTypes.size())
212 return FunctionTypes[ID].get();
Chris Lattner36392bc2003-10-08 21:18:57 +0000213
Reid Spencer46b002c2004-07-11 17:28:43 +0000214 error("Illegal type reference!");
215 return Type::VoidTy;
Chris Lattner00950542001-06-06 20:29:01 +0000216}
217
Reid Spencer3795ad12006-12-03 05:47:10 +0000218/// This method just saves some coding. It uses read_vbr_uint to read in a
219/// type id, errors that its not the type type, and then calls getType to
220/// return the type value.
Reid Spencerd798a512006-11-14 04:47:22 +0000221inline const Type* BytecodeReader::readType() {
222 return getType(read_vbr_uint());
Reid Spencer04cde2c2004-07-04 11:33:49 +0000223}
224
225/// Get the slot number associated with a type accounting for primitive
226/// types, compaction tables, and function level vs module level.
Reid Spencer060d25d2004-06-29 23:29:38 +0000227unsigned BytecodeReader::getTypeSlot(const Type *Ty) {
228 if (Ty->isPrimitiveType())
229 return Ty->getTypeID();
230
231 // Scan the compaction table for the type if needed.
232 if (!CompactionTypes.empty()) {
Chris Lattner45b5dd22004-08-03 23:41:28 +0000233 for (unsigned i = 0, e = CompactionTypes.size(); i != e; ++i)
234 if (CompactionTypes[i].first == Ty)
Misha Brukman8a96c532005-04-21 21:44:41 +0000235 return Type::FirstDerivedTyID + i;
Reid Spencer060d25d2004-06-29 23:29:38 +0000236
Chris Lattner45b5dd22004-08-03 23:41:28 +0000237 error("Couldn't find type specified in compaction table!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000238 }
239
240 // Check the function level types first...
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000241 TypeListTy::iterator I = std::find(FunctionTypes.begin(),
242 FunctionTypes.end(), Ty);
Reid Spencer060d25d2004-06-29 23:29:38 +0000243
244 if (I != FunctionTypes.end())
Misha Brukman8a96c532005-04-21 21:44:41 +0000245 return Type::FirstDerivedTyID + ModuleTypes.size() +
Reid Spencer46b002c2004-07-11 17:28:43 +0000246 (&*I - &FunctionTypes[0]);
Reid Spencer060d25d2004-06-29 23:29:38 +0000247
Chris Lattnereebac5f2005-10-03 21:26:53 +0000248 // If we don't have our cache yet, build it now.
249 if (ModuleTypeIDCache.empty()) {
250 unsigned N = 0;
251 ModuleTypeIDCache.reserve(ModuleTypes.size());
252 for (TypeListTy::iterator I = ModuleTypes.begin(), E = ModuleTypes.end();
253 I != E; ++I, ++N)
254 ModuleTypeIDCache.push_back(std::make_pair(*I, N));
255
256 std::sort(ModuleTypeIDCache.begin(), ModuleTypeIDCache.end());
257 }
258
259 // Binary search the cache for the entry.
260 std::vector<std::pair<const Type*, unsigned> >::iterator IT =
261 std::lower_bound(ModuleTypeIDCache.begin(), ModuleTypeIDCache.end(),
262 std::make_pair(Ty, 0U));
263 if (IT == ModuleTypeIDCache.end() || IT->first != Ty)
Reid Spencer24399722004-07-09 22:21:33 +0000264 error("Didn't find type in ModuleTypes.");
Chris Lattnereebac5f2005-10-03 21:26:53 +0000265
266 return Type::FirstDerivedTyID + IT->second;
Chris Lattner80b97342004-01-17 23:25:43 +0000267}
268
Reid Spencer04cde2c2004-07-04 11:33:49 +0000269/// This is just like getType, but when a compaction table is in use, it is
270/// ignored. It also ignores function level types.
271/// @see getType
Reid Spencer060d25d2004-06-29 23:29:38 +0000272const Type *BytecodeReader::getGlobalTableType(unsigned Slot) {
273 if (Slot < Type::FirstDerivedTyID) {
274 const Type *Ty = Type::getPrimitiveType((Type::TypeID)Slot);
Reid Spencer46b002c2004-07-11 17:28:43 +0000275 if (!Ty)
Reid Spencer24399722004-07-09 22:21:33 +0000276 error("Not a primitive type ID?");
Reid Spencer060d25d2004-06-29 23:29:38 +0000277 return Ty;
278 }
279 Slot -= Type::FirstDerivedTyID;
280 if (Slot >= ModuleTypes.size())
Reid Spencer24399722004-07-09 22:21:33 +0000281 error("Illegal compaction table type reference!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000282 return ModuleTypes[Slot];
Chris Lattner52e20b02003-03-19 20:54:26 +0000283}
284
Reid Spencer04cde2c2004-07-04 11:33:49 +0000285/// This is just like getTypeSlot, but when a compaction table is in use, it
286/// is ignored. It also ignores function level types.
Reid Spencer060d25d2004-06-29 23:29:38 +0000287unsigned BytecodeReader::getGlobalTableTypeSlot(const Type *Ty) {
288 if (Ty->isPrimitiveType())
289 return Ty->getTypeID();
Chris Lattnereebac5f2005-10-03 21:26:53 +0000290
291 // If we don't have our cache yet, build it now.
292 if (ModuleTypeIDCache.empty()) {
293 unsigned N = 0;
294 ModuleTypeIDCache.reserve(ModuleTypes.size());
295 for (TypeListTy::iterator I = ModuleTypes.begin(), E = ModuleTypes.end();
296 I != E; ++I, ++N)
297 ModuleTypeIDCache.push_back(std::make_pair(*I, N));
298
299 std::sort(ModuleTypeIDCache.begin(), ModuleTypeIDCache.end());
300 }
301
302 // Binary search the cache for the entry.
303 std::vector<std::pair<const Type*, unsigned> >::iterator IT =
304 std::lower_bound(ModuleTypeIDCache.begin(), ModuleTypeIDCache.end(),
305 std::make_pair(Ty, 0U));
306 if (IT == ModuleTypeIDCache.end() || IT->first != Ty)
Reid Spencer24399722004-07-09 22:21:33 +0000307 error("Didn't find type in ModuleTypes.");
Chris Lattnereebac5f2005-10-03 21:26:53 +0000308
309 return Type::FirstDerivedTyID + IT->second;
Reid Spencer060d25d2004-06-29 23:29:38 +0000310}
311
Misha Brukman8a96c532005-04-21 21:44:41 +0000312/// Retrieve a value of a given type and slot number, possibly creating
313/// it if it doesn't already exist.
Reid Spencer060d25d2004-06-29 23:29:38 +0000314Value * BytecodeReader::getValue(unsigned type, unsigned oNum, bool Create) {
Chris Lattner4ee8ef22003-10-08 22:52:54 +0000315 assert(type != Type::LabelTyID && "getValue() cannot get blocks!");
Chris Lattner00950542001-06-06 20:29:01 +0000316 unsigned Num = oNum;
Chris Lattner00950542001-06-06 20:29:01 +0000317
Chris Lattner89e02532004-01-18 21:08:15 +0000318 // If there is a compaction table active, it defines the low-level numbers.
319 // If not, the module values define the low-level numbers.
Reid Spencer060d25d2004-06-29 23:29:38 +0000320 if (CompactionValues.size() > type && !CompactionValues[type].empty()) {
321 if (Num < CompactionValues[type].size())
322 return CompactionValues[type][Num];
323 Num -= CompactionValues[type].size();
Chris Lattner89e02532004-01-18 21:08:15 +0000324 } else {
Reid Spencer060d25d2004-06-29 23:29:38 +0000325 // By default, the global type id is the type id passed in
Chris Lattner52f86d62004-01-20 00:54:06 +0000326 unsigned GlobalTyID = type;
Reid Spencer060d25d2004-06-29 23:29:38 +0000327
Chris Lattner45b5dd22004-08-03 23:41:28 +0000328 // If the type plane was compactified, figure out the global type ID by
329 // adding the derived type ids and the distance.
330 if (!CompactionTypes.empty() && type >= Type::FirstDerivedTyID)
331 GlobalTyID = CompactionTypes[type-Type::FirstDerivedTyID].second;
Chris Lattner00950542001-06-06 20:29:01 +0000332
Reid Spencer060d25d2004-06-29 23:29:38 +0000333 if (hasImplicitNull(GlobalTyID)) {
Chris Lattneraba5ff52005-05-05 20:57:00 +0000334 const Type *Ty = getType(type);
335 if (!isa<OpaqueType>(Ty)) {
336 if (Num == 0)
337 return Constant::getNullValue(Ty);
338 --Num;
339 }
Chris Lattner89e02532004-01-18 21:08:15 +0000340 }
341
Chris Lattner52f86d62004-01-20 00:54:06 +0000342 if (GlobalTyID < ModuleValues.size() && ModuleValues[GlobalTyID]) {
343 if (Num < ModuleValues[GlobalTyID]->size())
Reid Spencer04cde2c2004-07-04 11:33:49 +0000344 return ModuleValues[GlobalTyID]->getOperand(Num);
Chris Lattner52f86d62004-01-20 00:54:06 +0000345 Num -= ModuleValues[GlobalTyID]->size();
Chris Lattner89e02532004-01-18 21:08:15 +0000346 }
Chris Lattner52e20b02003-03-19 20:54:26 +0000347 }
348
Misha Brukman8a96c532005-04-21 21:44:41 +0000349 if (FunctionValues.size() > type &&
350 FunctionValues[type] &&
Reid Spencer060d25d2004-06-29 23:29:38 +0000351 Num < FunctionValues[type]->size())
352 return FunctionValues[type]->getOperand(Num);
Chris Lattner00950542001-06-06 20:29:01 +0000353
Chris Lattner74734132002-08-17 22:01:27 +0000354 if (!Create) return 0; // Do not create a placeholder?
Chris Lattner00950542001-06-06 20:29:01 +0000355
Reid Spencer551ccae2004-09-01 22:55:40 +0000356 // Did we already create a place holder?
Chris Lattner8eb10ce2003-10-09 06:05:40 +0000357 std::pair<unsigned,unsigned> KeyValue(type, oNum);
Reid Spencer060d25d2004-06-29 23:29:38 +0000358 ForwardReferenceMap::iterator I = ForwardReferences.lower_bound(KeyValue);
Chris Lattner8eb10ce2003-10-09 06:05:40 +0000359 if (I != ForwardReferences.end() && I->first == KeyValue)
360 return I->second; // We have already created this placeholder
361
Reid Spencer551ccae2004-09-01 22:55:40 +0000362 // If the type exists (it should)
363 if (const Type* Ty = getType(type)) {
364 // Create the place holder
365 Value *Val = new Argument(Ty);
366 ForwardReferences.insert(I, std::make_pair(KeyValue, Val));
367 return Val;
368 }
Reid Spencer233fe722006-08-22 16:09:19 +0000369 error("Can't create placeholder for value of type slot #" + utostr(type));
370 return 0; // just silence warning, error calls longjmp
Chris Lattner00950542001-06-06 20:29:01 +0000371}
372
Misha Brukman8a96c532005-04-21 21:44:41 +0000373/// This is just like getValue, but when a compaction table is in use, it
374/// is ignored. Also, no forward references or other fancy features are
Reid Spencer04cde2c2004-07-04 11:33:49 +0000375/// supported.
Chris Lattner2c6c14d2004-08-04 00:19:23 +0000376Value* BytecodeReader::getGlobalTableValue(unsigned TyID, unsigned SlotNo) {
377 if (SlotNo == 0)
378 return Constant::getNullValue(getType(TyID));
379
380 if (!CompactionTypes.empty() && TyID >= Type::FirstDerivedTyID) {
381 TyID -= Type::FirstDerivedTyID;
382 if (TyID >= CompactionTypes.size())
383 error("Type ID out of range for compaction table!");
384 TyID = CompactionTypes[TyID].second;
Reid Spencer060d25d2004-06-29 23:29:38 +0000385 }
386
Chris Lattner2c6c14d2004-08-04 00:19:23 +0000387 --SlotNo;
388
Reid Spencer060d25d2004-06-29 23:29:38 +0000389 if (TyID >= ModuleValues.size() || ModuleValues[TyID] == 0 ||
390 SlotNo >= ModuleValues[TyID]->size()) {
Chris Lattner2c6c14d2004-08-04 00:19:23 +0000391 if (TyID >= ModuleValues.size() || ModuleValues[TyID] == 0)
392 error("Corrupt compaction table entry!"
Misha Brukman8a96c532005-04-21 21:44:41 +0000393 + utostr(TyID) + ", " + utostr(SlotNo) + ": "
Chris Lattner2c6c14d2004-08-04 00:19:23 +0000394 + utostr(ModuleValues.size()));
Misha Brukman8a96c532005-04-21 21:44:41 +0000395 else
Chris Lattner2c6c14d2004-08-04 00:19:23 +0000396 error("Corrupt compaction table entry!"
Misha Brukman8a96c532005-04-21 21:44:41 +0000397 + utostr(TyID) + ", " + utostr(SlotNo) + ": "
Chris Lattner2c6c14d2004-08-04 00:19:23 +0000398 + utostr(ModuleValues.size()) + ", "
Reid Spencer9a7e0c52004-08-04 22:56:46 +0000399 + utohexstr(reinterpret_cast<uint64_t>(((void*)ModuleValues[TyID])))
400 + ", "
Chris Lattner2c6c14d2004-08-04 00:19:23 +0000401 + utostr(ModuleValues[TyID]->size()));
Reid Spencer060d25d2004-06-29 23:29:38 +0000402 }
403 return ModuleValues[TyID]->getOperand(SlotNo);
404}
405
Reid Spencer04cde2c2004-07-04 11:33:49 +0000406/// Just like getValue, except that it returns a null pointer
407/// only on error. It always returns a constant (meaning that if the value is
408/// defined, but is not a constant, that is an error). If the specified
Misha Brukman8a96c532005-04-21 21:44:41 +0000409/// constant hasn't been parsed yet, a placeholder is defined and used.
Reid Spencer04cde2c2004-07-04 11:33:49 +0000410/// Later, after the real value is parsed, the placeholder is eliminated.
Reid Spencer060d25d2004-06-29 23:29:38 +0000411Constant* BytecodeReader::getConstantValue(unsigned TypeSlot, unsigned Slot) {
412 if (Value *V = getValue(TypeSlot, Slot, false))
413 if (Constant *C = dyn_cast<Constant>(V))
414 return C; // If we already have the value parsed, just return it
Reid Spencer060d25d2004-06-29 23:29:38 +0000415 else
Misha Brukman8a96c532005-04-21 21:44:41 +0000416 error("Value for slot " + utostr(Slot) +
Reid Spencera86037e2004-07-18 00:12:03 +0000417 " is expected to be a constant!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000418
Chris Lattner389bd042004-12-09 06:19:44 +0000419 std::pair<unsigned, unsigned> Key(TypeSlot, Slot);
Reid Spencer060d25d2004-06-29 23:29:38 +0000420 ConstantRefsType::iterator I = ConstantFwdRefs.lower_bound(Key);
421
422 if (I != ConstantFwdRefs.end() && I->first == Key) {
423 return I->second;
424 } else {
425 // Create a placeholder for the constant reference and
426 // keep track of the fact that we have a forward ref to recycle it
Chris Lattner389bd042004-12-09 06:19:44 +0000427 Constant *C = new ConstantPlaceHolder(getType(TypeSlot));
Misha Brukman8a96c532005-04-21 21:44:41 +0000428
Reid Spencer060d25d2004-06-29 23:29:38 +0000429 // Keep track of the fact that we have a forward ref to recycle it
430 ConstantFwdRefs.insert(I, std::make_pair(Key, C));
431 return C;
432 }
433}
434
435//===----------------------------------------------------------------------===//
436// IR Construction Methods
437//===----------------------------------------------------------------------===//
438
Reid Spencer04cde2c2004-07-04 11:33:49 +0000439/// As values are created, they are inserted into the appropriate place
440/// with this method. The ValueTable argument must be one of ModuleValues
441/// or FunctionValues data members of this class.
Misha Brukman8a96c532005-04-21 21:44:41 +0000442unsigned BytecodeReader::insertValue(Value *Val, unsigned type,
Reid Spencer46b002c2004-07-11 17:28:43 +0000443 ValueTable &ValueTab) {
Reid Spencer060d25d2004-06-29 23:29:38 +0000444 if (ValueTab.size() <= type)
445 ValueTab.resize(type+1);
446
447 if (!ValueTab[type]) ValueTab[type] = new ValueList();
448
449 ValueTab[type]->push_back(Val);
450
Chris Lattneraba5ff52005-05-05 20:57:00 +0000451 bool HasOffset = hasImplicitNull(type) && !isa<OpaqueType>(Val->getType());
Reid Spencer060d25d2004-06-29 23:29:38 +0000452 return ValueTab[type]->size()-1 + HasOffset;
453}
454
Reid Spencer04cde2c2004-07-04 11:33:49 +0000455/// Insert the arguments of a function as new values in the reader.
Reid Spencer46b002c2004-07-11 17:28:43 +0000456void BytecodeReader::insertArguments(Function* F) {
Reid Spencer060d25d2004-06-29 23:29:38 +0000457 const FunctionType *FT = F->getFunctionType();
Chris Lattnere4d5c442005-03-15 04:54:21 +0000458 Function::arg_iterator AI = F->arg_begin();
Reid Spencer060d25d2004-06-29 23:29:38 +0000459 for (FunctionType::param_iterator It = FT->param_begin();
460 It != FT->param_end(); ++It, ++AI)
461 insertValue(AI, getTypeSlot(AI->getType()), FunctionValues);
462}
463
464//===----------------------------------------------------------------------===//
465// Bytecode Parsing Methods
466//===----------------------------------------------------------------------===//
467
Reid Spencer04cde2c2004-07-04 11:33:49 +0000468/// This method parses a single instruction. The instruction is
469/// inserted at the end of the \p BB provided. The arguments of
Misha Brukman44666b12004-09-28 16:57:46 +0000470/// the instruction are provided in the \p Oprnds vector.
Reid Spencer060d25d2004-06-29 23:29:38 +0000471void BytecodeReader::ParseInstruction(std::vector<unsigned> &Oprnds,
Reid Spencer46b002c2004-07-11 17:28:43 +0000472 BasicBlock* BB) {
Reid Spencer060d25d2004-06-29 23:29:38 +0000473 BufPtr SaveAt = At;
474
475 // Clear instruction data
476 Oprnds.clear();
477 unsigned iType = 0;
478 unsigned Opcode = 0;
479 unsigned Op = read_uint();
480
481 // bits Instruction format: Common to all formats
482 // --------------------------
483 // 01-00: Opcode type, fixed to 1.
484 // 07-02: Opcode
485 Opcode = (Op >> 2) & 63;
486 Oprnds.resize((Op >> 0) & 03);
487
488 // Extract the operands
489 switch (Oprnds.size()) {
490 case 1:
491 // bits Instruction format:
492 // --------------------------
493 // 19-08: Resulting type plane
494 // 31-20: Operand #1 (if set to (2^12-1), then zero operands)
495 //
496 iType = (Op >> 8) & 4095;
497 Oprnds[0] = (Op >> 20) & 4095;
498 if (Oprnds[0] == 4095) // Handle special encoding for 0 operands...
499 Oprnds.resize(0);
500 break;
501 case 2:
502 // bits Instruction format:
503 // --------------------------
504 // 15-08: Resulting type plane
505 // 23-16: Operand #1
Misha Brukman8a96c532005-04-21 21:44:41 +0000506 // 31-24: Operand #2
Reid Spencer060d25d2004-06-29 23:29:38 +0000507 //
508 iType = (Op >> 8) & 255;
509 Oprnds[0] = (Op >> 16) & 255;
510 Oprnds[1] = (Op >> 24) & 255;
511 break;
512 case 3:
513 // bits Instruction format:
514 // --------------------------
515 // 13-08: Resulting type plane
516 // 19-14: Operand #1
517 // 25-20: Operand #2
518 // 31-26: Operand #3
519 //
520 iType = (Op >> 8) & 63;
521 Oprnds[0] = (Op >> 14) & 63;
522 Oprnds[1] = (Op >> 20) & 63;
523 Oprnds[2] = (Op >> 26) & 63;
524 break;
525 case 0:
526 At -= 4; // Hrm, try this again...
527 Opcode = read_vbr_uint();
528 Opcode >>= 2;
529 iType = read_vbr_uint();
530
531 unsigned NumOprnds = read_vbr_uint();
532 Oprnds.resize(NumOprnds);
533
534 if (NumOprnds == 0)
Reid Spencer24399722004-07-09 22:21:33 +0000535 error("Zero-argument instruction found; this is invalid.");
Reid Spencer060d25d2004-06-29 23:29:38 +0000536
537 for (unsigned i = 0; i != NumOprnds; ++i)
538 Oprnds[i] = read_vbr_uint();
Reid Spencer060d25d2004-06-29 23:29:38 +0000539 break;
540 }
541
Reid Spencerd798a512006-11-14 04:47:22 +0000542 const Type *InstTy = getType(iType);
Reid Spencer060d25d2004-06-29 23:29:38 +0000543
Reid Spencer1628cec2006-10-26 06:15:43 +0000544 // Make the necessary adjustments for dealing with backwards compatibility
545 // of opcodes.
Reid Spencer3795ad12006-12-03 05:47:10 +0000546 Instruction* Result = 0;
Reid Spencer1628cec2006-10-26 06:15:43 +0000547
Reid Spencer46b002c2004-07-11 17:28:43 +0000548 // We have enough info to inform the handler now.
Reid Spencer1628cec2006-10-26 06:15:43 +0000549 if (Handler)
550 Handler->handleInstruction(Opcode, InstTy, Oprnds, At-SaveAt);
Reid Spencer060d25d2004-06-29 23:29:38 +0000551
Reid Spencer3795ad12006-12-03 05:47:10 +0000552 // First, handle the easy binary operators case
553 if (Opcode >= Instruction::BinaryOpsBegin &&
Reid Spencerc8dab492006-12-03 06:28:54 +0000554 Opcode < Instruction::BinaryOpsEnd && Oprnds.size() == 2) {
Reid Spencer3795ad12006-12-03 05:47:10 +0000555 Result = BinaryOperator::create(Instruction::BinaryOps(Opcode),
556 getValue(iType, Oprnds[0]),
557 getValue(iType, Oprnds[1]));
Reid Spencerc8dab492006-12-03 06:28:54 +0000558 } else {
Reid Spencer1628cec2006-10-26 06:15:43 +0000559 // Indicate that we don't think this is a call instruction (yet).
560 // Process based on the Opcode read
561 switch (Opcode) {
562 default: // There was an error, this shouldn't happen.
563 if (Result == 0)
564 error("Illegal instruction read!");
565 break;
566 case Instruction::VAArg:
567 if (Oprnds.size() != 2)
568 error("Invalid VAArg instruction!");
569 Result = new VAArgInst(getValue(iType, Oprnds[0]),
Reid Spencerd798a512006-11-14 04:47:22 +0000570 getType(Oprnds[1]));
Reid Spencer1628cec2006-10-26 06:15:43 +0000571 break;
572 case Instruction::ExtractElement: {
573 if (Oprnds.size() != 2)
574 error("Invalid extractelement instruction!");
575 Value *V1 = getValue(iType, Oprnds[0]);
Reid Spencer88cfda22006-12-31 05:44:24 +0000576 Value *V2 = getValue(Type::Int32TyID, Oprnds[1]);
Chris Lattner59fecec2006-04-08 04:09:19 +0000577
Reid Spencer1628cec2006-10-26 06:15:43 +0000578 if (!ExtractElementInst::isValidOperands(V1, V2))
579 error("Invalid extractelement instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000580
Reid Spencer1628cec2006-10-26 06:15:43 +0000581 Result = new ExtractElementInst(V1, V2);
582 break;
Chris Lattnera65371e2006-05-26 18:42:34 +0000583 }
Reid Spencer1628cec2006-10-26 06:15:43 +0000584 case Instruction::InsertElement: {
585 const PackedType *PackedTy = dyn_cast<PackedType>(InstTy);
586 if (!PackedTy || Oprnds.size() != 3)
587 error("Invalid insertelement instruction!");
588
589 Value *V1 = getValue(iType, Oprnds[0]);
590 Value *V2 = getValue(getTypeSlot(PackedTy->getElementType()),Oprnds[1]);
Reid Spencer88cfda22006-12-31 05:44:24 +0000591 Value *V3 = getValue(Type::Int32TyID, Oprnds[2]);
Reid Spencer1628cec2006-10-26 06:15:43 +0000592
593 if (!InsertElementInst::isValidOperands(V1, V2, V3))
594 error("Invalid insertelement instruction!");
595 Result = new InsertElementInst(V1, V2, V3);
596 break;
597 }
598 case Instruction::ShuffleVector: {
599 const PackedType *PackedTy = dyn_cast<PackedType>(InstTy);
600 if (!PackedTy || Oprnds.size() != 3)
601 error("Invalid shufflevector instruction!");
602 Value *V1 = getValue(iType, Oprnds[0]);
603 Value *V2 = getValue(iType, Oprnds[1]);
604 const PackedType *EltTy =
Reid Spencer88cfda22006-12-31 05:44:24 +0000605 PackedType::get(Type::Int32Ty, PackedTy->getNumElements());
Reid Spencer1628cec2006-10-26 06:15:43 +0000606 Value *V3 = getValue(getTypeSlot(EltTy), Oprnds[2]);
607 if (!ShuffleVectorInst::isValidOperands(V1, V2, V3))
608 error("Invalid shufflevector instruction!");
609 Result = new ShuffleVectorInst(V1, V2, V3);
610 break;
611 }
Reid Spencer3da59db2006-11-27 01:05:10 +0000612 case Instruction::Trunc:
613 if (Oprnds.size() != 2)
614 error("Invalid cast instruction!");
615 Result = new TruncInst(getValue(iType, Oprnds[0]),
616 getType(Oprnds[1]));
617 break;
618 case Instruction::ZExt:
619 if (Oprnds.size() != 2)
620 error("Invalid cast instruction!");
621 Result = new ZExtInst(getValue(iType, Oprnds[0]),
622 getType(Oprnds[1]));
623 break;
624 case Instruction::SExt:
Reid Spencer1628cec2006-10-26 06:15:43 +0000625 if (Oprnds.size() != 2)
626 error("Invalid Cast instruction!");
Reid Spencer3da59db2006-11-27 01:05:10 +0000627 Result = new SExtInst(getValue(iType, Oprnds[0]),
Reid Spencerd798a512006-11-14 04:47:22 +0000628 getType(Oprnds[1]));
Reid Spencer1628cec2006-10-26 06:15:43 +0000629 break;
Reid Spencer3da59db2006-11-27 01:05:10 +0000630 case Instruction::FPTrunc:
631 if (Oprnds.size() != 2)
632 error("Invalid cast instruction!");
633 Result = new FPTruncInst(getValue(iType, Oprnds[0]),
634 getType(Oprnds[1]));
635 break;
636 case Instruction::FPExt:
637 if (Oprnds.size() != 2)
638 error("Invalid cast instruction!");
639 Result = new FPExtInst(getValue(iType, Oprnds[0]),
640 getType(Oprnds[1]));
641 break;
642 case Instruction::UIToFP:
643 if (Oprnds.size() != 2)
644 error("Invalid cast instruction!");
645 Result = new UIToFPInst(getValue(iType, Oprnds[0]),
646 getType(Oprnds[1]));
647 break;
648 case Instruction::SIToFP:
649 if (Oprnds.size() != 2)
650 error("Invalid cast instruction!");
651 Result = new SIToFPInst(getValue(iType, Oprnds[0]),
652 getType(Oprnds[1]));
653 break;
654 case Instruction::FPToUI:
655 if (Oprnds.size() != 2)
656 error("Invalid cast instruction!");
657 Result = new FPToUIInst(getValue(iType, Oprnds[0]),
658 getType(Oprnds[1]));
659 break;
660 case Instruction::FPToSI:
661 if (Oprnds.size() != 2)
662 error("Invalid cast instruction!");
663 Result = new FPToSIInst(getValue(iType, Oprnds[0]),
664 getType(Oprnds[1]));
665 break;
666 case Instruction::IntToPtr:
667 if (Oprnds.size() != 2)
668 error("Invalid cast instruction!");
669 Result = new IntToPtrInst(getValue(iType, Oprnds[0]),
670 getType(Oprnds[1]));
671 break;
672 case Instruction::PtrToInt:
673 if (Oprnds.size() != 2)
674 error("Invalid cast instruction!");
675 Result = new PtrToIntInst(getValue(iType, Oprnds[0]),
676 getType(Oprnds[1]));
677 break;
678 case Instruction::BitCast:
679 if (Oprnds.size() != 2)
680 error("Invalid cast instruction!");
681 Result = new BitCastInst(getValue(iType, Oprnds[0]),
682 getType(Oprnds[1]));
683 break;
Reid Spencer1628cec2006-10-26 06:15:43 +0000684 case Instruction::Select:
685 if (Oprnds.size() != 3)
686 error("Invalid Select instruction!");
687 Result = new SelectInst(getValue(Type::BoolTyID, Oprnds[0]),
688 getValue(iType, Oprnds[1]),
689 getValue(iType, Oprnds[2]));
690 break;
691 case Instruction::PHI: {
692 if (Oprnds.size() == 0 || (Oprnds.size() & 1))
693 error("Invalid phi node encountered!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000694
Reid Spencer1628cec2006-10-26 06:15:43 +0000695 PHINode *PN = new PHINode(InstTy);
696 PN->reserveOperandSpace(Oprnds.size());
697 for (unsigned i = 0, e = Oprnds.size(); i != e; i += 2)
698 PN->addIncoming(
699 getValue(iType, Oprnds[i]), getBasicBlock(Oprnds[i+1]));
700 Result = PN;
701 break;
702 }
Reid Spencerc8dab492006-12-03 06:28:54 +0000703 case Instruction::ICmp:
704 case Instruction::FCmp:
Reid Spencer9f132762006-12-03 17:17:02 +0000705 if (Oprnds.size() != 3)
706 error("Cmp instructions requires 3 operands");
Reid Spencerc8dab492006-12-03 06:28:54 +0000707 // These instructions encode the comparison predicate as the 3rd operand.
708 Result = CmpInst::create(Instruction::OtherOps(Opcode),
709 static_cast<unsigned short>(Oprnds[2]),
710 getValue(iType, Oprnds[0]), getValue(iType, Oprnds[1]));
711 break;
Reid Spencer1628cec2006-10-26 06:15:43 +0000712 case Instruction::Shl:
Reid Spencer3822ff52006-11-08 06:47:33 +0000713 case Instruction::LShr:
714 case Instruction::AShr:
Reid Spencer1628cec2006-10-26 06:15:43 +0000715 Result = new ShiftInst(Instruction::OtherOps(Opcode),
716 getValue(iType, Oprnds[0]),
Reid Spencer88cfda22006-12-31 05:44:24 +0000717 getValue(Type::Int8TyID, Oprnds[1]));
Reid Spencer1628cec2006-10-26 06:15:43 +0000718 break;
719 case Instruction::Ret:
720 if (Oprnds.size() == 0)
721 Result = new ReturnInst();
722 else if (Oprnds.size() == 1)
723 Result = new ReturnInst(getValue(iType, Oprnds[0]));
724 else
725 error("Unrecognized instruction!");
726 break;
727
728 case Instruction::Br:
729 if (Oprnds.size() == 1)
730 Result = new BranchInst(getBasicBlock(Oprnds[0]));
731 else if (Oprnds.size() == 3)
732 Result = new BranchInst(getBasicBlock(Oprnds[0]),
733 getBasicBlock(Oprnds[1]), getValue(Type::BoolTyID , Oprnds[2]));
734 else
735 error("Invalid number of operands for a 'br' instruction!");
736 break;
737 case Instruction::Switch: {
738 if (Oprnds.size() & 1)
739 error("Switch statement with odd number of arguments!");
740
741 SwitchInst *I = new SwitchInst(getValue(iType, Oprnds[0]),
742 getBasicBlock(Oprnds[1]),
743 Oprnds.size()/2-1);
744 for (unsigned i = 2, e = Oprnds.size(); i != e; i += 2)
745 I->addCase(cast<ConstantInt>(getValue(iType, Oprnds[i])),
746 getBasicBlock(Oprnds[i+1]));
747 Result = I;
748 break;
749 }
750 case 58: // Call with extra operand for calling conv
751 case 59: // tail call, Fast CC
752 case 60: // normal call, Fast CC
753 case 61: // tail call, C Calling Conv
754 case Instruction::Call: { // Normal Call, C Calling Convention
755 if (Oprnds.size() == 0)
756 error("Invalid call instruction encountered!");
Reid Spencer1628cec2006-10-26 06:15:43 +0000757 Value *F = getValue(iType, Oprnds[0]);
758
759 unsigned CallingConv = CallingConv::C;
760 bool isTailCall = false;
761
762 if (Opcode == 61 || Opcode == 59)
763 isTailCall = true;
764
765 if (Opcode == 58) {
766 isTailCall = Oprnds.back() & 1;
767 CallingConv = Oprnds.back() >> 1;
768 Oprnds.pop_back();
769 } else if (Opcode == 59 || Opcode == 60) {
770 CallingConv = CallingConv::Fast;
771 }
772
773 // Check to make sure we have a pointer to function type
774 const PointerType *PTy = dyn_cast<PointerType>(F->getType());
775 if (PTy == 0) error("Call to non function pointer value!");
776 const FunctionType *FTy = dyn_cast<FunctionType>(PTy->getElementType());
777 if (FTy == 0) error("Call to non function pointer value!");
778
779 std::vector<Value *> Params;
780 if (!FTy->isVarArg()) {
781 FunctionType::param_iterator It = FTy->param_begin();
782
783 for (unsigned i = 1, e = Oprnds.size(); i != e; ++i) {
784 if (It == FTy->param_end())
785 error("Invalid call instruction!");
786 Params.push_back(getValue(getTypeSlot(*It++), Oprnds[i]));
787 }
788 if (It != FTy->param_end())
Reid Spencer24399722004-07-09 22:21:33 +0000789 error("Invalid call instruction!");
Reid Spencer1628cec2006-10-26 06:15:43 +0000790 } else {
791 Oprnds.erase(Oprnds.begin(), Oprnds.begin()+1);
792
793 unsigned FirstVariableOperand;
794 if (Oprnds.size() < FTy->getNumParams())
795 error("Call instruction missing operands!");
796
797 // Read all of the fixed arguments
798 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
799 Params.push_back(
800 getValue(getTypeSlot(FTy->getParamType(i)),Oprnds[i]));
801
802 FirstVariableOperand = FTy->getNumParams();
803
804 if ((Oprnds.size()-FirstVariableOperand) & 1)
805 error("Invalid call instruction!"); // Must be pairs of type/value
806
807 for (unsigned i = FirstVariableOperand, e = Oprnds.size();
808 i != e; i += 2)
809 Params.push_back(getValue(Oprnds[i], Oprnds[i+1]));
Reid Spencer060d25d2004-06-29 23:29:38 +0000810 }
Reid Spencer060d25d2004-06-29 23:29:38 +0000811
Reid Spencer1628cec2006-10-26 06:15:43 +0000812 Result = new CallInst(F, Params);
813 if (isTailCall) cast<CallInst>(Result)->setTailCall();
814 if (CallingConv) cast<CallInst>(Result)->setCallingConv(CallingConv);
815 break;
Reid Spencer060d25d2004-06-29 23:29:38 +0000816 }
Reid Spencer1628cec2006-10-26 06:15:43 +0000817 case Instruction::Invoke: { // Invoke C CC
818 if (Oprnds.size() < 3)
819 error("Invalid invoke instruction!");
820 Value *F = getValue(iType, Oprnds[0]);
Reid Spencer060d25d2004-06-29 23:29:38 +0000821
Reid Spencer1628cec2006-10-26 06:15:43 +0000822 // Check to make sure we have a pointer to function type
823 const PointerType *PTy = dyn_cast<PointerType>(F->getType());
824 if (PTy == 0)
825 error("Invoke to non function pointer value!");
826 const FunctionType *FTy = dyn_cast<FunctionType>(PTy->getElementType());
827 if (FTy == 0)
828 error("Invoke to non function pointer value!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000829
Reid Spencer1628cec2006-10-26 06:15:43 +0000830 std::vector<Value *> Params;
831 BasicBlock *Normal, *Except;
Reid Spencer3da59db2006-11-27 01:05:10 +0000832 unsigned CallingConv = Oprnds.back();
833 Oprnds.pop_back();
Chris Lattnerdee199f2005-05-06 22:34:01 +0000834
Reid Spencer1628cec2006-10-26 06:15:43 +0000835 if (!FTy->isVarArg()) {
836 Normal = getBasicBlock(Oprnds[1]);
837 Except = getBasicBlock(Oprnds[2]);
Reid Spencer060d25d2004-06-29 23:29:38 +0000838
Reid Spencer1628cec2006-10-26 06:15:43 +0000839 FunctionType::param_iterator It = FTy->param_begin();
840 for (unsigned i = 3, e = Oprnds.size(); i != e; ++i) {
841 if (It == FTy->param_end())
842 error("Invalid invoke instruction!");
843 Params.push_back(getValue(getTypeSlot(*It++), Oprnds[i]));
844 }
845 if (It != FTy->param_end())
Reid Spencer24399722004-07-09 22:21:33 +0000846 error("Invalid invoke instruction!");
Reid Spencer1628cec2006-10-26 06:15:43 +0000847 } else {
848 Oprnds.erase(Oprnds.begin(), Oprnds.begin()+1);
849
850 Normal = getBasicBlock(Oprnds[0]);
851 Except = getBasicBlock(Oprnds[1]);
852
853 unsigned FirstVariableArgument = FTy->getNumParams()+2;
854 for (unsigned i = 2; i != FirstVariableArgument; ++i)
855 Params.push_back(getValue(getTypeSlot(FTy->getParamType(i-2)),
856 Oprnds[i]));
857
858 // Must be type/value pairs. If not, error out.
859 if (Oprnds.size()-FirstVariableArgument & 1)
860 error("Invalid invoke instruction!");
861
862 for (unsigned i = FirstVariableArgument; i < Oprnds.size(); i += 2)
863 Params.push_back(getValue(Oprnds[i], Oprnds[i+1]));
Reid Spencer060d25d2004-06-29 23:29:38 +0000864 }
Reid Spencer060d25d2004-06-29 23:29:38 +0000865
Reid Spencer1628cec2006-10-26 06:15:43 +0000866 Result = new InvokeInst(F, Normal, Except, Params);
867 if (CallingConv) cast<InvokeInst>(Result)->setCallingConv(CallingConv);
868 break;
Reid Spencer060d25d2004-06-29 23:29:38 +0000869 }
Reid Spencer1628cec2006-10-26 06:15:43 +0000870 case Instruction::Malloc: {
871 unsigned Align = 0;
872 if (Oprnds.size() == 2)
873 Align = (1 << Oprnds[1]) >> 1;
874 else if (Oprnds.size() > 2)
875 error("Invalid malloc instruction!");
876 if (!isa<PointerType>(InstTy))
877 error("Invalid malloc instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000878
Reid Spencer1628cec2006-10-26 06:15:43 +0000879 Result = new MallocInst(cast<PointerType>(InstTy)->getElementType(),
Reid Spencer88cfda22006-12-31 05:44:24 +0000880 getValue(Type::Int32TyID, Oprnds[0]), Align);
Reid Spencer1628cec2006-10-26 06:15:43 +0000881 break;
882 }
883 case Instruction::Alloca: {
884 unsigned Align = 0;
885 if (Oprnds.size() == 2)
886 Align = (1 << Oprnds[1]) >> 1;
887 else if (Oprnds.size() > 2)
888 error("Invalid alloca instruction!");
889 if (!isa<PointerType>(InstTy))
890 error("Invalid alloca instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000891
Reid Spencer1628cec2006-10-26 06:15:43 +0000892 Result = new AllocaInst(cast<PointerType>(InstTy)->getElementType(),
Reid Spencer88cfda22006-12-31 05:44:24 +0000893 getValue(Type::Int32TyID, Oprnds[0]), Align);
Reid Spencer1628cec2006-10-26 06:15:43 +0000894 break;
895 }
896 case Instruction::Free:
897 if (!isa<PointerType>(InstTy))
898 error("Invalid free instruction!");
899 Result = new FreeInst(getValue(iType, Oprnds[0]));
900 break;
901 case Instruction::GetElementPtr: {
902 if (Oprnds.size() == 0 || !isa<PointerType>(InstTy))
Misha Brukman8a96c532005-04-21 21:44:41 +0000903 error("Invalid getelementptr instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000904
Reid Spencer1628cec2006-10-26 06:15:43 +0000905 std::vector<Value*> Idx;
906
907 const Type *NextTy = InstTy;
908 for (unsigned i = 1, e = Oprnds.size(); i != e; ++i) {
909 const CompositeType *TopTy = dyn_cast_or_null<CompositeType>(NextTy);
910 if (!TopTy)
911 error("Invalid getelementptr instruction!");
912
913 unsigned ValIdx = Oprnds[i];
914 unsigned IdxTy = 0;
Reid Spencerd798a512006-11-14 04:47:22 +0000915 // Struct indices are always uints, sequential type indices can be
916 // any of the 32 or 64-bit integer types. The actual choice of
Reid Spencer88cfda22006-12-31 05:44:24 +0000917 // type is encoded in the low bit of the slot number.
Reid Spencerd798a512006-11-14 04:47:22 +0000918 if (isa<StructType>(TopTy))
Reid Spencer88cfda22006-12-31 05:44:24 +0000919 IdxTy = Type::Int32TyID;
Reid Spencerd798a512006-11-14 04:47:22 +0000920 else {
Reid Spencer88cfda22006-12-31 05:44:24 +0000921 switch (ValIdx & 1) {
Reid Spencerd798a512006-11-14 04:47:22 +0000922 default:
Reid Spencer88cfda22006-12-31 05:44:24 +0000923 case 0: IdxTy = Type::Int32TyID; break;
924 case 1: IdxTy = Type::Int64TyID; break;
Reid Spencer060d25d2004-06-29 23:29:38 +0000925 }
Reid Spencer88cfda22006-12-31 05:44:24 +0000926 ValIdx >>= 1;
Reid Spencer060d25d2004-06-29 23:29:38 +0000927 }
Reid Spencer1628cec2006-10-26 06:15:43 +0000928 Idx.push_back(getValue(IdxTy, ValIdx));
Reid Spencer1628cec2006-10-26 06:15:43 +0000929 NextTy = GetElementPtrInst::getIndexedType(InstTy, Idx, true);
Reid Spencer060d25d2004-06-29 23:29:38 +0000930 }
931
Reid Spencer1628cec2006-10-26 06:15:43 +0000932 Result = new GetElementPtrInst(getValue(iType, Oprnds[0]), Idx);
933 break;
Reid Spencer060d25d2004-06-29 23:29:38 +0000934 }
Reid Spencer1628cec2006-10-26 06:15:43 +0000935 case 62: // volatile load
936 case Instruction::Load:
937 if (Oprnds.size() != 1 || !isa<PointerType>(InstTy))
938 error("Invalid load instruction!");
939 Result = new LoadInst(getValue(iType, Oprnds[0]), "", Opcode == 62);
940 break;
941 case 63: // volatile store
942 case Instruction::Store: {
943 if (!isa<PointerType>(InstTy) || Oprnds.size() != 2)
944 error("Invalid store instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000945
Reid Spencer1628cec2006-10-26 06:15:43 +0000946 Value *Ptr = getValue(iType, Oprnds[1]);
947 const Type *ValTy = cast<PointerType>(Ptr->getType())->getElementType();
948 Result = new StoreInst(getValue(getTypeSlot(ValTy), Oprnds[0]), Ptr,
949 Opcode == 63);
950 break;
951 }
952 case Instruction::Unwind:
953 if (Oprnds.size() != 0) error("Invalid unwind instruction!");
954 Result = new UnwindInst();
955 break;
956 case Instruction::Unreachable:
957 if (Oprnds.size() != 0) error("Invalid unreachable instruction!");
958 Result = new UnreachableInst();
959 break;
960 } // end switch(Opcode)
Reid Spencer3795ad12006-12-03 05:47:10 +0000961 } // end if !Result
Reid Spencer060d25d2004-06-29 23:29:38 +0000962
Reid Spencere1e96c02006-01-19 07:02:16 +0000963 BB->getInstList().push_back(Result);
964
Reid Spencer060d25d2004-06-29 23:29:38 +0000965 unsigned TypeSlot;
966 if (Result->getType() == InstTy)
967 TypeSlot = iType;
968 else
969 TypeSlot = getTypeSlot(Result->getType());
970
971 insertValue(Result, TypeSlot, FunctionValues);
Reid Spencer060d25d2004-06-29 23:29:38 +0000972}
973
Reid Spencer04cde2c2004-07-04 11:33:49 +0000974/// Get a particular numbered basic block, which might be a forward reference.
Reid Spencerd798a512006-11-14 04:47:22 +0000975/// This works together with ParseInstructionList to handle these forward
976/// references in a clean manner. This function is used when constructing
977/// phi, br, switch, and other instructions that reference basic blocks.
978/// Blocks are numbered sequentially as they appear in the function.
Reid Spencer060d25d2004-06-29 23:29:38 +0000979BasicBlock *BytecodeReader::getBasicBlock(unsigned ID) {
Chris Lattner4ee8ef22003-10-08 22:52:54 +0000980 // Make sure there is room in the table...
981 if (ParsedBasicBlocks.size() <= ID) ParsedBasicBlocks.resize(ID+1);
982
Reid Spencerd798a512006-11-14 04:47:22 +0000983 // First check to see if this is a backwards reference, i.e. this block
984 // has already been created, or if the forward reference has already
Chris Lattner4ee8ef22003-10-08 22:52:54 +0000985 // been created.
986 if (ParsedBasicBlocks[ID])
987 return ParsedBasicBlocks[ID];
988
989 // Otherwise, the basic block has not yet been created. Do so and add it to
990 // the ParsedBasicBlocks list.
991 return ParsedBasicBlocks[ID] = new BasicBlock();
992}
993
Reid Spencer04cde2c2004-07-04 11:33:49 +0000994/// Parse all of the BasicBlock's & Instruction's in the body of a function.
Misha Brukman8a96c532005-04-21 21:44:41 +0000995/// In post 1.0 bytecode files, we no longer emit basic block individually,
Reid Spencer04cde2c2004-07-04 11:33:49 +0000996/// in order to avoid per-basic-block overhead.
Reid Spencerd798a512006-11-14 04:47:22 +0000997/// @returns the number of basic blocks encountered.
Reid Spencer060d25d2004-06-29 23:29:38 +0000998unsigned BytecodeReader::ParseInstructionList(Function* F) {
Chris Lattner8d1dbd22003-12-01 07:05:31 +0000999 unsigned BlockNo = 0;
1000 std::vector<unsigned> Args;
1001
Reid Spencer46b002c2004-07-11 17:28:43 +00001002 while (moreInBlock()) {
1003 if (Handler) Handler->handleBasicBlockBegin(BlockNo);
Chris Lattner8d1dbd22003-12-01 07:05:31 +00001004 BasicBlock *BB;
1005 if (ParsedBasicBlocks.size() == BlockNo)
1006 ParsedBasicBlocks.push_back(BB = new BasicBlock());
1007 else if (ParsedBasicBlocks[BlockNo] == 0)
1008 BB = ParsedBasicBlocks[BlockNo] = new BasicBlock();
1009 else
1010 BB = ParsedBasicBlocks[BlockNo];
1011 ++BlockNo;
1012 F->getBasicBlockList().push_back(BB);
1013
1014 // Read instructions into this basic block until we get to a terminator
Reid Spencer46b002c2004-07-11 17:28:43 +00001015 while (moreInBlock() && !BB->getTerminator())
Reid Spencer060d25d2004-06-29 23:29:38 +00001016 ParseInstruction(Args, BB);
Chris Lattner8d1dbd22003-12-01 07:05:31 +00001017
1018 if (!BB->getTerminator())
Reid Spencer24399722004-07-09 22:21:33 +00001019 error("Non-terminated basic block found!");
Reid Spencer5c15fe52004-07-05 00:57:50 +00001020
Reid Spencer46b002c2004-07-11 17:28:43 +00001021 if (Handler) Handler->handleBasicBlockEnd(BlockNo-1);
Chris Lattner8d1dbd22003-12-01 07:05:31 +00001022 }
1023
1024 return BlockNo;
1025}
1026
Reid Spencer78d033e2007-01-06 07:24:44 +00001027/// Parse a type symbol table.
1028void BytecodeReader::ParseTypeSymbolTable(TypeSymbolTable *TST) {
1029 // Type Symtab block header: [num entries]
1030 unsigned NumEntries = read_vbr_uint();
1031 for (unsigned i = 0; i < NumEntries; ++i) {
1032 // Symtab entry: [type slot #][name]
1033 unsigned slot = read_vbr_uint();
1034 std::string Name = read_str();
1035 const Type* T = getType(slot);
1036 TST->insert(Name, T);
1037 }
1038}
1039
1040/// Parse a value symbol table. This works for both module level and function
Reid Spencer04cde2c2004-07-04 11:33:49 +00001041/// level symbol tables. For function level symbol tables, the CurrentFunction
1042/// parameter must be non-zero and the ST parameter must correspond to
1043/// CurrentFunction's symbol table. For Module level symbol tables, the
1044/// CurrentFunction argument must be zero.
Reid Spencer78d033e2007-01-06 07:24:44 +00001045void BytecodeReader::ParseValueSymbolTable(Function *CurrentFunction,
1046 SymbolTable *ST) {
1047
Reid Spencer04cde2c2004-07-04 11:33:49 +00001048 if (Handler) Handler->handleSymbolTableBegin(CurrentFunction,ST);
Reid Spencer060d25d2004-06-29 23:29:38 +00001049
Chris Lattner39cacce2003-10-10 05:43:47 +00001050 // Allow efficient basic block lookup by number.
1051 std::vector<BasicBlock*> BBMap;
1052 if (CurrentFunction)
1053 for (Function::iterator I = CurrentFunction->begin(),
1054 E = CurrentFunction->end(); I != E; ++I)
1055 BBMap.push_back(I);
1056
Reid Spencer46b002c2004-07-11 17:28:43 +00001057 while (moreInBlock()) {
Chris Lattner00950542001-06-06 20:29:01 +00001058 // Symtab block header: [num entries][type id number]
Reid Spencer060d25d2004-06-29 23:29:38 +00001059 unsigned NumEntries = read_vbr_uint();
Reid Spencerd798a512006-11-14 04:47:22 +00001060 unsigned Typ = read_vbr_uint();
Chris Lattner1d670cc2001-09-07 16:37:43 +00001061
Chris Lattner7dc3a2e2003-10-13 14:57:53 +00001062 for (unsigned i = 0; i != NumEntries; ++i) {
Chris Lattner00950542001-06-06 20:29:01 +00001063 // Symtab entry: [def slot #][name]
Reid Spencer060d25d2004-06-29 23:29:38 +00001064 unsigned slot = read_vbr_uint();
1065 std::string Name = read_str();
Reid Spencerd798a512006-11-14 04:47:22 +00001066 Value *V = 0;
1067 if (Typ == Type::LabelTyID) {
1068 if (slot < BBMap.size())
1069 V = BBMap[slot];
Chris Lattner39cacce2003-10-10 05:43:47 +00001070 } else {
Reid Spencerd798a512006-11-14 04:47:22 +00001071 V = getValue(Typ, slot, false); // Find mapping...
Chris Lattner39cacce2003-10-10 05:43:47 +00001072 }
Reid Spencerd798a512006-11-14 04:47:22 +00001073 if (V == 0)
1074 error("Failed value look-up for name '" + Name + "'");
1075 V->setName(Name);
Chris Lattner00950542001-06-06 20:29:01 +00001076 }
1077 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001078 checkPastBlockEnd("Symbol Table");
Reid Spencer04cde2c2004-07-04 11:33:49 +00001079 if (Handler) Handler->handleSymbolTableEnd();
Chris Lattner00950542001-06-06 20:29:01 +00001080}
1081
Misha Brukman8a96c532005-04-21 21:44:41 +00001082/// Read in the types portion of a compaction table.
Reid Spencer46b002c2004-07-11 17:28:43 +00001083void BytecodeReader::ParseCompactionTypes(unsigned NumEntries) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001084 for (unsigned i = 0; i != NumEntries; ++i) {
Reid Spencerd798a512006-11-14 04:47:22 +00001085 unsigned TypeSlot = read_vbr_uint();
Reid Spencer04cde2c2004-07-04 11:33:49 +00001086 const Type *Typ = getGlobalTableType(TypeSlot);
Chris Lattner45b5dd22004-08-03 23:41:28 +00001087 CompactionTypes.push_back(std::make_pair(Typ, TypeSlot));
Reid Spencer46b002c2004-07-11 17:28:43 +00001088 if (Handler) Handler->handleCompactionTableType(i, TypeSlot, Typ);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001089 }
1090}
1091
1092/// Parse a compaction table.
Reid Spencer060d25d2004-06-29 23:29:38 +00001093void BytecodeReader::ParseCompactionTable() {
1094
Reid Spencer46b002c2004-07-11 17:28:43 +00001095 // Notify handler that we're beginning a compaction table.
Reid Spencer04cde2c2004-07-04 11:33:49 +00001096 if (Handler) Handler->handleCompactionTableBegin();
1097
Reid Spencerd798a512006-11-14 04:47:22 +00001098 // Get the types for the compaction table.
1099 unsigned NumEntries = read_vbr_uint();
1100 ParseCompactionTypes(NumEntries);
Reid Spencer060d25d2004-06-29 23:29:38 +00001101
Reid Spencer46b002c2004-07-11 17:28:43 +00001102 // Compaction tables live in separate blocks so we have to loop
1103 // until we've read the whole thing.
1104 while (moreInBlock()) {
1105 // Read the number of Value* entries in the compaction table
Reid Spencer060d25d2004-06-29 23:29:38 +00001106 unsigned NumEntries = read_vbr_uint();
Reid Spencer04cde2c2004-07-04 11:33:49 +00001107 unsigned Ty = 0;
Reid Spencer060d25d2004-06-29 23:29:38 +00001108
Reid Spencer46b002c2004-07-11 17:28:43 +00001109 // Decode the type from value read in. Most compaction table
1110 // planes will have one or two entries in them. If that's the
1111 // case then the length is encoded in the bottom two bits and
1112 // the higher bits encode the type. This saves another VBR value.
Reid Spencer060d25d2004-06-29 23:29:38 +00001113 if ((NumEntries & 3) == 3) {
Reid Spencer46b002c2004-07-11 17:28:43 +00001114 // In this case, both low-order bits are set (value 3). This
1115 // is a signal that the typeid follows.
Reid Spencer060d25d2004-06-29 23:29:38 +00001116 NumEntries >>= 2;
Reid Spencerd798a512006-11-14 04:47:22 +00001117 Ty = read_vbr_uint();
Reid Spencer060d25d2004-06-29 23:29:38 +00001118 } else {
Reid Spencer46b002c2004-07-11 17:28:43 +00001119 // In this case, the low-order bits specify the number of entries
1120 // and the high order bits specify the type.
Reid Spencer060d25d2004-06-29 23:29:38 +00001121 Ty = NumEntries >> 2;
1122 NumEntries &= 3;
1123 }
1124
Reid Spencerd798a512006-11-14 04:47:22 +00001125 // Make sure we have enough room for the plane.
1126 if (Ty >= CompactionValues.size())
1127 CompactionValues.resize(Ty+1);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001128
Reid Spencerd798a512006-11-14 04:47:22 +00001129 // Make sure the plane is empty or we have some kind of error.
1130 if (!CompactionValues[Ty].empty())
1131 error("Compaction table plane contains multiple entries!");
Reid Spencer04cde2c2004-07-04 11:33:49 +00001132
Reid Spencerd798a512006-11-14 04:47:22 +00001133 // Notify handler about the plane.
1134 if (Handler) Handler->handleCompactionTablePlane(Ty, NumEntries);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001135
Reid Spencerd798a512006-11-14 04:47:22 +00001136 // Push the implicit zero.
1137 CompactionValues[Ty].push_back(Constant::getNullValue(getType(Ty)));
Reid Spencer46b002c2004-07-11 17:28:43 +00001138
Reid Spencerd798a512006-11-14 04:47:22 +00001139 // Read in each of the entries, put them in the compaction table
1140 // and notify the handler that we have a new compaction table value.
1141 for (unsigned i = 0; i != NumEntries; ++i) {
1142 unsigned ValSlot = read_vbr_uint();
1143 Value *V = getGlobalTableValue(Ty, ValSlot);
1144 CompactionValues[Ty].push_back(V);
1145 if (Handler) Handler->handleCompactionTableValue(i, Ty, ValSlot);
Reid Spencer060d25d2004-06-29 23:29:38 +00001146 }
1147 }
Reid Spencer46b002c2004-07-11 17:28:43 +00001148 // Notify handler that the compaction table is done.
Reid Spencer04cde2c2004-07-04 11:33:49 +00001149 if (Handler) Handler->handleCompactionTableEnd();
Reid Spencer060d25d2004-06-29 23:29:38 +00001150}
Misha Brukman8a96c532005-04-21 21:44:41 +00001151
Reid Spencer46b002c2004-07-11 17:28:43 +00001152// Parse a single type. The typeid is read in first. If its a primitive type
1153// then nothing else needs to be read, we know how to instantiate it. If its
Misha Brukman8a96c532005-04-21 21:44:41 +00001154// a derived type, then additional data is read to fill out the type
Reid Spencer46b002c2004-07-11 17:28:43 +00001155// definition.
1156const Type *BytecodeReader::ParseType() {
Reid Spencerd798a512006-11-14 04:47:22 +00001157 unsigned PrimType = read_vbr_uint();
Reid Spencer060d25d2004-06-29 23:29:38 +00001158 const Type *Result = 0;
1159 if ((Result = Type::getPrimitiveType((Type::TypeID)PrimType)))
1160 return Result;
Misha Brukman8a96c532005-04-21 21:44:41 +00001161
Reid Spencer060d25d2004-06-29 23:29:38 +00001162 switch (PrimType) {
1163 case Type::FunctionTyID: {
Reid Spencerd798a512006-11-14 04:47:22 +00001164 const Type *RetType = readType();
Reid Spencer88cfda22006-12-31 05:44:24 +00001165 unsigned RetAttr = read_vbr_uint();
Reid Spencer060d25d2004-06-29 23:29:38 +00001166
1167 unsigned NumParams = read_vbr_uint();
1168
1169 std::vector<const Type*> Params;
Reid Spencer88cfda22006-12-31 05:44:24 +00001170 std::vector<FunctionType::ParameterAttributes> Attrs;
1171 Attrs.push_back(FunctionType::ParameterAttributes(RetAttr));
1172 while (NumParams--) {
Reid Spencerd798a512006-11-14 04:47:22 +00001173 Params.push_back(readType());
Reid Spencer88cfda22006-12-31 05:44:24 +00001174 if (Params.back() != Type::VoidTy)
1175 Attrs.push_back(FunctionType::ParameterAttributes(read_vbr_uint()));
1176 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001177
1178 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1179 if (isVarArg) Params.pop_back();
1180
Reid Spencer88cfda22006-12-31 05:44:24 +00001181 Result = FunctionType::get(RetType, Params, isVarArg, Attrs);
Reid Spencer060d25d2004-06-29 23:29:38 +00001182 break;
1183 }
1184 case Type::ArrayTyID: {
Reid Spencerd798a512006-11-14 04:47:22 +00001185 const Type *ElementType = readType();
Reid Spencer060d25d2004-06-29 23:29:38 +00001186 unsigned NumElements = read_vbr_uint();
Reid Spencer060d25d2004-06-29 23:29:38 +00001187 Result = ArrayType::get(ElementType, NumElements);
1188 break;
1189 }
Brian Gaeke715c90b2004-08-20 06:00:58 +00001190 case Type::PackedTyID: {
Reid Spencerd798a512006-11-14 04:47:22 +00001191 const Type *ElementType = readType();
Brian Gaeke715c90b2004-08-20 06:00:58 +00001192 unsigned NumElements = read_vbr_uint();
1193 Result = PackedType::get(ElementType, NumElements);
1194 break;
1195 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001196 case Type::StructTyID: {
1197 std::vector<const Type*> Elements;
Reid Spencerd798a512006-11-14 04:47:22 +00001198 unsigned Typ = read_vbr_uint();
Reid Spencer060d25d2004-06-29 23:29:38 +00001199 while (Typ) { // List is terminated by void/0 typeid
1200 Elements.push_back(getType(Typ));
Reid Spencerd798a512006-11-14 04:47:22 +00001201 Typ = read_vbr_uint();
Reid Spencer060d25d2004-06-29 23:29:38 +00001202 }
1203
Andrew Lenharth38ecbf12006-12-08 18:06:16 +00001204 Result = StructType::get(Elements, false);
1205 break;
1206 }
1207 case Type::BC_ONLY_PackedStructTyID: {
1208 std::vector<const Type*> Elements;
1209 unsigned Typ = read_vbr_uint();
1210 while (Typ) { // List is terminated by void/0 typeid
1211 Elements.push_back(getType(Typ));
1212 Typ = read_vbr_uint();
1213 }
1214
1215 Result = StructType::get(Elements, true);
Reid Spencer060d25d2004-06-29 23:29:38 +00001216 break;
1217 }
1218 case Type::PointerTyID: {
Reid Spencerd798a512006-11-14 04:47:22 +00001219 Result = PointerType::get(readType());
Reid Spencer060d25d2004-06-29 23:29:38 +00001220 break;
1221 }
1222
1223 case Type::OpaqueTyID: {
1224 Result = OpaqueType::get();
1225 break;
1226 }
1227
1228 default:
Reid Spencer24399722004-07-09 22:21:33 +00001229 error("Don't know how to deserialize primitive type " + utostr(PrimType));
Reid Spencer060d25d2004-06-29 23:29:38 +00001230 break;
1231 }
Reid Spencer46b002c2004-07-11 17:28:43 +00001232 if (Handler) Handler->handleType(Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001233 return Result;
1234}
1235
Reid Spencer5b472d92004-08-21 20:49:23 +00001236// ParseTypes - We have to use this weird code to handle recursive
Reid Spencer060d25d2004-06-29 23:29:38 +00001237// types. We know that recursive types will only reference the current slab of
1238// values in the type plane, but they can forward reference types before they
1239// have been read. For example, Type #0 might be '{ Ty#1 }' and Type #1 might
1240// be 'Ty#0*'. When reading Type #0, type number one doesn't exist. To fix
1241// this ugly problem, we pessimistically insert an opaque type for each type we
1242// are about to read. This means that forward references will resolve to
1243// something and when we reread the type later, we can replace the opaque type
1244// with a new resolved concrete type.
1245//
Reid Spencer46b002c2004-07-11 17:28:43 +00001246void BytecodeReader::ParseTypes(TypeListTy &Tab, unsigned NumEntries){
Reid Spencer060d25d2004-06-29 23:29:38 +00001247 assert(Tab.size() == 0 && "should not have read type constants in before!");
1248
1249 // Insert a bunch of opaque types to be resolved later...
1250 Tab.reserve(NumEntries);
1251 for (unsigned i = 0; i != NumEntries; ++i)
1252 Tab.push_back(OpaqueType::get());
1253
Misha Brukman8a96c532005-04-21 21:44:41 +00001254 if (Handler)
Reid Spencer5b472d92004-08-21 20:49:23 +00001255 Handler->handleTypeList(NumEntries);
1256
Chris Lattnereebac5f2005-10-03 21:26:53 +00001257 // If we are about to resolve types, make sure the type cache is clear.
1258 if (NumEntries)
1259 ModuleTypeIDCache.clear();
1260
Reid Spencer060d25d2004-06-29 23:29:38 +00001261 // Loop through reading all of the types. Forward types will make use of the
1262 // opaque types just inserted.
1263 //
1264 for (unsigned i = 0; i != NumEntries; ++i) {
Reid Spencer46b002c2004-07-11 17:28:43 +00001265 const Type* NewTy = ParseType();
Reid Spencer04cde2c2004-07-04 11:33:49 +00001266 const Type* OldTy = Tab[i].get();
Misha Brukman8a96c532005-04-21 21:44:41 +00001267 if (NewTy == 0)
Reid Spencer24399722004-07-09 22:21:33 +00001268 error("Couldn't parse type!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001269
Misha Brukman8a96c532005-04-21 21:44:41 +00001270 // Don't directly push the new type on the Tab. Instead we want to replace
Reid Spencer060d25d2004-06-29 23:29:38 +00001271 // the opaque type we previously inserted with the new concrete value. This
1272 // approach helps with forward references to types. The refinement from the
1273 // abstract (opaque) type to the new type causes all uses of the abstract
1274 // type to use the concrete type (NewTy). This will also cause the opaque
1275 // type to be deleted.
1276 cast<DerivedType>(const_cast<Type*>(OldTy))->refineAbstractTypeTo(NewTy);
1277
1278 // This should have replaced the old opaque type with the new type in the
1279 // value table... or with a preexisting type that was already in the system.
1280 // Let's just make sure it did.
1281 assert(Tab[i] != OldTy && "refineAbstractType didn't work!");
1282 }
1283}
1284
Reid Spencer04cde2c2004-07-04 11:33:49 +00001285/// Parse a single constant value
Chris Lattner3bc5a602006-01-25 23:08:15 +00001286Value *BytecodeReader::ParseConstantPoolValue(unsigned TypeID) {
Reid Spencer060d25d2004-06-29 23:29:38 +00001287 // We must check for a ConstantExpr before switching by type because
1288 // a ConstantExpr can be of any type, and has no explicit value.
Misha Brukman8a96c532005-04-21 21:44:41 +00001289 //
Reid Spencer060d25d2004-06-29 23:29:38 +00001290 // 0 if not expr; numArgs if is expr
1291 unsigned isExprNumArgs = read_vbr_uint();
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001292
Reid Spencer060d25d2004-06-29 23:29:38 +00001293 if (isExprNumArgs) {
Reid Spencerd798a512006-11-14 04:47:22 +00001294 // 'undef' is encoded with 'exprnumargs' == 1.
1295 if (isExprNumArgs == 1)
1296 return UndefValue::get(getType(TypeID));
Misha Brukman8a96c532005-04-21 21:44:41 +00001297
Reid Spencerd798a512006-11-14 04:47:22 +00001298 // Inline asm is encoded with exprnumargs == ~0U.
1299 if (isExprNumArgs == ~0U) {
1300 std::string AsmStr = read_str();
1301 std::string ConstraintStr = read_str();
1302 unsigned Flags = read_vbr_uint();
Chris Lattner3bc5a602006-01-25 23:08:15 +00001303
Reid Spencerd798a512006-11-14 04:47:22 +00001304 const PointerType *PTy = dyn_cast<PointerType>(getType(TypeID));
1305 const FunctionType *FTy =
1306 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
1307
1308 if (!FTy || !InlineAsm::Verify(FTy, ConstraintStr))
1309 error("Invalid constraints for inline asm");
1310 if (Flags & ~1U)
1311 error("Invalid flags for inline asm");
1312 bool HasSideEffects = Flags & 1;
1313 return InlineAsm::get(FTy, AsmStr, ConstraintStr, HasSideEffects);
Chris Lattner3bc5a602006-01-25 23:08:15 +00001314 }
Reid Spencerd798a512006-11-14 04:47:22 +00001315
1316 --isExprNumArgs;
Chris Lattner3bc5a602006-01-25 23:08:15 +00001317
Reid Spencer060d25d2004-06-29 23:29:38 +00001318 // FIXME: Encoding of constant exprs could be much more compact!
1319 std::vector<Constant*> ArgVec;
1320 ArgVec.reserve(isExprNumArgs);
1321 unsigned Opcode = read_vbr_uint();
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001322
Reid Spencer060d25d2004-06-29 23:29:38 +00001323 // Read the slot number and types of each of the arguments
1324 for (unsigned i = 0; i != isExprNumArgs; ++i) {
1325 unsigned ArgValSlot = read_vbr_uint();
Reid Spencerd798a512006-11-14 04:47:22 +00001326 unsigned ArgTypeSlot = read_vbr_uint();
Misha Brukman8a96c532005-04-21 21:44:41 +00001327
Reid Spencer060d25d2004-06-29 23:29:38 +00001328 // Get the arg value from its slot if it exists, otherwise a placeholder
1329 ArgVec.push_back(getConstantValue(ArgTypeSlot, ArgValSlot));
1330 }
Misha Brukman8a96c532005-04-21 21:44:41 +00001331
Reid Spencer060d25d2004-06-29 23:29:38 +00001332 // Construct a ConstantExpr of the appropriate kind
1333 if (isExprNumArgs == 1) { // All one-operand expressions
Reid Spencer3da59db2006-11-27 01:05:10 +00001334 if (!Instruction::isCast(Opcode))
Chris Lattner02dce162004-12-04 05:28:27 +00001335 error("Only cast instruction has one argument for ConstantExpr");
Reid Spencer46b002c2004-07-11 17:28:43 +00001336
Reid Spencera77fa7e2006-12-11 23:20:20 +00001337 Constant *Result = ConstantExpr::getCast(Opcode, ArgVec[0],
1338 getType(TypeID));
Reid Spencer04cde2c2004-07-04 11:33:49 +00001339 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001340 return Result;
1341 } else if (Opcode == Instruction::GetElementPtr) { // GetElementPtr
1342 std::vector<Constant*> IdxList(ArgVec.begin()+1, ArgVec.end());
Reid Spencer3da59db2006-11-27 01:05:10 +00001343 Constant *Result = ConstantExpr::getGetElementPtr(ArgVec[0], IdxList);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001344 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001345 return Result;
1346 } else if (Opcode == Instruction::Select) {
Reid Spencer46b002c2004-07-11 17:28:43 +00001347 if (ArgVec.size() != 3)
1348 error("Select instruction must have three arguments.");
Misha Brukman8a96c532005-04-21 21:44:41 +00001349 Constant* Result = ConstantExpr::getSelect(ArgVec[0], ArgVec[1],
Reid Spencer04cde2c2004-07-04 11:33:49 +00001350 ArgVec[2]);
1351 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001352 return Result;
Robert Bocchinofee31b32006-01-10 19:04:39 +00001353 } else if (Opcode == Instruction::ExtractElement) {
Chris Lattner59fecec2006-04-08 04:09:19 +00001354 if (ArgVec.size() != 2 ||
1355 !ExtractElementInst::isValidOperands(ArgVec[0], ArgVec[1]))
1356 error("Invalid extractelement constand expr arguments");
Robert Bocchinofee31b32006-01-10 19:04:39 +00001357 Constant* Result = ConstantExpr::getExtractElement(ArgVec[0], ArgVec[1]);
1358 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
1359 return Result;
Robert Bocchinob1f240b2006-01-17 20:06:35 +00001360 } else if (Opcode == Instruction::InsertElement) {
Chris Lattner59fecec2006-04-08 04:09:19 +00001361 if (ArgVec.size() != 3 ||
1362 !InsertElementInst::isValidOperands(ArgVec[0], ArgVec[1], ArgVec[2]))
1363 error("Invalid insertelement constand expr arguments");
1364
1365 Constant *Result =
Robert Bocchinob1f240b2006-01-17 20:06:35 +00001366 ConstantExpr::getInsertElement(ArgVec[0], ArgVec[1], ArgVec[2]);
1367 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
1368 return Result;
Chris Lattner30b44b62006-04-08 01:17:59 +00001369 } else if (Opcode == Instruction::ShuffleVector) {
1370 if (ArgVec.size() != 3 ||
1371 !ShuffleVectorInst::isValidOperands(ArgVec[0], ArgVec[1], ArgVec[2]))
Chris Lattner59fecec2006-04-08 04:09:19 +00001372 error("Invalid shufflevector constant expr arguments.");
Chris Lattner30b44b62006-04-08 01:17:59 +00001373 Constant *Result =
1374 ConstantExpr::getShuffleVector(ArgVec[0], ArgVec[1], ArgVec[2]);
1375 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
1376 return Result;
Reid Spencer9f132762006-12-03 17:17:02 +00001377 } else if (Opcode == Instruction::ICmp) {
1378 if (ArgVec.size() != 2)
Reid Spencer595b4772006-12-04 05:23:49 +00001379 error("Invalid ICmp constant expr arguments.");
1380 unsigned predicate = read_vbr_uint();
1381 Constant *Result = ConstantExpr::getICmp(predicate, ArgVec[0], ArgVec[1]);
1382 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
1383 return Result;
Reid Spencer9f132762006-12-03 17:17:02 +00001384 } else if (Opcode == Instruction::FCmp) {
1385 if (ArgVec.size() != 2)
Reid Spencer595b4772006-12-04 05:23:49 +00001386 error("Invalid FCmp constant expr arguments.");
1387 unsigned predicate = read_vbr_uint();
1388 Constant *Result = ConstantExpr::getFCmp(predicate, ArgVec[0], ArgVec[1]);
1389 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
1390 return Result;
Reid Spencer060d25d2004-06-29 23:29:38 +00001391 } else { // All other 2-operand expressions
1392 Constant* Result = ConstantExpr::get(Opcode, ArgVec[0], ArgVec[1]);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001393 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001394 return Result;
1395 }
1396 }
Misha Brukman8a96c532005-04-21 21:44:41 +00001397
Reid Spencer060d25d2004-06-29 23:29:38 +00001398 // Ok, not an ConstantExpr. We now know how to read the given type...
1399 const Type *Ty = getType(TypeID);
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001400 Constant *Result = 0;
Reid Spencer060d25d2004-06-29 23:29:38 +00001401 switch (Ty->getTypeID()) {
1402 case Type::BoolTyID: {
1403 unsigned Val = read_vbr_uint();
Misha Brukman8a96c532005-04-21 21:44:41 +00001404 if (Val != 0 && Val != 1)
Reid Spencer24399722004-07-09 22:21:33 +00001405 error("Invalid boolean value read.");
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001406 Result = ConstantBool::get(Val == 1);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001407 if (Handler) Handler->handleConstantValue(Result);
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001408 break;
Reid Spencer060d25d2004-06-29 23:29:38 +00001409 }
1410
Reid Spencer88cfda22006-12-31 05:44:24 +00001411 case Type::Int8TyID: // Unsigned integer types...
1412 case Type::Int16TyID:
1413 case Type::Int32TyID: {
Reid Spencer060d25d2004-06-29 23:29:38 +00001414 unsigned Val = read_vbr_uint();
Reid Spencerb83eb642006-10-20 07:07:24 +00001415 if (!ConstantInt::isValueValidForType(Ty, uint64_t(Val)))
Reid Spencer24399722004-07-09 22:21:33 +00001416 error("Invalid unsigned byte/short/int read.");
Reid Spencerb83eb642006-10-20 07:07:24 +00001417 Result = ConstantInt::get(Ty, Val);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001418 if (Handler) Handler->handleConstantValue(Result);
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001419 break;
Reid Spencer060d25d2004-06-29 23:29:38 +00001420 }
1421
Reid Spencer88cfda22006-12-31 05:44:24 +00001422 case Type::Int64TyID: {
1423 uint64_t Val = read_vbr_uint64();
Reid Spencerb83eb642006-10-20 07:07:24 +00001424 if (!ConstantInt::isValueValidForType(Ty, Val))
Reid Spencer88cfda22006-12-31 05:44:24 +00001425 error("Invalid constant integer read.");
Reid Spencerb83eb642006-10-20 07:07:24 +00001426 Result = ConstantInt::get(Ty, Val);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001427 if (Handler) Handler->handleConstantValue(Result);
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001428 break;
Reid Spencer060d25d2004-06-29 23:29:38 +00001429 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001430 case Type::FloatTyID: {
Reid Spencer46b002c2004-07-11 17:28:43 +00001431 float Val;
1432 read_float(Val);
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001433 Result = ConstantFP::get(Ty, Val);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001434 if (Handler) Handler->handleConstantValue(Result);
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001435 break;
Reid Spencer060d25d2004-06-29 23:29:38 +00001436 }
1437
1438 case Type::DoubleTyID: {
1439 double Val;
Reid Spencer46b002c2004-07-11 17:28:43 +00001440 read_double(Val);
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001441 Result = ConstantFP::get(Ty, Val);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001442 if (Handler) Handler->handleConstantValue(Result);
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001443 break;
Reid Spencer060d25d2004-06-29 23:29:38 +00001444 }
1445
Reid Spencer060d25d2004-06-29 23:29:38 +00001446 case Type::ArrayTyID: {
1447 const ArrayType *AT = cast<ArrayType>(Ty);
1448 unsigned NumElements = AT->getNumElements();
1449 unsigned TypeSlot = getTypeSlot(AT->getElementType());
1450 std::vector<Constant*> Elements;
1451 Elements.reserve(NumElements);
1452 while (NumElements--) // Read all of the elements of the constant.
1453 Elements.push_back(getConstantValue(TypeSlot,
1454 read_vbr_uint()));
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001455 Result = ConstantArray::get(AT, Elements);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001456 if (Handler) Handler->handleConstantArray(AT, Elements, TypeSlot, Result);
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001457 break;
Reid Spencer060d25d2004-06-29 23:29:38 +00001458 }
1459
1460 case Type::StructTyID: {
1461 const StructType *ST = cast<StructType>(Ty);
1462
1463 std::vector<Constant *> Elements;
1464 Elements.reserve(ST->getNumElements());
1465 for (unsigned i = 0; i != ST->getNumElements(); ++i)
1466 Elements.push_back(getConstantValue(ST->getElementType(i),
1467 read_vbr_uint()));
1468
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001469 Result = ConstantStruct::get(ST, Elements);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001470 if (Handler) Handler->handleConstantStruct(ST, Elements, Result);
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001471 break;
Misha Brukman8a96c532005-04-21 21:44:41 +00001472 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001473
Brian Gaeke715c90b2004-08-20 06:00:58 +00001474 case Type::PackedTyID: {
1475 const PackedType *PT = cast<PackedType>(Ty);
1476 unsigned NumElements = PT->getNumElements();
1477 unsigned TypeSlot = getTypeSlot(PT->getElementType());
1478 std::vector<Constant*> Elements;
1479 Elements.reserve(NumElements);
1480 while (NumElements--) // Read all of the elements of the constant.
1481 Elements.push_back(getConstantValue(TypeSlot,
1482 read_vbr_uint()));
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001483 Result = ConstantPacked::get(PT, Elements);
Brian Gaeke715c90b2004-08-20 06:00:58 +00001484 if (Handler) Handler->handleConstantPacked(PT, Elements, TypeSlot, Result);
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001485 break;
Brian Gaeke715c90b2004-08-20 06:00:58 +00001486 }
1487
Chris Lattner638c3812004-11-19 16:24:05 +00001488 case Type::PointerTyID: { // ConstantPointerRef value (backwards compat).
Reid Spencer060d25d2004-06-29 23:29:38 +00001489 const PointerType *PT = cast<PointerType>(Ty);
1490 unsigned Slot = read_vbr_uint();
Misha Brukman8a96c532005-04-21 21:44:41 +00001491
Reid Spencer060d25d2004-06-29 23:29:38 +00001492 // Check to see if we have already read this global variable...
1493 Value *Val = getValue(TypeID, Slot, false);
Reid Spencer060d25d2004-06-29 23:29:38 +00001494 if (Val) {
Chris Lattnerbcb11cf2004-07-27 02:34:49 +00001495 GlobalValue *GV = dyn_cast<GlobalValue>(Val);
1496 if (!GV) error("GlobalValue not in ValueTable!");
1497 if (Handler) Handler->handleConstantPointer(PT, Slot, GV);
1498 return GV;
Reid Spencer060d25d2004-06-29 23:29:38 +00001499 } else {
Reid Spencer24399722004-07-09 22:21:33 +00001500 error("Forward references are not allowed here.");
Reid Spencer060d25d2004-06-29 23:29:38 +00001501 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001502 }
1503
1504 default:
Reid Spencer24399722004-07-09 22:21:33 +00001505 error("Don't know how to deserialize constant value of type '" +
Reid Spencer060d25d2004-06-29 23:29:38 +00001506 Ty->getDescription());
1507 break;
1508 }
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001509
1510 // Check that we didn't read a null constant if they are implicit for this
1511 // type plane. Do not do this check for constantexprs, as they may be folded
1512 // to a null value in a way that isn't predicted when a .bc file is initially
1513 // produced.
1514 assert((!isa<Constant>(Result) || !cast<Constant>(Result)->isNullValue()) ||
1515 !hasImplicitNull(TypeID) &&
1516 "Cannot read null values from bytecode!");
1517 return Result;
Reid Spencer060d25d2004-06-29 23:29:38 +00001518}
1519
Misha Brukman8a96c532005-04-21 21:44:41 +00001520/// Resolve references for constants. This function resolves the forward
1521/// referenced constants in the ConstantFwdRefs map. It uses the
Reid Spencer04cde2c2004-07-04 11:33:49 +00001522/// replaceAllUsesWith method of Value class to substitute the placeholder
1523/// instance with the actual instance.
Chris Lattner389bd042004-12-09 06:19:44 +00001524void BytecodeReader::ResolveReferencesToConstant(Constant *NewV, unsigned Typ,
1525 unsigned Slot) {
Chris Lattner29b789b2003-11-19 17:27:18 +00001526 ConstantRefsType::iterator I =
Chris Lattner389bd042004-12-09 06:19:44 +00001527 ConstantFwdRefs.find(std::make_pair(Typ, Slot));
Chris Lattner29b789b2003-11-19 17:27:18 +00001528 if (I == ConstantFwdRefs.end()) return; // Never forward referenced?
Chris Lattner00950542001-06-06 20:29:01 +00001529
Chris Lattner29b789b2003-11-19 17:27:18 +00001530 Value *PH = I->second; // Get the placeholder...
1531 PH->replaceAllUsesWith(NewV);
1532 delete PH; // Delete the old placeholder
1533 ConstantFwdRefs.erase(I); // Remove the map entry for it
Vikram S. Advec1e4a812002-07-14 23:04:18 +00001534}
1535
Reid Spencer04cde2c2004-07-04 11:33:49 +00001536/// Parse the constant strings section.
Reid Spencer060d25d2004-06-29 23:29:38 +00001537void BytecodeReader::ParseStringConstants(unsigned NumEntries, ValueTable &Tab){
1538 for (; NumEntries; --NumEntries) {
Reid Spencerd798a512006-11-14 04:47:22 +00001539 unsigned Typ = read_vbr_uint();
Reid Spencer060d25d2004-06-29 23:29:38 +00001540 const Type *Ty = getType(Typ);
1541 if (!isa<ArrayType>(Ty))
Reid Spencer24399722004-07-09 22:21:33 +00001542 error("String constant data invalid!");
Misha Brukman8a96c532005-04-21 21:44:41 +00001543
Reid Spencer060d25d2004-06-29 23:29:38 +00001544 const ArrayType *ATy = cast<ArrayType>(Ty);
Reid Spencer88cfda22006-12-31 05:44:24 +00001545 if (ATy->getElementType() != Type::Int8Ty &&
1546 ATy->getElementType() != Type::Int8Ty)
Reid Spencer24399722004-07-09 22:21:33 +00001547 error("String constant data invalid!");
Misha Brukman8a96c532005-04-21 21:44:41 +00001548
Reid Spencer060d25d2004-06-29 23:29:38 +00001549 // Read character data. The type tells us how long the string is.
Misha Brukman8a96c532005-04-21 21:44:41 +00001550 char *Data = reinterpret_cast<char *>(alloca(ATy->getNumElements()));
Reid Spencer060d25d2004-06-29 23:29:38 +00001551 read_data(Data, Data+ATy->getNumElements());
Chris Lattner52e20b02003-03-19 20:54:26 +00001552
Reid Spencer060d25d2004-06-29 23:29:38 +00001553 std::vector<Constant*> Elements(ATy->getNumElements());
Reid Spencerb83eb642006-10-20 07:07:24 +00001554 const Type* ElemType = ATy->getElementType();
1555 for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
1556 Elements[i] = ConstantInt::get(ElemType, (unsigned char)Data[i]);
Misha Brukman12c29d12003-09-22 23:38:23 +00001557
Reid Spencer060d25d2004-06-29 23:29:38 +00001558 // Create the constant, inserting it as needed.
1559 Constant *C = ConstantArray::get(ATy, Elements);
1560 unsigned Slot = insertValue(C, Typ, Tab);
Chris Lattner389bd042004-12-09 06:19:44 +00001561 ResolveReferencesToConstant(C, Typ, Slot);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001562 if (Handler) Handler->handleConstantString(cast<ConstantArray>(C));
Reid Spencer060d25d2004-06-29 23:29:38 +00001563 }
Misha Brukman12c29d12003-09-22 23:38:23 +00001564}
1565
Reid Spencer04cde2c2004-07-04 11:33:49 +00001566/// Parse the constant pool.
Misha Brukman8a96c532005-04-21 21:44:41 +00001567void BytecodeReader::ParseConstantPool(ValueTable &Tab,
Reid Spencer04cde2c2004-07-04 11:33:49 +00001568 TypeListTy &TypeTab,
Reid Spencer46b002c2004-07-11 17:28:43 +00001569 bool isFunction) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001570 if (Handler) Handler->handleGlobalConstantsBegin();
1571
1572 /// In LLVM 1.3 Type does not derive from Value so the types
1573 /// do not occupy a plane. Consequently, we read the types
1574 /// first in the constant pool.
Reid Spencerd798a512006-11-14 04:47:22 +00001575 if (isFunction) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001576 unsigned NumEntries = read_vbr_uint();
Reid Spencer46b002c2004-07-11 17:28:43 +00001577 ParseTypes(TypeTab, NumEntries);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001578 }
1579
Reid Spencer46b002c2004-07-11 17:28:43 +00001580 while (moreInBlock()) {
Reid Spencer060d25d2004-06-29 23:29:38 +00001581 unsigned NumEntries = read_vbr_uint();
Reid Spencerd798a512006-11-14 04:47:22 +00001582 unsigned Typ = read_vbr_uint();
Reid Spencer04cde2c2004-07-04 11:33:49 +00001583
Reid Spencerd798a512006-11-14 04:47:22 +00001584 if (Typ == Type::VoidTyID) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001585 /// Use of Type::VoidTyID is a misnomer. It actually means
1586 /// that the following plane is constant strings
Reid Spencer060d25d2004-06-29 23:29:38 +00001587 assert(&Tab == &ModuleValues && "Cannot read strings in functions!");
1588 ParseStringConstants(NumEntries, Tab);
1589 } else {
1590 for (unsigned i = 0; i < NumEntries; ++i) {
Chris Lattner3bc5a602006-01-25 23:08:15 +00001591 Value *V = ParseConstantPoolValue(Typ);
1592 assert(V && "ParseConstantPoolValue returned NULL!");
1593 unsigned Slot = insertValue(V, Typ, Tab);
Chris Lattner29b789b2003-11-19 17:27:18 +00001594
Reid Spencer060d25d2004-06-29 23:29:38 +00001595 // If we are reading a function constant table, make sure that we adjust
1596 // the slot number to be the real global constant number.
1597 //
1598 if (&Tab != &ModuleValues && Typ < ModuleValues.size() &&
1599 ModuleValues[Typ])
1600 Slot += ModuleValues[Typ]->size();
Chris Lattner3bc5a602006-01-25 23:08:15 +00001601 if (Constant *C = dyn_cast<Constant>(V))
1602 ResolveReferencesToConstant(C, Typ, Slot);
Reid Spencer060d25d2004-06-29 23:29:38 +00001603 }
1604 }
1605 }
Chris Lattner02dce162004-12-04 05:28:27 +00001606
1607 // After we have finished parsing the constant pool, we had better not have
1608 // any dangling references left.
Reid Spencer3c391272004-12-04 22:19:53 +00001609 if (!ConstantFwdRefs.empty()) {
Reid Spencer3c391272004-12-04 22:19:53 +00001610 ConstantRefsType::const_iterator I = ConstantFwdRefs.begin();
Reid Spencer3c391272004-12-04 22:19:53 +00001611 Constant* missingConst = I->second;
Misha Brukman8a96c532005-04-21 21:44:41 +00001612 error(utostr(ConstantFwdRefs.size()) +
1613 " unresolved constant reference exist. First one is '" +
1614 missingConst->getName() + "' of type '" +
Chris Lattner389bd042004-12-09 06:19:44 +00001615 missingConst->getType()->getDescription() + "'.");
Reid Spencer3c391272004-12-04 22:19:53 +00001616 }
Chris Lattner02dce162004-12-04 05:28:27 +00001617
Reid Spencer060d25d2004-06-29 23:29:38 +00001618 checkPastBlockEnd("Constant Pool");
Reid Spencer04cde2c2004-07-04 11:33:49 +00001619 if (Handler) Handler->handleGlobalConstantsEnd();
Reid Spencer060d25d2004-06-29 23:29:38 +00001620}
Chris Lattner00950542001-06-06 20:29:01 +00001621
Reid Spencer04cde2c2004-07-04 11:33:49 +00001622/// Parse the contents of a function. Note that this function can be
1623/// called lazily by materializeFunction
1624/// @see materializeFunction
Reid Spencer46b002c2004-07-11 17:28:43 +00001625void BytecodeReader::ParseFunctionBody(Function* F) {
Reid Spencer060d25d2004-06-29 23:29:38 +00001626
1627 unsigned FuncSize = BlockEnd - At;
Chris Lattnere3869c82003-04-16 21:16:05 +00001628 GlobalValue::LinkageTypes Linkage = GlobalValue::ExternalLinkage;
1629
Reid Spencer060d25d2004-06-29 23:29:38 +00001630 unsigned LinkageType = read_vbr_uint();
Chris Lattnerc08912f2004-01-14 16:44:44 +00001631 switch (LinkageType) {
1632 case 0: Linkage = GlobalValue::ExternalLinkage; break;
1633 case 1: Linkage = GlobalValue::WeakLinkage; break;
1634 case 2: Linkage = GlobalValue::AppendingLinkage; break;
1635 case 3: Linkage = GlobalValue::InternalLinkage; break;
1636 case 4: Linkage = GlobalValue::LinkOnceLinkage; break;
Anton Korobeynikovb74ed072006-09-14 18:23:27 +00001637 case 5: Linkage = GlobalValue::DLLImportLinkage; break;
1638 case 6: Linkage = GlobalValue::DLLExportLinkage; break;
1639 case 7: Linkage = GlobalValue::ExternalWeakLinkage; break;
Reid Spencer060d25d2004-06-29 23:29:38 +00001640 default:
Reid Spencer24399722004-07-09 22:21:33 +00001641 error("Invalid linkage type for Function.");
Reid Spencer060d25d2004-06-29 23:29:38 +00001642 Linkage = GlobalValue::InternalLinkage;
1643 break;
Chris Lattnere3869c82003-04-16 21:16:05 +00001644 }
Chris Lattnerd23b1d32001-11-26 18:56:10 +00001645
Reid Spencer46b002c2004-07-11 17:28:43 +00001646 F->setLinkage(Linkage);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001647 if (Handler) Handler->handleFunctionBegin(F,FuncSize);
Chris Lattner00950542001-06-06 20:29:01 +00001648
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001649 // Keep track of how many basic blocks we have read in...
1650 unsigned BlockNum = 0;
Chris Lattner89e02532004-01-18 21:08:15 +00001651 bool InsertedArguments = false;
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001652
Reid Spencer060d25d2004-06-29 23:29:38 +00001653 BufPtr MyEnd = BlockEnd;
Reid Spencer46b002c2004-07-11 17:28:43 +00001654 while (At < MyEnd) {
Chris Lattner00950542001-06-06 20:29:01 +00001655 unsigned Type, Size;
Reid Spencer060d25d2004-06-29 23:29:38 +00001656 BufPtr OldAt = At;
1657 read_block(Type, Size);
Chris Lattner00950542001-06-06 20:29:01 +00001658
1659 switch (Type) {
Reid Spencerad89bd62004-07-25 18:07:36 +00001660 case BytecodeFormat::ConstantPoolBlockID:
Chris Lattner89e02532004-01-18 21:08:15 +00001661 if (!InsertedArguments) {
1662 // Insert arguments into the value table before we parse the first basic
1663 // block in the function, but after we potentially read in the
1664 // compaction table.
Reid Spencer04cde2c2004-07-04 11:33:49 +00001665 insertArguments(F);
Chris Lattner89e02532004-01-18 21:08:15 +00001666 InsertedArguments = true;
1667 }
1668
Reid Spencer04cde2c2004-07-04 11:33:49 +00001669 ParseConstantPool(FunctionValues, FunctionTypes, true);
Chris Lattner00950542001-06-06 20:29:01 +00001670 break;
1671
Reid Spencerad89bd62004-07-25 18:07:36 +00001672 case BytecodeFormat::CompactionTableBlockID:
Reid Spencer060d25d2004-06-29 23:29:38 +00001673 ParseCompactionTable();
Chris Lattner89e02532004-01-18 21:08:15 +00001674 break;
1675
Reid Spencerad89bd62004-07-25 18:07:36 +00001676 case BytecodeFormat::InstructionListBlockID: {
Chris Lattner89e02532004-01-18 21:08:15 +00001677 // Insert arguments into the value table before we parse the instruction
1678 // list for the function, but after we potentially read in the compaction
1679 // table.
1680 if (!InsertedArguments) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001681 insertArguments(F);
Chris Lattner89e02532004-01-18 21:08:15 +00001682 InsertedArguments = true;
1683 }
1684
Misha Brukman8a96c532005-04-21 21:44:41 +00001685 if (BlockNum)
Reid Spencer24399722004-07-09 22:21:33 +00001686 error("Already parsed basic blocks!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001687 BlockNum = ParseInstructionList(F);
Chris Lattner8d1dbd22003-12-01 07:05:31 +00001688 break;
1689 }
1690
Reid Spencer78d033e2007-01-06 07:24:44 +00001691 case BytecodeFormat::ValueSymbolTableBlockID:
1692 ParseValueSymbolTable(F, &F->getValueSymbolTable());
1693 break;
1694
1695 case BytecodeFormat::TypeSymbolTableBlockID:
1696 error("Functions don't have type symbol tables");
Chris Lattner00950542001-06-06 20:29:01 +00001697 break;
1698
1699 default:
Reid Spencer060d25d2004-06-29 23:29:38 +00001700 At += Size;
Misha Brukman8a96c532005-04-21 21:44:41 +00001701 if (OldAt > At)
Reid Spencer24399722004-07-09 22:21:33 +00001702 error("Wrapped around reading bytecode.");
Chris Lattner00950542001-06-06 20:29:01 +00001703 break;
1704 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001705 BlockEnd = MyEnd;
Chris Lattner00950542001-06-06 20:29:01 +00001706 }
1707
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001708 // Make sure there were no references to non-existant basic blocks.
1709 if (BlockNum != ParsedBasicBlocks.size())
Reid Spencer24399722004-07-09 22:21:33 +00001710 error("Illegal basic block operand reference");
Reid Spencer060d25d2004-06-29 23:29:38 +00001711
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001712 ParsedBasicBlocks.clear();
1713
Chris Lattner97330cf2003-10-09 23:10:14 +00001714 // Resolve forward references. Replace any uses of a forward reference value
1715 // with the real value.
Chris Lattner8eb10ce2003-10-09 06:05:40 +00001716 while (!ForwardReferences.empty()) {
Chris Lattnerc4d69162004-12-09 04:51:50 +00001717 std::map<std::pair<unsigned,unsigned>, Value*>::iterator
1718 I = ForwardReferences.begin();
1719 Value *V = getValue(I->first.first, I->first.second, false);
Chris Lattner8eb10ce2003-10-09 06:05:40 +00001720 Value *PlaceHolder = I->second;
Chris Lattnerc4d69162004-12-09 04:51:50 +00001721 PlaceHolder->replaceAllUsesWith(V);
Chris Lattner8eb10ce2003-10-09 06:05:40 +00001722 ForwardReferences.erase(I);
Chris Lattner8eb10ce2003-10-09 06:05:40 +00001723 delete PlaceHolder;
Chris Lattner6e448022003-10-08 21:51:46 +00001724 }
Chris Lattner00950542001-06-06 20:29:01 +00001725
Misha Brukman12c29d12003-09-22 23:38:23 +00001726 // Clear out function-level types...
Reid Spencer060d25d2004-06-29 23:29:38 +00001727 FunctionTypes.clear();
1728 CompactionTypes.clear();
1729 CompactionValues.clear();
1730 freeTable(FunctionValues);
1731
Reid Spencer04cde2c2004-07-04 11:33:49 +00001732 if (Handler) Handler->handleFunctionEnd(F);
Chris Lattner00950542001-06-06 20:29:01 +00001733}
1734
Reid Spencer04cde2c2004-07-04 11:33:49 +00001735/// This function parses LLVM functions lazily. It obtains the type of the
1736/// function and records where the body of the function is in the bytecode
Misha Brukman8a96c532005-04-21 21:44:41 +00001737/// buffer. The caller can then use the ParseNextFunction and
Reid Spencer04cde2c2004-07-04 11:33:49 +00001738/// ParseAllFunctionBodies to get handler events for the functions.
Reid Spencer060d25d2004-06-29 23:29:38 +00001739void BytecodeReader::ParseFunctionLazily() {
1740 if (FunctionSignatureList.empty())
Reid Spencer24399722004-07-09 22:21:33 +00001741 error("FunctionSignatureList empty!");
Chris Lattner89e02532004-01-18 21:08:15 +00001742
Reid Spencer060d25d2004-06-29 23:29:38 +00001743 Function *Func = FunctionSignatureList.back();
1744 FunctionSignatureList.pop_back();
Chris Lattner24102432004-01-18 22:35:34 +00001745
Reid Spencer060d25d2004-06-29 23:29:38 +00001746 // Save the information for future reading of the function
1747 LazyFunctionLoadMap[Func] = LazyFunctionInfo(BlockStart, BlockEnd);
Chris Lattner89e02532004-01-18 21:08:15 +00001748
Misha Brukmana3e6ad62004-11-14 21:02:55 +00001749 // This function has a body but it's not loaded so it appears `External'.
1750 // Mark it as a `Ghost' instead to notify the users that it has a body.
1751 Func->setLinkage(GlobalValue::GhostLinkage);
1752
Reid Spencer060d25d2004-06-29 23:29:38 +00001753 // Pretend we've `parsed' this function
1754 At = BlockEnd;
1755}
Chris Lattner89e02532004-01-18 21:08:15 +00001756
Misha Brukman8a96c532005-04-21 21:44:41 +00001757/// The ParserFunction method lazily parses one function. Use this method to
1758/// casue the parser to parse a specific function in the module. Note that
1759/// this will remove the function from what is to be included by
Reid Spencer04cde2c2004-07-04 11:33:49 +00001760/// ParseAllFunctionBodies.
1761/// @see ParseAllFunctionBodies
1762/// @see ParseBytecode
Reid Spencer99655e12006-08-25 19:54:53 +00001763bool BytecodeReader::ParseFunction(Function* Func, std::string* ErrMsg) {
1764
Reid Spencer9b84ad12006-12-15 19:49:23 +00001765 if (setjmp(context)) {
1766 // Set caller's error message, if requested
1767 if (ErrMsg)
1768 *ErrMsg = ErrorMsg;
1769 // Indicate an error occurred
Reid Spencer99655e12006-08-25 19:54:53 +00001770 return true;
Reid Spencer9b84ad12006-12-15 19:49:23 +00001771 }
Reid Spencer99655e12006-08-25 19:54:53 +00001772
Reid Spencer060d25d2004-06-29 23:29:38 +00001773 // Find {start, end} pointers and slot in the map. If not there, we're done.
1774 LazyFunctionMap::iterator Fi = LazyFunctionLoadMap.find(Func);
Chris Lattner89e02532004-01-18 21:08:15 +00001775
Reid Spencer060d25d2004-06-29 23:29:38 +00001776 // Make sure we found it
Reid Spencer46b002c2004-07-11 17:28:43 +00001777 if (Fi == LazyFunctionLoadMap.end()) {
Reid Spencer24399722004-07-09 22:21:33 +00001778 error("Unrecognized function of type " + Func->getType()->getDescription());
Reid Spencer99655e12006-08-25 19:54:53 +00001779 return true;
Chris Lattner89e02532004-01-18 21:08:15 +00001780 }
1781
Reid Spencer060d25d2004-06-29 23:29:38 +00001782 BlockStart = At = Fi->second.Buf;
1783 BlockEnd = Fi->second.EndBuf;
Reid Spencer24399722004-07-09 22:21:33 +00001784 assert(Fi->first == Func && "Found wrong function?");
Reid Spencer060d25d2004-06-29 23:29:38 +00001785
1786 LazyFunctionLoadMap.erase(Fi);
1787
Reid Spencer46b002c2004-07-11 17:28:43 +00001788 this->ParseFunctionBody(Func);
Reid Spencer99655e12006-08-25 19:54:53 +00001789 return false;
Chris Lattner89e02532004-01-18 21:08:15 +00001790}
1791
Reid Spencer04cde2c2004-07-04 11:33:49 +00001792/// The ParseAllFunctionBodies method parses through all the previously
1793/// unparsed functions in the bytecode file. If you want to completely parse
1794/// a bytecode file, this method should be called after Parsebytecode because
1795/// Parsebytecode only records the locations in the bytecode file of where
1796/// the function definitions are located. This function uses that information
1797/// to materialize the functions.
1798/// @see ParseBytecode
Reid Spencer99655e12006-08-25 19:54:53 +00001799bool BytecodeReader::ParseAllFunctionBodies(std::string* ErrMsg) {
Reid Spencer9b84ad12006-12-15 19:49:23 +00001800 if (setjmp(context)) {
1801 // Set caller's error message, if requested
1802 if (ErrMsg)
1803 *ErrMsg = ErrorMsg;
1804 // Indicate an error occurred
Reid Spencer99655e12006-08-25 19:54:53 +00001805 return true;
Reid Spencer9b84ad12006-12-15 19:49:23 +00001806 }
Reid Spencer99655e12006-08-25 19:54:53 +00001807
Reid Spencer060d25d2004-06-29 23:29:38 +00001808 LazyFunctionMap::iterator Fi = LazyFunctionLoadMap.begin();
1809 LazyFunctionMap::iterator Fe = LazyFunctionLoadMap.end();
Chris Lattner89e02532004-01-18 21:08:15 +00001810
Reid Spencer46b002c2004-07-11 17:28:43 +00001811 while (Fi != Fe) {
Reid Spencer060d25d2004-06-29 23:29:38 +00001812 Function* Func = Fi->first;
1813 BlockStart = At = Fi->second.Buf;
1814 BlockEnd = Fi->second.EndBuf;
Chris Lattnerb52f1c22005-02-13 17:48:18 +00001815 ParseFunctionBody(Func);
Reid Spencer060d25d2004-06-29 23:29:38 +00001816 ++Fi;
1817 }
Chris Lattnerb52f1c22005-02-13 17:48:18 +00001818 LazyFunctionLoadMap.clear();
Reid Spencer99655e12006-08-25 19:54:53 +00001819 return false;
Reid Spencer060d25d2004-06-29 23:29:38 +00001820}
Chris Lattner89e02532004-01-18 21:08:15 +00001821
Reid Spencer04cde2c2004-07-04 11:33:49 +00001822/// Parse the global type list
Reid Spencer060d25d2004-06-29 23:29:38 +00001823void BytecodeReader::ParseGlobalTypes() {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001824 // Read the number of types
1825 unsigned NumEntries = read_vbr_uint();
Reid Spencer46b002c2004-07-11 17:28:43 +00001826 ParseTypes(ModuleTypes, NumEntries);
Reid Spencer060d25d2004-06-29 23:29:38 +00001827}
1828
Reid Spencer04cde2c2004-07-04 11:33:49 +00001829/// Parse the Global info (types, global vars, constants)
Reid Spencer060d25d2004-06-29 23:29:38 +00001830void BytecodeReader::ParseModuleGlobalInfo() {
1831
Reid Spencer04cde2c2004-07-04 11:33:49 +00001832 if (Handler) Handler->handleModuleGlobalsBegin();
Chris Lattner00950542001-06-06 20:29:01 +00001833
Chris Lattner404cddf2005-11-12 01:33:40 +00001834 // SectionID - If a global has an explicit section specified, this map
1835 // remembers the ID until we can translate it into a string.
1836 std::map<GlobalValue*, unsigned> SectionID;
1837
Chris Lattner70cc3392001-09-10 07:58:01 +00001838 // Read global variables...
Reid Spencer060d25d2004-06-29 23:29:38 +00001839 unsigned VarType = read_vbr_uint();
Chris Lattner70cc3392001-09-10 07:58:01 +00001840 while (VarType != Type::VoidTyID) { // List is terminated by Void
Chris Lattner9dd87702004-04-03 23:43:42 +00001841 // VarType Fields: bit0 = isConstant, bit1 = hasInitializer, bit2,3,4 =
1842 // Linkage, bit4+ = slot#
1843 unsigned SlotNo = VarType >> 5;
1844 unsigned LinkageID = (VarType >> 2) & 7;
Reid Spencer060d25d2004-06-29 23:29:38 +00001845 bool isConstant = VarType & 1;
Chris Lattnerce5e04e2005-11-06 08:23:17 +00001846 bool hasInitializer = (VarType & 2) != 0;
Chris Lattner8eb52dd2005-11-06 07:11:04 +00001847 unsigned Alignment = 0;
Chris Lattner404cddf2005-11-12 01:33:40 +00001848 unsigned GlobalSectionID = 0;
Chris Lattner8eb52dd2005-11-06 07:11:04 +00001849
1850 // An extension word is present when linkage = 3 (internal) and hasinit = 0.
1851 if (LinkageID == 3 && !hasInitializer) {
1852 unsigned ExtWord = read_vbr_uint();
1853 // The extension word has this format: bit 0 = has initializer, bit 1-3 =
1854 // linkage, bit 4-8 = alignment (log2), bits 10+ = future use.
1855 hasInitializer = ExtWord & 1;
1856 LinkageID = (ExtWord >> 1) & 7;
1857 Alignment = (1 << ((ExtWord >> 4) & 31)) >> 1;
Chris Lattner404cddf2005-11-12 01:33:40 +00001858
1859 if (ExtWord & (1 << 9)) // Has a section ID.
1860 GlobalSectionID = read_vbr_uint();
Chris Lattner8eb52dd2005-11-06 07:11:04 +00001861 }
Chris Lattnere3869c82003-04-16 21:16:05 +00001862
Chris Lattnerce5e04e2005-11-06 08:23:17 +00001863 GlobalValue::LinkageTypes Linkage;
Chris Lattnerc08912f2004-01-14 16:44:44 +00001864 switch (LinkageID) {
Chris Lattnerc08912f2004-01-14 16:44:44 +00001865 case 0: Linkage = GlobalValue::ExternalLinkage; break;
1866 case 1: Linkage = GlobalValue::WeakLinkage; break;
1867 case 2: Linkage = GlobalValue::AppendingLinkage; break;
1868 case 3: Linkage = GlobalValue::InternalLinkage; break;
1869 case 4: Linkage = GlobalValue::LinkOnceLinkage; break;
Anton Korobeynikovb74ed072006-09-14 18:23:27 +00001870 case 5: Linkage = GlobalValue::DLLImportLinkage; break;
1871 case 6: Linkage = GlobalValue::DLLExportLinkage; break;
1872 case 7: Linkage = GlobalValue::ExternalWeakLinkage; break;
Misha Brukman8a96c532005-04-21 21:44:41 +00001873 default:
Reid Spencer24399722004-07-09 22:21:33 +00001874 error("Unknown linkage type: " + utostr(LinkageID));
Reid Spencer060d25d2004-06-29 23:29:38 +00001875 Linkage = GlobalValue::InternalLinkage;
1876 break;
Chris Lattnere3869c82003-04-16 21:16:05 +00001877 }
1878
1879 const Type *Ty = getType(SlotNo);
Chris Lattnere73bd452005-11-06 07:43:39 +00001880 if (!Ty)
Reid Spencer24399722004-07-09 22:21:33 +00001881 error("Global has no type! SlotNo=" + utostr(SlotNo));
Reid Spencer060d25d2004-06-29 23:29:38 +00001882
Chris Lattnere73bd452005-11-06 07:43:39 +00001883 if (!isa<PointerType>(Ty))
Reid Spencer24399722004-07-09 22:21:33 +00001884 error("Global not a pointer type! Ty= " + Ty->getDescription());
Chris Lattner70cc3392001-09-10 07:58:01 +00001885
Chris Lattner52e20b02003-03-19 20:54:26 +00001886 const Type *ElTy = cast<PointerType>(Ty)->getElementType();
Chris Lattnerd70684f2001-09-18 04:01:05 +00001887
Chris Lattner70cc3392001-09-10 07:58:01 +00001888 // Create the global variable...
Reid Spencer060d25d2004-06-29 23:29:38 +00001889 GlobalVariable *GV = new GlobalVariable(ElTy, isConstant, Linkage,
Chris Lattner52e20b02003-03-19 20:54:26 +00001890 0, "", TheModule);
Chris Lattner8eb52dd2005-11-06 07:11:04 +00001891 GV->setAlignment(Alignment);
Chris Lattner29b789b2003-11-19 17:27:18 +00001892 insertValue(GV, SlotNo, ModuleValues);
Chris Lattner05950c32001-10-13 06:47:01 +00001893
Chris Lattner404cddf2005-11-12 01:33:40 +00001894 if (GlobalSectionID != 0)
1895 SectionID[GV] = GlobalSectionID;
1896
Reid Spencer060d25d2004-06-29 23:29:38 +00001897 unsigned initSlot = 0;
Misha Brukman8a96c532005-04-21 21:44:41 +00001898 if (hasInitializer) {
Reid Spencer060d25d2004-06-29 23:29:38 +00001899 initSlot = read_vbr_uint();
1900 GlobalInits.push_back(std::make_pair(GV, initSlot));
1901 }
1902
1903 // Notify handler about the global value.
Chris Lattner4a242b32004-10-14 01:39:18 +00001904 if (Handler)
1905 Handler->handleGlobalVariable(ElTy, isConstant, Linkage, SlotNo,initSlot);
Reid Spencer060d25d2004-06-29 23:29:38 +00001906
1907 // Get next item
1908 VarType = read_vbr_uint();
Chris Lattner70cc3392001-09-10 07:58:01 +00001909 }
1910
Chris Lattner52e20b02003-03-19 20:54:26 +00001911 // Read the function objects for all of the functions that are coming
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001912 unsigned FnSignature = read_vbr_uint();
Reid Spencer24399722004-07-09 22:21:33 +00001913
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001914 // List is terminated by VoidTy.
Chris Lattnere73bd452005-11-06 07:43:39 +00001915 while (((FnSignature & (~0U >> 1)) >> 5) != Type::VoidTyID) {
1916 const Type *Ty = getType((FnSignature & (~0U >> 1)) >> 5);
Chris Lattner927b1852003-10-09 20:22:47 +00001917 if (!isa<PointerType>(Ty) ||
Reid Spencer060d25d2004-06-29 23:29:38 +00001918 !isa<FunctionType>(cast<PointerType>(Ty)->getElementType())) {
Misha Brukman8a96c532005-04-21 21:44:41 +00001919 error("Function not a pointer to function type! Ty = " +
Reid Spencer46b002c2004-07-11 17:28:43 +00001920 Ty->getDescription());
Reid Spencer060d25d2004-06-29 23:29:38 +00001921 }
Chris Lattner8cdc6b72002-10-23 00:51:54 +00001922
Chris Lattner2a7b6ba2003-03-06 17:15:19 +00001923 // We create functions by passing the underlying FunctionType to create...
Misha Brukman8a96c532005-04-21 21:44:41 +00001924 const FunctionType* FTy =
Reid Spencer060d25d2004-06-29 23:29:38 +00001925 cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
Chris Lattner00950542001-06-06 20:29:01 +00001926
Chris Lattner18549c22004-11-15 21:43:03 +00001927 // Insert the place holder.
Chris Lattner404cddf2005-11-12 01:33:40 +00001928 Function *Func = new Function(FTy, GlobalValue::ExternalLinkage,
Reid Spencer04cde2c2004-07-04 11:33:49 +00001929 "", TheModule);
Reid Spencere1e96c02006-01-19 07:02:16 +00001930
Chris Lattnere73bd452005-11-06 07:43:39 +00001931 insertValue(Func, (FnSignature & (~0U >> 1)) >> 5, ModuleValues);
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001932
1933 // Flags are not used yet.
Chris Lattner97fbc502004-11-15 22:38:52 +00001934 unsigned Flags = FnSignature & 31;
Chris Lattner00950542001-06-06 20:29:01 +00001935
Chris Lattner97fbc502004-11-15 22:38:52 +00001936 // Save this for later so we know type of lazily instantiated functions.
1937 // Note that known-external functions do not have FunctionInfo blocks, so we
1938 // do not add them to the FunctionSignatureList.
1939 if ((Flags & (1 << 4)) == 0)
1940 FunctionSignatureList.push_back(Func);
Chris Lattner52e20b02003-03-19 20:54:26 +00001941
Chris Lattnere73bd452005-11-06 07:43:39 +00001942 // Get the calling convention from the low bits.
1943 unsigned CC = Flags & 15;
1944 unsigned Alignment = 0;
1945 if (FnSignature & (1 << 31)) { // Has extension word?
1946 unsigned ExtWord = read_vbr_uint();
1947 Alignment = (1 << (ExtWord & 31)) >> 1;
1948 CC |= ((ExtWord >> 5) & 15) << 4;
Chris Lattner404cddf2005-11-12 01:33:40 +00001949
1950 if (ExtWord & (1 << 10)) // Has a section ID.
1951 SectionID[Func] = read_vbr_uint();
Anton Korobeynikovb74ed072006-09-14 18:23:27 +00001952
1953 // Parse external declaration linkage
1954 switch ((ExtWord >> 11) & 3) {
1955 case 0: break;
1956 case 1: Func->setLinkage(Function::DLLImportLinkage); break;
1957 case 2: Func->setLinkage(Function::ExternalWeakLinkage); break;
1958 default: assert(0 && "Unsupported external linkage");
1959 }
Chris Lattnere73bd452005-11-06 07:43:39 +00001960 }
1961
Chris Lattner54b369e2005-11-06 07:46:13 +00001962 Func->setCallingConv(CC-1);
Chris Lattnere73bd452005-11-06 07:43:39 +00001963 Func->setAlignment(Alignment);
Chris Lattner479ffeb2005-05-06 20:42:57 +00001964
Reid Spencer04cde2c2004-07-04 11:33:49 +00001965 if (Handler) Handler->handleFunctionDeclaration(Func);
Reid Spencer060d25d2004-06-29 23:29:38 +00001966
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001967 // Get the next function signature.
1968 FnSignature = read_vbr_uint();
Chris Lattner00950542001-06-06 20:29:01 +00001969 }
1970
Misha Brukman8a96c532005-04-21 21:44:41 +00001971 // Now that the function signature list is set up, reverse it so that we can
Chris Lattner74734132002-08-17 22:01:27 +00001972 // remove elements efficiently from the back of the vector.
1973 std::reverse(FunctionSignatureList.begin(), FunctionSignatureList.end());
Chris Lattner00950542001-06-06 20:29:01 +00001974
Chris Lattner404cddf2005-11-12 01:33:40 +00001975 /// SectionNames - This contains the list of section names encoded in the
1976 /// moduleinfoblock. Functions and globals with an explicit section index
1977 /// into this to get their section name.
1978 std::vector<std::string> SectionNames;
1979
Reid Spencerd798a512006-11-14 04:47:22 +00001980 // Read in the dependent library information.
1981 unsigned num_dep_libs = read_vbr_uint();
1982 std::string dep_lib;
1983 while (num_dep_libs--) {
1984 dep_lib = read_str();
1985 TheModule->addLibrary(dep_lib);
Reid Spencer5b472d92004-08-21 20:49:23 +00001986 if (Handler)
Reid Spencerd798a512006-11-14 04:47:22 +00001987 Handler->handleDependentLibrary(dep_lib);
Reid Spencerad89bd62004-07-25 18:07:36 +00001988 }
1989
Reid Spencerd798a512006-11-14 04:47:22 +00001990 // Read target triple and place into the module.
1991 std::string triple = read_str();
1992 TheModule->setTargetTriple(triple);
1993 if (Handler)
1994 Handler->handleTargetTriple(triple);
1995
1996 if (At != BlockEnd) {
1997 // If the file has section info in it, read the section names now.
1998 unsigned NumSections = read_vbr_uint();
1999 while (NumSections--)
2000 SectionNames.push_back(read_str());
2001 }
2002
2003 // If the file has module-level inline asm, read it now.
2004 if (At != BlockEnd)
2005 TheModule->setModuleInlineAsm(read_str());
2006
Chris Lattner404cddf2005-11-12 01:33:40 +00002007 // If any globals are in specified sections, assign them now.
2008 for (std::map<GlobalValue*, unsigned>::iterator I = SectionID.begin(), E =
2009 SectionID.end(); I != E; ++I)
2010 if (I->second) {
2011 if (I->second > SectionID.size())
2012 error("SectionID out of range for global!");
2013 I->first->setSection(SectionNames[I->second-1]);
2014 }
Reid Spencerad89bd62004-07-25 18:07:36 +00002015
Chris Lattner00950542001-06-06 20:29:01 +00002016 // This is for future proofing... in the future extra fields may be added that
2017 // we don't understand, so we transparently ignore them.
2018 //
Reid Spencer060d25d2004-06-29 23:29:38 +00002019 At = BlockEnd;
2020
Reid Spencer04cde2c2004-07-04 11:33:49 +00002021 if (Handler) Handler->handleModuleGlobalsEnd();
Chris Lattner00950542001-06-06 20:29:01 +00002022}
2023
Reid Spencer04cde2c2004-07-04 11:33:49 +00002024/// Parse the version information and decode it by setting flags on the
2025/// Reader that enable backward compatibility of the reader.
Reid Spencer060d25d2004-06-29 23:29:38 +00002026void BytecodeReader::ParseVersionInfo() {
2027 unsigned Version = read_vbr_uint();
Chris Lattner036b8aa2003-03-06 17:55:45 +00002028
2029 // Unpack version number: low four bits are for flags, top bits = version
Chris Lattnerd445c6b2003-08-24 13:47:36 +00002030 Module::Endianness Endianness;
2031 Module::PointerSize PointerSize;
2032 Endianness = (Version & 1) ? Module::BigEndian : Module::LittleEndian;
2033 PointerSize = (Version & 2) ? Module::Pointer64 : Module::Pointer32;
2034
2035 bool hasNoEndianness = Version & 4;
2036 bool hasNoPointerSize = Version & 8;
Misha Brukman8a96c532005-04-21 21:44:41 +00002037
Chris Lattnerd445c6b2003-08-24 13:47:36 +00002038 RevisionNum = Version >> 4;
Chris Lattnere3869c82003-04-16 21:16:05 +00002039
Reid Spencer3795ad12006-12-03 05:47:10 +00002040 // We don't provide backwards compatibility in the Reader any more. To
2041 // upgrade, the user should use llvm-upgrade.
2042 if (RevisionNum < 7)
2043 error("Bytecode formats < 7 are no longer supported. Use llvm-upgrade.");
Chris Lattner036b8aa2003-03-06 17:55:45 +00002044
Chris Lattnerd445c6b2003-08-24 13:47:36 +00002045 if (hasNoEndianness) Endianness = Module::AnyEndianness;
2046 if (hasNoPointerSize) PointerSize = Module::AnyPointerSize;
Chris Lattner76e38962003-04-22 18:15:10 +00002047
Brian Gaekefe2102b2004-07-14 20:33:13 +00002048 TheModule->setEndianness(Endianness);
2049 TheModule->setPointerSize(PointerSize);
2050
Reid Spencer46b002c2004-07-11 17:28:43 +00002051 if (Handler) Handler->handleVersionInfo(RevisionNum, Endianness, PointerSize);
Chris Lattner036b8aa2003-03-06 17:55:45 +00002052}
2053
Reid Spencer04cde2c2004-07-04 11:33:49 +00002054/// Parse a whole module.
Reid Spencer060d25d2004-06-29 23:29:38 +00002055void BytecodeReader::ParseModule() {
Chris Lattner00950542001-06-06 20:29:01 +00002056 unsigned Type, Size;
Chris Lattner00950542001-06-06 20:29:01 +00002057
Reid Spencer060d25d2004-06-29 23:29:38 +00002058 FunctionSignatureList.clear(); // Just in case...
Chris Lattner00950542001-06-06 20:29:01 +00002059
2060 // Read into instance variables...
Reid Spencer060d25d2004-06-29 23:29:38 +00002061 ParseVersionInfo();
Chris Lattner00950542001-06-06 20:29:01 +00002062
Reid Spencer060d25d2004-06-29 23:29:38 +00002063 bool SeenModuleGlobalInfo = false;
2064 bool SeenGlobalTypePlane = false;
2065 BufPtr MyEnd = BlockEnd;
2066 while (At < MyEnd) {
2067 BufPtr OldAt = At;
2068 read_block(Type, Size);
2069
Chris Lattner00950542001-06-06 20:29:01 +00002070 switch (Type) {
Reid Spencer060d25d2004-06-29 23:29:38 +00002071
Reid Spencerad89bd62004-07-25 18:07:36 +00002072 case BytecodeFormat::GlobalTypePlaneBlockID:
Reid Spencer46b002c2004-07-11 17:28:43 +00002073 if (SeenGlobalTypePlane)
Reid Spencer24399722004-07-09 22:21:33 +00002074 error("Two GlobalTypePlane Blocks Encountered!");
Reid Spencer060d25d2004-06-29 23:29:38 +00002075
Reid Spencer5b472d92004-08-21 20:49:23 +00002076 if (Size > 0)
2077 ParseGlobalTypes();
Reid Spencer060d25d2004-06-29 23:29:38 +00002078 SeenGlobalTypePlane = true;
Chris Lattner52e20b02003-03-19 20:54:26 +00002079 break;
2080
Misha Brukman8a96c532005-04-21 21:44:41 +00002081 case BytecodeFormat::ModuleGlobalInfoBlockID:
Reid Spencer46b002c2004-07-11 17:28:43 +00002082 if (SeenModuleGlobalInfo)
Reid Spencer24399722004-07-09 22:21:33 +00002083 error("Two ModuleGlobalInfo Blocks Encountered!");
Reid Spencer060d25d2004-06-29 23:29:38 +00002084 ParseModuleGlobalInfo();
2085 SeenModuleGlobalInfo = true;
Chris Lattner52e20b02003-03-19 20:54:26 +00002086 break;
2087
Reid Spencerad89bd62004-07-25 18:07:36 +00002088 case BytecodeFormat::ConstantPoolBlockID:
Reid Spencer04cde2c2004-07-04 11:33:49 +00002089 ParseConstantPool(ModuleValues, ModuleTypes,false);
Chris Lattner00950542001-06-06 20:29:01 +00002090 break;
2091
Reid Spencerad89bd62004-07-25 18:07:36 +00002092 case BytecodeFormat::FunctionBlockID:
Reid Spencer060d25d2004-06-29 23:29:38 +00002093 ParseFunctionLazily();
Chris Lattner00950542001-06-06 20:29:01 +00002094 break;
Chris Lattner00950542001-06-06 20:29:01 +00002095
Reid Spencer78d033e2007-01-06 07:24:44 +00002096 case BytecodeFormat::ValueSymbolTableBlockID:
2097 ParseValueSymbolTable(0, &TheModule->getValueSymbolTable());
2098 break;
2099
2100 case BytecodeFormat::TypeSymbolTableBlockID:
2101 ParseTypeSymbolTable(&TheModule->getTypeSymbolTable());
Chris Lattner00950542001-06-06 20:29:01 +00002102 break;
Reid Spencer060d25d2004-06-29 23:29:38 +00002103
Chris Lattner00950542001-06-06 20:29:01 +00002104 default:
Reid Spencer060d25d2004-06-29 23:29:38 +00002105 At += Size;
2106 if (OldAt > At) {
Reid Spencer46b002c2004-07-11 17:28:43 +00002107 error("Unexpected Block of Type #" + utostr(Type) + " encountered!");
Reid Spencer060d25d2004-06-29 23:29:38 +00002108 }
Chris Lattner00950542001-06-06 20:29:01 +00002109 break;
2110 }
Reid Spencer060d25d2004-06-29 23:29:38 +00002111 BlockEnd = MyEnd;
Chris Lattner00950542001-06-06 20:29:01 +00002112 }
2113
Chris Lattner52e20b02003-03-19 20:54:26 +00002114 // After the module constant pool has been read, we can safely initialize
2115 // global variables...
2116 while (!GlobalInits.empty()) {
2117 GlobalVariable *GV = GlobalInits.back().first;
2118 unsigned Slot = GlobalInits.back().second;
2119 GlobalInits.pop_back();
2120
2121 // Look up the initializer value...
Chris Lattner29b789b2003-11-19 17:27:18 +00002122 // FIXME: Preserve this type ID!
Reid Spencer060d25d2004-06-29 23:29:38 +00002123
2124 const llvm::PointerType* GVType = GV->getType();
2125 unsigned TypeSlot = getTypeSlot(GVType->getElementType());
Chris Lattner93361992004-01-15 18:45:25 +00002126 if (Constant *CV = getConstantValue(TypeSlot, Slot)) {
Misha Brukman8a96c532005-04-21 21:44:41 +00002127 if (GV->hasInitializer())
Reid Spencer24399722004-07-09 22:21:33 +00002128 error("Global *already* has an initializer?!");
Reid Spencer04cde2c2004-07-04 11:33:49 +00002129 if (Handler) Handler->handleGlobalInitializer(GV,CV);
Chris Lattner93361992004-01-15 18:45:25 +00002130 GV->setInitializer(CV);
Chris Lattner52e20b02003-03-19 20:54:26 +00002131 } else
Reid Spencer24399722004-07-09 22:21:33 +00002132 error("Cannot find initializer value.");
Chris Lattner52e20b02003-03-19 20:54:26 +00002133 }
2134
Chris Lattneraba5ff52005-05-05 20:57:00 +00002135 if (!ConstantFwdRefs.empty())
2136 error("Use of undefined constants in a module");
2137
Reid Spencer060d25d2004-06-29 23:29:38 +00002138 /// Make sure we pulled them all out. If we didn't then there's a declaration
2139 /// but a missing body. That's not allowed.
Misha Brukman12c29d12003-09-22 23:38:23 +00002140 if (!FunctionSignatureList.empty())
Reid Spencer24399722004-07-09 22:21:33 +00002141 error("Function declared, but bytecode stream ended before definition");
Chris Lattner00950542001-06-06 20:29:01 +00002142}
2143
Reid Spencer04cde2c2004-07-04 11:33:49 +00002144/// This function completely parses a bytecode buffer given by the \p Buf
2145/// and \p Length parameters.
Anton Korobeynikov7d515442006-09-01 20:35:17 +00002146bool BytecodeReader::ParseBytecode(volatile BufPtr Buf, unsigned Length,
Reid Spencer233fe722006-08-22 16:09:19 +00002147 const std::string &ModuleID,
2148 std::string* ErrMsg) {
Misha Brukmane0dd0d42003-09-23 16:15:29 +00002149
Reid Spencer233fe722006-08-22 16:09:19 +00002150 /// We handle errors by
2151 if (setjmp(context)) {
2152 // Cleanup after error
2153 if (Handler) Handler->handleError(ErrorMsg);
Reid Spencer060d25d2004-06-29 23:29:38 +00002154 freeState();
Chris Lattner2a7b6ba2003-03-06 17:15:19 +00002155 delete TheModule;
2156 TheModule = 0;
Chris Lattner3bdad692004-11-15 21:55:33 +00002157 if (decompressedBlock != 0 ) {
Reid Spencer61aaf2e2004-11-14 21:59:21 +00002158 ::free(decompressedBlock);
Chris Lattner3bdad692004-11-15 21:55:33 +00002159 decompressedBlock = 0;
2160 }
Reid Spencer233fe722006-08-22 16:09:19 +00002161 // Set caller's error message, if requested
2162 if (ErrMsg)
2163 *ErrMsg = ErrorMsg;
2164 // Indicate an error occurred
2165 return true;
Chris Lattner2a7b6ba2003-03-06 17:15:19 +00002166 }
Reid Spencer233fe722006-08-22 16:09:19 +00002167
2168 RevisionNum = 0;
2169 At = MemStart = BlockStart = Buf;
2170 MemEnd = BlockEnd = Buf + Length;
2171
2172 // Create the module
2173 TheModule = new Module(ModuleID);
2174
2175 if (Handler) Handler->handleStart(TheModule, Length);
2176
2177 // Read the four bytes of the signature.
2178 unsigned Sig = read_uint();
2179
2180 // If this is a compressed file
2181 if (Sig == ('l' | ('l' << 8) | ('v' << 16) | ('c' << 24))) {
2182
2183 // Invoke the decompression of the bytecode. Note that we have to skip the
2184 // file's magic number which is not part of the compressed block. Hence,
2185 // the Buf+4 and Length-4. The result goes into decompressedBlock, a data
2186 // member for retention until BytecodeReader is destructed.
2187 unsigned decompressedLength = Compressor::decompressToNewBuffer(
2188 (char*)Buf+4,Length-4,decompressedBlock);
2189
2190 // We must adjust the buffer pointers used by the bytecode reader to point
2191 // into the new decompressed block. After decompression, the
2192 // decompressedBlock will point to a contiguous memory area that has
2193 // the decompressed data.
2194 At = MemStart = BlockStart = Buf = (BufPtr) decompressedBlock;
2195 MemEnd = BlockEnd = Buf + decompressedLength;
2196
2197 // else if this isn't a regular (uncompressed) bytecode file, then its
2198 // and error, generate that now.
2199 } else if (Sig != ('l' | ('l' << 8) | ('v' << 16) | ('m' << 24))) {
2200 error("Invalid bytecode signature: " + utohexstr(Sig));
2201 }
2202
2203 // Tell the handler we're starting a module
2204 if (Handler) Handler->handleModuleBegin(ModuleID);
2205
2206 // Get the module block and size and verify. This is handled specially
2207 // because the module block/size is always written in long format. Other
2208 // blocks are written in short format so the read_block method is used.
2209 unsigned Type, Size;
2210 Type = read_uint();
2211 Size = read_uint();
2212 if (Type != BytecodeFormat::ModuleBlockID) {
2213 error("Expected Module Block! Type:" + utostr(Type) + ", Size:"
2214 + utostr(Size));
2215 }
2216
2217 // It looks like the darwin ranlib program is broken, and adds trailing
2218 // garbage to the end of some bytecode files. This hack allows the bc
2219 // reader to ignore trailing garbage on bytecode files.
2220 if (At + Size < MemEnd)
2221 MemEnd = BlockEnd = At+Size;
2222
2223 if (At + Size != MemEnd)
2224 error("Invalid Top Level Block Length! Type:" + utostr(Type)
2225 + ", Size:" + utostr(Size));
2226
2227 // Parse the module contents
2228 this->ParseModule();
2229
2230 // Check for missing functions
2231 if (hasFunctions())
2232 error("Function expected, but bytecode stream ended!");
2233
Reid Spencer233fe722006-08-22 16:09:19 +00002234 // Tell the handler we're done with the module
2235 if (Handler)
2236 Handler->handleModuleEnd(ModuleID);
2237
2238 // Tell the handler we're finished the parse
2239 if (Handler) Handler->handleFinish();
2240
2241 return false;
2242
Chris Lattner00950542001-06-06 20:29:01 +00002243}
Reid Spencer060d25d2004-06-29 23:29:38 +00002244
2245//===----------------------------------------------------------------------===//
2246//=== Default Implementations of Handler Methods
2247//===----------------------------------------------------------------------===//
2248
2249BytecodeHandler::~BytecodeHandler() {}
Reid Spencer060d25d2004-06-29 23:29:38 +00002250