blob: 86e011eb0aa5d84eb4c204342668bfea3966a372 [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
Reid Spencer967413f2006-11-18 04:37:19 +00001509 else if (Opcode >= 16 && Opcode <= 35) // And through Shr
Reid Spencer6996feb2006-11-08 21:27:54 +00001510 // Adjust for new instruction codes
1511 Opcode -= 4;
Reid Spencer967413f2006-11-18 04:37:19 +00001512 else if (Opcode >= 36 && Opcode <= 42) // Everything after Select
1513 // In vers 6 bytecode we eliminated the placeholders for the obsolete
1514 // VAARG and VANEXT instructions. Consequently those two slots were
1515 // filled starting with Select (36) which was 34. So now we only need
1516 // to subtract two. This circumvents hitting opcodes 32 and 33
1517 Opcode -= 2;
1518 else { // Opcode < 10 or > 42
1519 // No upgrade necessary.
1520 return 0;
1521 }
Reid Spencer6996feb2006-11-08 21:27:54 +00001522 }
1523
Reid Spencer1628cec2006-10-26 06:15:43 +00001524 switch (Opcode) {
1525 default: // Pass Through
1526 // If we don't match any of the cases here then the opcode is fine the
1527 // way it is.
1528 break;
1529 case 7: // Add
1530 Opcode = Instruction::Add;
1531 break;
1532 case 8: // Sub
1533 Opcode = Instruction::Sub;
1534 break;
1535 case 9: // Mul
1536 Opcode = Instruction::Mul;
1537 break;
1538 case 10: // Div
1539 // The type of the instruction is based on the operands. We need to select
1540 // either udiv or sdiv based on that type. This expression selects the
1541 // cases where the type is floating point or signed in which case we
1542 // generated an sdiv instruction.
1543 if (ArgVec[0]->getType()->isFloatingPoint())
1544 Opcode = Instruction::FDiv;
1545 else if (ArgVec[0]->getType()->isSigned())
1546 Opcode = Instruction::SDiv;
1547 else
1548 Opcode = Instruction::UDiv;
1549 break;
Reid Spencer1628cec2006-10-26 06:15:43 +00001550 case 11: // Rem
Reid Spencer0a783f72006-11-02 01:53:59 +00001551 // As with "Div", make the signed/unsigned or floating point Rem
1552 // instruction choice based on the type of the operands.
Reid Spencer1628cec2006-10-26 06:15:43 +00001553 if (ArgVec[0]->getType()->isFloatingPoint())
Reid Spencer0a783f72006-11-02 01:53:59 +00001554 Opcode = Instruction::FRem;
Reid Spencer1628cec2006-10-26 06:15:43 +00001555 else if (ArgVec[0]->getType()->isSigned())
Reid Spencer0a783f72006-11-02 01:53:59 +00001556 Opcode = Instruction::SRem;
Reid Spencer1628cec2006-10-26 06:15:43 +00001557 else
Reid Spencer0a783f72006-11-02 01:53:59 +00001558 Opcode = Instruction::URem;
Reid Spencer1628cec2006-10-26 06:15:43 +00001559 break;
Reid Spencer1628cec2006-10-26 06:15:43 +00001560 case 12: // And
1561 Opcode = Instruction::And;
1562 break;
1563 case 13: // Or
1564 Opcode = Instruction::Or;
1565 break;
1566 case 14: // Xor
1567 Opcode = Instruction::Xor;
1568 break;
1569 case 15: // SetEQ
1570 Opcode = Instruction::SetEQ;
1571 break;
1572 case 16: // SetNE
1573 Opcode = Instruction::SetNE;
1574 break;
1575 case 17: // SetLE
1576 Opcode = Instruction::SetLE;
1577 break;
1578 case 18: // SetGE
1579 Opcode = Instruction::SetGE;
1580 break;
1581 case 19: // SetLT
1582 Opcode = Instruction::SetLT;
1583 break;
1584 case 20: // SetGT
1585 Opcode = Instruction::SetGT;
1586 break;
1587 case 26: // GetElementPtr
1588 Opcode = Instruction::GetElementPtr;
1589 break;
1590 case 28: // Cast
1591 Opcode = Instruction::Cast;
1592 break;
1593 case 30: // Shl
1594 Opcode = Instruction::Shl;
1595 break;
1596 case 31: // Shr
Reid Spencer3822ff52006-11-08 06:47:33 +00001597 if (ArgVec[0]->getType()->isSigned())
1598 Opcode = Instruction::AShr;
1599 else
1600 Opcode = Instruction::LShr;
Reid Spencer1628cec2006-10-26 06:15:43 +00001601 break;
1602 case 34: // Select
1603 Opcode = Instruction::Select;
1604 break;
1605 case 38: // ExtractElement
1606 Opcode = Instruction::ExtractElement;
1607 break;
1608 case 39: // InsertElement
1609 Opcode = Instruction::InsertElement;
1610 break;
1611 case 40: // ShuffleVector
1612 Opcode = Instruction::ShuffleVector;
1613 break;
1614 }
1615 return Opcode;
1616}
1617
Reid Spencer04cde2c2004-07-04 11:33:49 +00001618/// Parse a single constant value
Chris Lattner3bc5a602006-01-25 23:08:15 +00001619Value *BytecodeReader::ParseConstantPoolValue(unsigned TypeID) {
Reid Spencer060d25d2004-06-29 23:29:38 +00001620 // We must check for a ConstantExpr before switching by type because
1621 // a ConstantExpr can be of any type, and has no explicit value.
Misha Brukman8a96c532005-04-21 21:44:41 +00001622 //
Reid Spencer060d25d2004-06-29 23:29:38 +00001623 // 0 if not expr; numArgs if is expr
1624 unsigned isExprNumArgs = read_vbr_uint();
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001625
Reid Spencer060d25d2004-06-29 23:29:38 +00001626 if (isExprNumArgs) {
Reid Spencerd798a512006-11-14 04:47:22 +00001627 // 'undef' is encoded with 'exprnumargs' == 1.
1628 if (isExprNumArgs == 1)
1629 return UndefValue::get(getType(TypeID));
Misha Brukman8a96c532005-04-21 21:44:41 +00001630
Reid Spencerd798a512006-11-14 04:47:22 +00001631 // Inline asm is encoded with exprnumargs == ~0U.
1632 if (isExprNumArgs == ~0U) {
1633 std::string AsmStr = read_str();
1634 std::string ConstraintStr = read_str();
1635 unsigned Flags = read_vbr_uint();
Chris Lattner3bc5a602006-01-25 23:08:15 +00001636
Reid Spencerd798a512006-11-14 04:47:22 +00001637 const PointerType *PTy = dyn_cast<PointerType>(getType(TypeID));
1638 const FunctionType *FTy =
1639 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
1640
1641 if (!FTy || !InlineAsm::Verify(FTy, ConstraintStr))
1642 error("Invalid constraints for inline asm");
1643 if (Flags & ~1U)
1644 error("Invalid flags for inline asm");
1645 bool HasSideEffects = Flags & 1;
1646 return InlineAsm::get(FTy, AsmStr, ConstraintStr, HasSideEffects);
Chris Lattner3bc5a602006-01-25 23:08:15 +00001647 }
Reid Spencerd798a512006-11-14 04:47:22 +00001648
1649 --isExprNumArgs;
Chris Lattner3bc5a602006-01-25 23:08:15 +00001650
Reid Spencer060d25d2004-06-29 23:29:38 +00001651 // FIXME: Encoding of constant exprs could be much more compact!
1652 std::vector<Constant*> ArgVec;
1653 ArgVec.reserve(isExprNumArgs);
1654 unsigned Opcode = read_vbr_uint();
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001655
Reid Spencer060d25d2004-06-29 23:29:38 +00001656 // Read the slot number and types of each of the arguments
1657 for (unsigned i = 0; i != isExprNumArgs; ++i) {
1658 unsigned ArgValSlot = read_vbr_uint();
Reid Spencerd798a512006-11-14 04:47:22 +00001659 unsigned ArgTypeSlot = read_vbr_uint();
Misha Brukman8a96c532005-04-21 21:44:41 +00001660
Reid Spencer060d25d2004-06-29 23:29:38 +00001661 // Get the arg value from its slot if it exists, otherwise a placeholder
1662 ArgVec.push_back(getConstantValue(ArgTypeSlot, ArgValSlot));
1663 }
Misha Brukman8a96c532005-04-21 21:44:41 +00001664
Reid Spencer1628cec2006-10-26 06:15:43 +00001665 // Handle backwards compatibility for the opcode numbers
Reid Spencer6996feb2006-11-08 21:27:54 +00001666 Opcode = upgradeCEOpcodes(Opcode, ArgVec);
Reid Spencer1628cec2006-10-26 06:15:43 +00001667
Reid Spencer060d25d2004-06-29 23:29:38 +00001668 // Construct a ConstantExpr of the appropriate kind
1669 if (isExprNumArgs == 1) { // All one-operand expressions
Reid Spencer46b002c2004-07-11 17:28:43 +00001670 if (Opcode != Instruction::Cast)
Chris Lattner02dce162004-12-04 05:28:27 +00001671 error("Only cast instruction has one argument for ConstantExpr");
Reid Spencer46b002c2004-07-11 17:28:43 +00001672
Reid Spencer060d25d2004-06-29 23:29:38 +00001673 Constant* Result = ConstantExpr::getCast(ArgVec[0], getType(TypeID));
Reid Spencer04cde2c2004-07-04 11:33:49 +00001674 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001675 return Result;
1676 } else if (Opcode == Instruction::GetElementPtr) { // GetElementPtr
1677 std::vector<Constant*> IdxList(ArgVec.begin()+1, ArgVec.end());
Reid Spencer060d25d2004-06-29 23:29:38 +00001678 Constant* Result = ConstantExpr::getGetElementPtr(ArgVec[0], IdxList);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001679 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001680 return Result;
1681 } else if (Opcode == Instruction::Select) {
Reid Spencer46b002c2004-07-11 17:28:43 +00001682 if (ArgVec.size() != 3)
1683 error("Select instruction must have three arguments.");
Misha Brukman8a96c532005-04-21 21:44:41 +00001684 Constant* Result = ConstantExpr::getSelect(ArgVec[0], ArgVec[1],
Reid Spencer04cde2c2004-07-04 11:33:49 +00001685 ArgVec[2]);
1686 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001687 return Result;
Robert Bocchinofee31b32006-01-10 19:04:39 +00001688 } else if (Opcode == Instruction::ExtractElement) {
Chris Lattner59fecec2006-04-08 04:09:19 +00001689 if (ArgVec.size() != 2 ||
1690 !ExtractElementInst::isValidOperands(ArgVec[0], ArgVec[1]))
1691 error("Invalid extractelement constand expr arguments");
Robert Bocchinofee31b32006-01-10 19:04:39 +00001692 Constant* Result = ConstantExpr::getExtractElement(ArgVec[0], ArgVec[1]);
1693 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
1694 return Result;
Robert Bocchinob1f240b2006-01-17 20:06:35 +00001695 } else if (Opcode == Instruction::InsertElement) {
Chris Lattner59fecec2006-04-08 04:09:19 +00001696 if (ArgVec.size() != 3 ||
1697 !InsertElementInst::isValidOperands(ArgVec[0], ArgVec[1], ArgVec[2]))
1698 error("Invalid insertelement constand expr arguments");
1699
1700 Constant *Result =
Robert Bocchinob1f240b2006-01-17 20:06:35 +00001701 ConstantExpr::getInsertElement(ArgVec[0], ArgVec[1], ArgVec[2]);
1702 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
1703 return Result;
Chris Lattner30b44b62006-04-08 01:17:59 +00001704 } else if (Opcode == Instruction::ShuffleVector) {
1705 if (ArgVec.size() != 3 ||
1706 !ShuffleVectorInst::isValidOperands(ArgVec[0], ArgVec[1], ArgVec[2]))
Chris Lattner59fecec2006-04-08 04:09:19 +00001707 error("Invalid shufflevector constant expr arguments.");
Chris Lattner30b44b62006-04-08 01:17:59 +00001708 Constant *Result =
1709 ConstantExpr::getShuffleVector(ArgVec[0], ArgVec[1], ArgVec[2]);
1710 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
1711 return Result;
Reid Spencer060d25d2004-06-29 23:29:38 +00001712 } else { // All other 2-operand expressions
1713 Constant* Result = ConstantExpr::get(Opcode, ArgVec[0], ArgVec[1]);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001714 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001715 return Result;
1716 }
1717 }
Misha Brukman8a96c532005-04-21 21:44:41 +00001718
Reid Spencer060d25d2004-06-29 23:29:38 +00001719 // Ok, not an ConstantExpr. We now know how to read the given type...
1720 const Type *Ty = getType(TypeID);
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001721 Constant *Result = 0;
Reid Spencer060d25d2004-06-29 23:29:38 +00001722 switch (Ty->getTypeID()) {
1723 case Type::BoolTyID: {
1724 unsigned Val = read_vbr_uint();
Misha Brukman8a96c532005-04-21 21:44:41 +00001725 if (Val != 0 && Val != 1)
Reid Spencer24399722004-07-09 22:21:33 +00001726 error("Invalid boolean value read.");
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001727 Result = ConstantBool::get(Val == 1);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001728 if (Handler) Handler->handleConstantValue(Result);
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001729 break;
Reid Spencer060d25d2004-06-29 23:29:38 +00001730 }
1731
1732 case Type::UByteTyID: // Unsigned integer types...
1733 case Type::UShortTyID:
1734 case Type::UIntTyID: {
1735 unsigned Val = read_vbr_uint();
Reid Spencerb83eb642006-10-20 07:07:24 +00001736 if (!ConstantInt::isValueValidForType(Ty, uint64_t(Val)))
Reid Spencer24399722004-07-09 22:21:33 +00001737 error("Invalid unsigned byte/short/int read.");
Reid Spencerb83eb642006-10-20 07:07:24 +00001738 Result = ConstantInt::get(Ty, Val);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001739 if (Handler) Handler->handleConstantValue(Result);
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001740 break;
Reid Spencer060d25d2004-06-29 23:29:38 +00001741 }
1742
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001743 case Type::ULongTyID:
Reid Spencerb83eb642006-10-20 07:07:24 +00001744 Result = ConstantInt::get(Ty, read_vbr_uint64());
Reid Spencer04cde2c2004-07-04 11:33:49 +00001745 if (Handler) Handler->handleConstantValue(Result);
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001746 break;
1747
Reid Spencer060d25d2004-06-29 23:29:38 +00001748 case Type::SByteTyID: // Signed integer types...
1749 case Type::ShortTyID:
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001750 case Type::IntTyID:
1751 case Type::LongTyID: {
Reid Spencer060d25d2004-06-29 23:29:38 +00001752 int64_t Val = read_vbr_int64();
Reid Spencerb83eb642006-10-20 07:07:24 +00001753 if (!ConstantInt::isValueValidForType(Ty, Val))
Reid Spencer24399722004-07-09 22:21:33 +00001754 error("Invalid signed byte/short/int/long read.");
Reid Spencerb83eb642006-10-20 07:07:24 +00001755 Result = ConstantInt::get(Ty, Val);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001756 if (Handler) Handler->handleConstantValue(Result);
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001757 break;
Reid Spencer060d25d2004-06-29 23:29:38 +00001758 }
1759
1760 case Type::FloatTyID: {
Reid Spencer46b002c2004-07-11 17:28:43 +00001761 float Val;
1762 read_float(Val);
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001763 Result = ConstantFP::get(Ty, Val);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001764 if (Handler) Handler->handleConstantValue(Result);
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001765 break;
Reid Spencer060d25d2004-06-29 23:29:38 +00001766 }
1767
1768 case Type::DoubleTyID: {
1769 double Val;
Reid Spencer46b002c2004-07-11 17:28:43 +00001770 read_double(Val);
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001771 Result = ConstantFP::get(Ty, Val);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001772 if (Handler) Handler->handleConstantValue(Result);
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001773 break;
Reid Spencer060d25d2004-06-29 23:29:38 +00001774 }
1775
Reid Spencer060d25d2004-06-29 23:29:38 +00001776 case Type::ArrayTyID: {
1777 const ArrayType *AT = cast<ArrayType>(Ty);
1778 unsigned NumElements = AT->getNumElements();
1779 unsigned TypeSlot = getTypeSlot(AT->getElementType());
1780 std::vector<Constant*> Elements;
1781 Elements.reserve(NumElements);
1782 while (NumElements--) // Read all of the elements of the constant.
1783 Elements.push_back(getConstantValue(TypeSlot,
1784 read_vbr_uint()));
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001785 Result = ConstantArray::get(AT, Elements);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001786 if (Handler) Handler->handleConstantArray(AT, Elements, TypeSlot, Result);
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001787 break;
Reid Spencer060d25d2004-06-29 23:29:38 +00001788 }
1789
1790 case Type::StructTyID: {
1791 const StructType *ST = cast<StructType>(Ty);
1792
1793 std::vector<Constant *> Elements;
1794 Elements.reserve(ST->getNumElements());
1795 for (unsigned i = 0; i != ST->getNumElements(); ++i)
1796 Elements.push_back(getConstantValue(ST->getElementType(i),
1797 read_vbr_uint()));
1798
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001799 Result = ConstantStruct::get(ST, Elements);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001800 if (Handler) Handler->handleConstantStruct(ST, Elements, Result);
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001801 break;
Misha Brukman8a96c532005-04-21 21:44:41 +00001802 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001803
Brian Gaeke715c90b2004-08-20 06:00:58 +00001804 case Type::PackedTyID: {
1805 const PackedType *PT = cast<PackedType>(Ty);
1806 unsigned NumElements = PT->getNumElements();
1807 unsigned TypeSlot = getTypeSlot(PT->getElementType());
1808 std::vector<Constant*> Elements;
1809 Elements.reserve(NumElements);
1810 while (NumElements--) // Read all of the elements of the constant.
1811 Elements.push_back(getConstantValue(TypeSlot,
1812 read_vbr_uint()));
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001813 Result = ConstantPacked::get(PT, Elements);
Brian Gaeke715c90b2004-08-20 06:00:58 +00001814 if (Handler) Handler->handleConstantPacked(PT, Elements, TypeSlot, Result);
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001815 break;
Brian Gaeke715c90b2004-08-20 06:00:58 +00001816 }
1817
Chris Lattner638c3812004-11-19 16:24:05 +00001818 case Type::PointerTyID: { // ConstantPointerRef value (backwards compat).
Reid Spencer060d25d2004-06-29 23:29:38 +00001819 const PointerType *PT = cast<PointerType>(Ty);
1820 unsigned Slot = read_vbr_uint();
Misha Brukman8a96c532005-04-21 21:44:41 +00001821
Reid Spencer060d25d2004-06-29 23:29:38 +00001822 // Check to see if we have already read this global variable...
1823 Value *Val = getValue(TypeID, Slot, false);
Reid Spencer060d25d2004-06-29 23:29:38 +00001824 if (Val) {
Chris Lattnerbcb11cf2004-07-27 02:34:49 +00001825 GlobalValue *GV = dyn_cast<GlobalValue>(Val);
1826 if (!GV) error("GlobalValue not in ValueTable!");
1827 if (Handler) Handler->handleConstantPointer(PT, Slot, GV);
1828 return GV;
Reid Spencer060d25d2004-06-29 23:29:38 +00001829 } else {
Reid Spencer24399722004-07-09 22:21:33 +00001830 error("Forward references are not allowed here.");
Reid Spencer060d25d2004-06-29 23:29:38 +00001831 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001832 }
1833
1834 default:
Reid Spencer24399722004-07-09 22:21:33 +00001835 error("Don't know how to deserialize constant value of type '" +
Reid Spencer060d25d2004-06-29 23:29:38 +00001836 Ty->getDescription());
1837 break;
1838 }
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001839
1840 // Check that we didn't read a null constant if they are implicit for this
1841 // type plane. Do not do this check for constantexprs, as they may be folded
1842 // to a null value in a way that isn't predicted when a .bc file is initially
1843 // produced.
1844 assert((!isa<Constant>(Result) || !cast<Constant>(Result)->isNullValue()) ||
1845 !hasImplicitNull(TypeID) &&
1846 "Cannot read null values from bytecode!");
1847 return Result;
Reid Spencer060d25d2004-06-29 23:29:38 +00001848}
1849
Misha Brukman8a96c532005-04-21 21:44:41 +00001850/// Resolve references for constants. This function resolves the forward
1851/// referenced constants in the ConstantFwdRefs map. It uses the
Reid Spencer04cde2c2004-07-04 11:33:49 +00001852/// replaceAllUsesWith method of Value class to substitute the placeholder
1853/// instance with the actual instance.
Chris Lattner389bd042004-12-09 06:19:44 +00001854void BytecodeReader::ResolveReferencesToConstant(Constant *NewV, unsigned Typ,
1855 unsigned Slot) {
Chris Lattner29b789b2003-11-19 17:27:18 +00001856 ConstantRefsType::iterator I =
Chris Lattner389bd042004-12-09 06:19:44 +00001857 ConstantFwdRefs.find(std::make_pair(Typ, Slot));
Chris Lattner29b789b2003-11-19 17:27:18 +00001858 if (I == ConstantFwdRefs.end()) return; // Never forward referenced?
Chris Lattner00950542001-06-06 20:29:01 +00001859
Chris Lattner29b789b2003-11-19 17:27:18 +00001860 Value *PH = I->second; // Get the placeholder...
1861 PH->replaceAllUsesWith(NewV);
1862 delete PH; // Delete the old placeholder
1863 ConstantFwdRefs.erase(I); // Remove the map entry for it
Vikram S. Advec1e4a812002-07-14 23:04:18 +00001864}
1865
Reid Spencer04cde2c2004-07-04 11:33:49 +00001866/// Parse the constant strings section.
Reid Spencer060d25d2004-06-29 23:29:38 +00001867void BytecodeReader::ParseStringConstants(unsigned NumEntries, ValueTable &Tab){
1868 for (; NumEntries; --NumEntries) {
Reid Spencerd798a512006-11-14 04:47:22 +00001869 unsigned Typ = read_vbr_uint();
Reid Spencer060d25d2004-06-29 23:29:38 +00001870 const Type *Ty = getType(Typ);
1871 if (!isa<ArrayType>(Ty))
Reid Spencer24399722004-07-09 22:21:33 +00001872 error("String constant data invalid!");
Misha Brukman8a96c532005-04-21 21:44:41 +00001873
Reid Spencer060d25d2004-06-29 23:29:38 +00001874 const ArrayType *ATy = cast<ArrayType>(Ty);
1875 if (ATy->getElementType() != Type::SByteTy &&
1876 ATy->getElementType() != Type::UByteTy)
Reid Spencer24399722004-07-09 22:21:33 +00001877 error("String constant data invalid!");
Misha Brukman8a96c532005-04-21 21:44:41 +00001878
Reid Spencer060d25d2004-06-29 23:29:38 +00001879 // Read character data. The type tells us how long the string is.
Misha Brukman8a96c532005-04-21 21:44:41 +00001880 char *Data = reinterpret_cast<char *>(alloca(ATy->getNumElements()));
Reid Spencer060d25d2004-06-29 23:29:38 +00001881 read_data(Data, Data+ATy->getNumElements());
Chris Lattner52e20b02003-03-19 20:54:26 +00001882
Reid Spencer060d25d2004-06-29 23:29:38 +00001883 std::vector<Constant*> Elements(ATy->getNumElements());
Reid Spencerb83eb642006-10-20 07:07:24 +00001884 const Type* ElemType = ATy->getElementType();
1885 for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
1886 Elements[i] = ConstantInt::get(ElemType, (unsigned char)Data[i]);
Misha Brukman12c29d12003-09-22 23:38:23 +00001887
Reid Spencer060d25d2004-06-29 23:29:38 +00001888 // Create the constant, inserting it as needed.
1889 Constant *C = ConstantArray::get(ATy, Elements);
1890 unsigned Slot = insertValue(C, Typ, Tab);
Chris Lattner389bd042004-12-09 06:19:44 +00001891 ResolveReferencesToConstant(C, Typ, Slot);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001892 if (Handler) Handler->handleConstantString(cast<ConstantArray>(C));
Reid Spencer060d25d2004-06-29 23:29:38 +00001893 }
Misha Brukman12c29d12003-09-22 23:38:23 +00001894}
1895
Reid Spencer04cde2c2004-07-04 11:33:49 +00001896/// Parse the constant pool.
Misha Brukman8a96c532005-04-21 21:44:41 +00001897void BytecodeReader::ParseConstantPool(ValueTable &Tab,
Reid Spencer04cde2c2004-07-04 11:33:49 +00001898 TypeListTy &TypeTab,
Reid Spencer46b002c2004-07-11 17:28:43 +00001899 bool isFunction) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001900 if (Handler) Handler->handleGlobalConstantsBegin();
1901
1902 /// In LLVM 1.3 Type does not derive from Value so the types
1903 /// do not occupy a plane. Consequently, we read the types
1904 /// first in the constant pool.
Reid Spencerd798a512006-11-14 04:47:22 +00001905 if (isFunction) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001906 unsigned NumEntries = read_vbr_uint();
Reid Spencer46b002c2004-07-11 17:28:43 +00001907 ParseTypes(TypeTab, NumEntries);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001908 }
1909
Reid Spencer46b002c2004-07-11 17:28:43 +00001910 while (moreInBlock()) {
Reid Spencer060d25d2004-06-29 23:29:38 +00001911 unsigned NumEntries = read_vbr_uint();
Reid Spencerd798a512006-11-14 04:47:22 +00001912 unsigned Typ = read_vbr_uint();
Reid Spencer04cde2c2004-07-04 11:33:49 +00001913
Reid Spencerd798a512006-11-14 04:47:22 +00001914 if (Typ == Type::VoidTyID) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001915 /// Use of Type::VoidTyID is a misnomer. It actually means
1916 /// that the following plane is constant strings
Reid Spencer060d25d2004-06-29 23:29:38 +00001917 assert(&Tab == &ModuleValues && "Cannot read strings in functions!");
1918 ParseStringConstants(NumEntries, Tab);
1919 } else {
1920 for (unsigned i = 0; i < NumEntries; ++i) {
Chris Lattner3bc5a602006-01-25 23:08:15 +00001921 Value *V = ParseConstantPoolValue(Typ);
1922 assert(V && "ParseConstantPoolValue returned NULL!");
1923 unsigned Slot = insertValue(V, Typ, Tab);
Chris Lattner29b789b2003-11-19 17:27:18 +00001924
Reid Spencer060d25d2004-06-29 23:29:38 +00001925 // If we are reading a function constant table, make sure that we adjust
1926 // the slot number to be the real global constant number.
1927 //
1928 if (&Tab != &ModuleValues && Typ < ModuleValues.size() &&
1929 ModuleValues[Typ])
1930 Slot += ModuleValues[Typ]->size();
Chris Lattner3bc5a602006-01-25 23:08:15 +00001931 if (Constant *C = dyn_cast<Constant>(V))
1932 ResolveReferencesToConstant(C, Typ, Slot);
Reid Spencer060d25d2004-06-29 23:29:38 +00001933 }
1934 }
1935 }
Chris Lattner02dce162004-12-04 05:28:27 +00001936
1937 // After we have finished parsing the constant pool, we had better not have
1938 // any dangling references left.
Reid Spencer3c391272004-12-04 22:19:53 +00001939 if (!ConstantFwdRefs.empty()) {
Reid Spencer3c391272004-12-04 22:19:53 +00001940 ConstantRefsType::const_iterator I = ConstantFwdRefs.begin();
Reid Spencer3c391272004-12-04 22:19:53 +00001941 Constant* missingConst = I->second;
Misha Brukman8a96c532005-04-21 21:44:41 +00001942 error(utostr(ConstantFwdRefs.size()) +
1943 " unresolved constant reference exist. First one is '" +
1944 missingConst->getName() + "' of type '" +
Chris Lattner389bd042004-12-09 06:19:44 +00001945 missingConst->getType()->getDescription() + "'.");
Reid Spencer3c391272004-12-04 22:19:53 +00001946 }
Chris Lattner02dce162004-12-04 05:28:27 +00001947
Reid Spencer060d25d2004-06-29 23:29:38 +00001948 checkPastBlockEnd("Constant Pool");
Reid Spencer04cde2c2004-07-04 11:33:49 +00001949 if (Handler) Handler->handleGlobalConstantsEnd();
Reid Spencer060d25d2004-06-29 23:29:38 +00001950}
Chris Lattner00950542001-06-06 20:29:01 +00001951
Reid Spencer04cde2c2004-07-04 11:33:49 +00001952/// Parse the contents of a function. Note that this function can be
1953/// called lazily by materializeFunction
1954/// @see materializeFunction
Reid Spencer46b002c2004-07-11 17:28:43 +00001955void BytecodeReader::ParseFunctionBody(Function* F) {
Reid Spencer060d25d2004-06-29 23:29:38 +00001956
1957 unsigned FuncSize = BlockEnd - At;
Chris Lattnere3869c82003-04-16 21:16:05 +00001958 GlobalValue::LinkageTypes Linkage = GlobalValue::ExternalLinkage;
1959
Reid Spencer060d25d2004-06-29 23:29:38 +00001960 unsigned LinkageType = read_vbr_uint();
Chris Lattnerc08912f2004-01-14 16:44:44 +00001961 switch (LinkageType) {
1962 case 0: Linkage = GlobalValue::ExternalLinkage; break;
1963 case 1: Linkage = GlobalValue::WeakLinkage; break;
1964 case 2: Linkage = GlobalValue::AppendingLinkage; break;
1965 case 3: Linkage = GlobalValue::InternalLinkage; break;
1966 case 4: Linkage = GlobalValue::LinkOnceLinkage; break;
Anton Korobeynikovb74ed072006-09-14 18:23:27 +00001967 case 5: Linkage = GlobalValue::DLLImportLinkage; break;
1968 case 6: Linkage = GlobalValue::DLLExportLinkage; break;
1969 case 7: Linkage = GlobalValue::ExternalWeakLinkage; break;
Reid Spencer060d25d2004-06-29 23:29:38 +00001970 default:
Reid Spencer24399722004-07-09 22:21:33 +00001971 error("Invalid linkage type for Function.");
Reid Spencer060d25d2004-06-29 23:29:38 +00001972 Linkage = GlobalValue::InternalLinkage;
1973 break;
Chris Lattnere3869c82003-04-16 21:16:05 +00001974 }
Chris Lattnerd23b1d32001-11-26 18:56:10 +00001975
Reid Spencer46b002c2004-07-11 17:28:43 +00001976 F->setLinkage(Linkage);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001977 if (Handler) Handler->handleFunctionBegin(F,FuncSize);
Chris Lattner00950542001-06-06 20:29:01 +00001978
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001979 // Keep track of how many basic blocks we have read in...
1980 unsigned BlockNum = 0;
Chris Lattner89e02532004-01-18 21:08:15 +00001981 bool InsertedArguments = false;
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001982
Reid Spencer060d25d2004-06-29 23:29:38 +00001983 BufPtr MyEnd = BlockEnd;
Reid Spencer46b002c2004-07-11 17:28:43 +00001984 while (At < MyEnd) {
Chris Lattner00950542001-06-06 20:29:01 +00001985 unsigned Type, Size;
Reid Spencer060d25d2004-06-29 23:29:38 +00001986 BufPtr OldAt = At;
1987 read_block(Type, Size);
Chris Lattner00950542001-06-06 20:29:01 +00001988
1989 switch (Type) {
Reid Spencerad89bd62004-07-25 18:07:36 +00001990 case BytecodeFormat::ConstantPoolBlockID:
Chris Lattner89e02532004-01-18 21:08:15 +00001991 if (!InsertedArguments) {
1992 // Insert arguments into the value table before we parse the first basic
1993 // block in the function, but after we potentially read in the
1994 // compaction table.
Reid Spencer04cde2c2004-07-04 11:33:49 +00001995 insertArguments(F);
Chris Lattner89e02532004-01-18 21:08:15 +00001996 InsertedArguments = true;
1997 }
1998
Reid Spencer04cde2c2004-07-04 11:33:49 +00001999 ParseConstantPool(FunctionValues, FunctionTypes, true);
Chris Lattner00950542001-06-06 20:29:01 +00002000 break;
2001
Reid Spencerad89bd62004-07-25 18:07:36 +00002002 case BytecodeFormat::CompactionTableBlockID:
Reid Spencer060d25d2004-06-29 23:29:38 +00002003 ParseCompactionTable();
Chris Lattner89e02532004-01-18 21:08:15 +00002004 break;
2005
Reid Spencerad89bd62004-07-25 18:07:36 +00002006 case BytecodeFormat::InstructionListBlockID: {
Chris Lattner89e02532004-01-18 21:08:15 +00002007 // Insert arguments into the value table before we parse the instruction
2008 // list for the function, but after we potentially read in the compaction
2009 // table.
2010 if (!InsertedArguments) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00002011 insertArguments(F);
Chris Lattner89e02532004-01-18 21:08:15 +00002012 InsertedArguments = true;
2013 }
2014
Misha Brukman8a96c532005-04-21 21:44:41 +00002015 if (BlockNum)
Reid Spencer24399722004-07-09 22:21:33 +00002016 error("Already parsed basic blocks!");
Reid Spencer060d25d2004-06-29 23:29:38 +00002017 BlockNum = ParseInstructionList(F);
Chris Lattner8d1dbd22003-12-01 07:05:31 +00002018 break;
2019 }
2020
Reid Spencerad89bd62004-07-25 18:07:36 +00002021 case BytecodeFormat::SymbolTableBlockID:
Reid Spencer060d25d2004-06-29 23:29:38 +00002022 ParseSymbolTable(F, &F->getSymbolTable());
Chris Lattner00950542001-06-06 20:29:01 +00002023 break;
2024
2025 default:
Reid Spencer060d25d2004-06-29 23:29:38 +00002026 At += Size;
Misha Brukman8a96c532005-04-21 21:44:41 +00002027 if (OldAt > At)
Reid Spencer24399722004-07-09 22:21:33 +00002028 error("Wrapped around reading bytecode.");
Chris Lattner00950542001-06-06 20:29:01 +00002029 break;
2030 }
Reid Spencer060d25d2004-06-29 23:29:38 +00002031 BlockEnd = MyEnd;
Chris Lattner00950542001-06-06 20:29:01 +00002032 }
2033
Chris Lattner4ee8ef22003-10-08 22:52:54 +00002034 // Make sure there were no references to non-existant basic blocks.
2035 if (BlockNum != ParsedBasicBlocks.size())
Reid Spencer24399722004-07-09 22:21:33 +00002036 error("Illegal basic block operand reference");
Reid Spencer060d25d2004-06-29 23:29:38 +00002037
Chris Lattner4ee8ef22003-10-08 22:52:54 +00002038 ParsedBasicBlocks.clear();
2039
Chris Lattner97330cf2003-10-09 23:10:14 +00002040 // Resolve forward references. Replace any uses of a forward reference value
2041 // with the real value.
Chris Lattner8eb10ce2003-10-09 06:05:40 +00002042 while (!ForwardReferences.empty()) {
Chris Lattnerc4d69162004-12-09 04:51:50 +00002043 std::map<std::pair<unsigned,unsigned>, Value*>::iterator
2044 I = ForwardReferences.begin();
2045 Value *V = getValue(I->first.first, I->first.second, false);
Chris Lattner8eb10ce2003-10-09 06:05:40 +00002046 Value *PlaceHolder = I->second;
Chris Lattnerc4d69162004-12-09 04:51:50 +00002047 PlaceHolder->replaceAllUsesWith(V);
Chris Lattner8eb10ce2003-10-09 06:05:40 +00002048 ForwardReferences.erase(I);
Chris Lattner8eb10ce2003-10-09 06:05:40 +00002049 delete PlaceHolder;
Chris Lattner6e448022003-10-08 21:51:46 +00002050 }
Chris Lattner00950542001-06-06 20:29:01 +00002051
Reid Spencere2a5fb02006-01-27 11:49:27 +00002052 // If upgraded intrinsic functions were detected during reading of the
2053 // module information, then we need to look for instructions that need to
2054 // be upgraded. This can't be done while the instructions are read in because
2055 // additional instructions inserted mess up the slot numbering.
2056 if (!upgradedFunctions.empty()) {
2057 for (Function::iterator BI = F->begin(), BE = F->end(); BI != BE; ++BI)
2058 for (BasicBlock::iterator II = BI->begin(), IE = BI->end();
Jim Laskeyf4321a32006-03-13 13:07:37 +00002059 II != IE;)
2060 if (CallInst* CI = dyn_cast<CallInst>(II++)) {
Reid Spencere2a5fb02006-01-27 11:49:27 +00002061 std::map<Function*,Function*>::iterator FI =
2062 upgradedFunctions.find(CI->getCalledFunction());
Chris Lattnerbad08002006-03-02 23:59:12 +00002063 if (FI != upgradedFunctions.end())
2064 UpgradeIntrinsicCall(CI, FI->second);
Reid Spencere2a5fb02006-01-27 11:49:27 +00002065 }
2066 }
2067
Misha Brukman12c29d12003-09-22 23:38:23 +00002068 // Clear out function-level types...
Reid Spencer060d25d2004-06-29 23:29:38 +00002069 FunctionTypes.clear();
2070 CompactionTypes.clear();
2071 CompactionValues.clear();
2072 freeTable(FunctionValues);
2073
Reid Spencer04cde2c2004-07-04 11:33:49 +00002074 if (Handler) Handler->handleFunctionEnd(F);
Chris Lattner00950542001-06-06 20:29:01 +00002075}
2076
Reid Spencer04cde2c2004-07-04 11:33:49 +00002077/// This function parses LLVM functions lazily. It obtains the type of the
2078/// function and records where the body of the function is in the bytecode
Misha Brukman8a96c532005-04-21 21:44:41 +00002079/// buffer. The caller can then use the ParseNextFunction and
Reid Spencer04cde2c2004-07-04 11:33:49 +00002080/// ParseAllFunctionBodies to get handler events for the functions.
Reid Spencer060d25d2004-06-29 23:29:38 +00002081void BytecodeReader::ParseFunctionLazily() {
2082 if (FunctionSignatureList.empty())
Reid Spencer24399722004-07-09 22:21:33 +00002083 error("FunctionSignatureList empty!");
Chris Lattner89e02532004-01-18 21:08:15 +00002084
Reid Spencer060d25d2004-06-29 23:29:38 +00002085 Function *Func = FunctionSignatureList.back();
2086 FunctionSignatureList.pop_back();
Chris Lattner24102432004-01-18 22:35:34 +00002087
Reid Spencer060d25d2004-06-29 23:29:38 +00002088 // Save the information for future reading of the function
2089 LazyFunctionLoadMap[Func] = LazyFunctionInfo(BlockStart, BlockEnd);
Chris Lattner89e02532004-01-18 21:08:15 +00002090
Misha Brukmana3e6ad62004-11-14 21:02:55 +00002091 // This function has a body but it's not loaded so it appears `External'.
2092 // Mark it as a `Ghost' instead to notify the users that it has a body.
2093 Func->setLinkage(GlobalValue::GhostLinkage);
2094
Reid Spencer060d25d2004-06-29 23:29:38 +00002095 // Pretend we've `parsed' this function
2096 At = BlockEnd;
2097}
Chris Lattner89e02532004-01-18 21:08:15 +00002098
Misha Brukman8a96c532005-04-21 21:44:41 +00002099/// The ParserFunction method lazily parses one function. Use this method to
2100/// casue the parser to parse a specific function in the module. Note that
2101/// this will remove the function from what is to be included by
Reid Spencer04cde2c2004-07-04 11:33:49 +00002102/// ParseAllFunctionBodies.
2103/// @see ParseAllFunctionBodies
2104/// @see ParseBytecode
Reid Spencer99655e12006-08-25 19:54:53 +00002105bool BytecodeReader::ParseFunction(Function* Func, std::string* ErrMsg) {
2106
2107 if (setjmp(context))
2108 return true;
2109
Reid Spencer060d25d2004-06-29 23:29:38 +00002110 // Find {start, end} pointers and slot in the map. If not there, we're done.
2111 LazyFunctionMap::iterator Fi = LazyFunctionLoadMap.find(Func);
Chris Lattner89e02532004-01-18 21:08:15 +00002112
Reid Spencer060d25d2004-06-29 23:29:38 +00002113 // Make sure we found it
Reid Spencer46b002c2004-07-11 17:28:43 +00002114 if (Fi == LazyFunctionLoadMap.end()) {
Reid Spencer24399722004-07-09 22:21:33 +00002115 error("Unrecognized function of type " + Func->getType()->getDescription());
Reid Spencer99655e12006-08-25 19:54:53 +00002116 return true;
Chris Lattner89e02532004-01-18 21:08:15 +00002117 }
2118
Reid Spencer060d25d2004-06-29 23:29:38 +00002119 BlockStart = At = Fi->second.Buf;
2120 BlockEnd = Fi->second.EndBuf;
Reid Spencer24399722004-07-09 22:21:33 +00002121 assert(Fi->first == Func && "Found wrong function?");
Reid Spencer060d25d2004-06-29 23:29:38 +00002122
2123 LazyFunctionLoadMap.erase(Fi);
2124
Reid Spencer46b002c2004-07-11 17:28:43 +00002125 this->ParseFunctionBody(Func);
Reid Spencer99655e12006-08-25 19:54:53 +00002126 return false;
Chris Lattner89e02532004-01-18 21:08:15 +00002127}
2128
Reid Spencer04cde2c2004-07-04 11:33:49 +00002129/// The ParseAllFunctionBodies method parses through all the previously
2130/// unparsed functions in the bytecode file. If you want to completely parse
2131/// a bytecode file, this method should be called after Parsebytecode because
2132/// Parsebytecode only records the locations in the bytecode file of where
2133/// the function definitions are located. This function uses that information
2134/// to materialize the functions.
2135/// @see ParseBytecode
Reid Spencer99655e12006-08-25 19:54:53 +00002136bool BytecodeReader::ParseAllFunctionBodies(std::string* ErrMsg) {
2137 if (setjmp(context))
2138 return true;
2139
Reid Spencer060d25d2004-06-29 23:29:38 +00002140 LazyFunctionMap::iterator Fi = LazyFunctionLoadMap.begin();
2141 LazyFunctionMap::iterator Fe = LazyFunctionLoadMap.end();
Chris Lattner89e02532004-01-18 21:08:15 +00002142
Reid Spencer46b002c2004-07-11 17:28:43 +00002143 while (Fi != Fe) {
Reid Spencer060d25d2004-06-29 23:29:38 +00002144 Function* Func = Fi->first;
2145 BlockStart = At = Fi->second.Buf;
2146 BlockEnd = Fi->second.EndBuf;
Chris Lattnerb52f1c22005-02-13 17:48:18 +00002147 ParseFunctionBody(Func);
Reid Spencer060d25d2004-06-29 23:29:38 +00002148 ++Fi;
2149 }
Chris Lattnerb52f1c22005-02-13 17:48:18 +00002150 LazyFunctionLoadMap.clear();
Reid Spencer99655e12006-08-25 19:54:53 +00002151 return false;
Reid Spencer060d25d2004-06-29 23:29:38 +00002152}
Chris Lattner89e02532004-01-18 21:08:15 +00002153
Reid Spencer04cde2c2004-07-04 11:33:49 +00002154/// Parse the global type list
Reid Spencer060d25d2004-06-29 23:29:38 +00002155void BytecodeReader::ParseGlobalTypes() {
Reid Spencer04cde2c2004-07-04 11:33:49 +00002156 // Read the number of types
2157 unsigned NumEntries = read_vbr_uint();
Reid Spencer46b002c2004-07-11 17:28:43 +00002158 ParseTypes(ModuleTypes, NumEntries);
Reid Spencer060d25d2004-06-29 23:29:38 +00002159}
2160
Reid Spencer04cde2c2004-07-04 11:33:49 +00002161/// Parse the Global info (types, global vars, constants)
Reid Spencer060d25d2004-06-29 23:29:38 +00002162void BytecodeReader::ParseModuleGlobalInfo() {
2163
Reid Spencer04cde2c2004-07-04 11:33:49 +00002164 if (Handler) Handler->handleModuleGlobalsBegin();
Chris Lattner00950542001-06-06 20:29:01 +00002165
Chris Lattner404cddf2005-11-12 01:33:40 +00002166 // SectionID - If a global has an explicit section specified, this map
2167 // remembers the ID until we can translate it into a string.
2168 std::map<GlobalValue*, unsigned> SectionID;
2169
Chris Lattner70cc3392001-09-10 07:58:01 +00002170 // Read global variables...
Reid Spencer060d25d2004-06-29 23:29:38 +00002171 unsigned VarType = read_vbr_uint();
Chris Lattner70cc3392001-09-10 07:58:01 +00002172 while (VarType != Type::VoidTyID) { // List is terminated by Void
Chris Lattner9dd87702004-04-03 23:43:42 +00002173 // VarType Fields: bit0 = isConstant, bit1 = hasInitializer, bit2,3,4 =
2174 // Linkage, bit4+ = slot#
2175 unsigned SlotNo = VarType >> 5;
2176 unsigned LinkageID = (VarType >> 2) & 7;
Reid Spencer060d25d2004-06-29 23:29:38 +00002177 bool isConstant = VarType & 1;
Chris Lattnerce5e04e2005-11-06 08:23:17 +00002178 bool hasInitializer = (VarType & 2) != 0;
Chris Lattner8eb52dd2005-11-06 07:11:04 +00002179 unsigned Alignment = 0;
Chris Lattner404cddf2005-11-12 01:33:40 +00002180 unsigned GlobalSectionID = 0;
Chris Lattner8eb52dd2005-11-06 07:11:04 +00002181
2182 // An extension word is present when linkage = 3 (internal) and hasinit = 0.
2183 if (LinkageID == 3 && !hasInitializer) {
2184 unsigned ExtWord = read_vbr_uint();
2185 // The extension word has this format: bit 0 = has initializer, bit 1-3 =
2186 // linkage, bit 4-8 = alignment (log2), bits 10+ = future use.
2187 hasInitializer = ExtWord & 1;
2188 LinkageID = (ExtWord >> 1) & 7;
2189 Alignment = (1 << ((ExtWord >> 4) & 31)) >> 1;
Chris Lattner404cddf2005-11-12 01:33:40 +00002190
2191 if (ExtWord & (1 << 9)) // Has a section ID.
2192 GlobalSectionID = read_vbr_uint();
Chris Lattner8eb52dd2005-11-06 07:11:04 +00002193 }
Chris Lattnere3869c82003-04-16 21:16:05 +00002194
Chris Lattnerce5e04e2005-11-06 08:23:17 +00002195 GlobalValue::LinkageTypes Linkage;
Chris Lattnerc08912f2004-01-14 16:44:44 +00002196 switch (LinkageID) {
Chris Lattnerc08912f2004-01-14 16:44:44 +00002197 case 0: Linkage = GlobalValue::ExternalLinkage; break;
2198 case 1: Linkage = GlobalValue::WeakLinkage; break;
2199 case 2: Linkage = GlobalValue::AppendingLinkage; break;
2200 case 3: Linkage = GlobalValue::InternalLinkage; break;
2201 case 4: Linkage = GlobalValue::LinkOnceLinkage; break;
Anton Korobeynikovb74ed072006-09-14 18:23:27 +00002202 case 5: Linkage = GlobalValue::DLLImportLinkage; break;
2203 case 6: Linkage = GlobalValue::DLLExportLinkage; break;
2204 case 7: Linkage = GlobalValue::ExternalWeakLinkage; break;
Misha Brukman8a96c532005-04-21 21:44:41 +00002205 default:
Reid Spencer24399722004-07-09 22:21:33 +00002206 error("Unknown linkage type: " + utostr(LinkageID));
Reid Spencer060d25d2004-06-29 23:29:38 +00002207 Linkage = GlobalValue::InternalLinkage;
2208 break;
Chris Lattnere3869c82003-04-16 21:16:05 +00002209 }
2210
2211 const Type *Ty = getType(SlotNo);
Chris Lattnere73bd452005-11-06 07:43:39 +00002212 if (!Ty)
Reid Spencer24399722004-07-09 22:21:33 +00002213 error("Global has no type! SlotNo=" + utostr(SlotNo));
Reid Spencer060d25d2004-06-29 23:29:38 +00002214
Chris Lattnere73bd452005-11-06 07:43:39 +00002215 if (!isa<PointerType>(Ty))
Reid Spencer24399722004-07-09 22:21:33 +00002216 error("Global not a pointer type! Ty= " + Ty->getDescription());
Chris Lattner70cc3392001-09-10 07:58:01 +00002217
Chris Lattner52e20b02003-03-19 20:54:26 +00002218 const Type *ElTy = cast<PointerType>(Ty)->getElementType();
Chris Lattnerd70684f2001-09-18 04:01:05 +00002219
Chris Lattner70cc3392001-09-10 07:58:01 +00002220 // Create the global variable...
Reid Spencer060d25d2004-06-29 23:29:38 +00002221 GlobalVariable *GV = new GlobalVariable(ElTy, isConstant, Linkage,
Chris Lattner52e20b02003-03-19 20:54:26 +00002222 0, "", TheModule);
Chris Lattner8eb52dd2005-11-06 07:11:04 +00002223 GV->setAlignment(Alignment);
Chris Lattner29b789b2003-11-19 17:27:18 +00002224 insertValue(GV, SlotNo, ModuleValues);
Chris Lattner05950c32001-10-13 06:47:01 +00002225
Chris Lattner404cddf2005-11-12 01:33:40 +00002226 if (GlobalSectionID != 0)
2227 SectionID[GV] = GlobalSectionID;
2228
Reid Spencer060d25d2004-06-29 23:29:38 +00002229 unsigned initSlot = 0;
Misha Brukman8a96c532005-04-21 21:44:41 +00002230 if (hasInitializer) {
Reid Spencer060d25d2004-06-29 23:29:38 +00002231 initSlot = read_vbr_uint();
2232 GlobalInits.push_back(std::make_pair(GV, initSlot));
2233 }
2234
2235 // Notify handler about the global value.
Chris Lattner4a242b32004-10-14 01:39:18 +00002236 if (Handler)
2237 Handler->handleGlobalVariable(ElTy, isConstant, Linkage, SlotNo,initSlot);
Reid Spencer060d25d2004-06-29 23:29:38 +00002238
2239 // Get next item
2240 VarType = read_vbr_uint();
Chris Lattner70cc3392001-09-10 07:58:01 +00002241 }
2242
Chris Lattner52e20b02003-03-19 20:54:26 +00002243 // Read the function objects for all of the functions that are coming
Chris Lattnera79e7cc2004-10-16 18:18:16 +00002244 unsigned FnSignature = read_vbr_uint();
Reid Spencer24399722004-07-09 22:21:33 +00002245
Chris Lattnera79e7cc2004-10-16 18:18:16 +00002246 // List is terminated by VoidTy.
Chris Lattnere73bd452005-11-06 07:43:39 +00002247 while (((FnSignature & (~0U >> 1)) >> 5) != Type::VoidTyID) {
2248 const Type *Ty = getType((FnSignature & (~0U >> 1)) >> 5);
Chris Lattner927b1852003-10-09 20:22:47 +00002249 if (!isa<PointerType>(Ty) ||
Reid Spencer060d25d2004-06-29 23:29:38 +00002250 !isa<FunctionType>(cast<PointerType>(Ty)->getElementType())) {
Misha Brukman8a96c532005-04-21 21:44:41 +00002251 error("Function not a pointer to function type! Ty = " +
Reid Spencer46b002c2004-07-11 17:28:43 +00002252 Ty->getDescription());
Reid Spencer060d25d2004-06-29 23:29:38 +00002253 }
Chris Lattner8cdc6b72002-10-23 00:51:54 +00002254
Chris Lattner2a7b6ba2003-03-06 17:15:19 +00002255 // We create functions by passing the underlying FunctionType to create...
Misha Brukman8a96c532005-04-21 21:44:41 +00002256 const FunctionType* FTy =
Reid Spencer060d25d2004-06-29 23:29:38 +00002257 cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
Chris Lattner00950542001-06-06 20:29:01 +00002258
Chris Lattner18549c22004-11-15 21:43:03 +00002259 // Insert the place holder.
Chris Lattner404cddf2005-11-12 01:33:40 +00002260 Function *Func = new Function(FTy, GlobalValue::ExternalLinkage,
Reid Spencer04cde2c2004-07-04 11:33:49 +00002261 "", TheModule);
Reid Spencere1e96c02006-01-19 07:02:16 +00002262
Chris Lattnere73bd452005-11-06 07:43:39 +00002263 insertValue(Func, (FnSignature & (~0U >> 1)) >> 5, ModuleValues);
Chris Lattnera79e7cc2004-10-16 18:18:16 +00002264
2265 // Flags are not used yet.
Chris Lattner97fbc502004-11-15 22:38:52 +00002266 unsigned Flags = FnSignature & 31;
Chris Lattner00950542001-06-06 20:29:01 +00002267
Chris Lattner97fbc502004-11-15 22:38:52 +00002268 // Save this for later so we know type of lazily instantiated functions.
2269 // Note that known-external functions do not have FunctionInfo blocks, so we
2270 // do not add them to the FunctionSignatureList.
2271 if ((Flags & (1 << 4)) == 0)
2272 FunctionSignatureList.push_back(Func);
Chris Lattner52e20b02003-03-19 20:54:26 +00002273
Chris Lattnere73bd452005-11-06 07:43:39 +00002274 // Get the calling convention from the low bits.
2275 unsigned CC = Flags & 15;
2276 unsigned Alignment = 0;
2277 if (FnSignature & (1 << 31)) { // Has extension word?
2278 unsigned ExtWord = read_vbr_uint();
2279 Alignment = (1 << (ExtWord & 31)) >> 1;
2280 CC |= ((ExtWord >> 5) & 15) << 4;
Chris Lattner404cddf2005-11-12 01:33:40 +00002281
2282 if (ExtWord & (1 << 10)) // Has a section ID.
2283 SectionID[Func] = read_vbr_uint();
Anton Korobeynikovb74ed072006-09-14 18:23:27 +00002284
2285 // Parse external declaration linkage
2286 switch ((ExtWord >> 11) & 3) {
2287 case 0: break;
2288 case 1: Func->setLinkage(Function::DLLImportLinkage); break;
2289 case 2: Func->setLinkage(Function::ExternalWeakLinkage); break;
2290 default: assert(0 && "Unsupported external linkage");
2291 }
Chris Lattnere73bd452005-11-06 07:43:39 +00002292 }
2293
Chris Lattner54b369e2005-11-06 07:46:13 +00002294 Func->setCallingConv(CC-1);
Chris Lattnere73bd452005-11-06 07:43:39 +00002295 Func->setAlignment(Alignment);
Chris Lattner479ffeb2005-05-06 20:42:57 +00002296
Reid Spencer04cde2c2004-07-04 11:33:49 +00002297 if (Handler) Handler->handleFunctionDeclaration(Func);
Reid Spencer060d25d2004-06-29 23:29:38 +00002298
Chris Lattnera79e7cc2004-10-16 18:18:16 +00002299 // Get the next function signature.
2300 FnSignature = read_vbr_uint();
Chris Lattner00950542001-06-06 20:29:01 +00002301 }
2302
Misha Brukman8a96c532005-04-21 21:44:41 +00002303 // Now that the function signature list is set up, reverse it so that we can
Chris Lattner74734132002-08-17 22:01:27 +00002304 // remove elements efficiently from the back of the vector.
2305 std::reverse(FunctionSignatureList.begin(), FunctionSignatureList.end());
Chris Lattner00950542001-06-06 20:29:01 +00002306
Chris Lattner404cddf2005-11-12 01:33:40 +00002307 /// SectionNames - This contains the list of section names encoded in the
2308 /// moduleinfoblock. Functions and globals with an explicit section index
2309 /// into this to get their section name.
2310 std::vector<std::string> SectionNames;
2311
Reid Spencerd798a512006-11-14 04:47:22 +00002312 // Read in the dependent library information.
2313 unsigned num_dep_libs = read_vbr_uint();
2314 std::string dep_lib;
2315 while (num_dep_libs--) {
2316 dep_lib = read_str();
2317 TheModule->addLibrary(dep_lib);
Reid Spencer5b472d92004-08-21 20:49:23 +00002318 if (Handler)
Reid Spencerd798a512006-11-14 04:47:22 +00002319 Handler->handleDependentLibrary(dep_lib);
Reid Spencerad89bd62004-07-25 18:07:36 +00002320 }
2321
Reid Spencerd798a512006-11-14 04:47:22 +00002322 // Read target triple and place into the module.
2323 std::string triple = read_str();
2324 TheModule->setTargetTriple(triple);
2325 if (Handler)
2326 Handler->handleTargetTriple(triple);
2327
2328 if (At != BlockEnd) {
2329 // If the file has section info in it, read the section names now.
2330 unsigned NumSections = read_vbr_uint();
2331 while (NumSections--)
2332 SectionNames.push_back(read_str());
2333 }
2334
2335 // If the file has module-level inline asm, read it now.
2336 if (At != BlockEnd)
2337 TheModule->setModuleInlineAsm(read_str());
2338
Chris Lattner404cddf2005-11-12 01:33:40 +00002339 // If any globals are in specified sections, assign them now.
2340 for (std::map<GlobalValue*, unsigned>::iterator I = SectionID.begin(), E =
2341 SectionID.end(); I != E; ++I)
2342 if (I->second) {
2343 if (I->second > SectionID.size())
2344 error("SectionID out of range for global!");
2345 I->first->setSection(SectionNames[I->second-1]);
2346 }
Reid Spencerad89bd62004-07-25 18:07:36 +00002347
Chris Lattner00950542001-06-06 20:29:01 +00002348 // This is for future proofing... in the future extra fields may be added that
2349 // we don't understand, so we transparently ignore them.
2350 //
Reid Spencer060d25d2004-06-29 23:29:38 +00002351 At = BlockEnd;
2352
Reid Spencer04cde2c2004-07-04 11:33:49 +00002353 if (Handler) Handler->handleModuleGlobalsEnd();
Chris Lattner00950542001-06-06 20:29:01 +00002354}
2355
Reid Spencer04cde2c2004-07-04 11:33:49 +00002356/// Parse the version information and decode it by setting flags on the
2357/// Reader that enable backward compatibility of the reader.
Reid Spencer060d25d2004-06-29 23:29:38 +00002358void BytecodeReader::ParseVersionInfo() {
2359 unsigned Version = read_vbr_uint();
Chris Lattner036b8aa2003-03-06 17:55:45 +00002360
2361 // Unpack version number: low four bits are for flags, top bits = version
Chris Lattnerd445c6b2003-08-24 13:47:36 +00002362 Module::Endianness Endianness;
2363 Module::PointerSize PointerSize;
2364 Endianness = (Version & 1) ? Module::BigEndian : Module::LittleEndian;
2365 PointerSize = (Version & 2) ? Module::Pointer64 : Module::Pointer32;
2366
2367 bool hasNoEndianness = Version & 4;
2368 bool hasNoPointerSize = Version & 8;
Misha Brukman8a96c532005-04-21 21:44:41 +00002369
Chris Lattnerd445c6b2003-08-24 13:47:36 +00002370 RevisionNum = Version >> 4;
Chris Lattnere3869c82003-04-16 21:16:05 +00002371
Reid Spencerd798a512006-11-14 04:47:22 +00002372 // Default the backwards compatibility flag values for the current BC version
Reid Spencer6996feb2006-11-08 21:27:54 +00002373 hasSignlessDivRem = false;
2374 hasSignlessShrCastSetcc = false;
Chris Lattner036b8aa2003-03-06 17:55:45 +00002375
Reid Spencer1628cec2006-10-26 06:15:43 +00002376 // Determine which backwards compatibility flags to set based on the
2377 // bytecode file's version number
Chris Lattner036b8aa2003-03-06 17:55:45 +00002378 switch (RevisionNum) {
Reid Spencerd798a512006-11-14 04:47:22 +00002379 case 0: // LLVM 1.0, 1.1 (Released)
2380 case 1: // LLVM 1.2 (Released)
2381 case 2: // 1.2.5 (Not Released)
2382 case 3: // LLVM 1.3 (Released)
2383 case 4: // 1.3.1 (Not Released)
2384 error("Old bytecode formats no longer supported");
2385 break;
Reid Spencer04cde2c2004-07-04 11:33:49 +00002386
Reid Spencerd798a512006-11-14 04:47:22 +00002387 case 5: // 1.4 (Released)
Reid Spencer6996feb2006-11-08 21:27:54 +00002388 // In version 6, the Div and Rem instructions were converted to their
2389 // signed and floating point counterparts: UDiv, SDiv, FDiv, URem, SRem,
2390 // and FRem. Versions prior to 6 need to indicate that they have the
2391 // signless Div and Rem instructions.
2392 hasSignlessDivRem = true;
2393
2394 // FALL THROUGH
2395
Reid Spencerd798a512006-11-14 04:47:22 +00002396 case 6: // 1.9 (Released)
Reid Spencer1628cec2006-10-26 06:15:43 +00002397 // In version 5 and prior, instructions were signless while integer types
2398 // were signed. In version 6, instructions became signed and types became
2399 // signless. For example in version 5 we have the DIV instruction but in
2400 // version 6 we have FDIV, SDIV and UDIV to replace it. This caused a
2401 // renumbering of the instruction codes in version 6 that must be dealt with
2402 // when reading old bytecode files.
Reid Spencer6996feb2006-11-08 21:27:54 +00002403 hasSignlessShrCastSetcc = true;
Reid Spencer1628cec2006-10-26 06:15:43 +00002404
2405 // FALL THROUGH
Reid Spencer6996feb2006-11-08 21:27:54 +00002406
2407 case 7:
Chris Lattnera79e7cc2004-10-16 18:18:16 +00002408 break;
2409
Chris Lattner036b8aa2003-03-06 17:55:45 +00002410 default:
Reid Spencer24399722004-07-09 22:21:33 +00002411 error("Unknown bytecode version number: " + itostr(RevisionNum));
Chris Lattner036b8aa2003-03-06 17:55:45 +00002412 }
2413
Chris Lattnerd445c6b2003-08-24 13:47:36 +00002414 if (hasNoEndianness) Endianness = Module::AnyEndianness;
2415 if (hasNoPointerSize) PointerSize = Module::AnyPointerSize;
Chris Lattner76e38962003-04-22 18:15:10 +00002416
Brian Gaekefe2102b2004-07-14 20:33:13 +00002417 TheModule->setEndianness(Endianness);
2418 TheModule->setPointerSize(PointerSize);
2419
Reid Spencer46b002c2004-07-11 17:28:43 +00002420 if (Handler) Handler->handleVersionInfo(RevisionNum, Endianness, PointerSize);
Chris Lattner036b8aa2003-03-06 17:55:45 +00002421}
2422
Reid Spencer04cde2c2004-07-04 11:33:49 +00002423/// Parse a whole module.
Reid Spencer060d25d2004-06-29 23:29:38 +00002424void BytecodeReader::ParseModule() {
Chris Lattner00950542001-06-06 20:29:01 +00002425 unsigned Type, Size;
Chris Lattner00950542001-06-06 20:29:01 +00002426
Reid Spencer060d25d2004-06-29 23:29:38 +00002427 FunctionSignatureList.clear(); // Just in case...
Chris Lattner00950542001-06-06 20:29:01 +00002428
2429 // Read into instance variables...
Reid Spencer060d25d2004-06-29 23:29:38 +00002430 ParseVersionInfo();
Chris Lattner00950542001-06-06 20:29:01 +00002431
Reid Spencer060d25d2004-06-29 23:29:38 +00002432 bool SeenModuleGlobalInfo = false;
2433 bool SeenGlobalTypePlane = false;
2434 BufPtr MyEnd = BlockEnd;
2435 while (At < MyEnd) {
2436 BufPtr OldAt = At;
2437 read_block(Type, Size);
2438
Chris Lattner00950542001-06-06 20:29:01 +00002439 switch (Type) {
Reid Spencer060d25d2004-06-29 23:29:38 +00002440
Reid Spencerad89bd62004-07-25 18:07:36 +00002441 case BytecodeFormat::GlobalTypePlaneBlockID:
Reid Spencer46b002c2004-07-11 17:28:43 +00002442 if (SeenGlobalTypePlane)
Reid Spencer24399722004-07-09 22:21:33 +00002443 error("Two GlobalTypePlane Blocks Encountered!");
Reid Spencer060d25d2004-06-29 23:29:38 +00002444
Reid Spencer5b472d92004-08-21 20:49:23 +00002445 if (Size > 0)
2446 ParseGlobalTypes();
Reid Spencer060d25d2004-06-29 23:29:38 +00002447 SeenGlobalTypePlane = true;
Chris Lattner52e20b02003-03-19 20:54:26 +00002448 break;
2449
Misha Brukman8a96c532005-04-21 21:44:41 +00002450 case BytecodeFormat::ModuleGlobalInfoBlockID:
Reid Spencer46b002c2004-07-11 17:28:43 +00002451 if (SeenModuleGlobalInfo)
Reid Spencer24399722004-07-09 22:21:33 +00002452 error("Two ModuleGlobalInfo Blocks Encountered!");
Reid Spencer060d25d2004-06-29 23:29:38 +00002453 ParseModuleGlobalInfo();
2454 SeenModuleGlobalInfo = true;
Chris Lattner52e20b02003-03-19 20:54:26 +00002455 break;
2456
Reid Spencerad89bd62004-07-25 18:07:36 +00002457 case BytecodeFormat::ConstantPoolBlockID:
Reid Spencer04cde2c2004-07-04 11:33:49 +00002458 ParseConstantPool(ModuleValues, ModuleTypes,false);
Chris Lattner00950542001-06-06 20:29:01 +00002459 break;
2460
Reid Spencerad89bd62004-07-25 18:07:36 +00002461 case BytecodeFormat::FunctionBlockID:
Reid Spencer060d25d2004-06-29 23:29:38 +00002462 ParseFunctionLazily();
Chris Lattner00950542001-06-06 20:29:01 +00002463 break;
Chris Lattner00950542001-06-06 20:29:01 +00002464
Reid Spencerad89bd62004-07-25 18:07:36 +00002465 case BytecodeFormat::SymbolTableBlockID:
Reid Spencer060d25d2004-06-29 23:29:38 +00002466 ParseSymbolTable(0, &TheModule->getSymbolTable());
Chris Lattner00950542001-06-06 20:29:01 +00002467 break;
Reid Spencer060d25d2004-06-29 23:29:38 +00002468
Chris Lattner00950542001-06-06 20:29:01 +00002469 default:
Reid Spencer060d25d2004-06-29 23:29:38 +00002470 At += Size;
2471 if (OldAt > At) {
Reid Spencer46b002c2004-07-11 17:28:43 +00002472 error("Unexpected Block of Type #" + utostr(Type) + " encountered!");
Reid Spencer060d25d2004-06-29 23:29:38 +00002473 }
Chris Lattner00950542001-06-06 20:29:01 +00002474 break;
2475 }
Reid Spencer060d25d2004-06-29 23:29:38 +00002476 BlockEnd = MyEnd;
Chris Lattner00950542001-06-06 20:29:01 +00002477 }
2478
Chris Lattner52e20b02003-03-19 20:54:26 +00002479 // After the module constant pool has been read, we can safely initialize
2480 // global variables...
2481 while (!GlobalInits.empty()) {
2482 GlobalVariable *GV = GlobalInits.back().first;
2483 unsigned Slot = GlobalInits.back().second;
2484 GlobalInits.pop_back();
2485
2486 // Look up the initializer value...
Chris Lattner29b789b2003-11-19 17:27:18 +00002487 // FIXME: Preserve this type ID!
Reid Spencer060d25d2004-06-29 23:29:38 +00002488
2489 const llvm::PointerType* GVType = GV->getType();
2490 unsigned TypeSlot = getTypeSlot(GVType->getElementType());
Chris Lattner93361992004-01-15 18:45:25 +00002491 if (Constant *CV = getConstantValue(TypeSlot, Slot)) {
Misha Brukman8a96c532005-04-21 21:44:41 +00002492 if (GV->hasInitializer())
Reid Spencer24399722004-07-09 22:21:33 +00002493 error("Global *already* has an initializer?!");
Reid Spencer04cde2c2004-07-04 11:33:49 +00002494 if (Handler) Handler->handleGlobalInitializer(GV,CV);
Chris Lattner93361992004-01-15 18:45:25 +00002495 GV->setInitializer(CV);
Chris Lattner52e20b02003-03-19 20:54:26 +00002496 } else
Reid Spencer24399722004-07-09 22:21:33 +00002497 error("Cannot find initializer value.");
Chris Lattner52e20b02003-03-19 20:54:26 +00002498 }
2499
Chris Lattneraba5ff52005-05-05 20:57:00 +00002500 if (!ConstantFwdRefs.empty())
2501 error("Use of undefined constants in a module");
2502
Reid Spencer060d25d2004-06-29 23:29:38 +00002503 /// Make sure we pulled them all out. If we didn't then there's a declaration
2504 /// but a missing body. That's not allowed.
Misha Brukman12c29d12003-09-22 23:38:23 +00002505 if (!FunctionSignatureList.empty())
Reid Spencer24399722004-07-09 22:21:33 +00002506 error("Function declared, but bytecode stream ended before definition");
Chris Lattner00950542001-06-06 20:29:01 +00002507}
2508
Reid Spencer04cde2c2004-07-04 11:33:49 +00002509/// This function completely parses a bytecode buffer given by the \p Buf
2510/// and \p Length parameters.
Anton Korobeynikov7d515442006-09-01 20:35:17 +00002511bool BytecodeReader::ParseBytecode(volatile BufPtr Buf, unsigned Length,
Reid Spencer233fe722006-08-22 16:09:19 +00002512 const std::string &ModuleID,
2513 std::string* ErrMsg) {
Misha Brukmane0dd0d42003-09-23 16:15:29 +00002514
Reid Spencer233fe722006-08-22 16:09:19 +00002515 /// We handle errors by
2516 if (setjmp(context)) {
2517 // Cleanup after error
2518 if (Handler) Handler->handleError(ErrorMsg);
Reid Spencer060d25d2004-06-29 23:29:38 +00002519 freeState();
Chris Lattner2a7b6ba2003-03-06 17:15:19 +00002520 delete TheModule;
2521 TheModule = 0;
Chris Lattner3bdad692004-11-15 21:55:33 +00002522 if (decompressedBlock != 0 ) {
Reid Spencer61aaf2e2004-11-14 21:59:21 +00002523 ::free(decompressedBlock);
Chris Lattner3bdad692004-11-15 21:55:33 +00002524 decompressedBlock = 0;
2525 }
Reid Spencer233fe722006-08-22 16:09:19 +00002526 // Set caller's error message, if requested
2527 if (ErrMsg)
2528 *ErrMsg = ErrorMsg;
2529 // Indicate an error occurred
2530 return true;
Chris Lattner2a7b6ba2003-03-06 17:15:19 +00002531 }
Reid Spencer233fe722006-08-22 16:09:19 +00002532
2533 RevisionNum = 0;
2534 At = MemStart = BlockStart = Buf;
2535 MemEnd = BlockEnd = Buf + Length;
2536
2537 // Create the module
2538 TheModule = new Module(ModuleID);
2539
2540 if (Handler) Handler->handleStart(TheModule, Length);
2541
2542 // Read the four bytes of the signature.
2543 unsigned Sig = read_uint();
2544
2545 // If this is a compressed file
2546 if (Sig == ('l' | ('l' << 8) | ('v' << 16) | ('c' << 24))) {
2547
2548 // Invoke the decompression of the bytecode. Note that we have to skip the
2549 // file's magic number which is not part of the compressed block. Hence,
2550 // the Buf+4 and Length-4. The result goes into decompressedBlock, a data
2551 // member for retention until BytecodeReader is destructed.
2552 unsigned decompressedLength = Compressor::decompressToNewBuffer(
2553 (char*)Buf+4,Length-4,decompressedBlock);
2554
2555 // We must adjust the buffer pointers used by the bytecode reader to point
2556 // into the new decompressed block. After decompression, the
2557 // decompressedBlock will point to a contiguous memory area that has
2558 // the decompressed data.
2559 At = MemStart = BlockStart = Buf = (BufPtr) decompressedBlock;
2560 MemEnd = BlockEnd = Buf + decompressedLength;
2561
2562 // else if this isn't a regular (uncompressed) bytecode file, then its
2563 // and error, generate that now.
2564 } else if (Sig != ('l' | ('l' << 8) | ('v' << 16) | ('m' << 24))) {
2565 error("Invalid bytecode signature: " + utohexstr(Sig));
2566 }
2567
2568 // Tell the handler we're starting a module
2569 if (Handler) Handler->handleModuleBegin(ModuleID);
2570
2571 // Get the module block and size and verify. This is handled specially
2572 // because the module block/size is always written in long format. Other
2573 // blocks are written in short format so the read_block method is used.
2574 unsigned Type, Size;
2575 Type = read_uint();
2576 Size = read_uint();
2577 if (Type != BytecodeFormat::ModuleBlockID) {
2578 error("Expected Module Block! Type:" + utostr(Type) + ", Size:"
2579 + utostr(Size));
2580 }
2581
2582 // It looks like the darwin ranlib program is broken, and adds trailing
2583 // garbage to the end of some bytecode files. This hack allows the bc
2584 // reader to ignore trailing garbage on bytecode files.
2585 if (At + Size < MemEnd)
2586 MemEnd = BlockEnd = At+Size;
2587
2588 if (At + Size != MemEnd)
2589 error("Invalid Top Level Block Length! Type:" + utostr(Type)
2590 + ", Size:" + utostr(Size));
2591
2592 // Parse the module contents
2593 this->ParseModule();
2594
2595 // Check for missing functions
2596 if (hasFunctions())
2597 error("Function expected, but bytecode stream ended!");
2598
2599 // Look for intrinsic functions to upgrade, upgrade them, and save the
2600 // mapping from old function to new for use later when instructions are
2601 // converted.
2602 for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
2603 FI != FE; ++FI)
2604 if (Function* newF = UpgradeIntrinsicFunction(FI)) {
2605 upgradedFunctions.insert(std::make_pair(FI, newF));
2606 FI->setName("");
2607 }
2608
2609 // Tell the handler we're done with the module
2610 if (Handler)
2611 Handler->handleModuleEnd(ModuleID);
2612
2613 // Tell the handler we're finished the parse
2614 if (Handler) Handler->handleFinish();
2615
2616 return false;
2617
Chris Lattner00950542001-06-06 20:29:01 +00002618}
Reid Spencer060d25d2004-06-29 23:29:38 +00002619
2620//===----------------------------------------------------------------------===//
2621//=== Default Implementations of Handler Methods
2622//===----------------------------------------------------------------------===//
2623
2624BytecodeHandler::~BytecodeHandler() {}
Reid Spencer060d25d2004-06-29 23:29:38 +00002625