blob: 084b4fcade4dd2f785177729d1f3148326c8a22d [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"
Reid Spencer0b118202006-01-16 21:12:35 +000020#include "llvm/Assembly/AutoUpgrade.h"
Reid Spencer060d25d2004-06-29 23:29:38 +000021#include "llvm/Bytecode/BytecodeHandler.h"
22#include "llvm/BasicBlock.h"
Chris Lattnerdee199f2005-05-06 22:34:01 +000023#include "llvm/CallingConv.h"
Reid Spencer060d25d2004-06-29 23:29:38 +000024#include "llvm/Constants.h"
Chris Lattner3bc5a602006-01-25 23:08:15 +000025#include "llvm/InlineAsm.h"
Reid Spencer04cde2c2004-07-04 11:33:49 +000026#include "llvm/Instructions.h"
27#include "llvm/SymbolTable.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),
48 Op(UndefValue::get(Type::IntTy), this) {
49 }
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 Spencerd798a512006-11-14 04:47:22 +0000218/// This method just saves some coding. It uses read_vbr_uint to read
Reid Spencer24399722004-07-09 22:21:33 +0000219/// in a sanitized type id, errors that its not the type type, and
Reid Spencer04cde2c2004-07-04 11:33:49 +0000220/// then calls getType to 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
Reid Spencer1628cec2006-10-26 06:15:43 +0000464// Convert previous opcode values into the current value and/or construct
465// the instruction. This function handles all *abnormal* cases for instruction
466// generation based on obsolete opcode values. The normal cases are handled
467// in ParseInstruction below. Generally this function just produces a new
468// Opcode value (first argument). In a few cases (VAArg, VANext) the upgrade
469// path requies that the instruction (sequence) be generated differently from
470// the normal case in order to preserve the original semantics. In these
471// cases the result of the function will be a non-zero Instruction pointer. In
472// all other cases, zero will be returned indicating that the *normal*
473// instruction generation should be used, but with the new Opcode value.
474//
475Instruction*
Reid Spencer6996feb2006-11-08 21:27:54 +0000476BytecodeReader::upgradeInstrOpcodes(
Reid Spencer1628cec2006-10-26 06:15:43 +0000477 unsigned &Opcode, ///< The old opcode, possibly updated by this function
478 std::vector<unsigned> &Oprnds, ///< The operands to the instruction
479 unsigned &iType, ///< The type code from the bytecode file
480 const Type* InstTy, ///< The type of the instruction
481 BasicBlock* BB ///< The basic block to insert into, if we need to
482) {
483
484 // First, short circuit this if no conversion is required. When signless
Reid Spencer6996feb2006-11-08 21:27:54 +0000485 // instructions were implemented the entire opcode sequence was revised in
486 // two stages: first Div/Rem became signed, then Shr/Cast/Setcc became
487 // signed. If all of these instructions are signed then we don't have to
488 // upgrade the opcode.
489 if (!hasSignlessDivRem && !hasSignlessShrCastSetcc)
Reid Spencer1628cec2006-10-26 06:15:43 +0000490 return 0; // The opcode is fine the way it is.
491
Reid Spencer6996feb2006-11-08 21:27:54 +0000492 // If this is bytecode version 6, that only had signed Rem and Div
493 // instructions, then we must compensate for those two instructions only.
494 // So that the switch statement below works, we're trying to turn this into
495 // a version 5 opcode. To do that we must adjust the opcode to 10 (Div) if its
496 // any of the UDiv, SDiv or FDiv instructions; or, adjust the opcode to
497 // 11 (Rem) if its any of the URem, SRem, or FRem instructions; or, simply
498 // decrement the instruction code if its beyond FRem.
499 if (!hasSignlessDivRem) {
500 // If its one of the signed Div/Rem opcodes, its fine the way it is
501 if (Opcode >= 10 && Opcode <= 12) // UDiv through FDiv
502 Opcode = 10; // Div
503 else if (Opcode >=13 && Opcode <= 15) // URem through FRem
504 Opcode = 11; // Rem
505 else if (Opcode >= 16 && Opcode <= 35) // And through Shr
506 // Adjust for new instruction codes
507 Opcode -= 4;
508 else if (Opcode >= 36 && Opcode <= 42) // Everything after Select
509 // In vers 6 bytecode we eliminated the placeholders for the obsolete
510 // VAARG and VANEXT instructions. Consequently those two slots were
511 // filled starting with Select (36) which was 34. So now we only need
512 // to subtract two. This circumvents hitting opcodes 32 and 33
513 Opcode -= 2;
514 else { // Opcode < 10 or > 42
515 // No upgrade necessary.
516 return 0;
517 }
518 }
519
Reid Spencer1628cec2006-10-26 06:15:43 +0000520 // Declare the resulting instruction we might build. In general we just
521 // change the Opcode argument but in a few cases we need to generate the
522 // Instruction here because the upgrade case is significantly different from
523 // the normal case.
524 Instruction *Result = 0;
525
Reid Spencer1628cec2006-10-26 06:15:43 +0000526 // We're dealing with an upgrade situation. For each of the opcode values,
527 // perform the necessary conversion.
528 switch (Opcode) {
529 default: // Error
530 // This switch statement provides cases for all known opcodes prior to
531 // version 6 bytecode format. We know we're in an upgrade situation so
532 // if there isn't a match in this switch, then something is horribly
533 // wrong.
534 error("Unknown obsolete opcode encountered.");
535 break;
536 case 1: // Ret
537 Opcode = Instruction::Ret;
538 break;
539 case 2: // Br
540 Opcode = Instruction::Br;
541 break;
542 case 3: // Switch
543 Opcode = Instruction::Switch;
544 break;
545 case 4: // Invoke
546 Opcode = Instruction::Invoke;
547 break;
548 case 5: // Unwind
549 Opcode = Instruction::Unwind;
550 break;
551 case 6: // Unreachable
552 Opcode = Instruction::Unreachable;
553 break;
554 case 7: // Add
555 Opcode = Instruction::Add;
556 break;
557 case 8: // Sub
558 Opcode = Instruction::Sub;
559 break;
560 case 9: // Mul
561 Opcode = Instruction::Mul;
562 break;
563 case 10: // Div
564 // The type of the instruction is based on the operands. We need to select
565 // fdiv, udiv or sdiv based on that type. The iType values are hardcoded
566 // to the values used in bytecode version 5 (and prior) because it is
567 // likely these codes will change in future versions of LLVM.
568 if (iType == 10 || iType == 11 )
569 Opcode = Instruction::FDiv;
570 else if (iType >= 2 && iType <= 9 && iType % 2 != 0)
571 Opcode = Instruction::SDiv;
572 else
573 Opcode = Instruction::UDiv;
574 break;
575
576 case 11: // Rem
Reid Spencer0a783f72006-11-02 01:53:59 +0000577 // As with "Div", make the signed/unsigned or floating point Rem
578 // instruction choice based on the type of the operands.
579 if (iType == 10 || iType == 11)
580 Opcode = Instruction::FRem;
581 else if (iType >= 2 && iType <= 9 && iType % 2 != 0)
582 Opcode = Instruction::SRem;
583 else
584 Opcode = Instruction::URem;
Reid Spencer1628cec2006-10-26 06:15:43 +0000585 break;
586 case 12: // And
587 Opcode = Instruction::And;
588 break;
589 case 13: // Or
590 Opcode = Instruction::Or;
591 break;
592 case 14: // Xor
593 Opcode = Instruction::Xor;
594 break;
595 case 15: // SetEQ
596 Opcode = Instruction::SetEQ;
597 break;
598 case 16: // SetNE
599 Opcode = Instruction::SetNE;
600 break;
601 case 17: // SetLE
602 Opcode = Instruction::SetLE;
603 break;
604 case 18: // SetGE
605 Opcode = Instruction::SetGE;
606 break;
607 case 19: // SetLT
608 Opcode = Instruction::SetLT;
609 break;
610 case 20: // SetGT
611 Opcode = Instruction::SetGT;
612 break;
613 case 21: // Malloc
614 Opcode = Instruction::Malloc;
615 break;
616 case 22: // Free
617 Opcode = Instruction::Free;
618 break;
619 case 23: // Alloca
620 Opcode = Instruction::Alloca;
621 break;
622 case 24: // Load
623 Opcode = Instruction::Load;
624 break;
625 case 25: // Store
626 Opcode = Instruction::Store;
627 break;
628 case 26: // GetElementPtr
629 Opcode = Instruction::GetElementPtr;
630 break;
631 case 27: // PHI
632 Opcode = Instruction::PHI;
633 break;
634 case 28: // Cast
635 Opcode = Instruction::Cast;
636 break;
637 case 29: // Call
638 Opcode = Instruction::Call;
639 break;
640 case 30: // Shl
641 Opcode = Instruction::Shl;
642 break;
643 case 31: // Shr
Reid Spencer3822ff52006-11-08 06:47:33 +0000644 // The type of the instruction is based on the operands. We need to
645 // select ashr or lshr based on that type. The iType values are hardcoded
646 // to the values used in bytecode version 5 (and prior) because it is
647 // likely these codes will change in future versions of LLVM. This if
648 // statement says "if (integer type and signed)"
649 if (iType >= 2 && iType <= 9 && iType % 2 != 0)
650 Opcode = Instruction::AShr;
651 else
652 Opcode = Instruction::LShr;
Reid Spencer1628cec2006-10-26 06:15:43 +0000653 break;
654 case 32: { //VANext_old ( <= llvm 1.5 )
655 const Type* ArgTy = getValue(iType, Oprnds[0])->getType();
656 Function* NF = TheModule->getOrInsertFunction(
657 "llvm.va_copy", ArgTy, ArgTy, (Type *)0);
658
659 // In llvm 1.6 the VANext instruction was dropped because it was only
660 // necessary to have a VAArg instruction. The code below transforms an
661 // old vanext instruction into the equivalent code given only the
662 // availability of the new vaarg instruction. Essentially, the transform
663 // is as follows:
664 // b = vanext a, t ->
665 // foo = alloca 1 of t
666 // bar = vacopy a
667 // store bar -> foo
668 // tmp = vaarg foo, t
669 // b = load foo
670 AllocaInst* foo = new AllocaInst(ArgTy, 0, "vanext.fix");
671 BB->getInstList().push_back(foo);
672 CallInst* bar = new CallInst(NF, getValue(iType, Oprnds[0]));
673 BB->getInstList().push_back(bar);
674 BB->getInstList().push_back(new StoreInst(bar, foo));
Reid Spencerd798a512006-11-14 04:47:22 +0000675 Instruction* tmp = new VAArgInst(foo, getType(Oprnds[1]));
Reid Spencer1628cec2006-10-26 06:15:43 +0000676 BB->getInstList().push_back(tmp);
677 Result = new LoadInst(foo);
678 break;
679 }
680 case 33: { //VAArg_old
681 const Type* ArgTy = getValue(iType, Oprnds[0])->getType();
682 Function* NF = TheModule->getOrInsertFunction(
683 "llvm.va_copy", ArgTy, ArgTy, (Type *)0);
684
685 // In llvm 1.6 the VAArg's instruction semantics were changed. The code
686 // below transforms an old vaarg instruction into the equivalent code
687 // given only the availability of the new vaarg instruction. Essentially,
688 // the transform is as follows:
689 // b = vaarg a, t ->
690 // foo = alloca 1 of t
691 // bar = vacopy a
692 // store bar -> foo
693 // b = vaarg foo, t
694 AllocaInst* foo = new AllocaInst(ArgTy, 0, "vaarg.fix");
695 BB->getInstList().push_back(foo);
696 CallInst* bar = new CallInst(NF, getValue(iType, Oprnds[0]));
697 BB->getInstList().push_back(bar);
698 BB->getInstList().push_back(new StoreInst(bar, foo));
Reid Spencerd798a512006-11-14 04:47:22 +0000699 Result = new VAArgInst(foo, getType(Oprnds[1]));
Reid Spencer1628cec2006-10-26 06:15:43 +0000700 break;
701 }
702 case 34: // Select
703 Opcode = Instruction::Select;
704 break;
705 case 35: // UserOp1
706 Opcode = Instruction::UserOp1;
707 break;
708 case 36: // UserOp2
709 Opcode = Instruction::UserOp2;
710 break;
711 case 37: // VAArg
712 Opcode = Instruction::VAArg;
713 break;
714 case 38: // ExtractElement
715 Opcode = Instruction::ExtractElement;
716 break;
717 case 39: // InsertElement
718 Opcode = Instruction::InsertElement;
719 break;
720 case 40: // ShuffleVector
721 Opcode = Instruction::ShuffleVector;
722 break;
723 case 56: // Invoke with encoded CC
724 case 57: // Invoke Fast CC
725 case 58: // Call with extra operand for calling conv
726 case 59: // tail call, Fast CC
727 case 60: // normal call, Fast CC
728 case 61: // tail call, C Calling Conv
729 case 62: // volatile load
730 case 63: // volatile store
731 // In all these cases, we pass the opcode through. The new version uses
732 // the same code (for now, this might change in 2.0). These are listed
733 // here to document the opcodes in use in vers 5 bytecode and to make it
734 // easier to migrate these opcodes in the future.
735 break;
736 }
737 return Result;
738}
739
Reid Spencer060d25d2004-06-29 23:29:38 +0000740//===----------------------------------------------------------------------===//
741// Bytecode Parsing Methods
742//===----------------------------------------------------------------------===//
743
Reid Spencer04cde2c2004-07-04 11:33:49 +0000744/// This method parses a single instruction. The instruction is
745/// inserted at the end of the \p BB provided. The arguments of
Misha Brukman44666b12004-09-28 16:57:46 +0000746/// the instruction are provided in the \p Oprnds vector.
Reid Spencer060d25d2004-06-29 23:29:38 +0000747void BytecodeReader::ParseInstruction(std::vector<unsigned> &Oprnds,
Reid Spencer46b002c2004-07-11 17:28:43 +0000748 BasicBlock* BB) {
Reid Spencer060d25d2004-06-29 23:29:38 +0000749 BufPtr SaveAt = At;
750
751 // Clear instruction data
752 Oprnds.clear();
753 unsigned iType = 0;
754 unsigned Opcode = 0;
755 unsigned Op = read_uint();
756
757 // bits Instruction format: Common to all formats
758 // --------------------------
759 // 01-00: Opcode type, fixed to 1.
760 // 07-02: Opcode
761 Opcode = (Op >> 2) & 63;
762 Oprnds.resize((Op >> 0) & 03);
763
764 // Extract the operands
765 switch (Oprnds.size()) {
766 case 1:
767 // bits Instruction format:
768 // --------------------------
769 // 19-08: Resulting type plane
770 // 31-20: Operand #1 (if set to (2^12-1), then zero operands)
771 //
772 iType = (Op >> 8) & 4095;
773 Oprnds[0] = (Op >> 20) & 4095;
774 if (Oprnds[0] == 4095) // Handle special encoding for 0 operands...
775 Oprnds.resize(0);
776 break;
777 case 2:
778 // bits Instruction format:
779 // --------------------------
780 // 15-08: Resulting type plane
781 // 23-16: Operand #1
Misha Brukman8a96c532005-04-21 21:44:41 +0000782 // 31-24: Operand #2
Reid Spencer060d25d2004-06-29 23:29:38 +0000783 //
784 iType = (Op >> 8) & 255;
785 Oprnds[0] = (Op >> 16) & 255;
786 Oprnds[1] = (Op >> 24) & 255;
787 break;
788 case 3:
789 // bits Instruction format:
790 // --------------------------
791 // 13-08: Resulting type plane
792 // 19-14: Operand #1
793 // 25-20: Operand #2
794 // 31-26: Operand #3
795 //
796 iType = (Op >> 8) & 63;
797 Oprnds[0] = (Op >> 14) & 63;
798 Oprnds[1] = (Op >> 20) & 63;
799 Oprnds[2] = (Op >> 26) & 63;
800 break;
801 case 0:
802 At -= 4; // Hrm, try this again...
803 Opcode = read_vbr_uint();
804 Opcode >>= 2;
805 iType = read_vbr_uint();
806
807 unsigned NumOprnds = read_vbr_uint();
808 Oprnds.resize(NumOprnds);
809
810 if (NumOprnds == 0)
Reid Spencer24399722004-07-09 22:21:33 +0000811 error("Zero-argument instruction found; this is invalid.");
Reid Spencer060d25d2004-06-29 23:29:38 +0000812
813 for (unsigned i = 0; i != NumOprnds; ++i)
814 Oprnds[i] = read_vbr_uint();
Reid Spencer060d25d2004-06-29 23:29:38 +0000815 break;
816 }
817
Reid Spencerd798a512006-11-14 04:47:22 +0000818 const Type *InstTy = getType(iType);
Reid Spencer060d25d2004-06-29 23:29:38 +0000819
Reid Spencer1628cec2006-10-26 06:15:43 +0000820 // Make the necessary adjustments for dealing with backwards compatibility
821 // of opcodes.
822 Instruction* Result =
Reid Spencer6996feb2006-11-08 21:27:54 +0000823 upgradeInstrOpcodes(Opcode, Oprnds, iType, InstTy, BB);
Reid Spencer1628cec2006-10-26 06:15:43 +0000824
Reid Spencer46b002c2004-07-11 17:28:43 +0000825 // We have enough info to inform the handler now.
Reid Spencer1628cec2006-10-26 06:15:43 +0000826 if (Handler)
827 Handler->handleInstruction(Opcode, InstTy, Oprnds, At-SaveAt);
Reid Spencer060d25d2004-06-29 23:29:38 +0000828
Reid Spencer1628cec2006-10-26 06:15:43 +0000829 // If the backwards compatibility code didn't produce an instruction then
830 // we do the *normal* thing ..
831 if (!Result) {
832 // First, handle the easy binary operators case
833 if (Opcode >= Instruction::BinaryOpsBegin &&
834 Opcode < Instruction::BinaryOpsEnd && Oprnds.size() == 2)
835 Result = BinaryOperator::create(Instruction::BinaryOps(Opcode),
836 getValue(iType, Oprnds[0]),
837 getValue(iType, Oprnds[1]));
Reid Spencer060d25d2004-06-29 23:29:38 +0000838
Reid Spencer1628cec2006-10-26 06:15:43 +0000839 // Indicate that we don't think this is a call instruction (yet).
840 // Process based on the Opcode read
841 switch (Opcode) {
842 default: // There was an error, this shouldn't happen.
843 if (Result == 0)
844 error("Illegal instruction read!");
845 break;
846 case Instruction::VAArg:
847 if (Oprnds.size() != 2)
848 error("Invalid VAArg instruction!");
849 Result = new VAArgInst(getValue(iType, Oprnds[0]),
Reid Spencerd798a512006-11-14 04:47:22 +0000850 getType(Oprnds[1]));
Reid Spencer1628cec2006-10-26 06:15:43 +0000851 break;
852 case Instruction::ExtractElement: {
853 if (Oprnds.size() != 2)
854 error("Invalid extractelement instruction!");
855 Value *V1 = getValue(iType, Oprnds[0]);
856 Value *V2 = getValue(Type::UIntTyID, Oprnds[1]);
Chris Lattner59fecec2006-04-08 04:09:19 +0000857
Reid Spencer1628cec2006-10-26 06:15:43 +0000858 if (!ExtractElementInst::isValidOperands(V1, V2))
859 error("Invalid extractelement instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000860
Reid Spencer1628cec2006-10-26 06:15:43 +0000861 Result = new ExtractElementInst(V1, V2);
862 break;
Chris Lattnera65371e2006-05-26 18:42:34 +0000863 }
Reid Spencer1628cec2006-10-26 06:15:43 +0000864 case Instruction::InsertElement: {
865 const PackedType *PackedTy = dyn_cast<PackedType>(InstTy);
866 if (!PackedTy || Oprnds.size() != 3)
867 error("Invalid insertelement instruction!");
868
869 Value *V1 = getValue(iType, Oprnds[0]);
870 Value *V2 = getValue(getTypeSlot(PackedTy->getElementType()),Oprnds[1]);
871 Value *V3 = getValue(Type::UIntTyID, Oprnds[2]);
872
873 if (!InsertElementInst::isValidOperands(V1, V2, V3))
874 error("Invalid insertelement instruction!");
875 Result = new InsertElementInst(V1, V2, V3);
876 break;
877 }
878 case Instruction::ShuffleVector: {
879 const PackedType *PackedTy = dyn_cast<PackedType>(InstTy);
880 if (!PackedTy || Oprnds.size() != 3)
881 error("Invalid shufflevector instruction!");
882 Value *V1 = getValue(iType, Oprnds[0]);
883 Value *V2 = getValue(iType, Oprnds[1]);
884 const PackedType *EltTy =
885 PackedType::get(Type::UIntTy, PackedTy->getNumElements());
886 Value *V3 = getValue(getTypeSlot(EltTy), Oprnds[2]);
887 if (!ShuffleVectorInst::isValidOperands(V1, V2, V3))
888 error("Invalid shufflevector instruction!");
889 Result = new ShuffleVectorInst(V1, V2, V3);
890 break;
891 }
892 case Instruction::Cast:
893 if (Oprnds.size() != 2)
894 error("Invalid Cast instruction!");
895 Result = new CastInst(getValue(iType, Oprnds[0]),
Reid Spencerd798a512006-11-14 04:47:22 +0000896 getType(Oprnds[1]));
Reid Spencer1628cec2006-10-26 06:15:43 +0000897 break;
898 case Instruction::Select:
899 if (Oprnds.size() != 3)
900 error("Invalid Select instruction!");
901 Result = new SelectInst(getValue(Type::BoolTyID, Oprnds[0]),
902 getValue(iType, Oprnds[1]),
903 getValue(iType, Oprnds[2]));
904 break;
905 case Instruction::PHI: {
906 if (Oprnds.size() == 0 || (Oprnds.size() & 1))
907 error("Invalid phi node encountered!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000908
Reid Spencer1628cec2006-10-26 06:15:43 +0000909 PHINode *PN = new PHINode(InstTy);
910 PN->reserveOperandSpace(Oprnds.size());
911 for (unsigned i = 0, e = Oprnds.size(); i != e; i += 2)
912 PN->addIncoming(
913 getValue(iType, Oprnds[i]), getBasicBlock(Oprnds[i+1]));
914 Result = PN;
915 break;
916 }
Reid Spencer060d25d2004-06-29 23:29:38 +0000917
Reid Spencer1628cec2006-10-26 06:15:43 +0000918 case Instruction::Shl:
Reid Spencer3822ff52006-11-08 06:47:33 +0000919 case Instruction::LShr:
920 case Instruction::AShr:
Reid Spencer1628cec2006-10-26 06:15:43 +0000921 Result = new ShiftInst(Instruction::OtherOps(Opcode),
922 getValue(iType, Oprnds[0]),
923 getValue(Type::UByteTyID, Oprnds[1]));
924 break;
925 case Instruction::Ret:
926 if (Oprnds.size() == 0)
927 Result = new ReturnInst();
928 else if (Oprnds.size() == 1)
929 Result = new ReturnInst(getValue(iType, Oprnds[0]));
930 else
931 error("Unrecognized instruction!");
932 break;
933
934 case Instruction::Br:
935 if (Oprnds.size() == 1)
936 Result = new BranchInst(getBasicBlock(Oprnds[0]));
937 else if (Oprnds.size() == 3)
938 Result = new BranchInst(getBasicBlock(Oprnds[0]),
939 getBasicBlock(Oprnds[1]), getValue(Type::BoolTyID , Oprnds[2]));
940 else
941 error("Invalid number of operands for a 'br' instruction!");
942 break;
943 case Instruction::Switch: {
944 if (Oprnds.size() & 1)
945 error("Switch statement with odd number of arguments!");
946
947 SwitchInst *I = new SwitchInst(getValue(iType, Oprnds[0]),
948 getBasicBlock(Oprnds[1]),
949 Oprnds.size()/2-1);
950 for (unsigned i = 2, e = Oprnds.size(); i != e; i += 2)
951 I->addCase(cast<ConstantInt>(getValue(iType, Oprnds[i])),
952 getBasicBlock(Oprnds[i+1]));
953 Result = I;
954 break;
955 }
956 case 58: // Call with extra operand for calling conv
957 case 59: // tail call, Fast CC
958 case 60: // normal call, Fast CC
959 case 61: // tail call, C Calling Conv
960 case Instruction::Call: { // Normal Call, C Calling Convention
961 if (Oprnds.size() == 0)
962 error("Invalid call instruction encountered!");
963
964 Value *F = getValue(iType, Oprnds[0]);
965
966 unsigned CallingConv = CallingConv::C;
967 bool isTailCall = false;
968
969 if (Opcode == 61 || Opcode == 59)
970 isTailCall = true;
971
972 if (Opcode == 58) {
973 isTailCall = Oprnds.back() & 1;
974 CallingConv = Oprnds.back() >> 1;
975 Oprnds.pop_back();
976 } else if (Opcode == 59 || Opcode == 60) {
977 CallingConv = CallingConv::Fast;
978 }
979
980 // Check to make sure we have a pointer to function type
981 const PointerType *PTy = dyn_cast<PointerType>(F->getType());
982 if (PTy == 0) error("Call to non function pointer value!");
983 const FunctionType *FTy = dyn_cast<FunctionType>(PTy->getElementType());
984 if (FTy == 0) error("Call to non function pointer value!");
985
986 std::vector<Value *> Params;
987 if (!FTy->isVarArg()) {
988 FunctionType::param_iterator It = FTy->param_begin();
989
990 for (unsigned i = 1, e = Oprnds.size(); i != e; ++i) {
991 if (It == FTy->param_end())
992 error("Invalid call instruction!");
993 Params.push_back(getValue(getTypeSlot(*It++), Oprnds[i]));
994 }
995 if (It != FTy->param_end())
Reid Spencer24399722004-07-09 22:21:33 +0000996 error("Invalid call instruction!");
Reid Spencer1628cec2006-10-26 06:15:43 +0000997 } else {
998 Oprnds.erase(Oprnds.begin(), Oprnds.begin()+1);
999
1000 unsigned FirstVariableOperand;
1001 if (Oprnds.size() < FTy->getNumParams())
1002 error("Call instruction missing operands!");
1003
1004 // Read all of the fixed arguments
1005 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
1006 Params.push_back(
1007 getValue(getTypeSlot(FTy->getParamType(i)),Oprnds[i]));
1008
1009 FirstVariableOperand = FTy->getNumParams();
1010
1011 if ((Oprnds.size()-FirstVariableOperand) & 1)
1012 error("Invalid call instruction!"); // Must be pairs of type/value
1013
1014 for (unsigned i = FirstVariableOperand, e = Oprnds.size();
1015 i != e; i += 2)
1016 Params.push_back(getValue(Oprnds[i], Oprnds[i+1]));
Reid Spencer060d25d2004-06-29 23:29:38 +00001017 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001018
Reid Spencer1628cec2006-10-26 06:15:43 +00001019 Result = new CallInst(F, Params);
1020 if (isTailCall) cast<CallInst>(Result)->setTailCall();
1021 if (CallingConv) cast<CallInst>(Result)->setCallingConv(CallingConv);
1022 break;
Reid Spencer060d25d2004-06-29 23:29:38 +00001023 }
Reid Spencer1628cec2006-10-26 06:15:43 +00001024 case 56: // Invoke with encoded CC
1025 case 57: // Invoke Fast CC
1026 case Instruction::Invoke: { // Invoke C CC
1027 if (Oprnds.size() < 3)
1028 error("Invalid invoke instruction!");
1029 Value *F = getValue(iType, Oprnds[0]);
Reid Spencer060d25d2004-06-29 23:29:38 +00001030
Reid Spencer1628cec2006-10-26 06:15:43 +00001031 // Check to make sure we have a pointer to function type
1032 const PointerType *PTy = dyn_cast<PointerType>(F->getType());
1033 if (PTy == 0)
1034 error("Invoke to non function pointer value!");
1035 const FunctionType *FTy = dyn_cast<FunctionType>(PTy->getElementType());
1036 if (FTy == 0)
1037 error("Invoke to non function pointer value!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001038
Reid Spencer1628cec2006-10-26 06:15:43 +00001039 std::vector<Value *> Params;
1040 BasicBlock *Normal, *Except;
1041 unsigned CallingConv = CallingConv::C;
Reid Spencer060d25d2004-06-29 23:29:38 +00001042
Reid Spencer1628cec2006-10-26 06:15:43 +00001043 if (Opcode == 57)
1044 CallingConv = CallingConv::Fast;
1045 else if (Opcode == 56) {
1046 CallingConv = Oprnds.back();
1047 Oprnds.pop_back();
1048 }
Chris Lattnerdee199f2005-05-06 22:34:01 +00001049
Reid Spencer1628cec2006-10-26 06:15:43 +00001050 if (!FTy->isVarArg()) {
1051 Normal = getBasicBlock(Oprnds[1]);
1052 Except = getBasicBlock(Oprnds[2]);
Reid Spencer060d25d2004-06-29 23:29:38 +00001053
Reid Spencer1628cec2006-10-26 06:15:43 +00001054 FunctionType::param_iterator It = FTy->param_begin();
1055 for (unsigned i = 3, e = Oprnds.size(); i != e; ++i) {
1056 if (It == FTy->param_end())
1057 error("Invalid invoke instruction!");
1058 Params.push_back(getValue(getTypeSlot(*It++), Oprnds[i]));
1059 }
1060 if (It != FTy->param_end())
Reid Spencer24399722004-07-09 22:21:33 +00001061 error("Invalid invoke instruction!");
Reid Spencer1628cec2006-10-26 06:15:43 +00001062 } else {
1063 Oprnds.erase(Oprnds.begin(), Oprnds.begin()+1);
1064
1065 Normal = getBasicBlock(Oprnds[0]);
1066 Except = getBasicBlock(Oprnds[1]);
1067
1068 unsigned FirstVariableArgument = FTy->getNumParams()+2;
1069 for (unsigned i = 2; i != FirstVariableArgument; ++i)
1070 Params.push_back(getValue(getTypeSlot(FTy->getParamType(i-2)),
1071 Oprnds[i]));
1072
1073 // Must be type/value pairs. If not, error out.
1074 if (Oprnds.size()-FirstVariableArgument & 1)
1075 error("Invalid invoke instruction!");
1076
1077 for (unsigned i = FirstVariableArgument; i < Oprnds.size(); i += 2)
1078 Params.push_back(getValue(Oprnds[i], Oprnds[i+1]));
Reid Spencer060d25d2004-06-29 23:29:38 +00001079 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001080
Reid Spencer1628cec2006-10-26 06:15:43 +00001081 Result = new InvokeInst(F, Normal, Except, Params);
1082 if (CallingConv) cast<InvokeInst>(Result)->setCallingConv(CallingConv);
1083 break;
Reid Spencer060d25d2004-06-29 23:29:38 +00001084 }
Reid Spencer1628cec2006-10-26 06:15:43 +00001085 case Instruction::Malloc: {
1086 unsigned Align = 0;
1087 if (Oprnds.size() == 2)
1088 Align = (1 << Oprnds[1]) >> 1;
1089 else if (Oprnds.size() > 2)
1090 error("Invalid malloc instruction!");
1091 if (!isa<PointerType>(InstTy))
1092 error("Invalid malloc instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001093
Reid Spencer1628cec2006-10-26 06:15:43 +00001094 Result = new MallocInst(cast<PointerType>(InstTy)->getElementType(),
1095 getValue(Type::UIntTyID, Oprnds[0]), Align);
1096 break;
1097 }
1098 case Instruction::Alloca: {
1099 unsigned Align = 0;
1100 if (Oprnds.size() == 2)
1101 Align = (1 << Oprnds[1]) >> 1;
1102 else if (Oprnds.size() > 2)
1103 error("Invalid alloca instruction!");
1104 if (!isa<PointerType>(InstTy))
1105 error("Invalid alloca instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001106
Reid Spencer1628cec2006-10-26 06:15:43 +00001107 Result = new AllocaInst(cast<PointerType>(InstTy)->getElementType(),
1108 getValue(Type::UIntTyID, Oprnds[0]), Align);
1109 break;
1110 }
1111 case Instruction::Free:
1112 if (!isa<PointerType>(InstTy))
1113 error("Invalid free instruction!");
1114 Result = new FreeInst(getValue(iType, Oprnds[0]));
1115 break;
1116 case Instruction::GetElementPtr: {
1117 if (Oprnds.size() == 0 || !isa<PointerType>(InstTy))
Misha Brukman8a96c532005-04-21 21:44:41 +00001118 error("Invalid getelementptr instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001119
Reid Spencer1628cec2006-10-26 06:15:43 +00001120 std::vector<Value*> Idx;
1121
1122 const Type *NextTy = InstTy;
1123 for (unsigned i = 1, e = Oprnds.size(); i != e; ++i) {
1124 const CompositeType *TopTy = dyn_cast_or_null<CompositeType>(NextTy);
1125 if (!TopTy)
1126 error("Invalid getelementptr instruction!");
1127
1128 unsigned ValIdx = Oprnds[i];
1129 unsigned IdxTy = 0;
Reid Spencerd798a512006-11-14 04:47:22 +00001130 // Struct indices are always uints, sequential type indices can be
1131 // any of the 32 or 64-bit integer types. The actual choice of
1132 // type is encoded in the low two bits of the slot number.
1133 if (isa<StructType>(TopTy))
1134 IdxTy = Type::UIntTyID;
1135 else {
1136 switch (ValIdx & 3) {
1137 default:
1138 case 0: IdxTy = Type::UIntTyID; break;
1139 case 1: IdxTy = Type::IntTyID; break;
1140 case 2: IdxTy = Type::ULongTyID; break;
1141 case 3: IdxTy = Type::LongTyID; break;
Reid Spencer060d25d2004-06-29 23:29:38 +00001142 }
Reid Spencerd798a512006-11-14 04:47:22 +00001143 ValIdx >>= 2;
Reid Spencer060d25d2004-06-29 23:29:38 +00001144 }
Reid Spencer1628cec2006-10-26 06:15:43 +00001145 Idx.push_back(getValue(IdxTy, ValIdx));
Reid Spencer1628cec2006-10-26 06:15:43 +00001146 NextTy = GetElementPtrInst::getIndexedType(InstTy, Idx, true);
Reid Spencer060d25d2004-06-29 23:29:38 +00001147 }
1148
Reid Spencer1628cec2006-10-26 06:15:43 +00001149 Result = new GetElementPtrInst(getValue(iType, Oprnds[0]), Idx);
1150 break;
Reid Spencer060d25d2004-06-29 23:29:38 +00001151 }
Reid Spencer1628cec2006-10-26 06:15:43 +00001152 case 62: // volatile load
1153 case Instruction::Load:
1154 if (Oprnds.size() != 1 || !isa<PointerType>(InstTy))
1155 error("Invalid load instruction!");
1156 Result = new LoadInst(getValue(iType, Oprnds[0]), "", Opcode == 62);
1157 break;
1158 case 63: // volatile store
1159 case Instruction::Store: {
1160 if (!isa<PointerType>(InstTy) || Oprnds.size() != 2)
1161 error("Invalid store instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001162
Reid Spencer1628cec2006-10-26 06:15:43 +00001163 Value *Ptr = getValue(iType, Oprnds[1]);
1164 const Type *ValTy = cast<PointerType>(Ptr->getType())->getElementType();
1165 Result = new StoreInst(getValue(getTypeSlot(ValTy), Oprnds[0]), Ptr,
1166 Opcode == 63);
1167 break;
1168 }
1169 case Instruction::Unwind:
1170 if (Oprnds.size() != 0) error("Invalid unwind instruction!");
1171 Result = new UnwindInst();
1172 break;
1173 case Instruction::Unreachable:
1174 if (Oprnds.size() != 0) error("Invalid unreachable instruction!");
1175 Result = new UnreachableInst();
1176 break;
1177 } // end switch(Opcode)
1178 } // end if *normal*
Reid Spencer060d25d2004-06-29 23:29:38 +00001179
Reid Spencere1e96c02006-01-19 07:02:16 +00001180 BB->getInstList().push_back(Result);
1181
Reid Spencer060d25d2004-06-29 23:29:38 +00001182 unsigned TypeSlot;
1183 if (Result->getType() == InstTy)
1184 TypeSlot = iType;
1185 else
1186 TypeSlot = getTypeSlot(Result->getType());
1187
1188 insertValue(Result, TypeSlot, FunctionValues);
Reid Spencer060d25d2004-06-29 23:29:38 +00001189}
1190
Reid Spencer04cde2c2004-07-04 11:33:49 +00001191/// Get a particular numbered basic block, which might be a forward reference.
Reid Spencerd798a512006-11-14 04:47:22 +00001192/// This works together with ParseInstructionList to handle these forward
1193/// references in a clean manner. This function is used when constructing
1194/// phi, br, switch, and other instructions that reference basic blocks.
1195/// Blocks are numbered sequentially as they appear in the function.
Reid Spencer060d25d2004-06-29 23:29:38 +00001196BasicBlock *BytecodeReader::getBasicBlock(unsigned ID) {
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001197 // Make sure there is room in the table...
1198 if (ParsedBasicBlocks.size() <= ID) ParsedBasicBlocks.resize(ID+1);
1199
Reid Spencerd798a512006-11-14 04:47:22 +00001200 // First check to see if this is a backwards reference, i.e. this block
1201 // has already been created, or if the forward reference has already
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001202 // been created.
1203 if (ParsedBasicBlocks[ID])
1204 return ParsedBasicBlocks[ID];
1205
1206 // Otherwise, the basic block has not yet been created. Do so and add it to
1207 // the ParsedBasicBlocks list.
1208 return ParsedBasicBlocks[ID] = new BasicBlock();
1209}
1210
Reid Spencer04cde2c2004-07-04 11:33:49 +00001211/// Parse all of the BasicBlock's & Instruction's in the body of a function.
Misha Brukman8a96c532005-04-21 21:44:41 +00001212/// In post 1.0 bytecode files, we no longer emit basic block individually,
Reid Spencer04cde2c2004-07-04 11:33:49 +00001213/// in order to avoid per-basic-block overhead.
Reid Spencerd798a512006-11-14 04:47:22 +00001214/// @returns the number of basic blocks encountered.
Reid Spencer060d25d2004-06-29 23:29:38 +00001215unsigned BytecodeReader::ParseInstructionList(Function* F) {
Chris Lattner8d1dbd22003-12-01 07:05:31 +00001216 unsigned BlockNo = 0;
1217 std::vector<unsigned> Args;
1218
Reid Spencer46b002c2004-07-11 17:28:43 +00001219 while (moreInBlock()) {
1220 if (Handler) Handler->handleBasicBlockBegin(BlockNo);
Chris Lattner8d1dbd22003-12-01 07:05:31 +00001221 BasicBlock *BB;
1222 if (ParsedBasicBlocks.size() == BlockNo)
1223 ParsedBasicBlocks.push_back(BB = new BasicBlock());
1224 else if (ParsedBasicBlocks[BlockNo] == 0)
1225 BB = ParsedBasicBlocks[BlockNo] = new BasicBlock();
1226 else
1227 BB = ParsedBasicBlocks[BlockNo];
1228 ++BlockNo;
1229 F->getBasicBlockList().push_back(BB);
1230
1231 // Read instructions into this basic block until we get to a terminator
Reid Spencer46b002c2004-07-11 17:28:43 +00001232 while (moreInBlock() && !BB->getTerminator())
Reid Spencer060d25d2004-06-29 23:29:38 +00001233 ParseInstruction(Args, BB);
Chris Lattner8d1dbd22003-12-01 07:05:31 +00001234
1235 if (!BB->getTerminator())
Reid Spencer24399722004-07-09 22:21:33 +00001236 error("Non-terminated basic block found!");
Reid Spencer5c15fe52004-07-05 00:57:50 +00001237
Reid Spencer46b002c2004-07-11 17:28:43 +00001238 if (Handler) Handler->handleBasicBlockEnd(BlockNo-1);
Chris Lattner8d1dbd22003-12-01 07:05:31 +00001239 }
1240
1241 return BlockNo;
1242}
1243
Reid Spencer04cde2c2004-07-04 11:33:49 +00001244/// Parse a symbol table. This works for both module level and function
1245/// level symbol tables. For function level symbol tables, the CurrentFunction
1246/// parameter must be non-zero and the ST parameter must correspond to
1247/// CurrentFunction's symbol table. For Module level symbol tables, the
1248/// CurrentFunction argument must be zero.
Reid Spencer060d25d2004-06-29 23:29:38 +00001249void BytecodeReader::ParseSymbolTable(Function *CurrentFunction,
Reid Spencer04cde2c2004-07-04 11:33:49 +00001250 SymbolTable *ST) {
1251 if (Handler) Handler->handleSymbolTableBegin(CurrentFunction,ST);
Reid Spencer060d25d2004-06-29 23:29:38 +00001252
Chris Lattner39cacce2003-10-10 05:43:47 +00001253 // Allow efficient basic block lookup by number.
1254 std::vector<BasicBlock*> BBMap;
1255 if (CurrentFunction)
1256 for (Function::iterator I = CurrentFunction->begin(),
1257 E = CurrentFunction->end(); I != E; ++I)
1258 BBMap.push_back(I);
1259
Reid Spencerd798a512006-11-14 04:47:22 +00001260 // Symtab block header: [num entries]
1261 unsigned NumEntries = read_vbr_uint();
1262 for (unsigned i = 0; i < NumEntries; ++i) {
1263 // Symtab entry: [def slot #][name]
1264 unsigned slot = read_vbr_uint();
1265 std::string Name = read_str();
1266 const Type* T = getType(slot);
1267 ST->insert(Name, T);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001268 }
1269
Reid Spencer46b002c2004-07-11 17:28:43 +00001270 while (moreInBlock()) {
Chris Lattner00950542001-06-06 20:29:01 +00001271 // Symtab block header: [num entries][type id number]
Reid Spencer060d25d2004-06-29 23:29:38 +00001272 unsigned NumEntries = read_vbr_uint();
Reid Spencerd798a512006-11-14 04:47:22 +00001273 unsigned Typ = read_vbr_uint();
Chris Lattner1d670cc2001-09-07 16:37:43 +00001274
Chris Lattner7dc3a2e2003-10-13 14:57:53 +00001275 for (unsigned i = 0; i != NumEntries; ++i) {
Chris Lattner00950542001-06-06 20:29:01 +00001276 // Symtab entry: [def slot #][name]
Reid Spencer060d25d2004-06-29 23:29:38 +00001277 unsigned slot = read_vbr_uint();
1278 std::string Name = read_str();
Reid Spencerd798a512006-11-14 04:47:22 +00001279 Value *V = 0;
1280 if (Typ == Type::LabelTyID) {
1281 if (slot < BBMap.size())
1282 V = BBMap[slot];
Chris Lattner39cacce2003-10-10 05:43:47 +00001283 } else {
Reid Spencerd798a512006-11-14 04:47:22 +00001284 V = getValue(Typ, slot, false); // Find mapping...
Chris Lattner39cacce2003-10-10 05:43:47 +00001285 }
Reid Spencerd798a512006-11-14 04:47:22 +00001286 if (V == 0)
1287 error("Failed value look-up for name '" + Name + "'");
1288 V->setName(Name);
Chris Lattner00950542001-06-06 20:29:01 +00001289 }
1290 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001291 checkPastBlockEnd("Symbol Table");
Reid Spencer04cde2c2004-07-04 11:33:49 +00001292 if (Handler) Handler->handleSymbolTableEnd();
Chris Lattner00950542001-06-06 20:29:01 +00001293}
1294
Misha Brukman8a96c532005-04-21 21:44:41 +00001295/// Read in the types portion of a compaction table.
Reid Spencer46b002c2004-07-11 17:28:43 +00001296void BytecodeReader::ParseCompactionTypes(unsigned NumEntries) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001297 for (unsigned i = 0; i != NumEntries; ++i) {
Reid Spencerd798a512006-11-14 04:47:22 +00001298 unsigned TypeSlot = read_vbr_uint();
Reid Spencer04cde2c2004-07-04 11:33:49 +00001299 const Type *Typ = getGlobalTableType(TypeSlot);
Chris Lattner45b5dd22004-08-03 23:41:28 +00001300 CompactionTypes.push_back(std::make_pair(Typ, TypeSlot));
Reid Spencer46b002c2004-07-11 17:28:43 +00001301 if (Handler) Handler->handleCompactionTableType(i, TypeSlot, Typ);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001302 }
1303}
1304
1305/// Parse a compaction table.
Reid Spencer060d25d2004-06-29 23:29:38 +00001306void BytecodeReader::ParseCompactionTable() {
1307
Reid Spencer46b002c2004-07-11 17:28:43 +00001308 // Notify handler that we're beginning a compaction table.
Reid Spencer04cde2c2004-07-04 11:33:49 +00001309 if (Handler) Handler->handleCompactionTableBegin();
1310
Reid Spencerd798a512006-11-14 04:47:22 +00001311 // Get the types for the compaction table.
1312 unsigned NumEntries = read_vbr_uint();
1313 ParseCompactionTypes(NumEntries);
Reid Spencer060d25d2004-06-29 23:29:38 +00001314
Reid Spencer46b002c2004-07-11 17:28:43 +00001315 // Compaction tables live in separate blocks so we have to loop
1316 // until we've read the whole thing.
1317 while (moreInBlock()) {
1318 // Read the number of Value* entries in the compaction table
Reid Spencer060d25d2004-06-29 23:29:38 +00001319 unsigned NumEntries = read_vbr_uint();
Reid Spencer04cde2c2004-07-04 11:33:49 +00001320 unsigned Ty = 0;
Reid Spencer060d25d2004-06-29 23:29:38 +00001321
Reid Spencer46b002c2004-07-11 17:28:43 +00001322 // Decode the type from value read in. Most compaction table
1323 // planes will have one or two entries in them. If that's the
1324 // case then the length is encoded in the bottom two bits and
1325 // the higher bits encode the type. This saves another VBR value.
Reid Spencer060d25d2004-06-29 23:29:38 +00001326 if ((NumEntries & 3) == 3) {
Reid Spencer46b002c2004-07-11 17:28:43 +00001327 // In this case, both low-order bits are set (value 3). This
1328 // is a signal that the typeid follows.
Reid Spencer060d25d2004-06-29 23:29:38 +00001329 NumEntries >>= 2;
Reid Spencerd798a512006-11-14 04:47:22 +00001330 Ty = read_vbr_uint();
Reid Spencer060d25d2004-06-29 23:29:38 +00001331 } else {
Reid Spencer46b002c2004-07-11 17:28:43 +00001332 // In this case, the low-order bits specify the number of entries
1333 // and the high order bits specify the type.
Reid Spencer060d25d2004-06-29 23:29:38 +00001334 Ty = NumEntries >> 2;
1335 NumEntries &= 3;
1336 }
1337
Reid Spencerd798a512006-11-14 04:47:22 +00001338 // Make sure we have enough room for the plane.
1339 if (Ty >= CompactionValues.size())
1340 CompactionValues.resize(Ty+1);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001341
Reid Spencerd798a512006-11-14 04:47:22 +00001342 // Make sure the plane is empty or we have some kind of error.
1343 if (!CompactionValues[Ty].empty())
1344 error("Compaction table plane contains multiple entries!");
Reid Spencer04cde2c2004-07-04 11:33:49 +00001345
Reid Spencerd798a512006-11-14 04:47:22 +00001346 // Notify handler about the plane.
1347 if (Handler) Handler->handleCompactionTablePlane(Ty, NumEntries);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001348
Reid Spencerd798a512006-11-14 04:47:22 +00001349 // Push the implicit zero.
1350 CompactionValues[Ty].push_back(Constant::getNullValue(getType(Ty)));
Reid Spencer46b002c2004-07-11 17:28:43 +00001351
Reid Spencerd798a512006-11-14 04:47:22 +00001352 // Read in each of the entries, put them in the compaction table
1353 // and notify the handler that we have a new compaction table value.
1354 for (unsigned i = 0; i != NumEntries; ++i) {
1355 unsigned ValSlot = read_vbr_uint();
1356 Value *V = getGlobalTableValue(Ty, ValSlot);
1357 CompactionValues[Ty].push_back(V);
1358 if (Handler) Handler->handleCompactionTableValue(i, Ty, ValSlot);
Reid Spencer060d25d2004-06-29 23:29:38 +00001359 }
1360 }
Reid Spencer46b002c2004-07-11 17:28:43 +00001361 // Notify handler that the compaction table is done.
Reid Spencer04cde2c2004-07-04 11:33:49 +00001362 if (Handler) Handler->handleCompactionTableEnd();
Reid Spencer060d25d2004-06-29 23:29:38 +00001363}
Misha Brukman8a96c532005-04-21 21:44:41 +00001364
Reid Spencer46b002c2004-07-11 17:28:43 +00001365// Parse a single type. The typeid is read in first. If its a primitive type
1366// then nothing else needs to be read, we know how to instantiate it. If its
Misha Brukman8a96c532005-04-21 21:44:41 +00001367// a derived type, then additional data is read to fill out the type
Reid Spencer46b002c2004-07-11 17:28:43 +00001368// definition.
1369const Type *BytecodeReader::ParseType() {
Reid Spencerd798a512006-11-14 04:47:22 +00001370 unsigned PrimType = read_vbr_uint();
Reid Spencer060d25d2004-06-29 23:29:38 +00001371 const Type *Result = 0;
1372 if ((Result = Type::getPrimitiveType((Type::TypeID)PrimType)))
1373 return Result;
Misha Brukman8a96c532005-04-21 21:44:41 +00001374
Reid Spencer060d25d2004-06-29 23:29:38 +00001375 switch (PrimType) {
1376 case Type::FunctionTyID: {
Reid Spencerd798a512006-11-14 04:47:22 +00001377 const Type *RetType = readType();
Reid Spencer060d25d2004-06-29 23:29:38 +00001378
1379 unsigned NumParams = read_vbr_uint();
1380
1381 std::vector<const Type*> Params;
Misha Brukman8a96c532005-04-21 21:44:41 +00001382 while (NumParams--)
Reid Spencerd798a512006-11-14 04:47:22 +00001383 Params.push_back(readType());
Reid Spencer060d25d2004-06-29 23:29:38 +00001384
1385 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1386 if (isVarArg) Params.pop_back();
1387
1388 Result = FunctionType::get(RetType, Params, isVarArg);
1389 break;
1390 }
1391 case Type::ArrayTyID: {
Reid Spencerd798a512006-11-14 04:47:22 +00001392 const Type *ElementType = readType();
Reid Spencer060d25d2004-06-29 23:29:38 +00001393 unsigned NumElements = read_vbr_uint();
Reid Spencer060d25d2004-06-29 23:29:38 +00001394 Result = ArrayType::get(ElementType, NumElements);
1395 break;
1396 }
Brian Gaeke715c90b2004-08-20 06:00:58 +00001397 case Type::PackedTyID: {
Reid Spencerd798a512006-11-14 04:47:22 +00001398 const Type *ElementType = readType();
Brian Gaeke715c90b2004-08-20 06:00:58 +00001399 unsigned NumElements = read_vbr_uint();
1400 Result = PackedType::get(ElementType, NumElements);
1401 break;
1402 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001403 case Type::StructTyID: {
1404 std::vector<const Type*> Elements;
Reid Spencerd798a512006-11-14 04:47:22 +00001405 unsigned Typ = read_vbr_uint();
Reid Spencer060d25d2004-06-29 23:29:38 +00001406 while (Typ) { // List is terminated by void/0 typeid
1407 Elements.push_back(getType(Typ));
Reid Spencerd798a512006-11-14 04:47:22 +00001408 Typ = read_vbr_uint();
Reid Spencer060d25d2004-06-29 23:29:38 +00001409 }
1410
1411 Result = StructType::get(Elements);
1412 break;
1413 }
1414 case Type::PointerTyID: {
Reid Spencerd798a512006-11-14 04:47:22 +00001415 Result = PointerType::get(readType());
Reid Spencer060d25d2004-06-29 23:29:38 +00001416 break;
1417 }
1418
1419 case Type::OpaqueTyID: {
1420 Result = OpaqueType::get();
1421 break;
1422 }
1423
1424 default:
Reid Spencer24399722004-07-09 22:21:33 +00001425 error("Don't know how to deserialize primitive type " + utostr(PrimType));
Reid Spencer060d25d2004-06-29 23:29:38 +00001426 break;
1427 }
Reid Spencer46b002c2004-07-11 17:28:43 +00001428 if (Handler) Handler->handleType(Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001429 return Result;
1430}
1431
Reid Spencer5b472d92004-08-21 20:49:23 +00001432// ParseTypes - We have to use this weird code to handle recursive
Reid Spencer060d25d2004-06-29 23:29:38 +00001433// types. We know that recursive types will only reference the current slab of
1434// values in the type plane, but they can forward reference types before they
1435// have been read. For example, Type #0 might be '{ Ty#1 }' and Type #1 might
1436// be 'Ty#0*'. When reading Type #0, type number one doesn't exist. To fix
1437// this ugly problem, we pessimistically insert an opaque type for each type we
1438// are about to read. This means that forward references will resolve to
1439// something and when we reread the type later, we can replace the opaque type
1440// with a new resolved concrete type.
1441//
Reid Spencer46b002c2004-07-11 17:28:43 +00001442void BytecodeReader::ParseTypes(TypeListTy &Tab, unsigned NumEntries){
Reid Spencer060d25d2004-06-29 23:29:38 +00001443 assert(Tab.size() == 0 && "should not have read type constants in before!");
1444
1445 // Insert a bunch of opaque types to be resolved later...
1446 Tab.reserve(NumEntries);
1447 for (unsigned i = 0; i != NumEntries; ++i)
1448 Tab.push_back(OpaqueType::get());
1449
Misha Brukman8a96c532005-04-21 21:44:41 +00001450 if (Handler)
Reid Spencer5b472d92004-08-21 20:49:23 +00001451 Handler->handleTypeList(NumEntries);
1452
Chris Lattnereebac5f2005-10-03 21:26:53 +00001453 // If we are about to resolve types, make sure the type cache is clear.
1454 if (NumEntries)
1455 ModuleTypeIDCache.clear();
1456
Reid Spencer060d25d2004-06-29 23:29:38 +00001457 // Loop through reading all of the types. Forward types will make use of the
1458 // opaque types just inserted.
1459 //
1460 for (unsigned i = 0; i != NumEntries; ++i) {
Reid Spencer46b002c2004-07-11 17:28:43 +00001461 const Type* NewTy = ParseType();
Reid Spencer04cde2c2004-07-04 11:33:49 +00001462 const Type* OldTy = Tab[i].get();
Misha Brukman8a96c532005-04-21 21:44:41 +00001463 if (NewTy == 0)
Reid Spencer24399722004-07-09 22:21:33 +00001464 error("Couldn't parse type!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001465
Misha Brukman8a96c532005-04-21 21:44:41 +00001466 // Don't directly push the new type on the Tab. Instead we want to replace
Reid Spencer060d25d2004-06-29 23:29:38 +00001467 // the opaque type we previously inserted with the new concrete value. This
1468 // approach helps with forward references to types. The refinement from the
1469 // abstract (opaque) type to the new type causes all uses of the abstract
1470 // type to use the concrete type (NewTy). This will also cause the opaque
1471 // type to be deleted.
1472 cast<DerivedType>(const_cast<Type*>(OldTy))->refineAbstractTypeTo(NewTy);
1473
1474 // This should have replaced the old opaque type with the new type in the
1475 // value table... or with a preexisting type that was already in the system.
1476 // Let's just make sure it did.
1477 assert(Tab[i] != OldTy && "refineAbstractType didn't work!");
1478 }
1479}
1480
Reid Spencer1628cec2006-10-26 06:15:43 +00001481// Upgrade obsolete constant expression opcodes (ver. 5 and prior) to the new
1482// values used after ver 6. bytecode format. The operands are provided to the
1483// function so that decisions based on the operand type can be made when
1484// auto-upgrading obsolete opcodes to the new ones.
Reid Spencer6996feb2006-11-08 21:27:54 +00001485// NOTE: This code needs to be kept synchronized with upgradeInstrOpcodes.
Reid Spencer1628cec2006-10-26 06:15:43 +00001486// We can't use that function because of that functions argument requirements.
1487// This function only deals with the subset of opcodes that are applicable to
Reid Spencer6996feb2006-11-08 21:27:54 +00001488// constant expressions and is therefore simpler than upgradeInstrOpcodes.
1489inline unsigned BytecodeReader::upgradeCEOpcodes(
Reid Spencer1628cec2006-10-26 06:15:43 +00001490 unsigned Opcode, const std::vector<Constant*> &ArgVec
1491) {
Reid Spencer6996feb2006-11-08 21:27:54 +00001492 // Determine if no upgrade necessary
1493 if (!hasSignlessDivRem && !hasSignlessShrCastSetcc)
1494 return Opcode;
1495
Reid Spencer6996feb2006-11-08 21:27:54 +00001496 // If this is bytecode version 6, that only had signed Rem and Div
1497 // instructions, then we must compensate for those two instructions only.
1498 // So that the switch statement below works, we're trying to turn this into
1499 // a version 5 opcode. To do that we must adjust the opcode to 10 (Div) if its
1500 // any of the UDiv, SDiv or FDiv instructions; or, adjust the opcode to
1501 // 11 (Rem) if its any of the URem, SRem, or FRem instructions; or, simply
1502 // decrement the instruction code if its beyond FRem.
1503 if (!hasSignlessDivRem) {
1504 // If its one of the signed Div/Rem opcodes, its fine the way it is
1505 if (Opcode >= 10 && Opcode <= 12) // UDiv through FDiv
1506 Opcode = 10; // Div
1507 else if (Opcode >=13 && Opcode <= 15) // URem through FRem
1508 Opcode = 11; // Rem
1509 else if (Opcode > 15) // Everything above FRem
1510 // Adjust for new instruction codes
1511 Opcode -= 4;
1512 }
1513
Reid Spencer1628cec2006-10-26 06:15:43 +00001514 switch (Opcode) {
1515 default: // Pass Through
1516 // If we don't match any of the cases here then the opcode is fine the
1517 // way it is.
1518 break;
1519 case 7: // Add
1520 Opcode = Instruction::Add;
1521 break;
1522 case 8: // Sub
1523 Opcode = Instruction::Sub;
1524 break;
1525 case 9: // Mul
1526 Opcode = Instruction::Mul;
1527 break;
1528 case 10: // Div
1529 // The type of the instruction is based on the operands. We need to select
1530 // either udiv or sdiv based on that type. This expression selects the
1531 // cases where the type is floating point or signed in which case we
1532 // generated an sdiv instruction.
1533 if (ArgVec[0]->getType()->isFloatingPoint())
1534 Opcode = Instruction::FDiv;
1535 else if (ArgVec[0]->getType()->isSigned())
1536 Opcode = Instruction::SDiv;
1537 else
1538 Opcode = Instruction::UDiv;
1539 break;
Reid Spencer1628cec2006-10-26 06:15:43 +00001540 case 11: // Rem
Reid Spencer0a783f72006-11-02 01:53:59 +00001541 // As with "Div", make the signed/unsigned or floating point Rem
1542 // instruction choice based on the type of the operands.
Reid Spencer1628cec2006-10-26 06:15:43 +00001543 if (ArgVec[0]->getType()->isFloatingPoint())
Reid Spencer0a783f72006-11-02 01:53:59 +00001544 Opcode = Instruction::FRem;
Reid Spencer1628cec2006-10-26 06:15:43 +00001545 else if (ArgVec[0]->getType()->isSigned())
Reid Spencer0a783f72006-11-02 01:53:59 +00001546 Opcode = Instruction::SRem;
Reid Spencer1628cec2006-10-26 06:15:43 +00001547 else
Reid Spencer0a783f72006-11-02 01:53:59 +00001548 Opcode = Instruction::URem;
Reid Spencer1628cec2006-10-26 06:15:43 +00001549 break;
Reid Spencer1628cec2006-10-26 06:15:43 +00001550 case 12: // And
1551 Opcode = Instruction::And;
1552 break;
1553 case 13: // Or
1554 Opcode = Instruction::Or;
1555 break;
1556 case 14: // Xor
1557 Opcode = Instruction::Xor;
1558 break;
1559 case 15: // SetEQ
1560 Opcode = Instruction::SetEQ;
1561 break;
1562 case 16: // SetNE
1563 Opcode = Instruction::SetNE;
1564 break;
1565 case 17: // SetLE
1566 Opcode = Instruction::SetLE;
1567 break;
1568 case 18: // SetGE
1569 Opcode = Instruction::SetGE;
1570 break;
1571 case 19: // SetLT
1572 Opcode = Instruction::SetLT;
1573 break;
1574 case 20: // SetGT
1575 Opcode = Instruction::SetGT;
1576 break;
1577 case 26: // GetElementPtr
1578 Opcode = Instruction::GetElementPtr;
1579 break;
1580 case 28: // Cast
1581 Opcode = Instruction::Cast;
1582 break;
1583 case 30: // Shl
1584 Opcode = Instruction::Shl;
1585 break;
1586 case 31: // Shr
Reid Spencer3822ff52006-11-08 06:47:33 +00001587 if (ArgVec[0]->getType()->isSigned())
1588 Opcode = Instruction::AShr;
1589 else
1590 Opcode = Instruction::LShr;
Reid Spencer1628cec2006-10-26 06:15:43 +00001591 break;
1592 case 34: // Select
1593 Opcode = Instruction::Select;
1594 break;
1595 case 38: // ExtractElement
1596 Opcode = Instruction::ExtractElement;
1597 break;
1598 case 39: // InsertElement
1599 Opcode = Instruction::InsertElement;
1600 break;
1601 case 40: // ShuffleVector
1602 Opcode = Instruction::ShuffleVector;
1603 break;
1604 }
1605 return Opcode;
1606}
1607
Reid Spencer04cde2c2004-07-04 11:33:49 +00001608/// Parse a single constant value
Chris Lattner3bc5a602006-01-25 23:08:15 +00001609Value *BytecodeReader::ParseConstantPoolValue(unsigned TypeID) {
Reid Spencer060d25d2004-06-29 23:29:38 +00001610 // We must check for a ConstantExpr before switching by type because
1611 // a ConstantExpr can be of any type, and has no explicit value.
Misha Brukman8a96c532005-04-21 21:44:41 +00001612 //
Reid Spencer060d25d2004-06-29 23:29:38 +00001613 // 0 if not expr; numArgs if is expr
1614 unsigned isExprNumArgs = read_vbr_uint();
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001615
Reid Spencer060d25d2004-06-29 23:29:38 +00001616 if (isExprNumArgs) {
Reid Spencerd798a512006-11-14 04:47:22 +00001617 // 'undef' is encoded with 'exprnumargs' == 1.
1618 if (isExprNumArgs == 1)
1619 return UndefValue::get(getType(TypeID));
Misha Brukman8a96c532005-04-21 21:44:41 +00001620
Reid Spencerd798a512006-11-14 04:47:22 +00001621 // Inline asm is encoded with exprnumargs == ~0U.
1622 if (isExprNumArgs == ~0U) {
1623 std::string AsmStr = read_str();
1624 std::string ConstraintStr = read_str();
1625 unsigned Flags = read_vbr_uint();
Chris Lattner3bc5a602006-01-25 23:08:15 +00001626
Reid Spencerd798a512006-11-14 04:47:22 +00001627 const PointerType *PTy = dyn_cast<PointerType>(getType(TypeID));
1628 const FunctionType *FTy =
1629 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
1630
1631 if (!FTy || !InlineAsm::Verify(FTy, ConstraintStr))
1632 error("Invalid constraints for inline asm");
1633 if (Flags & ~1U)
1634 error("Invalid flags for inline asm");
1635 bool HasSideEffects = Flags & 1;
1636 return InlineAsm::get(FTy, AsmStr, ConstraintStr, HasSideEffects);
Chris Lattner3bc5a602006-01-25 23:08:15 +00001637 }
Reid Spencerd798a512006-11-14 04:47:22 +00001638
1639 --isExprNumArgs;
Chris Lattner3bc5a602006-01-25 23:08:15 +00001640
Reid Spencer060d25d2004-06-29 23:29:38 +00001641 // FIXME: Encoding of constant exprs could be much more compact!
1642 std::vector<Constant*> ArgVec;
1643 ArgVec.reserve(isExprNumArgs);
1644 unsigned Opcode = read_vbr_uint();
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001645
Reid Spencer060d25d2004-06-29 23:29:38 +00001646 // Read the slot number and types of each of the arguments
1647 for (unsigned i = 0; i != isExprNumArgs; ++i) {
1648 unsigned ArgValSlot = read_vbr_uint();
Reid Spencerd798a512006-11-14 04:47:22 +00001649 unsigned ArgTypeSlot = read_vbr_uint();
Misha Brukman8a96c532005-04-21 21:44:41 +00001650
Reid Spencer060d25d2004-06-29 23:29:38 +00001651 // Get the arg value from its slot if it exists, otherwise a placeholder
1652 ArgVec.push_back(getConstantValue(ArgTypeSlot, ArgValSlot));
1653 }
Misha Brukman8a96c532005-04-21 21:44:41 +00001654
Reid Spencer1628cec2006-10-26 06:15:43 +00001655 // Handle backwards compatibility for the opcode numbers
Reid Spencer6996feb2006-11-08 21:27:54 +00001656 Opcode = upgradeCEOpcodes(Opcode, ArgVec);
Reid Spencer1628cec2006-10-26 06:15:43 +00001657
Reid Spencer060d25d2004-06-29 23:29:38 +00001658 // Construct a ConstantExpr of the appropriate kind
1659 if (isExprNumArgs == 1) { // All one-operand expressions
Reid Spencer46b002c2004-07-11 17:28:43 +00001660 if (Opcode != Instruction::Cast)
Chris Lattner02dce162004-12-04 05:28:27 +00001661 error("Only cast instruction has one argument for ConstantExpr");
Reid Spencer46b002c2004-07-11 17:28:43 +00001662
Reid Spencer060d25d2004-06-29 23:29:38 +00001663 Constant* Result = ConstantExpr::getCast(ArgVec[0], getType(TypeID));
Reid Spencer04cde2c2004-07-04 11:33:49 +00001664 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001665 return Result;
1666 } else if (Opcode == Instruction::GetElementPtr) { // GetElementPtr
1667 std::vector<Constant*> IdxList(ArgVec.begin()+1, ArgVec.end());
Reid Spencer060d25d2004-06-29 23:29:38 +00001668 Constant* Result = ConstantExpr::getGetElementPtr(ArgVec[0], IdxList);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001669 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001670 return Result;
1671 } else if (Opcode == Instruction::Select) {
Reid Spencer46b002c2004-07-11 17:28:43 +00001672 if (ArgVec.size() != 3)
1673 error("Select instruction must have three arguments.");
Misha Brukman8a96c532005-04-21 21:44:41 +00001674 Constant* Result = ConstantExpr::getSelect(ArgVec[0], ArgVec[1],
Reid Spencer04cde2c2004-07-04 11:33:49 +00001675 ArgVec[2]);
1676 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001677 return Result;
Robert Bocchinofee31b32006-01-10 19:04:39 +00001678 } else if (Opcode == Instruction::ExtractElement) {
Chris Lattner59fecec2006-04-08 04:09:19 +00001679 if (ArgVec.size() != 2 ||
1680 !ExtractElementInst::isValidOperands(ArgVec[0], ArgVec[1]))
1681 error("Invalid extractelement constand expr arguments");
Robert Bocchinofee31b32006-01-10 19:04:39 +00001682 Constant* Result = ConstantExpr::getExtractElement(ArgVec[0], ArgVec[1]);
1683 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
1684 return Result;
Robert Bocchinob1f240b2006-01-17 20:06:35 +00001685 } else if (Opcode == Instruction::InsertElement) {
Chris Lattner59fecec2006-04-08 04:09:19 +00001686 if (ArgVec.size() != 3 ||
1687 !InsertElementInst::isValidOperands(ArgVec[0], ArgVec[1], ArgVec[2]))
1688 error("Invalid insertelement constand expr arguments");
1689
1690 Constant *Result =
Robert Bocchinob1f240b2006-01-17 20:06:35 +00001691 ConstantExpr::getInsertElement(ArgVec[0], ArgVec[1], ArgVec[2]);
1692 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
1693 return Result;
Chris Lattner30b44b62006-04-08 01:17:59 +00001694 } else if (Opcode == Instruction::ShuffleVector) {
1695 if (ArgVec.size() != 3 ||
1696 !ShuffleVectorInst::isValidOperands(ArgVec[0], ArgVec[1], ArgVec[2]))
Chris Lattner59fecec2006-04-08 04:09:19 +00001697 error("Invalid shufflevector constant expr arguments.");
Chris Lattner30b44b62006-04-08 01:17:59 +00001698 Constant *Result =
1699 ConstantExpr::getShuffleVector(ArgVec[0], ArgVec[1], ArgVec[2]);
1700 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
1701 return Result;
Reid Spencer060d25d2004-06-29 23:29:38 +00001702 } else { // All other 2-operand expressions
1703 Constant* Result = ConstantExpr::get(Opcode, ArgVec[0], ArgVec[1]);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001704 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001705 return Result;
1706 }
1707 }
Misha Brukman8a96c532005-04-21 21:44:41 +00001708
Reid Spencer060d25d2004-06-29 23:29:38 +00001709 // Ok, not an ConstantExpr. We now know how to read the given type...
1710 const Type *Ty = getType(TypeID);
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001711 Constant *Result = 0;
Reid Spencer060d25d2004-06-29 23:29:38 +00001712 switch (Ty->getTypeID()) {
1713 case Type::BoolTyID: {
1714 unsigned Val = read_vbr_uint();
Misha Brukman8a96c532005-04-21 21:44:41 +00001715 if (Val != 0 && Val != 1)
Reid Spencer24399722004-07-09 22:21:33 +00001716 error("Invalid boolean value read.");
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001717 Result = ConstantBool::get(Val == 1);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001718 if (Handler) Handler->handleConstantValue(Result);
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001719 break;
Reid Spencer060d25d2004-06-29 23:29:38 +00001720 }
1721
1722 case Type::UByteTyID: // Unsigned integer types...
1723 case Type::UShortTyID:
1724 case Type::UIntTyID: {
1725 unsigned Val = read_vbr_uint();
Reid Spencerb83eb642006-10-20 07:07:24 +00001726 if (!ConstantInt::isValueValidForType(Ty, uint64_t(Val)))
Reid Spencer24399722004-07-09 22:21:33 +00001727 error("Invalid unsigned byte/short/int read.");
Reid Spencerb83eb642006-10-20 07:07:24 +00001728 Result = ConstantInt::get(Ty, Val);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001729 if (Handler) Handler->handleConstantValue(Result);
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001730 break;
Reid Spencer060d25d2004-06-29 23:29:38 +00001731 }
1732
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001733 case Type::ULongTyID:
Reid Spencerb83eb642006-10-20 07:07:24 +00001734 Result = ConstantInt::get(Ty, read_vbr_uint64());
Reid Spencer04cde2c2004-07-04 11:33:49 +00001735 if (Handler) Handler->handleConstantValue(Result);
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001736 break;
1737
Reid Spencer060d25d2004-06-29 23:29:38 +00001738 case Type::SByteTyID: // Signed integer types...
1739 case Type::ShortTyID:
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001740 case Type::IntTyID:
1741 case Type::LongTyID: {
Reid Spencer060d25d2004-06-29 23:29:38 +00001742 int64_t Val = read_vbr_int64();
Reid Spencerb83eb642006-10-20 07:07:24 +00001743 if (!ConstantInt::isValueValidForType(Ty, Val))
Reid Spencer24399722004-07-09 22:21:33 +00001744 error("Invalid signed byte/short/int/long read.");
Reid Spencerb83eb642006-10-20 07:07:24 +00001745 Result = ConstantInt::get(Ty, Val);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001746 if (Handler) Handler->handleConstantValue(Result);
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001747 break;
Reid Spencer060d25d2004-06-29 23:29:38 +00001748 }
1749
1750 case Type::FloatTyID: {
Reid Spencer46b002c2004-07-11 17:28:43 +00001751 float Val;
1752 read_float(Val);
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001753 Result = ConstantFP::get(Ty, Val);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001754 if (Handler) Handler->handleConstantValue(Result);
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001755 break;
Reid Spencer060d25d2004-06-29 23:29:38 +00001756 }
1757
1758 case Type::DoubleTyID: {
1759 double Val;
Reid Spencer46b002c2004-07-11 17:28:43 +00001760 read_double(Val);
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001761 Result = ConstantFP::get(Ty, Val);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001762 if (Handler) Handler->handleConstantValue(Result);
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001763 break;
Reid Spencer060d25d2004-06-29 23:29:38 +00001764 }
1765
Reid Spencer060d25d2004-06-29 23:29:38 +00001766 case Type::ArrayTyID: {
1767 const ArrayType *AT = cast<ArrayType>(Ty);
1768 unsigned NumElements = AT->getNumElements();
1769 unsigned TypeSlot = getTypeSlot(AT->getElementType());
1770 std::vector<Constant*> Elements;
1771 Elements.reserve(NumElements);
1772 while (NumElements--) // Read all of the elements of the constant.
1773 Elements.push_back(getConstantValue(TypeSlot,
1774 read_vbr_uint()));
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001775 Result = ConstantArray::get(AT, Elements);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001776 if (Handler) Handler->handleConstantArray(AT, Elements, TypeSlot, Result);
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001777 break;
Reid Spencer060d25d2004-06-29 23:29:38 +00001778 }
1779
1780 case Type::StructTyID: {
1781 const StructType *ST = cast<StructType>(Ty);
1782
1783 std::vector<Constant *> Elements;
1784 Elements.reserve(ST->getNumElements());
1785 for (unsigned i = 0; i != ST->getNumElements(); ++i)
1786 Elements.push_back(getConstantValue(ST->getElementType(i),
1787 read_vbr_uint()));
1788
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001789 Result = ConstantStruct::get(ST, Elements);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001790 if (Handler) Handler->handleConstantStruct(ST, Elements, Result);
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001791 break;
Misha Brukman8a96c532005-04-21 21:44:41 +00001792 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001793
Brian Gaeke715c90b2004-08-20 06:00:58 +00001794 case Type::PackedTyID: {
1795 const PackedType *PT = cast<PackedType>(Ty);
1796 unsigned NumElements = PT->getNumElements();
1797 unsigned TypeSlot = getTypeSlot(PT->getElementType());
1798 std::vector<Constant*> Elements;
1799 Elements.reserve(NumElements);
1800 while (NumElements--) // Read all of the elements of the constant.
1801 Elements.push_back(getConstantValue(TypeSlot,
1802 read_vbr_uint()));
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001803 Result = ConstantPacked::get(PT, Elements);
Brian Gaeke715c90b2004-08-20 06:00:58 +00001804 if (Handler) Handler->handleConstantPacked(PT, Elements, TypeSlot, Result);
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001805 break;
Brian Gaeke715c90b2004-08-20 06:00:58 +00001806 }
1807
Chris Lattner638c3812004-11-19 16:24:05 +00001808 case Type::PointerTyID: { // ConstantPointerRef value (backwards compat).
Reid Spencer060d25d2004-06-29 23:29:38 +00001809 const PointerType *PT = cast<PointerType>(Ty);
1810 unsigned Slot = read_vbr_uint();
Misha Brukman8a96c532005-04-21 21:44:41 +00001811
Reid Spencer060d25d2004-06-29 23:29:38 +00001812 // Check to see if we have already read this global variable...
1813 Value *Val = getValue(TypeID, Slot, false);
Reid Spencer060d25d2004-06-29 23:29:38 +00001814 if (Val) {
Chris Lattnerbcb11cf2004-07-27 02:34:49 +00001815 GlobalValue *GV = dyn_cast<GlobalValue>(Val);
1816 if (!GV) error("GlobalValue not in ValueTable!");
1817 if (Handler) Handler->handleConstantPointer(PT, Slot, GV);
1818 return GV;
Reid Spencer060d25d2004-06-29 23:29:38 +00001819 } else {
Reid Spencer24399722004-07-09 22:21:33 +00001820 error("Forward references are not allowed here.");
Reid Spencer060d25d2004-06-29 23:29:38 +00001821 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001822 }
1823
1824 default:
Reid Spencer24399722004-07-09 22:21:33 +00001825 error("Don't know how to deserialize constant value of type '" +
Reid Spencer060d25d2004-06-29 23:29:38 +00001826 Ty->getDescription());
1827 break;
1828 }
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001829
1830 // Check that we didn't read a null constant if they are implicit for this
1831 // type plane. Do not do this check for constantexprs, as they may be folded
1832 // to a null value in a way that isn't predicted when a .bc file is initially
1833 // produced.
1834 assert((!isa<Constant>(Result) || !cast<Constant>(Result)->isNullValue()) ||
1835 !hasImplicitNull(TypeID) &&
1836 "Cannot read null values from bytecode!");
1837 return Result;
Reid Spencer060d25d2004-06-29 23:29:38 +00001838}
1839
Misha Brukman8a96c532005-04-21 21:44:41 +00001840/// Resolve references for constants. This function resolves the forward
1841/// referenced constants in the ConstantFwdRefs map. It uses the
Reid Spencer04cde2c2004-07-04 11:33:49 +00001842/// replaceAllUsesWith method of Value class to substitute the placeholder
1843/// instance with the actual instance.
Chris Lattner389bd042004-12-09 06:19:44 +00001844void BytecodeReader::ResolveReferencesToConstant(Constant *NewV, unsigned Typ,
1845 unsigned Slot) {
Chris Lattner29b789b2003-11-19 17:27:18 +00001846 ConstantRefsType::iterator I =
Chris Lattner389bd042004-12-09 06:19:44 +00001847 ConstantFwdRefs.find(std::make_pair(Typ, Slot));
Chris Lattner29b789b2003-11-19 17:27:18 +00001848 if (I == ConstantFwdRefs.end()) return; // Never forward referenced?
Chris Lattner00950542001-06-06 20:29:01 +00001849
Chris Lattner29b789b2003-11-19 17:27:18 +00001850 Value *PH = I->second; // Get the placeholder...
1851 PH->replaceAllUsesWith(NewV);
1852 delete PH; // Delete the old placeholder
1853 ConstantFwdRefs.erase(I); // Remove the map entry for it
Vikram S. Advec1e4a812002-07-14 23:04:18 +00001854}
1855
Reid Spencer04cde2c2004-07-04 11:33:49 +00001856/// Parse the constant strings section.
Reid Spencer060d25d2004-06-29 23:29:38 +00001857void BytecodeReader::ParseStringConstants(unsigned NumEntries, ValueTable &Tab){
1858 for (; NumEntries; --NumEntries) {
Reid Spencerd798a512006-11-14 04:47:22 +00001859 unsigned Typ = read_vbr_uint();
Reid Spencer060d25d2004-06-29 23:29:38 +00001860 const Type *Ty = getType(Typ);
1861 if (!isa<ArrayType>(Ty))
Reid Spencer24399722004-07-09 22:21:33 +00001862 error("String constant data invalid!");
Misha Brukman8a96c532005-04-21 21:44:41 +00001863
Reid Spencer060d25d2004-06-29 23:29:38 +00001864 const ArrayType *ATy = cast<ArrayType>(Ty);
1865 if (ATy->getElementType() != Type::SByteTy &&
1866 ATy->getElementType() != Type::UByteTy)
Reid Spencer24399722004-07-09 22:21:33 +00001867 error("String constant data invalid!");
Misha Brukman8a96c532005-04-21 21:44:41 +00001868
Reid Spencer060d25d2004-06-29 23:29:38 +00001869 // Read character data. The type tells us how long the string is.
Misha Brukman8a96c532005-04-21 21:44:41 +00001870 char *Data = reinterpret_cast<char *>(alloca(ATy->getNumElements()));
Reid Spencer060d25d2004-06-29 23:29:38 +00001871 read_data(Data, Data+ATy->getNumElements());
Chris Lattner52e20b02003-03-19 20:54:26 +00001872
Reid Spencer060d25d2004-06-29 23:29:38 +00001873 std::vector<Constant*> Elements(ATy->getNumElements());
Reid Spencerb83eb642006-10-20 07:07:24 +00001874 const Type* ElemType = ATy->getElementType();
1875 for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
1876 Elements[i] = ConstantInt::get(ElemType, (unsigned char)Data[i]);
Misha Brukman12c29d12003-09-22 23:38:23 +00001877
Reid Spencer060d25d2004-06-29 23:29:38 +00001878 // Create the constant, inserting it as needed.
1879 Constant *C = ConstantArray::get(ATy, Elements);
1880 unsigned Slot = insertValue(C, Typ, Tab);
Chris Lattner389bd042004-12-09 06:19:44 +00001881 ResolveReferencesToConstant(C, Typ, Slot);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001882 if (Handler) Handler->handleConstantString(cast<ConstantArray>(C));
Reid Spencer060d25d2004-06-29 23:29:38 +00001883 }
Misha Brukman12c29d12003-09-22 23:38:23 +00001884}
1885
Reid Spencer04cde2c2004-07-04 11:33:49 +00001886/// Parse the constant pool.
Misha Brukman8a96c532005-04-21 21:44:41 +00001887void BytecodeReader::ParseConstantPool(ValueTable &Tab,
Reid Spencer04cde2c2004-07-04 11:33:49 +00001888 TypeListTy &TypeTab,
Reid Spencer46b002c2004-07-11 17:28:43 +00001889 bool isFunction) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001890 if (Handler) Handler->handleGlobalConstantsBegin();
1891
1892 /// In LLVM 1.3 Type does not derive from Value so the types
1893 /// do not occupy a plane. Consequently, we read the types
1894 /// first in the constant pool.
Reid Spencerd798a512006-11-14 04:47:22 +00001895 if (isFunction) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001896 unsigned NumEntries = read_vbr_uint();
Reid Spencer46b002c2004-07-11 17:28:43 +00001897 ParseTypes(TypeTab, NumEntries);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001898 }
1899
Reid Spencer46b002c2004-07-11 17:28:43 +00001900 while (moreInBlock()) {
Reid Spencer060d25d2004-06-29 23:29:38 +00001901 unsigned NumEntries = read_vbr_uint();
Reid Spencerd798a512006-11-14 04:47:22 +00001902 unsigned Typ = read_vbr_uint();
Reid Spencer04cde2c2004-07-04 11:33:49 +00001903
Reid Spencerd798a512006-11-14 04:47:22 +00001904 if (Typ == Type::VoidTyID) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001905 /// Use of Type::VoidTyID is a misnomer. It actually means
1906 /// that the following plane is constant strings
Reid Spencer060d25d2004-06-29 23:29:38 +00001907 assert(&Tab == &ModuleValues && "Cannot read strings in functions!");
1908 ParseStringConstants(NumEntries, Tab);
1909 } else {
1910 for (unsigned i = 0; i < NumEntries; ++i) {
Chris Lattner3bc5a602006-01-25 23:08:15 +00001911 Value *V = ParseConstantPoolValue(Typ);
1912 assert(V && "ParseConstantPoolValue returned NULL!");
1913 unsigned Slot = insertValue(V, Typ, Tab);
Chris Lattner29b789b2003-11-19 17:27:18 +00001914
Reid Spencer060d25d2004-06-29 23:29:38 +00001915 // If we are reading a function constant table, make sure that we adjust
1916 // the slot number to be the real global constant number.
1917 //
1918 if (&Tab != &ModuleValues && Typ < ModuleValues.size() &&
1919 ModuleValues[Typ])
1920 Slot += ModuleValues[Typ]->size();
Chris Lattner3bc5a602006-01-25 23:08:15 +00001921 if (Constant *C = dyn_cast<Constant>(V))
1922 ResolveReferencesToConstant(C, Typ, Slot);
Reid Spencer060d25d2004-06-29 23:29:38 +00001923 }
1924 }
1925 }
Chris Lattner02dce162004-12-04 05:28:27 +00001926
1927 // After we have finished parsing the constant pool, we had better not have
1928 // any dangling references left.
Reid Spencer3c391272004-12-04 22:19:53 +00001929 if (!ConstantFwdRefs.empty()) {
Reid Spencer3c391272004-12-04 22:19:53 +00001930 ConstantRefsType::const_iterator I = ConstantFwdRefs.begin();
Reid Spencer3c391272004-12-04 22:19:53 +00001931 Constant* missingConst = I->second;
Misha Brukman8a96c532005-04-21 21:44:41 +00001932 error(utostr(ConstantFwdRefs.size()) +
1933 " unresolved constant reference exist. First one is '" +
1934 missingConst->getName() + "' of type '" +
Chris Lattner389bd042004-12-09 06:19:44 +00001935 missingConst->getType()->getDescription() + "'.");
Reid Spencer3c391272004-12-04 22:19:53 +00001936 }
Chris Lattner02dce162004-12-04 05:28:27 +00001937
Reid Spencer060d25d2004-06-29 23:29:38 +00001938 checkPastBlockEnd("Constant Pool");
Reid Spencer04cde2c2004-07-04 11:33:49 +00001939 if (Handler) Handler->handleGlobalConstantsEnd();
Reid Spencer060d25d2004-06-29 23:29:38 +00001940}
Chris Lattner00950542001-06-06 20:29:01 +00001941
Reid Spencer04cde2c2004-07-04 11:33:49 +00001942/// Parse the contents of a function. Note that this function can be
1943/// called lazily by materializeFunction
1944/// @see materializeFunction
Reid Spencer46b002c2004-07-11 17:28:43 +00001945void BytecodeReader::ParseFunctionBody(Function* F) {
Reid Spencer060d25d2004-06-29 23:29:38 +00001946
1947 unsigned FuncSize = BlockEnd - At;
Chris Lattnere3869c82003-04-16 21:16:05 +00001948 GlobalValue::LinkageTypes Linkage = GlobalValue::ExternalLinkage;
1949
Reid Spencer060d25d2004-06-29 23:29:38 +00001950 unsigned LinkageType = read_vbr_uint();
Chris Lattnerc08912f2004-01-14 16:44:44 +00001951 switch (LinkageType) {
1952 case 0: Linkage = GlobalValue::ExternalLinkage; break;
1953 case 1: Linkage = GlobalValue::WeakLinkage; break;
1954 case 2: Linkage = GlobalValue::AppendingLinkage; break;
1955 case 3: Linkage = GlobalValue::InternalLinkage; break;
1956 case 4: Linkage = GlobalValue::LinkOnceLinkage; break;
Anton Korobeynikovb74ed072006-09-14 18:23:27 +00001957 case 5: Linkage = GlobalValue::DLLImportLinkage; break;
1958 case 6: Linkage = GlobalValue::DLLExportLinkage; break;
1959 case 7: Linkage = GlobalValue::ExternalWeakLinkage; break;
Reid Spencer060d25d2004-06-29 23:29:38 +00001960 default:
Reid Spencer24399722004-07-09 22:21:33 +00001961 error("Invalid linkage type for Function.");
Reid Spencer060d25d2004-06-29 23:29:38 +00001962 Linkage = GlobalValue::InternalLinkage;
1963 break;
Chris Lattnere3869c82003-04-16 21:16:05 +00001964 }
Chris Lattnerd23b1d32001-11-26 18:56:10 +00001965
Reid Spencer46b002c2004-07-11 17:28:43 +00001966 F->setLinkage(Linkage);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001967 if (Handler) Handler->handleFunctionBegin(F,FuncSize);
Chris Lattner00950542001-06-06 20:29:01 +00001968
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001969 // Keep track of how many basic blocks we have read in...
1970 unsigned BlockNum = 0;
Chris Lattner89e02532004-01-18 21:08:15 +00001971 bool InsertedArguments = false;
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001972
Reid Spencer060d25d2004-06-29 23:29:38 +00001973 BufPtr MyEnd = BlockEnd;
Reid Spencer46b002c2004-07-11 17:28:43 +00001974 while (At < MyEnd) {
Chris Lattner00950542001-06-06 20:29:01 +00001975 unsigned Type, Size;
Reid Spencer060d25d2004-06-29 23:29:38 +00001976 BufPtr OldAt = At;
1977 read_block(Type, Size);
Chris Lattner00950542001-06-06 20:29:01 +00001978
1979 switch (Type) {
Reid Spencerad89bd62004-07-25 18:07:36 +00001980 case BytecodeFormat::ConstantPoolBlockID:
Chris Lattner89e02532004-01-18 21:08:15 +00001981 if (!InsertedArguments) {
1982 // Insert arguments into the value table before we parse the first basic
1983 // block in the function, but after we potentially read in the
1984 // compaction table.
Reid Spencer04cde2c2004-07-04 11:33:49 +00001985 insertArguments(F);
Chris Lattner89e02532004-01-18 21:08:15 +00001986 InsertedArguments = true;
1987 }
1988
Reid Spencer04cde2c2004-07-04 11:33:49 +00001989 ParseConstantPool(FunctionValues, FunctionTypes, true);
Chris Lattner00950542001-06-06 20:29:01 +00001990 break;
1991
Reid Spencerad89bd62004-07-25 18:07:36 +00001992 case BytecodeFormat::CompactionTableBlockID:
Reid Spencer060d25d2004-06-29 23:29:38 +00001993 ParseCompactionTable();
Chris Lattner89e02532004-01-18 21:08:15 +00001994 break;
1995
Reid Spencerad89bd62004-07-25 18:07:36 +00001996 case BytecodeFormat::InstructionListBlockID: {
Chris Lattner89e02532004-01-18 21:08:15 +00001997 // Insert arguments into the value table before we parse the instruction
1998 // list for the function, but after we potentially read in the compaction
1999 // table.
2000 if (!InsertedArguments) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00002001 insertArguments(F);
Chris Lattner89e02532004-01-18 21:08:15 +00002002 InsertedArguments = true;
2003 }
2004
Misha Brukman8a96c532005-04-21 21:44:41 +00002005 if (BlockNum)
Reid Spencer24399722004-07-09 22:21:33 +00002006 error("Already parsed basic blocks!");
Reid Spencer060d25d2004-06-29 23:29:38 +00002007 BlockNum = ParseInstructionList(F);
Chris Lattner8d1dbd22003-12-01 07:05:31 +00002008 break;
2009 }
2010
Reid Spencerad89bd62004-07-25 18:07:36 +00002011 case BytecodeFormat::SymbolTableBlockID:
Reid Spencer060d25d2004-06-29 23:29:38 +00002012 ParseSymbolTable(F, &F->getSymbolTable());
Chris Lattner00950542001-06-06 20:29:01 +00002013 break;
2014
2015 default:
Reid Spencer060d25d2004-06-29 23:29:38 +00002016 At += Size;
Misha Brukman8a96c532005-04-21 21:44:41 +00002017 if (OldAt > At)
Reid Spencer24399722004-07-09 22:21:33 +00002018 error("Wrapped around reading bytecode.");
Chris Lattner00950542001-06-06 20:29:01 +00002019 break;
2020 }
Reid Spencer060d25d2004-06-29 23:29:38 +00002021 BlockEnd = MyEnd;
Chris Lattner00950542001-06-06 20:29:01 +00002022 }
2023
Chris Lattner4ee8ef22003-10-08 22:52:54 +00002024 // Make sure there were no references to non-existant basic blocks.
2025 if (BlockNum != ParsedBasicBlocks.size())
Reid Spencer24399722004-07-09 22:21:33 +00002026 error("Illegal basic block operand reference");
Reid Spencer060d25d2004-06-29 23:29:38 +00002027
Chris Lattner4ee8ef22003-10-08 22:52:54 +00002028 ParsedBasicBlocks.clear();
2029
Chris Lattner97330cf2003-10-09 23:10:14 +00002030 // Resolve forward references. Replace any uses of a forward reference value
2031 // with the real value.
Chris Lattner8eb10ce2003-10-09 06:05:40 +00002032 while (!ForwardReferences.empty()) {
Chris Lattnerc4d69162004-12-09 04:51:50 +00002033 std::map<std::pair<unsigned,unsigned>, Value*>::iterator
2034 I = ForwardReferences.begin();
2035 Value *V = getValue(I->first.first, I->first.second, false);
Chris Lattner8eb10ce2003-10-09 06:05:40 +00002036 Value *PlaceHolder = I->second;
Chris Lattnerc4d69162004-12-09 04:51:50 +00002037 PlaceHolder->replaceAllUsesWith(V);
Chris Lattner8eb10ce2003-10-09 06:05:40 +00002038 ForwardReferences.erase(I);
Chris Lattner8eb10ce2003-10-09 06:05:40 +00002039 delete PlaceHolder;
Chris Lattner6e448022003-10-08 21:51:46 +00002040 }
Chris Lattner00950542001-06-06 20:29:01 +00002041
Reid Spencere2a5fb02006-01-27 11:49:27 +00002042 // If upgraded intrinsic functions were detected during reading of the
2043 // module information, then we need to look for instructions that need to
2044 // be upgraded. This can't be done while the instructions are read in because
2045 // additional instructions inserted mess up the slot numbering.
2046 if (!upgradedFunctions.empty()) {
2047 for (Function::iterator BI = F->begin(), BE = F->end(); BI != BE; ++BI)
2048 for (BasicBlock::iterator II = BI->begin(), IE = BI->end();
Jim Laskeyf4321a32006-03-13 13:07:37 +00002049 II != IE;)
2050 if (CallInst* CI = dyn_cast<CallInst>(II++)) {
Reid Spencere2a5fb02006-01-27 11:49:27 +00002051 std::map<Function*,Function*>::iterator FI =
2052 upgradedFunctions.find(CI->getCalledFunction());
Chris Lattnerbad08002006-03-02 23:59:12 +00002053 if (FI != upgradedFunctions.end())
2054 UpgradeIntrinsicCall(CI, FI->second);
Reid Spencere2a5fb02006-01-27 11:49:27 +00002055 }
2056 }
2057
Misha Brukman12c29d12003-09-22 23:38:23 +00002058 // Clear out function-level types...
Reid Spencer060d25d2004-06-29 23:29:38 +00002059 FunctionTypes.clear();
2060 CompactionTypes.clear();
2061 CompactionValues.clear();
2062 freeTable(FunctionValues);
2063
Reid Spencer04cde2c2004-07-04 11:33:49 +00002064 if (Handler) Handler->handleFunctionEnd(F);
Chris Lattner00950542001-06-06 20:29:01 +00002065}
2066
Reid Spencer04cde2c2004-07-04 11:33:49 +00002067/// This function parses LLVM functions lazily. It obtains the type of the
2068/// function and records where the body of the function is in the bytecode
Misha Brukman8a96c532005-04-21 21:44:41 +00002069/// buffer. The caller can then use the ParseNextFunction and
Reid Spencer04cde2c2004-07-04 11:33:49 +00002070/// ParseAllFunctionBodies to get handler events for the functions.
Reid Spencer060d25d2004-06-29 23:29:38 +00002071void BytecodeReader::ParseFunctionLazily() {
2072 if (FunctionSignatureList.empty())
Reid Spencer24399722004-07-09 22:21:33 +00002073 error("FunctionSignatureList empty!");
Chris Lattner89e02532004-01-18 21:08:15 +00002074
Reid Spencer060d25d2004-06-29 23:29:38 +00002075 Function *Func = FunctionSignatureList.back();
2076 FunctionSignatureList.pop_back();
Chris Lattner24102432004-01-18 22:35:34 +00002077
Reid Spencer060d25d2004-06-29 23:29:38 +00002078 // Save the information for future reading of the function
2079 LazyFunctionLoadMap[Func] = LazyFunctionInfo(BlockStart, BlockEnd);
Chris Lattner89e02532004-01-18 21:08:15 +00002080
Misha Brukmana3e6ad62004-11-14 21:02:55 +00002081 // This function has a body but it's not loaded so it appears `External'.
2082 // Mark it as a `Ghost' instead to notify the users that it has a body.
2083 Func->setLinkage(GlobalValue::GhostLinkage);
2084
Reid Spencer060d25d2004-06-29 23:29:38 +00002085 // Pretend we've `parsed' this function
2086 At = BlockEnd;
2087}
Chris Lattner89e02532004-01-18 21:08:15 +00002088
Misha Brukman8a96c532005-04-21 21:44:41 +00002089/// The ParserFunction method lazily parses one function. Use this method to
2090/// casue the parser to parse a specific function in the module. Note that
2091/// this will remove the function from what is to be included by
Reid Spencer04cde2c2004-07-04 11:33:49 +00002092/// ParseAllFunctionBodies.
2093/// @see ParseAllFunctionBodies
2094/// @see ParseBytecode
Reid Spencer99655e12006-08-25 19:54:53 +00002095bool BytecodeReader::ParseFunction(Function* Func, std::string* ErrMsg) {
2096
2097 if (setjmp(context))
2098 return true;
2099
Reid Spencer060d25d2004-06-29 23:29:38 +00002100 // Find {start, end} pointers and slot in the map. If not there, we're done.
2101 LazyFunctionMap::iterator Fi = LazyFunctionLoadMap.find(Func);
Chris Lattner89e02532004-01-18 21:08:15 +00002102
Reid Spencer060d25d2004-06-29 23:29:38 +00002103 // Make sure we found it
Reid Spencer46b002c2004-07-11 17:28:43 +00002104 if (Fi == LazyFunctionLoadMap.end()) {
Reid Spencer24399722004-07-09 22:21:33 +00002105 error("Unrecognized function of type " + Func->getType()->getDescription());
Reid Spencer99655e12006-08-25 19:54:53 +00002106 return true;
Chris Lattner89e02532004-01-18 21:08:15 +00002107 }
2108
Reid Spencer060d25d2004-06-29 23:29:38 +00002109 BlockStart = At = Fi->second.Buf;
2110 BlockEnd = Fi->second.EndBuf;
Reid Spencer24399722004-07-09 22:21:33 +00002111 assert(Fi->first == Func && "Found wrong function?");
Reid Spencer060d25d2004-06-29 23:29:38 +00002112
2113 LazyFunctionLoadMap.erase(Fi);
2114
Reid Spencer46b002c2004-07-11 17:28:43 +00002115 this->ParseFunctionBody(Func);
Reid Spencer99655e12006-08-25 19:54:53 +00002116 return false;
Chris Lattner89e02532004-01-18 21:08:15 +00002117}
2118
Reid Spencer04cde2c2004-07-04 11:33:49 +00002119/// The ParseAllFunctionBodies method parses through all the previously
2120/// unparsed functions in the bytecode file. If you want to completely parse
2121/// a bytecode file, this method should be called after Parsebytecode because
2122/// Parsebytecode only records the locations in the bytecode file of where
2123/// the function definitions are located. This function uses that information
2124/// to materialize the functions.
2125/// @see ParseBytecode
Reid Spencer99655e12006-08-25 19:54:53 +00002126bool BytecodeReader::ParseAllFunctionBodies(std::string* ErrMsg) {
2127 if (setjmp(context))
2128 return true;
2129
Reid Spencer060d25d2004-06-29 23:29:38 +00002130 LazyFunctionMap::iterator Fi = LazyFunctionLoadMap.begin();
2131 LazyFunctionMap::iterator Fe = LazyFunctionLoadMap.end();
Chris Lattner89e02532004-01-18 21:08:15 +00002132
Reid Spencer46b002c2004-07-11 17:28:43 +00002133 while (Fi != Fe) {
Reid Spencer060d25d2004-06-29 23:29:38 +00002134 Function* Func = Fi->first;
2135 BlockStart = At = Fi->second.Buf;
2136 BlockEnd = Fi->second.EndBuf;
Chris Lattnerb52f1c22005-02-13 17:48:18 +00002137 ParseFunctionBody(Func);
Reid Spencer060d25d2004-06-29 23:29:38 +00002138 ++Fi;
2139 }
Chris Lattnerb52f1c22005-02-13 17:48:18 +00002140 LazyFunctionLoadMap.clear();
Reid Spencer99655e12006-08-25 19:54:53 +00002141 return false;
Reid Spencer060d25d2004-06-29 23:29:38 +00002142}
Chris Lattner89e02532004-01-18 21:08:15 +00002143
Reid Spencer04cde2c2004-07-04 11:33:49 +00002144/// Parse the global type list
Reid Spencer060d25d2004-06-29 23:29:38 +00002145void BytecodeReader::ParseGlobalTypes() {
Reid Spencer04cde2c2004-07-04 11:33:49 +00002146 // Read the number of types
2147 unsigned NumEntries = read_vbr_uint();
Reid Spencer46b002c2004-07-11 17:28:43 +00002148 ParseTypes(ModuleTypes, NumEntries);
Reid Spencer060d25d2004-06-29 23:29:38 +00002149}
2150
Reid Spencer04cde2c2004-07-04 11:33:49 +00002151/// Parse the Global info (types, global vars, constants)
Reid Spencer060d25d2004-06-29 23:29:38 +00002152void BytecodeReader::ParseModuleGlobalInfo() {
2153
Reid Spencer04cde2c2004-07-04 11:33:49 +00002154 if (Handler) Handler->handleModuleGlobalsBegin();
Chris Lattner00950542001-06-06 20:29:01 +00002155
Chris Lattner404cddf2005-11-12 01:33:40 +00002156 // SectionID - If a global has an explicit section specified, this map
2157 // remembers the ID until we can translate it into a string.
2158 std::map<GlobalValue*, unsigned> SectionID;
2159
Chris Lattner70cc3392001-09-10 07:58:01 +00002160 // Read global variables...
Reid Spencer060d25d2004-06-29 23:29:38 +00002161 unsigned VarType = read_vbr_uint();
Chris Lattner70cc3392001-09-10 07:58:01 +00002162 while (VarType != Type::VoidTyID) { // List is terminated by Void
Chris Lattner9dd87702004-04-03 23:43:42 +00002163 // VarType Fields: bit0 = isConstant, bit1 = hasInitializer, bit2,3,4 =
2164 // Linkage, bit4+ = slot#
2165 unsigned SlotNo = VarType >> 5;
2166 unsigned LinkageID = (VarType >> 2) & 7;
Reid Spencer060d25d2004-06-29 23:29:38 +00002167 bool isConstant = VarType & 1;
Chris Lattnerce5e04e2005-11-06 08:23:17 +00002168 bool hasInitializer = (VarType & 2) != 0;
Chris Lattner8eb52dd2005-11-06 07:11:04 +00002169 unsigned Alignment = 0;
Chris Lattner404cddf2005-11-12 01:33:40 +00002170 unsigned GlobalSectionID = 0;
Chris Lattner8eb52dd2005-11-06 07:11:04 +00002171
2172 // An extension word is present when linkage = 3 (internal) and hasinit = 0.
2173 if (LinkageID == 3 && !hasInitializer) {
2174 unsigned ExtWord = read_vbr_uint();
2175 // The extension word has this format: bit 0 = has initializer, bit 1-3 =
2176 // linkage, bit 4-8 = alignment (log2), bits 10+ = future use.
2177 hasInitializer = ExtWord & 1;
2178 LinkageID = (ExtWord >> 1) & 7;
2179 Alignment = (1 << ((ExtWord >> 4) & 31)) >> 1;
Chris Lattner404cddf2005-11-12 01:33:40 +00002180
2181 if (ExtWord & (1 << 9)) // Has a section ID.
2182 GlobalSectionID = read_vbr_uint();
Chris Lattner8eb52dd2005-11-06 07:11:04 +00002183 }
Chris Lattnere3869c82003-04-16 21:16:05 +00002184
Chris Lattnerce5e04e2005-11-06 08:23:17 +00002185 GlobalValue::LinkageTypes Linkage;
Chris Lattnerc08912f2004-01-14 16:44:44 +00002186 switch (LinkageID) {
Chris Lattnerc08912f2004-01-14 16:44:44 +00002187 case 0: Linkage = GlobalValue::ExternalLinkage; break;
2188 case 1: Linkage = GlobalValue::WeakLinkage; break;
2189 case 2: Linkage = GlobalValue::AppendingLinkage; break;
2190 case 3: Linkage = GlobalValue::InternalLinkage; break;
2191 case 4: Linkage = GlobalValue::LinkOnceLinkage; break;
Anton Korobeynikovb74ed072006-09-14 18:23:27 +00002192 case 5: Linkage = GlobalValue::DLLImportLinkage; break;
2193 case 6: Linkage = GlobalValue::DLLExportLinkage; break;
2194 case 7: Linkage = GlobalValue::ExternalWeakLinkage; break;
Misha Brukman8a96c532005-04-21 21:44:41 +00002195 default:
Reid Spencer24399722004-07-09 22:21:33 +00002196 error("Unknown linkage type: " + utostr(LinkageID));
Reid Spencer060d25d2004-06-29 23:29:38 +00002197 Linkage = GlobalValue::InternalLinkage;
2198 break;
Chris Lattnere3869c82003-04-16 21:16:05 +00002199 }
2200
2201 const Type *Ty = getType(SlotNo);
Chris Lattnere73bd452005-11-06 07:43:39 +00002202 if (!Ty)
Reid Spencer24399722004-07-09 22:21:33 +00002203 error("Global has no type! SlotNo=" + utostr(SlotNo));
Reid Spencer060d25d2004-06-29 23:29:38 +00002204
Chris Lattnere73bd452005-11-06 07:43:39 +00002205 if (!isa<PointerType>(Ty))
Reid Spencer24399722004-07-09 22:21:33 +00002206 error("Global not a pointer type! Ty= " + Ty->getDescription());
Chris Lattner70cc3392001-09-10 07:58:01 +00002207
Chris Lattner52e20b02003-03-19 20:54:26 +00002208 const Type *ElTy = cast<PointerType>(Ty)->getElementType();
Chris Lattnerd70684f2001-09-18 04:01:05 +00002209
Chris Lattner70cc3392001-09-10 07:58:01 +00002210 // Create the global variable...
Reid Spencer060d25d2004-06-29 23:29:38 +00002211 GlobalVariable *GV = new GlobalVariable(ElTy, isConstant, Linkage,
Chris Lattner52e20b02003-03-19 20:54:26 +00002212 0, "", TheModule);
Chris Lattner8eb52dd2005-11-06 07:11:04 +00002213 GV->setAlignment(Alignment);
Chris Lattner29b789b2003-11-19 17:27:18 +00002214 insertValue(GV, SlotNo, ModuleValues);
Chris Lattner05950c32001-10-13 06:47:01 +00002215
Chris Lattner404cddf2005-11-12 01:33:40 +00002216 if (GlobalSectionID != 0)
2217 SectionID[GV] = GlobalSectionID;
2218
Reid Spencer060d25d2004-06-29 23:29:38 +00002219 unsigned initSlot = 0;
Misha Brukman8a96c532005-04-21 21:44:41 +00002220 if (hasInitializer) {
Reid Spencer060d25d2004-06-29 23:29:38 +00002221 initSlot = read_vbr_uint();
2222 GlobalInits.push_back(std::make_pair(GV, initSlot));
2223 }
2224
2225 // Notify handler about the global value.
Chris Lattner4a242b32004-10-14 01:39:18 +00002226 if (Handler)
2227 Handler->handleGlobalVariable(ElTy, isConstant, Linkage, SlotNo,initSlot);
Reid Spencer060d25d2004-06-29 23:29:38 +00002228
2229 // Get next item
2230 VarType = read_vbr_uint();
Chris Lattner70cc3392001-09-10 07:58:01 +00002231 }
2232
Chris Lattner52e20b02003-03-19 20:54:26 +00002233 // Read the function objects for all of the functions that are coming
Chris Lattnera79e7cc2004-10-16 18:18:16 +00002234 unsigned FnSignature = read_vbr_uint();
Reid Spencer24399722004-07-09 22:21:33 +00002235
Chris Lattnera79e7cc2004-10-16 18:18:16 +00002236 // List is terminated by VoidTy.
Chris Lattnere73bd452005-11-06 07:43:39 +00002237 while (((FnSignature & (~0U >> 1)) >> 5) != Type::VoidTyID) {
2238 const Type *Ty = getType((FnSignature & (~0U >> 1)) >> 5);
Chris Lattner927b1852003-10-09 20:22:47 +00002239 if (!isa<PointerType>(Ty) ||
Reid Spencer060d25d2004-06-29 23:29:38 +00002240 !isa<FunctionType>(cast<PointerType>(Ty)->getElementType())) {
Misha Brukman8a96c532005-04-21 21:44:41 +00002241 error("Function not a pointer to function type! Ty = " +
Reid Spencer46b002c2004-07-11 17:28:43 +00002242 Ty->getDescription());
Reid Spencer060d25d2004-06-29 23:29:38 +00002243 }
Chris Lattner8cdc6b72002-10-23 00:51:54 +00002244
Chris Lattner2a7b6ba2003-03-06 17:15:19 +00002245 // We create functions by passing the underlying FunctionType to create...
Misha Brukman8a96c532005-04-21 21:44:41 +00002246 const FunctionType* FTy =
Reid Spencer060d25d2004-06-29 23:29:38 +00002247 cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
Chris Lattner00950542001-06-06 20:29:01 +00002248
Chris Lattner18549c22004-11-15 21:43:03 +00002249 // Insert the place holder.
Chris Lattner404cddf2005-11-12 01:33:40 +00002250 Function *Func = new Function(FTy, GlobalValue::ExternalLinkage,
Reid Spencer04cde2c2004-07-04 11:33:49 +00002251 "", TheModule);
Reid Spencere1e96c02006-01-19 07:02:16 +00002252
Chris Lattnere73bd452005-11-06 07:43:39 +00002253 insertValue(Func, (FnSignature & (~0U >> 1)) >> 5, ModuleValues);
Chris Lattnera79e7cc2004-10-16 18:18:16 +00002254
2255 // Flags are not used yet.
Chris Lattner97fbc502004-11-15 22:38:52 +00002256 unsigned Flags = FnSignature & 31;
Chris Lattner00950542001-06-06 20:29:01 +00002257
Chris Lattner97fbc502004-11-15 22:38:52 +00002258 // Save this for later so we know type of lazily instantiated functions.
2259 // Note that known-external functions do not have FunctionInfo blocks, so we
2260 // do not add them to the FunctionSignatureList.
2261 if ((Flags & (1 << 4)) == 0)
2262 FunctionSignatureList.push_back(Func);
Chris Lattner52e20b02003-03-19 20:54:26 +00002263
Chris Lattnere73bd452005-11-06 07:43:39 +00002264 // Get the calling convention from the low bits.
2265 unsigned CC = Flags & 15;
2266 unsigned Alignment = 0;
2267 if (FnSignature & (1 << 31)) { // Has extension word?
2268 unsigned ExtWord = read_vbr_uint();
2269 Alignment = (1 << (ExtWord & 31)) >> 1;
2270 CC |= ((ExtWord >> 5) & 15) << 4;
Chris Lattner404cddf2005-11-12 01:33:40 +00002271
2272 if (ExtWord & (1 << 10)) // Has a section ID.
2273 SectionID[Func] = read_vbr_uint();
Anton Korobeynikovb74ed072006-09-14 18:23:27 +00002274
2275 // Parse external declaration linkage
2276 switch ((ExtWord >> 11) & 3) {
2277 case 0: break;
2278 case 1: Func->setLinkage(Function::DLLImportLinkage); break;
2279 case 2: Func->setLinkage(Function::ExternalWeakLinkage); break;
2280 default: assert(0 && "Unsupported external linkage");
2281 }
Chris Lattnere73bd452005-11-06 07:43:39 +00002282 }
2283
Chris Lattner54b369e2005-11-06 07:46:13 +00002284 Func->setCallingConv(CC-1);
Chris Lattnere73bd452005-11-06 07:43:39 +00002285 Func->setAlignment(Alignment);
Chris Lattner479ffeb2005-05-06 20:42:57 +00002286
Reid Spencer04cde2c2004-07-04 11:33:49 +00002287 if (Handler) Handler->handleFunctionDeclaration(Func);
Reid Spencer060d25d2004-06-29 23:29:38 +00002288
Chris Lattnera79e7cc2004-10-16 18:18:16 +00002289 // Get the next function signature.
2290 FnSignature = read_vbr_uint();
Chris Lattner00950542001-06-06 20:29:01 +00002291 }
2292
Misha Brukman8a96c532005-04-21 21:44:41 +00002293 // Now that the function signature list is set up, reverse it so that we can
Chris Lattner74734132002-08-17 22:01:27 +00002294 // remove elements efficiently from the back of the vector.
2295 std::reverse(FunctionSignatureList.begin(), FunctionSignatureList.end());
Chris Lattner00950542001-06-06 20:29:01 +00002296
Chris Lattner404cddf2005-11-12 01:33:40 +00002297 /// SectionNames - This contains the list of section names encoded in the
2298 /// moduleinfoblock. Functions and globals with an explicit section index
2299 /// into this to get their section name.
2300 std::vector<std::string> SectionNames;
2301
Reid Spencerd798a512006-11-14 04:47:22 +00002302 // Read in the dependent library information.
2303 unsigned num_dep_libs = read_vbr_uint();
2304 std::string dep_lib;
2305 while (num_dep_libs--) {
2306 dep_lib = read_str();
2307 TheModule->addLibrary(dep_lib);
Reid Spencer5b472d92004-08-21 20:49:23 +00002308 if (Handler)
Reid Spencerd798a512006-11-14 04:47:22 +00002309 Handler->handleDependentLibrary(dep_lib);
Reid Spencerad89bd62004-07-25 18:07:36 +00002310 }
2311
Reid Spencerd798a512006-11-14 04:47:22 +00002312 // Read target triple and place into the module.
2313 std::string triple = read_str();
2314 TheModule->setTargetTriple(triple);
2315 if (Handler)
2316 Handler->handleTargetTriple(triple);
2317
2318 if (At != BlockEnd) {
2319 // If the file has section info in it, read the section names now.
2320 unsigned NumSections = read_vbr_uint();
2321 while (NumSections--)
2322 SectionNames.push_back(read_str());
2323 }
2324
2325 // If the file has module-level inline asm, read it now.
2326 if (At != BlockEnd)
2327 TheModule->setModuleInlineAsm(read_str());
2328
Chris Lattner404cddf2005-11-12 01:33:40 +00002329 // If any globals are in specified sections, assign them now.
2330 for (std::map<GlobalValue*, unsigned>::iterator I = SectionID.begin(), E =
2331 SectionID.end(); I != E; ++I)
2332 if (I->second) {
2333 if (I->second > SectionID.size())
2334 error("SectionID out of range for global!");
2335 I->first->setSection(SectionNames[I->second-1]);
2336 }
Reid Spencerad89bd62004-07-25 18:07:36 +00002337
Chris Lattner00950542001-06-06 20:29:01 +00002338 // This is for future proofing... in the future extra fields may be added that
2339 // we don't understand, so we transparently ignore them.
2340 //
Reid Spencer060d25d2004-06-29 23:29:38 +00002341 At = BlockEnd;
2342
Reid Spencer04cde2c2004-07-04 11:33:49 +00002343 if (Handler) Handler->handleModuleGlobalsEnd();
Chris Lattner00950542001-06-06 20:29:01 +00002344}
2345
Reid Spencer04cde2c2004-07-04 11:33:49 +00002346/// Parse the version information and decode it by setting flags on the
2347/// Reader that enable backward compatibility of the reader.
Reid Spencer060d25d2004-06-29 23:29:38 +00002348void BytecodeReader::ParseVersionInfo() {
2349 unsigned Version = read_vbr_uint();
Chris Lattner036b8aa2003-03-06 17:55:45 +00002350
2351 // Unpack version number: low four bits are for flags, top bits = version
Chris Lattnerd445c6b2003-08-24 13:47:36 +00002352 Module::Endianness Endianness;
2353 Module::PointerSize PointerSize;
2354 Endianness = (Version & 1) ? Module::BigEndian : Module::LittleEndian;
2355 PointerSize = (Version & 2) ? Module::Pointer64 : Module::Pointer32;
2356
2357 bool hasNoEndianness = Version & 4;
2358 bool hasNoPointerSize = Version & 8;
Misha Brukman8a96c532005-04-21 21:44:41 +00002359
Chris Lattnerd445c6b2003-08-24 13:47:36 +00002360 RevisionNum = Version >> 4;
Chris Lattnere3869c82003-04-16 21:16:05 +00002361
Reid Spencerd798a512006-11-14 04:47:22 +00002362 // Default the backwards compatibility flag values for the current BC version
Reid Spencer6996feb2006-11-08 21:27:54 +00002363 hasSignlessDivRem = false;
2364 hasSignlessShrCastSetcc = false;
Chris Lattner036b8aa2003-03-06 17:55:45 +00002365
Reid Spencer1628cec2006-10-26 06:15:43 +00002366 // Determine which backwards compatibility flags to set based on the
2367 // bytecode file's version number
Chris Lattner036b8aa2003-03-06 17:55:45 +00002368 switch (RevisionNum) {
Reid Spencerd798a512006-11-14 04:47:22 +00002369 case 0: // LLVM 1.0, 1.1 (Released)
2370 case 1: // LLVM 1.2 (Released)
2371 case 2: // 1.2.5 (Not Released)
2372 case 3: // LLVM 1.3 (Released)
2373 case 4: // 1.3.1 (Not Released)
2374 error("Old bytecode formats no longer supported");
2375 break;
Reid Spencer04cde2c2004-07-04 11:33:49 +00002376
Reid Spencerd798a512006-11-14 04:47:22 +00002377 case 5: // 1.4 (Released)
Reid Spencer6996feb2006-11-08 21:27:54 +00002378 // In version 6, the Div and Rem instructions were converted to their
2379 // signed and floating point counterparts: UDiv, SDiv, FDiv, URem, SRem,
2380 // and FRem. Versions prior to 6 need to indicate that they have the
2381 // signless Div and Rem instructions.
2382 hasSignlessDivRem = true;
2383
2384 // FALL THROUGH
2385
Reid Spencerd798a512006-11-14 04:47:22 +00002386 case 6: // 1.9 (Released)
Reid Spencer1628cec2006-10-26 06:15:43 +00002387 // In version 5 and prior, instructions were signless while integer types
2388 // were signed. In version 6, instructions became signed and types became
2389 // signless. For example in version 5 we have the DIV instruction but in
2390 // version 6 we have FDIV, SDIV and UDIV to replace it. This caused a
2391 // renumbering of the instruction codes in version 6 that must be dealt with
2392 // when reading old bytecode files.
Reid Spencer6996feb2006-11-08 21:27:54 +00002393 hasSignlessShrCastSetcc = true;
Reid Spencer1628cec2006-10-26 06:15:43 +00002394
2395 // FALL THROUGH
Reid Spencer6996feb2006-11-08 21:27:54 +00002396
2397 case 7:
Chris Lattnera79e7cc2004-10-16 18:18:16 +00002398 break;
2399
Chris Lattner036b8aa2003-03-06 17:55:45 +00002400 default:
Reid Spencer24399722004-07-09 22:21:33 +00002401 error("Unknown bytecode version number: " + itostr(RevisionNum));
Chris Lattner036b8aa2003-03-06 17:55:45 +00002402 }
2403
Chris Lattnerd445c6b2003-08-24 13:47:36 +00002404 if (hasNoEndianness) Endianness = Module::AnyEndianness;
2405 if (hasNoPointerSize) PointerSize = Module::AnyPointerSize;
Chris Lattner76e38962003-04-22 18:15:10 +00002406
Brian Gaekefe2102b2004-07-14 20:33:13 +00002407 TheModule->setEndianness(Endianness);
2408 TheModule->setPointerSize(PointerSize);
2409
Reid Spencer46b002c2004-07-11 17:28:43 +00002410 if (Handler) Handler->handleVersionInfo(RevisionNum, Endianness, PointerSize);
Chris Lattner036b8aa2003-03-06 17:55:45 +00002411}
2412
Reid Spencer04cde2c2004-07-04 11:33:49 +00002413/// Parse a whole module.
Reid Spencer060d25d2004-06-29 23:29:38 +00002414void BytecodeReader::ParseModule() {
Chris Lattner00950542001-06-06 20:29:01 +00002415 unsigned Type, Size;
Chris Lattner00950542001-06-06 20:29:01 +00002416
Reid Spencer060d25d2004-06-29 23:29:38 +00002417 FunctionSignatureList.clear(); // Just in case...
Chris Lattner00950542001-06-06 20:29:01 +00002418
2419 // Read into instance variables...
Reid Spencer060d25d2004-06-29 23:29:38 +00002420 ParseVersionInfo();
Chris Lattner00950542001-06-06 20:29:01 +00002421
Reid Spencer060d25d2004-06-29 23:29:38 +00002422 bool SeenModuleGlobalInfo = false;
2423 bool SeenGlobalTypePlane = false;
2424 BufPtr MyEnd = BlockEnd;
2425 while (At < MyEnd) {
2426 BufPtr OldAt = At;
2427 read_block(Type, Size);
2428
Chris Lattner00950542001-06-06 20:29:01 +00002429 switch (Type) {
Reid Spencer060d25d2004-06-29 23:29:38 +00002430
Reid Spencerad89bd62004-07-25 18:07:36 +00002431 case BytecodeFormat::GlobalTypePlaneBlockID:
Reid Spencer46b002c2004-07-11 17:28:43 +00002432 if (SeenGlobalTypePlane)
Reid Spencer24399722004-07-09 22:21:33 +00002433 error("Two GlobalTypePlane Blocks Encountered!");
Reid Spencer060d25d2004-06-29 23:29:38 +00002434
Reid Spencer5b472d92004-08-21 20:49:23 +00002435 if (Size > 0)
2436 ParseGlobalTypes();
Reid Spencer060d25d2004-06-29 23:29:38 +00002437 SeenGlobalTypePlane = true;
Chris Lattner52e20b02003-03-19 20:54:26 +00002438 break;
2439
Misha Brukman8a96c532005-04-21 21:44:41 +00002440 case BytecodeFormat::ModuleGlobalInfoBlockID:
Reid Spencer46b002c2004-07-11 17:28:43 +00002441 if (SeenModuleGlobalInfo)
Reid Spencer24399722004-07-09 22:21:33 +00002442 error("Two ModuleGlobalInfo Blocks Encountered!");
Reid Spencer060d25d2004-06-29 23:29:38 +00002443 ParseModuleGlobalInfo();
2444 SeenModuleGlobalInfo = true;
Chris Lattner52e20b02003-03-19 20:54:26 +00002445 break;
2446
Reid Spencerad89bd62004-07-25 18:07:36 +00002447 case BytecodeFormat::ConstantPoolBlockID:
Reid Spencer04cde2c2004-07-04 11:33:49 +00002448 ParseConstantPool(ModuleValues, ModuleTypes,false);
Chris Lattner00950542001-06-06 20:29:01 +00002449 break;
2450
Reid Spencerad89bd62004-07-25 18:07:36 +00002451 case BytecodeFormat::FunctionBlockID:
Reid Spencer060d25d2004-06-29 23:29:38 +00002452 ParseFunctionLazily();
Chris Lattner00950542001-06-06 20:29:01 +00002453 break;
Chris Lattner00950542001-06-06 20:29:01 +00002454
Reid Spencerad89bd62004-07-25 18:07:36 +00002455 case BytecodeFormat::SymbolTableBlockID:
Reid Spencer060d25d2004-06-29 23:29:38 +00002456 ParseSymbolTable(0, &TheModule->getSymbolTable());
Chris Lattner00950542001-06-06 20:29:01 +00002457 break;
Reid Spencer060d25d2004-06-29 23:29:38 +00002458
Chris Lattner00950542001-06-06 20:29:01 +00002459 default:
Reid Spencer060d25d2004-06-29 23:29:38 +00002460 At += Size;
2461 if (OldAt > At) {
Reid Spencer46b002c2004-07-11 17:28:43 +00002462 error("Unexpected Block of Type #" + utostr(Type) + " encountered!");
Reid Spencer060d25d2004-06-29 23:29:38 +00002463 }
Chris Lattner00950542001-06-06 20:29:01 +00002464 break;
2465 }
Reid Spencer060d25d2004-06-29 23:29:38 +00002466 BlockEnd = MyEnd;
Chris Lattner00950542001-06-06 20:29:01 +00002467 }
2468
Chris Lattner52e20b02003-03-19 20:54:26 +00002469 // After the module constant pool has been read, we can safely initialize
2470 // global variables...
2471 while (!GlobalInits.empty()) {
2472 GlobalVariable *GV = GlobalInits.back().first;
2473 unsigned Slot = GlobalInits.back().second;
2474 GlobalInits.pop_back();
2475
2476 // Look up the initializer value...
Chris Lattner29b789b2003-11-19 17:27:18 +00002477 // FIXME: Preserve this type ID!
Reid Spencer060d25d2004-06-29 23:29:38 +00002478
2479 const llvm::PointerType* GVType = GV->getType();
2480 unsigned TypeSlot = getTypeSlot(GVType->getElementType());
Chris Lattner93361992004-01-15 18:45:25 +00002481 if (Constant *CV = getConstantValue(TypeSlot, Slot)) {
Misha Brukman8a96c532005-04-21 21:44:41 +00002482 if (GV->hasInitializer())
Reid Spencer24399722004-07-09 22:21:33 +00002483 error("Global *already* has an initializer?!");
Reid Spencer04cde2c2004-07-04 11:33:49 +00002484 if (Handler) Handler->handleGlobalInitializer(GV,CV);
Chris Lattner93361992004-01-15 18:45:25 +00002485 GV->setInitializer(CV);
Chris Lattner52e20b02003-03-19 20:54:26 +00002486 } else
Reid Spencer24399722004-07-09 22:21:33 +00002487 error("Cannot find initializer value.");
Chris Lattner52e20b02003-03-19 20:54:26 +00002488 }
2489
Chris Lattneraba5ff52005-05-05 20:57:00 +00002490 if (!ConstantFwdRefs.empty())
2491 error("Use of undefined constants in a module");
2492
Reid Spencer060d25d2004-06-29 23:29:38 +00002493 /// Make sure we pulled them all out. If we didn't then there's a declaration
2494 /// but a missing body. That's not allowed.
Misha Brukman12c29d12003-09-22 23:38:23 +00002495 if (!FunctionSignatureList.empty())
Reid Spencer24399722004-07-09 22:21:33 +00002496 error("Function declared, but bytecode stream ended before definition");
Chris Lattner00950542001-06-06 20:29:01 +00002497}
2498
Reid Spencer04cde2c2004-07-04 11:33:49 +00002499/// This function completely parses a bytecode buffer given by the \p Buf
2500/// and \p Length parameters.
Anton Korobeynikov7d515442006-09-01 20:35:17 +00002501bool BytecodeReader::ParseBytecode(volatile BufPtr Buf, unsigned Length,
Reid Spencer233fe722006-08-22 16:09:19 +00002502 const std::string &ModuleID,
2503 std::string* ErrMsg) {
Misha Brukmane0dd0d42003-09-23 16:15:29 +00002504
Reid Spencer233fe722006-08-22 16:09:19 +00002505 /// We handle errors by
2506 if (setjmp(context)) {
2507 // Cleanup after error
2508 if (Handler) Handler->handleError(ErrorMsg);
Reid Spencer060d25d2004-06-29 23:29:38 +00002509 freeState();
Chris Lattner2a7b6ba2003-03-06 17:15:19 +00002510 delete TheModule;
2511 TheModule = 0;
Chris Lattner3bdad692004-11-15 21:55:33 +00002512 if (decompressedBlock != 0 ) {
Reid Spencer61aaf2e2004-11-14 21:59:21 +00002513 ::free(decompressedBlock);
Chris Lattner3bdad692004-11-15 21:55:33 +00002514 decompressedBlock = 0;
2515 }
Reid Spencer233fe722006-08-22 16:09:19 +00002516 // Set caller's error message, if requested
2517 if (ErrMsg)
2518 *ErrMsg = ErrorMsg;
2519 // Indicate an error occurred
2520 return true;
Chris Lattner2a7b6ba2003-03-06 17:15:19 +00002521 }
Reid Spencer233fe722006-08-22 16:09:19 +00002522
2523 RevisionNum = 0;
2524 At = MemStart = BlockStart = Buf;
2525 MemEnd = BlockEnd = Buf + Length;
2526
2527 // Create the module
2528 TheModule = new Module(ModuleID);
2529
2530 if (Handler) Handler->handleStart(TheModule, Length);
2531
2532 // Read the four bytes of the signature.
2533 unsigned Sig = read_uint();
2534
2535 // If this is a compressed file
2536 if (Sig == ('l' | ('l' << 8) | ('v' << 16) | ('c' << 24))) {
2537
2538 // Invoke the decompression of the bytecode. Note that we have to skip the
2539 // file's magic number which is not part of the compressed block. Hence,
2540 // the Buf+4 and Length-4. The result goes into decompressedBlock, a data
2541 // member for retention until BytecodeReader is destructed.
2542 unsigned decompressedLength = Compressor::decompressToNewBuffer(
2543 (char*)Buf+4,Length-4,decompressedBlock);
2544
2545 // We must adjust the buffer pointers used by the bytecode reader to point
2546 // into the new decompressed block. After decompression, the
2547 // decompressedBlock will point to a contiguous memory area that has
2548 // the decompressed data.
2549 At = MemStart = BlockStart = Buf = (BufPtr) decompressedBlock;
2550 MemEnd = BlockEnd = Buf + decompressedLength;
2551
2552 // else if this isn't a regular (uncompressed) bytecode file, then its
2553 // and error, generate that now.
2554 } else if (Sig != ('l' | ('l' << 8) | ('v' << 16) | ('m' << 24))) {
2555 error("Invalid bytecode signature: " + utohexstr(Sig));
2556 }
2557
2558 // Tell the handler we're starting a module
2559 if (Handler) Handler->handleModuleBegin(ModuleID);
2560
2561 // Get the module block and size and verify. This is handled specially
2562 // because the module block/size is always written in long format. Other
2563 // blocks are written in short format so the read_block method is used.
2564 unsigned Type, Size;
2565 Type = read_uint();
2566 Size = read_uint();
2567 if (Type != BytecodeFormat::ModuleBlockID) {
2568 error("Expected Module Block! Type:" + utostr(Type) + ", Size:"
2569 + utostr(Size));
2570 }
2571
2572 // It looks like the darwin ranlib program is broken, and adds trailing
2573 // garbage to the end of some bytecode files. This hack allows the bc
2574 // reader to ignore trailing garbage on bytecode files.
2575 if (At + Size < MemEnd)
2576 MemEnd = BlockEnd = At+Size;
2577
2578 if (At + Size != MemEnd)
2579 error("Invalid Top Level Block Length! Type:" + utostr(Type)
2580 + ", Size:" + utostr(Size));
2581
2582 // Parse the module contents
2583 this->ParseModule();
2584
2585 // Check for missing functions
2586 if (hasFunctions())
2587 error("Function expected, but bytecode stream ended!");
2588
2589 // Look for intrinsic functions to upgrade, upgrade them, and save the
2590 // mapping from old function to new for use later when instructions are
2591 // converted.
2592 for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
2593 FI != FE; ++FI)
2594 if (Function* newF = UpgradeIntrinsicFunction(FI)) {
2595 upgradedFunctions.insert(std::make_pair(FI, newF));
2596 FI->setName("");
2597 }
2598
2599 // Tell the handler we're done with the module
2600 if (Handler)
2601 Handler->handleModuleEnd(ModuleID);
2602
2603 // Tell the handler we're finished the parse
2604 if (Handler) Handler->handleFinish();
2605
2606 return false;
2607
Chris Lattner00950542001-06-06 20:29:01 +00002608}
Reid Spencer060d25d2004-06-29 23:29:38 +00002609
2610//===----------------------------------------------------------------------===//
2611//=== Default Implementations of Handler Methods
2612//===----------------------------------------------------------------------===//
2613
2614BytecodeHandler::~BytecodeHandler() {}
Reid Spencer060d25d2004-06-29 23:29:38 +00002615