blob: 17d68248f4336b07ee8044032556cd4b621e123a [file] [log] [blame]
Chris Lattnerd6b65252001-10-24 01:15:12 +00001//===- Reader.cpp - Code to read bytecode files ---------------------------===//
Misha Brukman8a96c532005-04-21 21:44:41 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
Misha Brukman8a96c532005-04-21 21:44:41 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner00950542001-06-06 20:29:01 +00009//
10// This library implements the functionality defined in llvm/Bytecode/Reader.h
11//
Misha Brukman8a96c532005-04-21 21:44:41 +000012// Note that this library should be as fast as possible, reentrant, and
Chris Lattner00950542001-06-06 20:29:01 +000013// threadsafe!!
14//
Chris Lattner00950542001-06-06 20:29:01 +000015// TODO: Allow passing in an option to ignore the symbol table
16//
Chris Lattnerd6b65252001-10-24 01:15:12 +000017//===----------------------------------------------------------------------===//
Chris Lattner00950542001-06-06 20:29:01 +000018
Reid Spencer060d25d2004-06-29 23:29:38 +000019#include "Reader.h"
20#include "llvm/Bytecode/BytecodeHandler.h"
21#include "llvm/BasicBlock.h"
Chris Lattnerdee199f2005-05-06 22:34:01 +000022#include "llvm/CallingConv.h"
Reid Spencer060d25d2004-06-29 23:29:38 +000023#include "llvm/Constants.h"
Chris Lattner3bc5a602006-01-25 23:08:15 +000024#include "llvm/InlineAsm.h"
Reid Spencer04cde2c2004-07-04 11:33:49 +000025#include "llvm/Instructions.h"
Reid Spencer78d033e2007-01-06 07:24:44 +000026#include "llvm/TypeSymbolTable.h"
Chris Lattner00950542001-06-06 20:29:01 +000027#include "llvm/Bytecode/Format.h"
Chris Lattnerdee199f2005-05-06 22:34:01 +000028#include "llvm/Config/alloca.h"
Reid Spencer060d25d2004-06-29 23:29:38 +000029#include "llvm/Support/GetElementPtrTypeIterator.h"
Reid Spencer17f52c52004-11-06 23:17:23 +000030#include "llvm/Support/Compressor.h"
Jim Laskeycb6682f2005-08-17 19:34:49 +000031#include "llvm/Support/MathExtras.h"
Chris Lattner4c3d3a92007-01-31 19:56:15 +000032#include "llvm/ADT/SmallVector.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000033#include "llvm/ADT/StringExtras.h"
Reid Spencer060d25d2004-06-29 23:29:38 +000034#include <sstream>
Alkis Evlogimenos20aa4742004-09-03 18:19:51 +000035#include <algorithm>
Chris Lattner29b789b2003-11-19 17:27:18 +000036using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000037
Reid Spencer46b002c2004-07-11 17:28:43 +000038namespace {
Chris Lattnercad28bd2005-01-29 00:36:19 +000039 /// @brief A class for maintaining the slot number definition
40 /// as a placeholder for the actual definition for forward constants defs.
41 class ConstantPlaceHolder : public ConstantExpr {
42 ConstantPlaceHolder(); // DO NOT IMPLEMENT
43 void operator=(const ConstantPlaceHolder &); // DO NOT IMPLEMENT
44 public:
Chris Lattner61323322005-01-31 01:11:13 +000045 Use Op;
Misha Brukman8a96c532005-04-21 21:44:41 +000046 ConstantPlaceHolder(const Type *Ty)
Chris Lattner61323322005-01-31 01:11:13 +000047 : ConstantExpr(Ty, Instruction::UserOp1, &Op, 1),
Reid Spencer88cfda22006-12-31 05:44:24 +000048 Op(UndefValue::get(Type::Int32Ty), this) {
Chris Lattner61323322005-01-31 01:11:13 +000049 }
Chris Lattnercad28bd2005-01-29 00:36:19 +000050 };
Reid Spencer46b002c2004-07-11 17:28:43 +000051}
Reid Spencer060d25d2004-06-29 23:29:38 +000052
Reid Spencer24399722004-07-09 22:21:33 +000053// Provide some details on error
Reid Spencer233fe722006-08-22 16:09:19 +000054inline void BytecodeReader::error(const std::string& err) {
55 ErrorMsg = err + " (Vers=" + itostr(RevisionNum) + ", Pos="
56 + itostr(At-MemStart) + ")";
Reid Spenceref9b9a72007-02-05 20:47:22 +000057 if (Handler) Handler->handleError(ErrorMsg);
Reid Spencer233fe722006-08-22 16:09:19 +000058 longjmp(context,1);
Reid Spencer24399722004-07-09 22:21:33 +000059}
60
Reid Spencer060d25d2004-06-29 23:29:38 +000061//===----------------------------------------------------------------------===//
62// Bytecode Reading Methods
63//===----------------------------------------------------------------------===//
64
Reid Spencer04cde2c2004-07-04 11:33:49 +000065/// Determine if the current block being read contains any more data.
Reid Spencer060d25d2004-06-29 23:29:38 +000066inline bool BytecodeReader::moreInBlock() {
67 return At < BlockEnd;
Chris Lattner00950542001-06-06 20:29:01 +000068}
69
Reid Spencer04cde2c2004-07-04 11:33:49 +000070/// Throw an error if we've read past the end of the current block
Reid Spencer060d25d2004-06-29 23:29:38 +000071inline void BytecodeReader::checkPastBlockEnd(const char * block_name) {
Reid Spencer46b002c2004-07-11 17:28:43 +000072 if (At > BlockEnd)
Chris Lattnera79e7cc2004-10-16 18:18:16 +000073 error(std::string("Attempt to read past the end of ") + block_name +
74 " block.");
Reid Spencer060d25d2004-06-29 23:29:38 +000075}
Chris Lattner36392bc2003-10-08 21:18:57 +000076
Reid Spencer04cde2c2004-07-04 11:33:49 +000077/// Read a whole unsigned integer
Reid Spencer060d25d2004-06-29 23:29:38 +000078inline unsigned BytecodeReader::read_uint() {
Misha Brukman8a96c532005-04-21 21:44:41 +000079 if (At+4 > BlockEnd)
Reid Spencer24399722004-07-09 22:21:33 +000080 error("Ran out of data reading uint!");
Reid Spencer060d25d2004-06-29 23:29:38 +000081 At += 4;
82 return At[-4] | (At[-3] << 8) | (At[-2] << 16) | (At[-1] << 24);
83}
84
Reid Spencer04cde2c2004-07-04 11:33:49 +000085/// Read a variable-bit-rate encoded unsigned integer
Reid Spencer060d25d2004-06-29 23:29:38 +000086inline unsigned BytecodeReader::read_vbr_uint() {
87 unsigned Shift = 0;
88 unsigned Result = 0;
89 BufPtr Save = At;
Misha Brukman8a96c532005-04-21 21:44:41 +000090
Reid Spencer060d25d2004-06-29 23:29:38 +000091 do {
Misha Brukman8a96c532005-04-21 21:44:41 +000092 if (At == BlockEnd)
Reid Spencer24399722004-07-09 22:21:33 +000093 error("Ran out of data reading vbr_uint!");
Reid Spencer060d25d2004-06-29 23:29:38 +000094 Result |= (unsigned)((*At++) & 0x7F) << Shift;
95 Shift += 7;
96 } while (At[-1] & 0x80);
Reid Spencer04cde2c2004-07-04 11:33:49 +000097 if (Handler) Handler->handleVBR32(At-Save);
Reid Spencer060d25d2004-06-29 23:29:38 +000098 return Result;
99}
100
Reid Spencer04cde2c2004-07-04 11:33:49 +0000101/// Read a variable-bit-rate encoded unsigned 64-bit integer.
Reid Spencer060d25d2004-06-29 23:29:38 +0000102inline uint64_t BytecodeReader::read_vbr_uint64() {
103 unsigned Shift = 0;
104 uint64_t Result = 0;
105 BufPtr Save = At;
Misha Brukman8a96c532005-04-21 21:44:41 +0000106
Reid Spencer060d25d2004-06-29 23:29:38 +0000107 do {
Misha Brukman8a96c532005-04-21 21:44:41 +0000108 if (At == BlockEnd)
Reid Spencer24399722004-07-09 22:21:33 +0000109 error("Ran out of data reading vbr_uint64!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000110 Result |= (uint64_t)((*At++) & 0x7F) << Shift;
111 Shift += 7;
112 } while (At[-1] & 0x80);
Reid Spencer04cde2c2004-07-04 11:33:49 +0000113 if (Handler) Handler->handleVBR64(At-Save);
Reid Spencer060d25d2004-06-29 23:29:38 +0000114 return Result;
115}
116
Reid Spencer04cde2c2004-07-04 11:33:49 +0000117/// Read a variable-bit-rate encoded signed 64-bit integer.
Reid Spencer060d25d2004-06-29 23:29:38 +0000118inline int64_t BytecodeReader::read_vbr_int64() {
119 uint64_t R = read_vbr_uint64();
120 if (R & 1) {
121 if (R != 1)
122 return -(int64_t)(R >> 1);
123 else // There is no such thing as -0 with integers. "-0" really means
124 // 0x8000000000000000.
125 return 1LL << 63;
126 } else
127 return (int64_t)(R >> 1);
128}
129
Reid Spencer04cde2c2004-07-04 11:33:49 +0000130/// Read a pascal-style string (length followed by text)
Reid Spencer060d25d2004-06-29 23:29:38 +0000131inline std::string BytecodeReader::read_str() {
132 unsigned Size = read_vbr_uint();
133 const unsigned char *OldAt = At;
134 At += Size;
135 if (At > BlockEnd) // Size invalid?
Reid Spencer24399722004-07-09 22:21:33 +0000136 error("Ran out of data reading a string!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000137 return std::string((char*)OldAt, Size);
138}
139
Reid Spencer04cde2c2004-07-04 11:33:49 +0000140/// Read an arbitrary block of data
Reid Spencer060d25d2004-06-29 23:29:38 +0000141inline void BytecodeReader::read_data(void *Ptr, void *End) {
142 unsigned char *Start = (unsigned char *)Ptr;
143 unsigned Amount = (unsigned char *)End - Start;
Misha Brukman8a96c532005-04-21 21:44:41 +0000144 if (At+Amount > BlockEnd)
Reid Spencer24399722004-07-09 22:21:33 +0000145 error("Ran out of data!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000146 std::copy(At, At+Amount, Start);
147 At += Amount;
148}
149
Reid Spencer46b002c2004-07-11 17:28:43 +0000150/// Read a float value in little-endian order
151inline void BytecodeReader::read_float(float& FloatVal) {
Reid Spencerada16182004-07-25 21:36:26 +0000152 /// FIXME: This isn't optimal, it has size problems on some platforms
153 /// where FP is not IEEE.
Jim Laskeycb6682f2005-08-17 19:34:49 +0000154 FloatVal = BitsToFloat(At[0] | (At[1] << 8) | (At[2] << 16) | (At[3] << 24));
Reid Spencerada16182004-07-25 21:36:26 +0000155 At+=sizeof(uint32_t);
Reid Spencer46b002c2004-07-11 17:28:43 +0000156}
157
158/// Read a double value in little-endian order
159inline void BytecodeReader::read_double(double& DoubleVal) {
Reid Spencerada16182004-07-25 21:36:26 +0000160 /// FIXME: This isn't optimal, it has size problems on some platforms
161 /// where FP is not IEEE.
Jim Laskeycb6682f2005-08-17 19:34:49 +0000162 DoubleVal = BitsToDouble((uint64_t(At[0]) << 0) | (uint64_t(At[1]) << 8) |
163 (uint64_t(At[2]) << 16) | (uint64_t(At[3]) << 24) |
164 (uint64_t(At[4]) << 32) | (uint64_t(At[5]) << 40) |
165 (uint64_t(At[6]) << 48) | (uint64_t(At[7]) << 56));
Reid Spencerada16182004-07-25 21:36:26 +0000166 At+=sizeof(uint64_t);
Reid Spencer46b002c2004-07-11 17:28:43 +0000167}
168
Reid Spencer04cde2c2004-07-04 11:33:49 +0000169/// Read a block header and obtain its type and size
Reid Spencer060d25d2004-06-29 23:29:38 +0000170inline void BytecodeReader::read_block(unsigned &Type, unsigned &Size) {
Reid Spencerd798a512006-11-14 04:47:22 +0000171 Size = read_uint(); // Read the header
172 Type = Size & 0x1F; // mask low order five bits to get type
173 Size >>= 5; // high order 27 bits is the size
Reid Spencer060d25d2004-06-29 23:29:38 +0000174 BlockStart = At;
Reid Spencer46b002c2004-07-11 17:28:43 +0000175 if (At + Size > BlockEnd)
Reid Spencer24399722004-07-09 22:21:33 +0000176 error("Attempt to size a block past end of memory");
Reid Spencer060d25d2004-06-29 23:29:38 +0000177 BlockEnd = At + Size;
Reid Spencer46b002c2004-07-11 17:28:43 +0000178 if (Handler) Handler->handleBlock(Type, BlockStart, Size);
Reid Spencer04cde2c2004-07-04 11:33:49 +0000179}
180
Reid Spencer060d25d2004-06-29 23:29:38 +0000181//===----------------------------------------------------------------------===//
182// IR Lookup Methods
183//===----------------------------------------------------------------------===//
184
Reid Spencer04cde2c2004-07-04 11:33:49 +0000185/// Determine if a type id has an implicit null value
Reid Spencer46b002c2004-07-11 17:28:43 +0000186inline bool BytecodeReader::hasImplicitNull(unsigned TyID) {
Reid Spencerd798a512006-11-14 04:47:22 +0000187 return TyID != Type::LabelTyID && TyID != Type::VoidTyID;
Reid Spencer060d25d2004-06-29 23:29:38 +0000188}
189
Reid Spencerd2bb8872007-01-30 19:36:46 +0000190/// Obtain a type given a typeid and account for things like function level vs
191/// module level, and the offsetting for the primitive types.
Reid Spencer060d25d2004-06-29 23:29:38 +0000192const Type *BytecodeReader::getType(unsigned ID) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000193 if (ID <= Type::LastPrimitiveTyID)
Chris Lattnerf70c22b2004-06-17 18:19:28 +0000194 if (const Type *T = Type::getPrimitiveType((Type::TypeID)ID))
Chris Lattner927b1852003-10-09 20:22:47 +0000195 return T; // Asked for a primitive type...
Chris Lattner36392bc2003-10-08 21:18:57 +0000196
197 // Otherwise, derived types need offset...
Chris Lattner89e02532004-01-18 21:08:15 +0000198 ID -= Type::FirstDerivedTyID;
199
Chris Lattner36392bc2003-10-08 21:18:57 +0000200 // Is it a module-level type?
Reid Spencer46b002c2004-07-11 17:28:43 +0000201 if (ID < ModuleTypes.size())
202 return ModuleTypes[ID].get();
Chris Lattner36392bc2003-10-08 21:18:57 +0000203
Reid Spencer46b002c2004-07-11 17:28:43 +0000204 // Nope, is it a function-level type?
205 ID -= ModuleTypes.size();
206 if (ID < FunctionTypes.size())
207 return FunctionTypes[ID].get();
Chris Lattner36392bc2003-10-08 21:18:57 +0000208
Reid Spencer46b002c2004-07-11 17:28:43 +0000209 error("Illegal type reference!");
210 return Type::VoidTy;
Chris Lattner00950542001-06-06 20:29:01 +0000211}
212
Reid Spencer3795ad12006-12-03 05:47:10 +0000213/// This method just saves some coding. It uses read_vbr_uint to read in a
214/// type id, errors that its not the type type, and then calls getType to
215/// return the type value.
Reid Spencerd798a512006-11-14 04:47:22 +0000216inline const Type* BytecodeReader::readType() {
217 return getType(read_vbr_uint());
Reid Spencer04cde2c2004-07-04 11:33:49 +0000218}
219
220/// Get the slot number associated with a type accounting for primitive
Reid Spencerd2bb8872007-01-30 19:36:46 +0000221/// types and function level vs module level.
Reid Spencer060d25d2004-06-29 23:29:38 +0000222unsigned BytecodeReader::getTypeSlot(const Type *Ty) {
223 if (Ty->isPrimitiveType())
224 return Ty->getTypeID();
225
Reid Spencer060d25d2004-06-29 23:29:38 +0000226 // Check the function level types first...
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000227 TypeListTy::iterator I = std::find(FunctionTypes.begin(),
228 FunctionTypes.end(), Ty);
Reid Spencer060d25d2004-06-29 23:29:38 +0000229
230 if (I != FunctionTypes.end())
Misha Brukman8a96c532005-04-21 21:44:41 +0000231 return Type::FirstDerivedTyID + ModuleTypes.size() +
Reid Spencer46b002c2004-07-11 17:28:43 +0000232 (&*I - &FunctionTypes[0]);
Reid Spencer060d25d2004-06-29 23:29:38 +0000233
Chris Lattnereebac5f2005-10-03 21:26:53 +0000234 // If we don't have our cache yet, build it now.
235 if (ModuleTypeIDCache.empty()) {
236 unsigned N = 0;
237 ModuleTypeIDCache.reserve(ModuleTypes.size());
238 for (TypeListTy::iterator I = ModuleTypes.begin(), E = ModuleTypes.end();
239 I != E; ++I, ++N)
240 ModuleTypeIDCache.push_back(std::make_pair(*I, N));
241
242 std::sort(ModuleTypeIDCache.begin(), ModuleTypeIDCache.end());
243 }
244
245 // Binary search the cache for the entry.
246 std::vector<std::pair<const Type*, unsigned> >::iterator IT =
247 std::lower_bound(ModuleTypeIDCache.begin(), ModuleTypeIDCache.end(),
248 std::make_pair(Ty, 0U));
249 if (IT == ModuleTypeIDCache.end() || IT->first != Ty)
Reid Spencer24399722004-07-09 22:21:33 +0000250 error("Didn't find type in ModuleTypes.");
Chris Lattnereebac5f2005-10-03 21:26:53 +0000251
252 return Type::FirstDerivedTyID + IT->second;
Chris Lattner80b97342004-01-17 23:25:43 +0000253}
254
Misha Brukman8a96c532005-04-21 21:44:41 +0000255/// Retrieve a value of a given type and slot number, possibly creating
256/// it if it doesn't already exist.
Reid Spencer060d25d2004-06-29 23:29:38 +0000257Value * BytecodeReader::getValue(unsigned type, unsigned oNum, bool Create) {
Chris Lattner4ee8ef22003-10-08 22:52:54 +0000258 assert(type != Type::LabelTyID && "getValue() cannot get blocks!");
Chris Lattner00950542001-06-06 20:29:01 +0000259 unsigned Num = oNum;
Chris Lattner00950542001-06-06 20:29:01 +0000260
Reid Spencerd2bb8872007-01-30 19:36:46 +0000261 // By default, the global type id is the type id passed in
262 unsigned GlobalTyID = type;
Reid Spencer060d25d2004-06-29 23:29:38 +0000263
Reid Spencerd2bb8872007-01-30 19:36:46 +0000264 if (hasImplicitNull(GlobalTyID)) {
265 const Type *Ty = getType(type);
266 if (!isa<OpaqueType>(Ty)) {
267 if (Num == 0)
268 return Constant::getNullValue(Ty);
269 --Num;
Chris Lattner89e02532004-01-18 21:08:15 +0000270 }
Reid Spencerd2bb8872007-01-30 19:36:46 +0000271 }
Chris Lattner89e02532004-01-18 21:08:15 +0000272
Reid Spencerd2bb8872007-01-30 19:36:46 +0000273 if (GlobalTyID < ModuleValues.size() && ModuleValues[GlobalTyID]) {
274 if (Num < ModuleValues[GlobalTyID]->size())
275 return ModuleValues[GlobalTyID]->getOperand(Num);
276 Num -= ModuleValues[GlobalTyID]->size();
Chris Lattner52e20b02003-03-19 20:54:26 +0000277 }
278
Misha Brukman8a96c532005-04-21 21:44:41 +0000279 if (FunctionValues.size() > type &&
280 FunctionValues[type] &&
Reid Spencer060d25d2004-06-29 23:29:38 +0000281 Num < FunctionValues[type]->size())
282 return FunctionValues[type]->getOperand(Num);
Chris Lattner00950542001-06-06 20:29:01 +0000283
Chris Lattner74734132002-08-17 22:01:27 +0000284 if (!Create) return 0; // Do not create a placeholder?
Chris Lattner00950542001-06-06 20:29:01 +0000285
Reid Spencer551ccae2004-09-01 22:55:40 +0000286 // Did we already create a place holder?
Chris Lattner8eb10ce2003-10-09 06:05:40 +0000287 std::pair<unsigned,unsigned> KeyValue(type, oNum);
Reid Spencer060d25d2004-06-29 23:29:38 +0000288 ForwardReferenceMap::iterator I = ForwardReferences.lower_bound(KeyValue);
Chris Lattner8eb10ce2003-10-09 06:05:40 +0000289 if (I != ForwardReferences.end() && I->first == KeyValue)
290 return I->second; // We have already created this placeholder
291
Reid Spencer551ccae2004-09-01 22:55:40 +0000292 // If the type exists (it should)
293 if (const Type* Ty = getType(type)) {
294 // Create the place holder
295 Value *Val = new Argument(Ty);
296 ForwardReferences.insert(I, std::make_pair(KeyValue, Val));
297 return Val;
298 }
Reid Spencer233fe722006-08-22 16:09:19 +0000299 error("Can't create placeholder for value of type slot #" + utostr(type));
300 return 0; // just silence warning, error calls longjmp
Chris Lattner00950542001-06-06 20:29:01 +0000301}
302
Reid Spencer060d25d2004-06-29 23:29:38 +0000303
Reid Spencer04cde2c2004-07-04 11:33:49 +0000304/// Just like getValue, except that it returns a null pointer
305/// only on error. It always returns a constant (meaning that if the value is
306/// defined, but is not a constant, that is an error). If the specified
Misha Brukman8a96c532005-04-21 21:44:41 +0000307/// constant hasn't been parsed yet, a placeholder is defined and used.
Reid Spencer04cde2c2004-07-04 11:33:49 +0000308/// Later, after the real value is parsed, the placeholder is eliminated.
Reid Spencer060d25d2004-06-29 23:29:38 +0000309Constant* BytecodeReader::getConstantValue(unsigned TypeSlot, unsigned Slot) {
310 if (Value *V = getValue(TypeSlot, Slot, false))
311 if (Constant *C = dyn_cast<Constant>(V))
312 return C; // If we already have the value parsed, just return it
Reid Spencer060d25d2004-06-29 23:29:38 +0000313 else
Misha Brukman8a96c532005-04-21 21:44:41 +0000314 error("Value for slot " + utostr(Slot) +
Reid Spencera86037e2004-07-18 00:12:03 +0000315 " is expected to be a constant!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000316
Chris Lattner389bd042004-12-09 06:19:44 +0000317 std::pair<unsigned, unsigned> Key(TypeSlot, Slot);
Reid Spencer060d25d2004-06-29 23:29:38 +0000318 ConstantRefsType::iterator I = ConstantFwdRefs.lower_bound(Key);
319
320 if (I != ConstantFwdRefs.end() && I->first == Key) {
321 return I->second;
322 } else {
323 // Create a placeholder for the constant reference and
324 // keep track of the fact that we have a forward ref to recycle it
Chris Lattner389bd042004-12-09 06:19:44 +0000325 Constant *C = new ConstantPlaceHolder(getType(TypeSlot));
Misha Brukman8a96c532005-04-21 21:44:41 +0000326
Reid Spencer060d25d2004-06-29 23:29:38 +0000327 // Keep track of the fact that we have a forward ref to recycle it
328 ConstantFwdRefs.insert(I, std::make_pair(Key, C));
329 return C;
330 }
331}
332
333//===----------------------------------------------------------------------===//
334// IR Construction Methods
335//===----------------------------------------------------------------------===//
336
Reid Spencer04cde2c2004-07-04 11:33:49 +0000337/// As values are created, they are inserted into the appropriate place
338/// with this method. The ValueTable argument must be one of ModuleValues
339/// or FunctionValues data members of this class.
Misha Brukman8a96c532005-04-21 21:44:41 +0000340unsigned BytecodeReader::insertValue(Value *Val, unsigned type,
Reid Spencer46b002c2004-07-11 17:28:43 +0000341 ValueTable &ValueTab) {
Reid Spencer060d25d2004-06-29 23:29:38 +0000342 if (ValueTab.size() <= type)
343 ValueTab.resize(type+1);
344
345 if (!ValueTab[type]) ValueTab[type] = new ValueList();
346
347 ValueTab[type]->push_back(Val);
348
Chris Lattneraba5ff52005-05-05 20:57:00 +0000349 bool HasOffset = hasImplicitNull(type) && !isa<OpaqueType>(Val->getType());
Reid Spencer060d25d2004-06-29 23:29:38 +0000350 return ValueTab[type]->size()-1 + HasOffset;
351}
352
Reid Spencer04cde2c2004-07-04 11:33:49 +0000353/// Insert the arguments of a function as new values in the reader.
Reid Spencer46b002c2004-07-11 17:28:43 +0000354void BytecodeReader::insertArguments(Function* F) {
Reid Spencer060d25d2004-06-29 23:29:38 +0000355 const FunctionType *FT = F->getFunctionType();
Chris Lattnere4d5c442005-03-15 04:54:21 +0000356 Function::arg_iterator AI = F->arg_begin();
Reid Spencer060d25d2004-06-29 23:29:38 +0000357 for (FunctionType::param_iterator It = FT->param_begin();
358 It != FT->param_end(); ++It, ++AI)
359 insertValue(AI, getTypeSlot(AI->getType()), FunctionValues);
360}
361
362//===----------------------------------------------------------------------===//
363// Bytecode Parsing Methods
364//===----------------------------------------------------------------------===//
365
Reid Spencer04cde2c2004-07-04 11:33:49 +0000366/// This method parses a single instruction. The instruction is
367/// inserted at the end of the \p BB provided. The arguments of
Misha Brukman44666b12004-09-28 16:57:46 +0000368/// the instruction are provided in the \p Oprnds vector.
Chris Lattner63cf59e2007-02-07 05:08:39 +0000369void BytecodeReader::ParseInstruction(SmallVector<unsigned, 8> &Oprnds,
Reid Spencer46b002c2004-07-11 17:28:43 +0000370 BasicBlock* BB) {
Reid Spencer060d25d2004-06-29 23:29:38 +0000371 BufPtr SaveAt = At;
372
373 // Clear instruction data
374 Oprnds.clear();
375 unsigned iType = 0;
376 unsigned Opcode = 0;
377 unsigned Op = read_uint();
378
379 // bits Instruction format: Common to all formats
380 // --------------------------
381 // 01-00: Opcode type, fixed to 1.
382 // 07-02: Opcode
383 Opcode = (Op >> 2) & 63;
384 Oprnds.resize((Op >> 0) & 03);
385
386 // Extract the operands
387 switch (Oprnds.size()) {
388 case 1:
389 // bits Instruction format:
390 // --------------------------
391 // 19-08: Resulting type plane
392 // 31-20: Operand #1 (if set to (2^12-1), then zero operands)
393 //
394 iType = (Op >> 8) & 4095;
395 Oprnds[0] = (Op >> 20) & 4095;
396 if (Oprnds[0] == 4095) // Handle special encoding for 0 operands...
397 Oprnds.resize(0);
398 break;
399 case 2:
400 // bits Instruction format:
401 // --------------------------
402 // 15-08: Resulting type plane
403 // 23-16: Operand #1
Misha Brukman8a96c532005-04-21 21:44:41 +0000404 // 31-24: Operand #2
Reid Spencer060d25d2004-06-29 23:29:38 +0000405 //
406 iType = (Op >> 8) & 255;
407 Oprnds[0] = (Op >> 16) & 255;
408 Oprnds[1] = (Op >> 24) & 255;
409 break;
410 case 3:
411 // bits Instruction format:
412 // --------------------------
413 // 13-08: Resulting type plane
414 // 19-14: Operand #1
415 // 25-20: Operand #2
416 // 31-26: Operand #3
417 //
418 iType = (Op >> 8) & 63;
419 Oprnds[0] = (Op >> 14) & 63;
420 Oprnds[1] = (Op >> 20) & 63;
421 Oprnds[2] = (Op >> 26) & 63;
422 break;
423 case 0:
424 At -= 4; // Hrm, try this again...
425 Opcode = read_vbr_uint();
426 Opcode >>= 2;
427 iType = read_vbr_uint();
428
429 unsigned NumOprnds = read_vbr_uint();
430 Oprnds.resize(NumOprnds);
431
432 if (NumOprnds == 0)
Reid Spencer24399722004-07-09 22:21:33 +0000433 error("Zero-argument instruction found; this is invalid.");
Reid Spencer060d25d2004-06-29 23:29:38 +0000434
435 for (unsigned i = 0; i != NumOprnds; ++i)
436 Oprnds[i] = read_vbr_uint();
Reid Spencer060d25d2004-06-29 23:29:38 +0000437 break;
438 }
439
Reid Spencerd798a512006-11-14 04:47:22 +0000440 const Type *InstTy = getType(iType);
Reid Spencer060d25d2004-06-29 23:29:38 +0000441
Reid Spencer1628cec2006-10-26 06:15:43 +0000442 // Make the necessary adjustments for dealing with backwards compatibility
443 // of opcodes.
Reid Spencer3795ad12006-12-03 05:47:10 +0000444 Instruction* Result = 0;
Reid Spencer1628cec2006-10-26 06:15:43 +0000445
Reid Spencer3795ad12006-12-03 05:47:10 +0000446 // First, handle the easy binary operators case
447 if (Opcode >= Instruction::BinaryOpsBegin &&
Reid Spencerc8dab492006-12-03 06:28:54 +0000448 Opcode < Instruction::BinaryOpsEnd && Oprnds.size() == 2) {
Reid Spencer3795ad12006-12-03 05:47:10 +0000449 Result = BinaryOperator::create(Instruction::BinaryOps(Opcode),
450 getValue(iType, Oprnds[0]),
451 getValue(iType, Oprnds[1]));
Reid Spencerc8dab492006-12-03 06:28:54 +0000452 } else {
Reid Spencer1628cec2006-10-26 06:15:43 +0000453 // Indicate that we don't think this is a call instruction (yet).
454 // Process based on the Opcode read
455 switch (Opcode) {
456 default: // There was an error, this shouldn't happen.
457 if (Result == 0)
458 error("Illegal instruction read!");
459 break;
460 case Instruction::VAArg:
461 if (Oprnds.size() != 2)
462 error("Invalid VAArg instruction!");
463 Result = new VAArgInst(getValue(iType, Oprnds[0]),
Reid Spencerd798a512006-11-14 04:47:22 +0000464 getType(Oprnds[1]));
Reid Spencer1628cec2006-10-26 06:15:43 +0000465 break;
466 case Instruction::ExtractElement: {
467 if (Oprnds.size() != 2)
468 error("Invalid extractelement instruction!");
469 Value *V1 = getValue(iType, Oprnds[0]);
Reid Spencera54b7cb2007-01-12 07:05:14 +0000470 Value *V2 = getValue(Int32TySlot, Oprnds[1]);
Chris Lattner59fecec2006-04-08 04:09:19 +0000471
Reid Spencer1628cec2006-10-26 06:15:43 +0000472 if (!ExtractElementInst::isValidOperands(V1, V2))
473 error("Invalid extractelement instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000474
Reid Spencer1628cec2006-10-26 06:15:43 +0000475 Result = new ExtractElementInst(V1, V2);
476 break;
Chris Lattnera65371e2006-05-26 18:42:34 +0000477 }
Reid Spencer1628cec2006-10-26 06:15:43 +0000478 case Instruction::InsertElement: {
479 const PackedType *PackedTy = dyn_cast<PackedType>(InstTy);
480 if (!PackedTy || Oprnds.size() != 3)
481 error("Invalid insertelement instruction!");
482
483 Value *V1 = getValue(iType, Oprnds[0]);
484 Value *V2 = getValue(getTypeSlot(PackedTy->getElementType()),Oprnds[1]);
Reid Spencera54b7cb2007-01-12 07:05:14 +0000485 Value *V3 = getValue(Int32TySlot, Oprnds[2]);
Reid Spencer1628cec2006-10-26 06:15:43 +0000486
487 if (!InsertElementInst::isValidOperands(V1, V2, V3))
488 error("Invalid insertelement instruction!");
489 Result = new InsertElementInst(V1, V2, V3);
490 break;
491 }
492 case Instruction::ShuffleVector: {
493 const PackedType *PackedTy = dyn_cast<PackedType>(InstTy);
494 if (!PackedTy || Oprnds.size() != 3)
495 error("Invalid shufflevector instruction!");
496 Value *V1 = getValue(iType, Oprnds[0]);
497 Value *V2 = getValue(iType, Oprnds[1]);
498 const PackedType *EltTy =
Reid Spencer88cfda22006-12-31 05:44:24 +0000499 PackedType::get(Type::Int32Ty, PackedTy->getNumElements());
Reid Spencer1628cec2006-10-26 06:15:43 +0000500 Value *V3 = getValue(getTypeSlot(EltTy), Oprnds[2]);
501 if (!ShuffleVectorInst::isValidOperands(V1, V2, V3))
502 error("Invalid shufflevector instruction!");
503 Result = new ShuffleVectorInst(V1, V2, V3);
504 break;
505 }
Reid Spencer3da59db2006-11-27 01:05:10 +0000506 case Instruction::Trunc:
507 if (Oprnds.size() != 2)
508 error("Invalid cast instruction!");
509 Result = new TruncInst(getValue(iType, Oprnds[0]),
510 getType(Oprnds[1]));
511 break;
512 case Instruction::ZExt:
513 if (Oprnds.size() != 2)
514 error("Invalid cast instruction!");
515 Result = new ZExtInst(getValue(iType, Oprnds[0]),
516 getType(Oprnds[1]));
517 break;
518 case Instruction::SExt:
Reid Spencer1628cec2006-10-26 06:15:43 +0000519 if (Oprnds.size() != 2)
520 error("Invalid Cast instruction!");
Reid Spencer3da59db2006-11-27 01:05:10 +0000521 Result = new SExtInst(getValue(iType, Oprnds[0]),
Reid Spencerd798a512006-11-14 04:47:22 +0000522 getType(Oprnds[1]));
Reid Spencer1628cec2006-10-26 06:15:43 +0000523 break;
Reid Spencer3da59db2006-11-27 01:05:10 +0000524 case Instruction::FPTrunc:
525 if (Oprnds.size() != 2)
526 error("Invalid cast instruction!");
527 Result = new FPTruncInst(getValue(iType, Oprnds[0]),
528 getType(Oprnds[1]));
529 break;
530 case Instruction::FPExt:
531 if (Oprnds.size() != 2)
532 error("Invalid cast instruction!");
533 Result = new FPExtInst(getValue(iType, Oprnds[0]),
534 getType(Oprnds[1]));
535 break;
536 case Instruction::UIToFP:
537 if (Oprnds.size() != 2)
538 error("Invalid cast instruction!");
539 Result = new UIToFPInst(getValue(iType, Oprnds[0]),
540 getType(Oprnds[1]));
541 break;
542 case Instruction::SIToFP:
543 if (Oprnds.size() != 2)
544 error("Invalid cast instruction!");
545 Result = new SIToFPInst(getValue(iType, Oprnds[0]),
546 getType(Oprnds[1]));
547 break;
548 case Instruction::FPToUI:
549 if (Oprnds.size() != 2)
550 error("Invalid cast instruction!");
551 Result = new FPToUIInst(getValue(iType, Oprnds[0]),
552 getType(Oprnds[1]));
553 break;
554 case Instruction::FPToSI:
555 if (Oprnds.size() != 2)
556 error("Invalid cast instruction!");
557 Result = new FPToSIInst(getValue(iType, Oprnds[0]),
558 getType(Oprnds[1]));
559 break;
560 case Instruction::IntToPtr:
561 if (Oprnds.size() != 2)
562 error("Invalid cast instruction!");
563 Result = new IntToPtrInst(getValue(iType, Oprnds[0]),
564 getType(Oprnds[1]));
565 break;
566 case Instruction::PtrToInt:
567 if (Oprnds.size() != 2)
568 error("Invalid cast instruction!");
569 Result = new PtrToIntInst(getValue(iType, Oprnds[0]),
570 getType(Oprnds[1]));
571 break;
572 case Instruction::BitCast:
573 if (Oprnds.size() != 2)
574 error("Invalid cast instruction!");
575 Result = new BitCastInst(getValue(iType, Oprnds[0]),
576 getType(Oprnds[1]));
577 break;
Reid Spencer1628cec2006-10-26 06:15:43 +0000578 case Instruction::Select:
579 if (Oprnds.size() != 3)
580 error("Invalid Select instruction!");
Reid Spencera54b7cb2007-01-12 07:05:14 +0000581 Result = new SelectInst(getValue(BoolTySlot, Oprnds[0]),
Reid Spencer1628cec2006-10-26 06:15:43 +0000582 getValue(iType, Oprnds[1]),
583 getValue(iType, Oprnds[2]));
584 break;
585 case Instruction::PHI: {
586 if (Oprnds.size() == 0 || (Oprnds.size() & 1))
587 error("Invalid phi node encountered!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000588
Reid Spencer1628cec2006-10-26 06:15:43 +0000589 PHINode *PN = new PHINode(InstTy);
590 PN->reserveOperandSpace(Oprnds.size());
591 for (unsigned i = 0, e = Oprnds.size(); i != e; i += 2)
592 PN->addIncoming(
593 getValue(iType, Oprnds[i]), getBasicBlock(Oprnds[i+1]));
594 Result = PN;
595 break;
596 }
Reid Spencerc8dab492006-12-03 06:28:54 +0000597 case Instruction::ICmp:
598 case Instruction::FCmp:
Reid Spencer9f132762006-12-03 17:17:02 +0000599 if (Oprnds.size() != 3)
600 error("Cmp instructions requires 3 operands");
Reid Spencerc8dab492006-12-03 06:28:54 +0000601 // These instructions encode the comparison predicate as the 3rd operand.
602 Result = CmpInst::create(Instruction::OtherOps(Opcode),
603 static_cast<unsigned short>(Oprnds[2]),
604 getValue(iType, Oprnds[0]), getValue(iType, Oprnds[1]));
605 break;
Reid Spencer1628cec2006-10-26 06:15:43 +0000606 case Instruction::Ret:
607 if (Oprnds.size() == 0)
608 Result = new ReturnInst();
609 else if (Oprnds.size() == 1)
610 Result = new ReturnInst(getValue(iType, Oprnds[0]));
611 else
612 error("Unrecognized instruction!");
613 break;
614
615 case Instruction::Br:
616 if (Oprnds.size() == 1)
617 Result = new BranchInst(getBasicBlock(Oprnds[0]));
618 else if (Oprnds.size() == 3)
619 Result = new BranchInst(getBasicBlock(Oprnds[0]),
Reid Spencera54b7cb2007-01-12 07:05:14 +0000620 getBasicBlock(Oprnds[1]), getValue(BoolTySlot, Oprnds[2]));
Reid Spencer1628cec2006-10-26 06:15:43 +0000621 else
622 error("Invalid number of operands for a 'br' instruction!");
623 break;
624 case Instruction::Switch: {
625 if (Oprnds.size() & 1)
626 error("Switch statement with odd number of arguments!");
627
628 SwitchInst *I = new SwitchInst(getValue(iType, Oprnds[0]),
629 getBasicBlock(Oprnds[1]),
630 Oprnds.size()/2-1);
631 for (unsigned i = 2, e = Oprnds.size(); i != e; i += 2)
632 I->addCase(cast<ConstantInt>(getValue(iType, Oprnds[i])),
633 getBasicBlock(Oprnds[i+1]));
634 Result = I;
635 break;
636 }
637 case 58: // Call with extra operand for calling conv
638 case 59: // tail call, Fast CC
639 case 60: // normal call, Fast CC
640 case 61: // tail call, C Calling Conv
641 case Instruction::Call: { // Normal Call, C Calling Convention
642 if (Oprnds.size() == 0)
643 error("Invalid call instruction encountered!");
Reid Spencer1628cec2006-10-26 06:15:43 +0000644 Value *F = getValue(iType, Oprnds[0]);
645
646 unsigned CallingConv = CallingConv::C;
647 bool isTailCall = false;
648
649 if (Opcode == 61 || Opcode == 59)
650 isTailCall = true;
651
652 if (Opcode == 58) {
653 isTailCall = Oprnds.back() & 1;
654 CallingConv = Oprnds.back() >> 1;
655 Oprnds.pop_back();
656 } else if (Opcode == 59 || Opcode == 60) {
657 CallingConv = CallingConv::Fast;
658 }
659
660 // Check to make sure we have a pointer to function type
661 const PointerType *PTy = dyn_cast<PointerType>(F->getType());
662 if (PTy == 0) error("Call to non function pointer value!");
663 const FunctionType *FTy = dyn_cast<FunctionType>(PTy->getElementType());
664 if (FTy == 0) error("Call to non function pointer value!");
665
666 std::vector<Value *> Params;
667 if (!FTy->isVarArg()) {
668 FunctionType::param_iterator It = FTy->param_begin();
669
670 for (unsigned i = 1, e = Oprnds.size(); i != e; ++i) {
671 if (It == FTy->param_end())
672 error("Invalid call instruction!");
673 Params.push_back(getValue(getTypeSlot(*It++), Oprnds[i]));
674 }
675 if (It != FTy->param_end())
Reid Spencer24399722004-07-09 22:21:33 +0000676 error("Invalid call instruction!");
Reid Spencer1628cec2006-10-26 06:15:43 +0000677 } else {
678 Oprnds.erase(Oprnds.begin(), Oprnds.begin()+1);
679
680 unsigned FirstVariableOperand;
681 if (Oprnds.size() < FTy->getNumParams())
682 error("Call instruction missing operands!");
683
684 // Read all of the fixed arguments
685 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
686 Params.push_back(
687 getValue(getTypeSlot(FTy->getParamType(i)),Oprnds[i]));
688
689 FirstVariableOperand = FTy->getNumParams();
690
691 if ((Oprnds.size()-FirstVariableOperand) & 1)
692 error("Invalid call instruction!"); // Must be pairs of type/value
693
694 for (unsigned i = FirstVariableOperand, e = Oprnds.size();
695 i != e; i += 2)
696 Params.push_back(getValue(Oprnds[i], Oprnds[i+1]));
Reid Spencer060d25d2004-06-29 23:29:38 +0000697 }
Reid Spencer060d25d2004-06-29 23:29:38 +0000698
Reid Spencer1628cec2006-10-26 06:15:43 +0000699 Result = new CallInst(F, Params);
700 if (isTailCall) cast<CallInst>(Result)->setTailCall();
701 if (CallingConv) cast<CallInst>(Result)->setCallingConv(CallingConv);
702 break;
Reid Spencer060d25d2004-06-29 23:29:38 +0000703 }
Reid Spencer1628cec2006-10-26 06:15:43 +0000704 case Instruction::Invoke: { // Invoke C CC
705 if (Oprnds.size() < 3)
706 error("Invalid invoke instruction!");
707 Value *F = getValue(iType, Oprnds[0]);
Reid Spencer060d25d2004-06-29 23:29:38 +0000708
Reid Spencer1628cec2006-10-26 06:15:43 +0000709 // Check to make sure we have a pointer to function type
710 const PointerType *PTy = dyn_cast<PointerType>(F->getType());
711 if (PTy == 0)
712 error("Invoke to non function pointer value!");
713 const FunctionType *FTy = dyn_cast<FunctionType>(PTy->getElementType());
714 if (FTy == 0)
715 error("Invoke to non function pointer value!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000716
Reid Spencer1628cec2006-10-26 06:15:43 +0000717 std::vector<Value *> Params;
718 BasicBlock *Normal, *Except;
Reid Spencer3da59db2006-11-27 01:05:10 +0000719 unsigned CallingConv = Oprnds.back();
720 Oprnds.pop_back();
Chris Lattnerdee199f2005-05-06 22:34:01 +0000721
Reid Spencer1628cec2006-10-26 06:15:43 +0000722 if (!FTy->isVarArg()) {
723 Normal = getBasicBlock(Oprnds[1]);
724 Except = getBasicBlock(Oprnds[2]);
Reid Spencer060d25d2004-06-29 23:29:38 +0000725
Reid Spencer1628cec2006-10-26 06:15:43 +0000726 FunctionType::param_iterator It = FTy->param_begin();
727 for (unsigned i = 3, e = Oprnds.size(); i != e; ++i) {
728 if (It == FTy->param_end())
729 error("Invalid invoke instruction!");
730 Params.push_back(getValue(getTypeSlot(*It++), Oprnds[i]));
731 }
732 if (It != FTy->param_end())
Reid Spencer24399722004-07-09 22:21:33 +0000733 error("Invalid invoke instruction!");
Reid Spencer1628cec2006-10-26 06:15:43 +0000734 } else {
735 Oprnds.erase(Oprnds.begin(), Oprnds.begin()+1);
736
737 Normal = getBasicBlock(Oprnds[0]);
738 Except = getBasicBlock(Oprnds[1]);
739
740 unsigned FirstVariableArgument = FTy->getNumParams()+2;
741 for (unsigned i = 2; i != FirstVariableArgument; ++i)
742 Params.push_back(getValue(getTypeSlot(FTy->getParamType(i-2)),
743 Oprnds[i]));
744
745 // Must be type/value pairs. If not, error out.
746 if (Oprnds.size()-FirstVariableArgument & 1)
747 error("Invalid invoke instruction!");
748
749 for (unsigned i = FirstVariableArgument; i < Oprnds.size(); i += 2)
750 Params.push_back(getValue(Oprnds[i], Oprnds[i+1]));
Reid Spencer060d25d2004-06-29 23:29:38 +0000751 }
Reid Spencer060d25d2004-06-29 23:29:38 +0000752
Reid Spencer1628cec2006-10-26 06:15:43 +0000753 Result = new InvokeInst(F, Normal, Except, Params);
754 if (CallingConv) cast<InvokeInst>(Result)->setCallingConv(CallingConv);
755 break;
Reid Spencer060d25d2004-06-29 23:29:38 +0000756 }
Reid Spencer1628cec2006-10-26 06:15:43 +0000757 case Instruction::Malloc: {
758 unsigned Align = 0;
759 if (Oprnds.size() == 2)
760 Align = (1 << Oprnds[1]) >> 1;
761 else if (Oprnds.size() > 2)
762 error("Invalid malloc instruction!");
763 if (!isa<PointerType>(InstTy))
764 error("Invalid malloc instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000765
Reid Spencer1628cec2006-10-26 06:15:43 +0000766 Result = new MallocInst(cast<PointerType>(InstTy)->getElementType(),
Reid Spencera54b7cb2007-01-12 07:05:14 +0000767 getValue(Int32TySlot, Oprnds[0]), Align);
Reid Spencer1628cec2006-10-26 06:15:43 +0000768 break;
769 }
770 case Instruction::Alloca: {
771 unsigned Align = 0;
772 if (Oprnds.size() == 2)
773 Align = (1 << Oprnds[1]) >> 1;
774 else if (Oprnds.size() > 2)
775 error("Invalid alloca instruction!");
776 if (!isa<PointerType>(InstTy))
777 error("Invalid alloca instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000778
Reid Spencer1628cec2006-10-26 06:15:43 +0000779 Result = new AllocaInst(cast<PointerType>(InstTy)->getElementType(),
Reid Spencera54b7cb2007-01-12 07:05:14 +0000780 getValue(Int32TySlot, Oprnds[0]), Align);
Reid Spencer1628cec2006-10-26 06:15:43 +0000781 break;
782 }
783 case Instruction::Free:
784 if (!isa<PointerType>(InstTy))
785 error("Invalid free instruction!");
786 Result = new FreeInst(getValue(iType, Oprnds[0]));
787 break;
788 case Instruction::GetElementPtr: {
789 if (Oprnds.size() == 0 || !isa<PointerType>(InstTy))
Misha Brukman8a96c532005-04-21 21:44:41 +0000790 error("Invalid getelementptr instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000791
Chris Lattner4c3d3a92007-01-31 19:56:15 +0000792 SmallVector<Value*, 8> Idx;
Reid Spencer1628cec2006-10-26 06:15:43 +0000793
794 const Type *NextTy = InstTy;
795 for (unsigned i = 1, e = Oprnds.size(); i != e; ++i) {
796 const CompositeType *TopTy = dyn_cast_or_null<CompositeType>(NextTy);
797 if (!TopTy)
798 error("Invalid getelementptr instruction!");
799
800 unsigned ValIdx = Oprnds[i];
801 unsigned IdxTy = 0;
Reid Spencerd798a512006-11-14 04:47:22 +0000802 // Struct indices are always uints, sequential type indices can be
803 // any of the 32 or 64-bit integer types. The actual choice of
Reid Spencer88cfda22006-12-31 05:44:24 +0000804 // type is encoded in the low bit of the slot number.
Reid Spencerd798a512006-11-14 04:47:22 +0000805 if (isa<StructType>(TopTy))
Reid Spencera54b7cb2007-01-12 07:05:14 +0000806 IdxTy = Int32TySlot;
Reid Spencerd798a512006-11-14 04:47:22 +0000807 else {
Reid Spencer88cfda22006-12-31 05:44:24 +0000808 switch (ValIdx & 1) {
Reid Spencerd798a512006-11-14 04:47:22 +0000809 default:
Reid Spencera54b7cb2007-01-12 07:05:14 +0000810 case 0: IdxTy = Int32TySlot; break;
811 case 1: IdxTy = Int64TySlot; break;
Reid Spencer060d25d2004-06-29 23:29:38 +0000812 }
Reid Spencer88cfda22006-12-31 05:44:24 +0000813 ValIdx >>= 1;
Reid Spencer060d25d2004-06-29 23:29:38 +0000814 }
Reid Spencer1628cec2006-10-26 06:15:43 +0000815 Idx.push_back(getValue(IdxTy, ValIdx));
Chris Lattner4c3d3a92007-01-31 19:56:15 +0000816 NextTy = GetElementPtrInst::getIndexedType(InstTy, &Idx[0], Idx.size(),
817 true);
Reid Spencer060d25d2004-06-29 23:29:38 +0000818 }
819
Chris Lattner4c3d3a92007-01-31 19:56:15 +0000820 Result = new GetElementPtrInst(getValue(iType, Oprnds[0]),
821 &Idx[0], Idx.size());
Reid Spencer1628cec2006-10-26 06:15:43 +0000822 break;
Reid Spencer060d25d2004-06-29 23:29:38 +0000823 }
Reid Spencer1628cec2006-10-26 06:15:43 +0000824 case 62: // volatile load
825 case Instruction::Load:
826 if (Oprnds.size() != 1 || !isa<PointerType>(InstTy))
827 error("Invalid load instruction!");
828 Result = new LoadInst(getValue(iType, Oprnds[0]), "", Opcode == 62);
829 break;
830 case 63: // volatile store
831 case Instruction::Store: {
832 if (!isa<PointerType>(InstTy) || Oprnds.size() != 2)
833 error("Invalid store instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000834
Reid Spencer1628cec2006-10-26 06:15:43 +0000835 Value *Ptr = getValue(iType, Oprnds[1]);
836 const Type *ValTy = cast<PointerType>(Ptr->getType())->getElementType();
837 Result = new StoreInst(getValue(getTypeSlot(ValTy), Oprnds[0]), Ptr,
838 Opcode == 63);
839 break;
840 }
841 case Instruction::Unwind:
842 if (Oprnds.size() != 0) error("Invalid unwind instruction!");
843 Result = new UnwindInst();
844 break;
845 case Instruction::Unreachable:
846 if (Oprnds.size() != 0) error("Invalid unreachable instruction!");
847 Result = new UnreachableInst();
848 break;
849 } // end switch(Opcode)
Reid Spencer3795ad12006-12-03 05:47:10 +0000850 } // end if !Result
Reid Spencer060d25d2004-06-29 23:29:38 +0000851
Reid Spencere1e96c02006-01-19 07:02:16 +0000852 BB->getInstList().push_back(Result);
853
Reid Spencer060d25d2004-06-29 23:29:38 +0000854 unsigned TypeSlot;
855 if (Result->getType() == InstTy)
856 TypeSlot = iType;
857 else
858 TypeSlot = getTypeSlot(Result->getType());
859
Reid Spenceref9b9a72007-02-05 20:47:22 +0000860 // We have enough info to inform the handler now.
861 if (Handler)
Chris Lattner63cf59e2007-02-07 05:08:39 +0000862 Handler->handleInstruction(Opcode, InstTy, &Oprnds[0], Oprnds.size(),
863 Result, At-SaveAt);
Reid Spenceref9b9a72007-02-05 20:47:22 +0000864
Reid Spencer060d25d2004-06-29 23:29:38 +0000865 insertValue(Result, TypeSlot, FunctionValues);
Reid Spencer060d25d2004-06-29 23:29:38 +0000866}
867
Reid Spencer04cde2c2004-07-04 11:33:49 +0000868/// Get a particular numbered basic block, which might be a forward reference.
Reid Spencerd798a512006-11-14 04:47:22 +0000869/// This works together with ParseInstructionList to handle these forward
870/// references in a clean manner. This function is used when constructing
871/// phi, br, switch, and other instructions that reference basic blocks.
872/// Blocks are numbered sequentially as they appear in the function.
Reid Spencer060d25d2004-06-29 23:29:38 +0000873BasicBlock *BytecodeReader::getBasicBlock(unsigned ID) {
Chris Lattner4ee8ef22003-10-08 22:52:54 +0000874 // Make sure there is room in the table...
875 if (ParsedBasicBlocks.size() <= ID) ParsedBasicBlocks.resize(ID+1);
876
Reid Spencerd798a512006-11-14 04:47:22 +0000877 // First check to see if this is a backwards reference, i.e. this block
878 // has already been created, or if the forward reference has already
Chris Lattner4ee8ef22003-10-08 22:52:54 +0000879 // been created.
880 if (ParsedBasicBlocks[ID])
881 return ParsedBasicBlocks[ID];
882
883 // Otherwise, the basic block has not yet been created. Do so and add it to
884 // the ParsedBasicBlocks list.
885 return ParsedBasicBlocks[ID] = new BasicBlock();
886}
887
Reid Spencer04cde2c2004-07-04 11:33:49 +0000888/// Parse all of the BasicBlock's & Instruction's in the body of a function.
Misha Brukman8a96c532005-04-21 21:44:41 +0000889/// In post 1.0 bytecode files, we no longer emit basic block individually,
Reid Spencer04cde2c2004-07-04 11:33:49 +0000890/// in order to avoid per-basic-block overhead.
Reid Spencerd798a512006-11-14 04:47:22 +0000891/// @returns the number of basic blocks encountered.
Reid Spencer060d25d2004-06-29 23:29:38 +0000892unsigned BytecodeReader::ParseInstructionList(Function* F) {
Chris Lattner8d1dbd22003-12-01 07:05:31 +0000893 unsigned BlockNo = 0;
Chris Lattner63cf59e2007-02-07 05:08:39 +0000894 SmallVector<unsigned, 8> Args;
Chris Lattner8d1dbd22003-12-01 07:05:31 +0000895
Reid Spencer46b002c2004-07-11 17:28:43 +0000896 while (moreInBlock()) {
897 if (Handler) Handler->handleBasicBlockBegin(BlockNo);
Chris Lattner8d1dbd22003-12-01 07:05:31 +0000898 BasicBlock *BB;
899 if (ParsedBasicBlocks.size() == BlockNo)
900 ParsedBasicBlocks.push_back(BB = new BasicBlock());
901 else if (ParsedBasicBlocks[BlockNo] == 0)
902 BB = ParsedBasicBlocks[BlockNo] = new BasicBlock();
903 else
904 BB = ParsedBasicBlocks[BlockNo];
905 ++BlockNo;
906 F->getBasicBlockList().push_back(BB);
907
908 // Read instructions into this basic block until we get to a terminator
Reid Spencer46b002c2004-07-11 17:28:43 +0000909 while (moreInBlock() && !BB->getTerminator())
Reid Spencer060d25d2004-06-29 23:29:38 +0000910 ParseInstruction(Args, BB);
Chris Lattner8d1dbd22003-12-01 07:05:31 +0000911
912 if (!BB->getTerminator())
Reid Spencer24399722004-07-09 22:21:33 +0000913 error("Non-terminated basic block found!");
Reid Spencer5c15fe52004-07-05 00:57:50 +0000914
Reid Spencer46b002c2004-07-11 17:28:43 +0000915 if (Handler) Handler->handleBasicBlockEnd(BlockNo-1);
Chris Lattner8d1dbd22003-12-01 07:05:31 +0000916 }
917
918 return BlockNo;
919}
920
Reid Spencer78d033e2007-01-06 07:24:44 +0000921/// Parse a type symbol table.
922void BytecodeReader::ParseTypeSymbolTable(TypeSymbolTable *TST) {
923 // Type Symtab block header: [num entries]
924 unsigned NumEntries = read_vbr_uint();
925 for (unsigned i = 0; i < NumEntries; ++i) {
926 // Symtab entry: [type slot #][name]
927 unsigned slot = read_vbr_uint();
928 std::string Name = read_str();
929 const Type* T = getType(slot);
930 TST->insert(Name, T);
931 }
932}
933
934/// Parse a value symbol table. This works for both module level and function
Reid Spencer04cde2c2004-07-04 11:33:49 +0000935/// level symbol tables. For function level symbol tables, the CurrentFunction
936/// parameter must be non-zero and the ST parameter must correspond to
937/// CurrentFunction's symbol table. For Module level symbol tables, the
938/// CurrentFunction argument must be zero.
Reid Spencer78d033e2007-01-06 07:24:44 +0000939void BytecodeReader::ParseValueSymbolTable(Function *CurrentFunction,
Reid Spenceref9b9a72007-02-05 20:47:22 +0000940 ValueSymbolTable *VST) {
Reid Spencer78d033e2007-01-06 07:24:44 +0000941
Reid Spenceref9b9a72007-02-05 20:47:22 +0000942 if (Handler) Handler->handleValueSymbolTableBegin(CurrentFunction,VST);
Reid Spencer060d25d2004-06-29 23:29:38 +0000943
Chris Lattner39cacce2003-10-10 05:43:47 +0000944 // Allow efficient basic block lookup by number.
Chris Lattner63cf59e2007-02-07 05:08:39 +0000945 SmallVector<BasicBlock*, 32> BBMap;
Chris Lattner39cacce2003-10-10 05:43:47 +0000946 if (CurrentFunction)
947 for (Function::iterator I = CurrentFunction->begin(),
948 E = CurrentFunction->end(); I != E; ++I)
949 BBMap.push_back(I);
950
Reid Spencer46b002c2004-07-11 17:28:43 +0000951 while (moreInBlock()) {
Chris Lattner00950542001-06-06 20:29:01 +0000952 // Symtab block header: [num entries][type id number]
Reid Spencer060d25d2004-06-29 23:29:38 +0000953 unsigned NumEntries = read_vbr_uint();
Reid Spencerd798a512006-11-14 04:47:22 +0000954 unsigned Typ = read_vbr_uint();
Chris Lattner1d670cc2001-09-07 16:37:43 +0000955
Chris Lattner7dc3a2e2003-10-13 14:57:53 +0000956 for (unsigned i = 0; i != NumEntries; ++i) {
Chris Lattner00950542001-06-06 20:29:01 +0000957 // Symtab entry: [def slot #][name]
Reid Spencer060d25d2004-06-29 23:29:38 +0000958 unsigned slot = read_vbr_uint();
959 std::string Name = read_str();
Reid Spencerd798a512006-11-14 04:47:22 +0000960 Value *V = 0;
Reid Spencera54b7cb2007-01-12 07:05:14 +0000961 if (Typ == LabelTySlot) {
Reid Spencerd798a512006-11-14 04:47:22 +0000962 if (slot < BBMap.size())
963 V = BBMap[slot];
Chris Lattner39cacce2003-10-10 05:43:47 +0000964 } else {
Reid Spencerd798a512006-11-14 04:47:22 +0000965 V = getValue(Typ, slot, false); // Find mapping...
Chris Lattner39cacce2003-10-10 05:43:47 +0000966 }
Reid Spenceref9b9a72007-02-05 20:47:22 +0000967 if (Handler) Handler->handleSymbolTableValue(Typ, slot, Name);
Reid Spencerd798a512006-11-14 04:47:22 +0000968 if (V == 0)
Reid Spenceref9b9a72007-02-05 20:47:22 +0000969 error("Failed value look-up for name '" + Name + "', type #" +
970 utostr(Typ) + " slot #" + utostr(slot));
Reid Spencerd798a512006-11-14 04:47:22 +0000971 V->setName(Name);
Chris Lattner00950542001-06-06 20:29:01 +0000972 }
973 }
Reid Spencer060d25d2004-06-29 23:29:38 +0000974 checkPastBlockEnd("Symbol Table");
Reid Spenceref9b9a72007-02-05 20:47:22 +0000975 if (Handler) Handler->handleValueSymbolTableEnd();
Chris Lattner00950542001-06-06 20:29:01 +0000976}
977
Reid Spencer46b002c2004-07-11 17:28:43 +0000978// Parse a single type. The typeid is read in first. If its a primitive type
979// then nothing else needs to be read, we know how to instantiate it. If its
Misha Brukman8a96c532005-04-21 21:44:41 +0000980// a derived type, then additional data is read to fill out the type
Reid Spencer46b002c2004-07-11 17:28:43 +0000981// definition.
982const Type *BytecodeReader::ParseType() {
Reid Spencerd798a512006-11-14 04:47:22 +0000983 unsigned PrimType = read_vbr_uint();
Reid Spencer060d25d2004-06-29 23:29:38 +0000984 const Type *Result = 0;
985 if ((Result = Type::getPrimitiveType((Type::TypeID)PrimType)))
986 return Result;
Misha Brukman8a96c532005-04-21 21:44:41 +0000987
Reid Spencer060d25d2004-06-29 23:29:38 +0000988 switch (PrimType) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000989 case Type::IntegerTyID: {
990 unsigned NumBits = read_vbr_uint();
991 Result = IntegerType::get(NumBits);
992 break;
993 }
Reid Spencer060d25d2004-06-29 23:29:38 +0000994 case Type::FunctionTyID: {
Reid Spencerd798a512006-11-14 04:47:22 +0000995 const Type *RetType = readType();
Reid Spencer88cfda22006-12-31 05:44:24 +0000996 unsigned RetAttr = read_vbr_uint();
Reid Spencer060d25d2004-06-29 23:29:38 +0000997
998 unsigned NumParams = read_vbr_uint();
999
1000 std::vector<const Type*> Params;
Reid Spencer88cfda22006-12-31 05:44:24 +00001001 std::vector<FunctionType::ParameterAttributes> Attrs;
1002 Attrs.push_back(FunctionType::ParameterAttributes(RetAttr));
1003 while (NumParams--) {
Reid Spencerd798a512006-11-14 04:47:22 +00001004 Params.push_back(readType());
Reid Spencer88cfda22006-12-31 05:44:24 +00001005 if (Params.back() != Type::VoidTy)
1006 Attrs.push_back(FunctionType::ParameterAttributes(read_vbr_uint()));
1007 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001008
1009 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1010 if (isVarArg) Params.pop_back();
1011
Reid Spencer88cfda22006-12-31 05:44:24 +00001012 Result = FunctionType::get(RetType, Params, isVarArg, Attrs);
Reid Spencer060d25d2004-06-29 23:29:38 +00001013 break;
1014 }
1015 case Type::ArrayTyID: {
Reid Spencerd798a512006-11-14 04:47:22 +00001016 const Type *ElementType = readType();
Reid Spencer060d25d2004-06-29 23:29:38 +00001017 unsigned NumElements = read_vbr_uint();
Reid Spencer060d25d2004-06-29 23:29:38 +00001018 Result = ArrayType::get(ElementType, NumElements);
1019 break;
1020 }
Brian Gaeke715c90b2004-08-20 06:00:58 +00001021 case Type::PackedTyID: {
Reid Spencerd798a512006-11-14 04:47:22 +00001022 const Type *ElementType = readType();
Brian Gaeke715c90b2004-08-20 06:00:58 +00001023 unsigned NumElements = read_vbr_uint();
1024 Result = PackedType::get(ElementType, NumElements);
1025 break;
1026 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001027 case Type::StructTyID: {
1028 std::vector<const Type*> Elements;
Reid Spencerd798a512006-11-14 04:47:22 +00001029 unsigned Typ = read_vbr_uint();
Reid Spencer060d25d2004-06-29 23:29:38 +00001030 while (Typ) { // List is terminated by void/0 typeid
1031 Elements.push_back(getType(Typ));
Reid Spencerd798a512006-11-14 04:47:22 +00001032 Typ = read_vbr_uint();
Reid Spencer060d25d2004-06-29 23:29:38 +00001033 }
1034
Andrew Lenharth38ecbf12006-12-08 18:06:16 +00001035 Result = StructType::get(Elements, false);
1036 break;
1037 }
Reid Spencera54b7cb2007-01-12 07:05:14 +00001038 case Type::PackedStructTyID: {
Andrew Lenharth38ecbf12006-12-08 18:06:16 +00001039 std::vector<const Type*> Elements;
1040 unsigned Typ = read_vbr_uint();
1041 while (Typ) { // List is terminated by void/0 typeid
1042 Elements.push_back(getType(Typ));
1043 Typ = read_vbr_uint();
1044 }
1045
1046 Result = StructType::get(Elements, true);
Reid Spencer060d25d2004-06-29 23:29:38 +00001047 break;
1048 }
1049 case Type::PointerTyID: {
Reid Spencerd798a512006-11-14 04:47:22 +00001050 Result = PointerType::get(readType());
Reid Spencer060d25d2004-06-29 23:29:38 +00001051 break;
1052 }
1053
1054 case Type::OpaqueTyID: {
1055 Result = OpaqueType::get();
1056 break;
1057 }
1058
1059 default:
Reid Spencer24399722004-07-09 22:21:33 +00001060 error("Don't know how to deserialize primitive type " + utostr(PrimType));
Reid Spencer060d25d2004-06-29 23:29:38 +00001061 break;
1062 }
Reid Spencer46b002c2004-07-11 17:28:43 +00001063 if (Handler) Handler->handleType(Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001064 return Result;
1065}
1066
Reid Spencer5b472d92004-08-21 20:49:23 +00001067// ParseTypes - We have to use this weird code to handle recursive
Reid Spencer060d25d2004-06-29 23:29:38 +00001068// types. We know that recursive types will only reference the current slab of
1069// values in the type plane, but they can forward reference types before they
1070// have been read. For example, Type #0 might be '{ Ty#1 }' and Type #1 might
1071// be 'Ty#0*'. When reading Type #0, type number one doesn't exist. To fix
1072// this ugly problem, we pessimistically insert an opaque type for each type we
1073// are about to read. This means that forward references will resolve to
1074// something and when we reread the type later, we can replace the opaque type
1075// with a new resolved concrete type.
1076//
Reid Spencer46b002c2004-07-11 17:28:43 +00001077void BytecodeReader::ParseTypes(TypeListTy &Tab, unsigned NumEntries){
Reid Spencer060d25d2004-06-29 23:29:38 +00001078 assert(Tab.size() == 0 && "should not have read type constants in before!");
1079
1080 // Insert a bunch of opaque types to be resolved later...
1081 Tab.reserve(NumEntries);
1082 for (unsigned i = 0; i != NumEntries; ++i)
1083 Tab.push_back(OpaqueType::get());
1084
Misha Brukman8a96c532005-04-21 21:44:41 +00001085 if (Handler)
Reid Spencer5b472d92004-08-21 20:49:23 +00001086 Handler->handleTypeList(NumEntries);
1087
Chris Lattnereebac5f2005-10-03 21:26:53 +00001088 // If we are about to resolve types, make sure the type cache is clear.
1089 if (NumEntries)
1090 ModuleTypeIDCache.clear();
1091
Reid Spencer060d25d2004-06-29 23:29:38 +00001092 // Loop through reading all of the types. Forward types will make use of the
1093 // opaque types just inserted.
1094 //
1095 for (unsigned i = 0; i != NumEntries; ++i) {
Reid Spencer46b002c2004-07-11 17:28:43 +00001096 const Type* NewTy = ParseType();
Reid Spencer04cde2c2004-07-04 11:33:49 +00001097 const Type* OldTy = Tab[i].get();
Misha Brukman8a96c532005-04-21 21:44:41 +00001098 if (NewTy == 0)
Reid Spencer24399722004-07-09 22:21:33 +00001099 error("Couldn't parse type!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001100
Misha Brukman8a96c532005-04-21 21:44:41 +00001101 // Don't directly push the new type on the Tab. Instead we want to replace
Reid Spencer060d25d2004-06-29 23:29:38 +00001102 // the opaque type we previously inserted with the new concrete value. This
1103 // approach helps with forward references to types. The refinement from the
1104 // abstract (opaque) type to the new type causes all uses of the abstract
1105 // type to use the concrete type (NewTy). This will also cause the opaque
1106 // type to be deleted.
1107 cast<DerivedType>(const_cast<Type*>(OldTy))->refineAbstractTypeTo(NewTy);
1108
1109 // This should have replaced the old opaque type with the new type in the
1110 // value table... or with a preexisting type that was already in the system.
1111 // Let's just make sure it did.
1112 assert(Tab[i] != OldTy && "refineAbstractType didn't work!");
1113 }
1114}
1115
Reid Spencer04cde2c2004-07-04 11:33:49 +00001116/// Parse a single constant value
Chris Lattner3bc5a602006-01-25 23:08:15 +00001117Value *BytecodeReader::ParseConstantPoolValue(unsigned TypeID) {
Reid Spencer060d25d2004-06-29 23:29:38 +00001118 // We must check for a ConstantExpr before switching by type because
1119 // a ConstantExpr can be of any type, and has no explicit value.
Misha Brukman8a96c532005-04-21 21:44:41 +00001120 //
Reid Spencer060d25d2004-06-29 23:29:38 +00001121 // 0 if not expr; numArgs if is expr
1122 unsigned isExprNumArgs = read_vbr_uint();
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001123
Reid Spencer060d25d2004-06-29 23:29:38 +00001124 if (isExprNumArgs) {
Reid Spencerd798a512006-11-14 04:47:22 +00001125 // 'undef' is encoded with 'exprnumargs' == 1.
1126 if (isExprNumArgs == 1)
1127 return UndefValue::get(getType(TypeID));
Misha Brukman8a96c532005-04-21 21:44:41 +00001128
Reid Spencerd798a512006-11-14 04:47:22 +00001129 // Inline asm is encoded with exprnumargs == ~0U.
1130 if (isExprNumArgs == ~0U) {
1131 std::string AsmStr = read_str();
1132 std::string ConstraintStr = read_str();
1133 unsigned Flags = read_vbr_uint();
Chris Lattner3bc5a602006-01-25 23:08:15 +00001134
Reid Spencerd798a512006-11-14 04:47:22 +00001135 const PointerType *PTy = dyn_cast<PointerType>(getType(TypeID));
1136 const FunctionType *FTy =
1137 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
1138
1139 if (!FTy || !InlineAsm::Verify(FTy, ConstraintStr))
1140 error("Invalid constraints for inline asm");
1141 if (Flags & ~1U)
1142 error("Invalid flags for inline asm");
1143 bool HasSideEffects = Flags & 1;
1144 return InlineAsm::get(FTy, AsmStr, ConstraintStr, HasSideEffects);
Chris Lattner3bc5a602006-01-25 23:08:15 +00001145 }
Reid Spencerd798a512006-11-14 04:47:22 +00001146
1147 --isExprNumArgs;
Chris Lattner3bc5a602006-01-25 23:08:15 +00001148
Reid Spencer060d25d2004-06-29 23:29:38 +00001149 // FIXME: Encoding of constant exprs could be much more compact!
1150 std::vector<Constant*> ArgVec;
1151 ArgVec.reserve(isExprNumArgs);
1152 unsigned Opcode = read_vbr_uint();
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001153
Reid Spencer060d25d2004-06-29 23:29:38 +00001154 // Read the slot number and types of each of the arguments
1155 for (unsigned i = 0; i != isExprNumArgs; ++i) {
1156 unsigned ArgValSlot = read_vbr_uint();
Reid Spencerd798a512006-11-14 04:47:22 +00001157 unsigned ArgTypeSlot = read_vbr_uint();
Misha Brukman8a96c532005-04-21 21:44:41 +00001158
Reid Spencer060d25d2004-06-29 23:29:38 +00001159 // Get the arg value from its slot if it exists, otherwise a placeholder
1160 ArgVec.push_back(getConstantValue(ArgTypeSlot, ArgValSlot));
1161 }
Misha Brukman8a96c532005-04-21 21:44:41 +00001162
Reid Spencer060d25d2004-06-29 23:29:38 +00001163 // Construct a ConstantExpr of the appropriate kind
1164 if (isExprNumArgs == 1) { // All one-operand expressions
Reid Spencer3da59db2006-11-27 01:05:10 +00001165 if (!Instruction::isCast(Opcode))
Chris Lattner02dce162004-12-04 05:28:27 +00001166 error("Only cast instruction has one argument for ConstantExpr");
Reid Spencer46b002c2004-07-11 17:28:43 +00001167
Reid Spencera77fa7e2006-12-11 23:20:20 +00001168 Constant *Result = ConstantExpr::getCast(Opcode, ArgVec[0],
1169 getType(TypeID));
Chris Lattner63cf59e2007-02-07 05:08:39 +00001170 if (Handler) Handler->handleConstantExpression(Opcode, &ArgVec[0],
1171 ArgVec.size(), Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001172 return Result;
1173 } else if (Opcode == Instruction::GetElementPtr) { // GetElementPtr
Chris Lattnere0135402007-01-31 04:43:46 +00001174 Constant *Result = ConstantExpr::getGetElementPtr(ArgVec[0], &ArgVec[1],
1175 ArgVec.size()-1);
Chris Lattner63cf59e2007-02-07 05:08:39 +00001176 if (Handler) Handler->handleConstantExpression(Opcode, &ArgVec[0],
1177 ArgVec.size(), Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001178 return Result;
1179 } else if (Opcode == Instruction::Select) {
Reid Spencer46b002c2004-07-11 17:28:43 +00001180 if (ArgVec.size() != 3)
1181 error("Select instruction must have three arguments.");
Misha Brukman8a96c532005-04-21 21:44:41 +00001182 Constant* Result = ConstantExpr::getSelect(ArgVec[0], ArgVec[1],
Reid Spencer04cde2c2004-07-04 11:33:49 +00001183 ArgVec[2]);
Chris Lattner63cf59e2007-02-07 05:08:39 +00001184 if (Handler) Handler->handleConstantExpression(Opcode, &ArgVec[0],
1185 ArgVec.size(), Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001186 return Result;
Robert Bocchinofee31b32006-01-10 19:04:39 +00001187 } else if (Opcode == Instruction::ExtractElement) {
Chris Lattner59fecec2006-04-08 04:09:19 +00001188 if (ArgVec.size() != 2 ||
1189 !ExtractElementInst::isValidOperands(ArgVec[0], ArgVec[1]))
1190 error("Invalid extractelement constand expr arguments");
Robert Bocchinofee31b32006-01-10 19:04:39 +00001191 Constant* Result = ConstantExpr::getExtractElement(ArgVec[0], ArgVec[1]);
Chris Lattner63cf59e2007-02-07 05:08:39 +00001192 if (Handler) Handler->handleConstantExpression(Opcode, &ArgVec[0],
1193 ArgVec.size(), Result);
Robert Bocchinofee31b32006-01-10 19:04:39 +00001194 return Result;
Robert Bocchinob1f240b2006-01-17 20:06:35 +00001195 } else if (Opcode == Instruction::InsertElement) {
Chris Lattner59fecec2006-04-08 04:09:19 +00001196 if (ArgVec.size() != 3 ||
1197 !InsertElementInst::isValidOperands(ArgVec[0], ArgVec[1], ArgVec[2]))
1198 error("Invalid insertelement constand expr arguments");
1199
1200 Constant *Result =
Robert Bocchinob1f240b2006-01-17 20:06:35 +00001201 ConstantExpr::getInsertElement(ArgVec[0], ArgVec[1], ArgVec[2]);
Chris Lattner63cf59e2007-02-07 05:08:39 +00001202 if (Handler) Handler->handleConstantExpression(Opcode, &ArgVec[0],
1203 ArgVec.size(), Result);
Robert Bocchinob1f240b2006-01-17 20:06:35 +00001204 return Result;
Chris Lattner30b44b62006-04-08 01:17:59 +00001205 } else if (Opcode == Instruction::ShuffleVector) {
1206 if (ArgVec.size() != 3 ||
1207 !ShuffleVectorInst::isValidOperands(ArgVec[0], ArgVec[1], ArgVec[2]))
Chris Lattner59fecec2006-04-08 04:09:19 +00001208 error("Invalid shufflevector constant expr arguments.");
Chris Lattner30b44b62006-04-08 01:17:59 +00001209 Constant *Result =
1210 ConstantExpr::getShuffleVector(ArgVec[0], ArgVec[1], ArgVec[2]);
Chris Lattner63cf59e2007-02-07 05:08:39 +00001211 if (Handler) Handler->handleConstantExpression(Opcode, &ArgVec[0],
1212 ArgVec.size(), Result);
Chris Lattner30b44b62006-04-08 01:17:59 +00001213 return Result;
Reid Spencer9f132762006-12-03 17:17:02 +00001214 } else if (Opcode == Instruction::ICmp) {
1215 if (ArgVec.size() != 2)
Reid Spencer595b4772006-12-04 05:23:49 +00001216 error("Invalid ICmp constant expr arguments.");
1217 unsigned predicate = read_vbr_uint();
1218 Constant *Result = ConstantExpr::getICmp(predicate, ArgVec[0], ArgVec[1]);
Chris Lattner63cf59e2007-02-07 05:08:39 +00001219 if (Handler) Handler->handleConstantExpression(Opcode, &ArgVec[0],
1220 ArgVec.size(), Result);
Reid Spencer595b4772006-12-04 05:23:49 +00001221 return Result;
Reid Spencer9f132762006-12-03 17:17:02 +00001222 } else if (Opcode == Instruction::FCmp) {
1223 if (ArgVec.size() != 2)
Reid Spencer595b4772006-12-04 05:23:49 +00001224 error("Invalid FCmp constant expr arguments.");
1225 unsigned predicate = read_vbr_uint();
1226 Constant *Result = ConstantExpr::getFCmp(predicate, ArgVec[0], ArgVec[1]);
Chris Lattner63cf59e2007-02-07 05:08:39 +00001227 if (Handler) Handler->handleConstantExpression(Opcode, &ArgVec[0],
1228 ArgVec.size(), Result);
Reid Spencer595b4772006-12-04 05:23:49 +00001229 return Result;
Reid Spencer060d25d2004-06-29 23:29:38 +00001230 } else { // All other 2-operand expressions
1231 Constant* Result = ConstantExpr::get(Opcode, ArgVec[0], ArgVec[1]);
Chris Lattner63cf59e2007-02-07 05:08:39 +00001232 if (Handler) Handler->handleConstantExpression(Opcode, &ArgVec[0],
1233 ArgVec.size(), Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001234 return Result;
1235 }
1236 }
Misha Brukman8a96c532005-04-21 21:44:41 +00001237
Reid Spencer060d25d2004-06-29 23:29:38 +00001238 // Ok, not an ConstantExpr. We now know how to read the given type...
1239 const Type *Ty = getType(TypeID);
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001240 Constant *Result = 0;
Reid Spencer060d25d2004-06-29 23:29:38 +00001241 switch (Ty->getTypeID()) {
Reid Spencera54b7cb2007-01-12 07:05:14 +00001242 case Type::IntegerTyID: {
1243 const IntegerType *IT = cast<IntegerType>(Ty);
1244 if (IT->getBitWidth() <= 32) {
1245 uint32_t Val = read_vbr_uint();
Reid Spencerb61c1ce2007-01-13 00:09:12 +00001246 if (!ConstantInt::isValueValidForType(Ty, uint64_t(Val)))
1247 error("Integer value read is invalid for type.");
1248 Result = ConstantInt::get(IT, Val);
1249 if (Handler) Handler->handleConstantValue(Result);
Reid Spencera54b7cb2007-01-12 07:05:14 +00001250 } else if (IT->getBitWidth() <= 64) {
1251 uint64_t Val = read_vbr_uint64();
1252 if (!ConstantInt::isValueValidForType(Ty, Val))
1253 error("Invalid constant integer read.");
1254 Result = ConstantInt::get(IT, Val);
1255 if (Handler) Handler->handleConstantValue(Result);
1256 } else
1257 assert("Integer types > 64 bits not supported");
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001258 break;
Reid Spencer060d25d2004-06-29 23:29:38 +00001259 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001260 case Type::FloatTyID: {
Reid Spencer46b002c2004-07-11 17:28:43 +00001261 float Val;
1262 read_float(Val);
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001263 Result = ConstantFP::get(Ty, Val);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001264 if (Handler) Handler->handleConstantValue(Result);
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001265 break;
Reid Spencer060d25d2004-06-29 23:29:38 +00001266 }
1267
1268 case Type::DoubleTyID: {
1269 double Val;
Reid Spencer46b002c2004-07-11 17:28:43 +00001270 read_double(Val);
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001271 Result = ConstantFP::get(Ty, Val);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001272 if (Handler) Handler->handleConstantValue(Result);
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001273 break;
Reid Spencer060d25d2004-06-29 23:29:38 +00001274 }
1275
Reid Spencer060d25d2004-06-29 23:29:38 +00001276 case Type::ArrayTyID: {
1277 const ArrayType *AT = cast<ArrayType>(Ty);
1278 unsigned NumElements = AT->getNumElements();
1279 unsigned TypeSlot = getTypeSlot(AT->getElementType());
1280 std::vector<Constant*> Elements;
1281 Elements.reserve(NumElements);
1282 while (NumElements--) // Read all of the elements of the constant.
1283 Elements.push_back(getConstantValue(TypeSlot,
1284 read_vbr_uint()));
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001285 Result = ConstantArray::get(AT, Elements);
Chris Lattner63cf59e2007-02-07 05:08:39 +00001286 if (Handler) Handler->handleConstantArray(AT, &Elements[0], Elements.size(),
1287 TypeSlot, Result);
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001288 break;
Reid Spencer060d25d2004-06-29 23:29:38 +00001289 }
1290
1291 case Type::StructTyID: {
1292 const StructType *ST = cast<StructType>(Ty);
1293
1294 std::vector<Constant *> Elements;
1295 Elements.reserve(ST->getNumElements());
1296 for (unsigned i = 0; i != ST->getNumElements(); ++i)
1297 Elements.push_back(getConstantValue(ST->getElementType(i),
1298 read_vbr_uint()));
1299
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001300 Result = ConstantStruct::get(ST, Elements);
Chris Lattner63cf59e2007-02-07 05:08:39 +00001301 if (Handler) Handler->handleConstantStruct(ST, &Elements[0],Elements.size(),
1302 Result);
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001303 break;
Misha Brukman8a96c532005-04-21 21:44:41 +00001304 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001305
Brian Gaeke715c90b2004-08-20 06:00:58 +00001306 case Type::PackedTyID: {
1307 const PackedType *PT = cast<PackedType>(Ty);
1308 unsigned NumElements = PT->getNumElements();
1309 unsigned TypeSlot = getTypeSlot(PT->getElementType());
1310 std::vector<Constant*> Elements;
1311 Elements.reserve(NumElements);
1312 while (NumElements--) // Read all of the elements of the constant.
1313 Elements.push_back(getConstantValue(TypeSlot,
1314 read_vbr_uint()));
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001315 Result = ConstantPacked::get(PT, Elements);
Chris Lattner63cf59e2007-02-07 05:08:39 +00001316 if (Handler) Handler->handleConstantPacked(PT, &Elements[0],Elements.size(),
1317 TypeSlot, Result);
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001318 break;
Brian Gaeke715c90b2004-08-20 06:00:58 +00001319 }
1320
Chris Lattner638c3812004-11-19 16:24:05 +00001321 case Type::PointerTyID: { // ConstantPointerRef value (backwards compat).
Reid Spencer060d25d2004-06-29 23:29:38 +00001322 const PointerType *PT = cast<PointerType>(Ty);
1323 unsigned Slot = read_vbr_uint();
Misha Brukman8a96c532005-04-21 21:44:41 +00001324
Reid Spencer060d25d2004-06-29 23:29:38 +00001325 // Check to see if we have already read this global variable...
1326 Value *Val = getValue(TypeID, Slot, false);
Reid Spencer060d25d2004-06-29 23:29:38 +00001327 if (Val) {
Chris Lattnerbcb11cf2004-07-27 02:34:49 +00001328 GlobalValue *GV = dyn_cast<GlobalValue>(Val);
1329 if (!GV) error("GlobalValue not in ValueTable!");
1330 if (Handler) Handler->handleConstantPointer(PT, Slot, GV);
1331 return GV;
Reid Spencer060d25d2004-06-29 23:29:38 +00001332 } else {
Reid Spencer24399722004-07-09 22:21:33 +00001333 error("Forward references are not allowed here.");
Reid Spencer060d25d2004-06-29 23:29:38 +00001334 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001335 }
1336
1337 default:
Reid Spencer24399722004-07-09 22:21:33 +00001338 error("Don't know how to deserialize constant value of type '" +
Reid Spencer060d25d2004-06-29 23:29:38 +00001339 Ty->getDescription());
1340 break;
1341 }
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001342
1343 // Check that we didn't read a null constant if they are implicit for this
1344 // type plane. Do not do this check for constantexprs, as they may be folded
1345 // to a null value in a way that isn't predicted when a .bc file is initially
1346 // produced.
1347 assert((!isa<Constant>(Result) || !cast<Constant>(Result)->isNullValue()) ||
1348 !hasImplicitNull(TypeID) &&
1349 "Cannot read null values from bytecode!");
1350 return Result;
Reid Spencer060d25d2004-06-29 23:29:38 +00001351}
1352
Misha Brukman8a96c532005-04-21 21:44:41 +00001353/// Resolve references for constants. This function resolves the forward
1354/// referenced constants in the ConstantFwdRefs map. It uses the
Reid Spencer04cde2c2004-07-04 11:33:49 +00001355/// replaceAllUsesWith method of Value class to substitute the placeholder
1356/// instance with the actual instance.
Chris Lattner389bd042004-12-09 06:19:44 +00001357void BytecodeReader::ResolveReferencesToConstant(Constant *NewV, unsigned Typ,
1358 unsigned Slot) {
Chris Lattner29b789b2003-11-19 17:27:18 +00001359 ConstantRefsType::iterator I =
Chris Lattner389bd042004-12-09 06:19:44 +00001360 ConstantFwdRefs.find(std::make_pair(Typ, Slot));
Chris Lattner29b789b2003-11-19 17:27:18 +00001361 if (I == ConstantFwdRefs.end()) return; // Never forward referenced?
Chris Lattner00950542001-06-06 20:29:01 +00001362
Chris Lattner29b789b2003-11-19 17:27:18 +00001363 Value *PH = I->second; // Get the placeholder...
1364 PH->replaceAllUsesWith(NewV);
1365 delete PH; // Delete the old placeholder
1366 ConstantFwdRefs.erase(I); // Remove the map entry for it
Vikram S. Advec1e4a812002-07-14 23:04:18 +00001367}
1368
Reid Spencer04cde2c2004-07-04 11:33:49 +00001369/// Parse the constant strings section.
Reid Spencer060d25d2004-06-29 23:29:38 +00001370void BytecodeReader::ParseStringConstants(unsigned NumEntries, ValueTable &Tab){
1371 for (; NumEntries; --NumEntries) {
Reid Spencerd798a512006-11-14 04:47:22 +00001372 unsigned Typ = read_vbr_uint();
Reid Spencer060d25d2004-06-29 23:29:38 +00001373 const Type *Ty = getType(Typ);
1374 if (!isa<ArrayType>(Ty))
Reid Spencer24399722004-07-09 22:21:33 +00001375 error("String constant data invalid!");
Misha Brukman8a96c532005-04-21 21:44:41 +00001376
Reid Spencer060d25d2004-06-29 23:29:38 +00001377 const ArrayType *ATy = cast<ArrayType>(Ty);
Reid Spencer88cfda22006-12-31 05:44:24 +00001378 if (ATy->getElementType() != Type::Int8Ty &&
1379 ATy->getElementType() != Type::Int8Ty)
Reid Spencer24399722004-07-09 22:21:33 +00001380 error("String constant data invalid!");
Misha Brukman8a96c532005-04-21 21:44:41 +00001381
Reid Spencer060d25d2004-06-29 23:29:38 +00001382 // Read character data. The type tells us how long the string is.
Misha Brukman8a96c532005-04-21 21:44:41 +00001383 char *Data = reinterpret_cast<char *>(alloca(ATy->getNumElements()));
Reid Spencer060d25d2004-06-29 23:29:38 +00001384 read_data(Data, Data+ATy->getNumElements());
Chris Lattner52e20b02003-03-19 20:54:26 +00001385
Reid Spencer060d25d2004-06-29 23:29:38 +00001386 std::vector<Constant*> Elements(ATy->getNumElements());
Reid Spencerb83eb642006-10-20 07:07:24 +00001387 const Type* ElemType = ATy->getElementType();
1388 for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
1389 Elements[i] = ConstantInt::get(ElemType, (unsigned char)Data[i]);
Misha Brukman12c29d12003-09-22 23:38:23 +00001390
Reid Spencer060d25d2004-06-29 23:29:38 +00001391 // Create the constant, inserting it as needed.
1392 Constant *C = ConstantArray::get(ATy, Elements);
1393 unsigned Slot = insertValue(C, Typ, Tab);
Chris Lattner389bd042004-12-09 06:19:44 +00001394 ResolveReferencesToConstant(C, Typ, Slot);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001395 if (Handler) Handler->handleConstantString(cast<ConstantArray>(C));
Reid Spencer060d25d2004-06-29 23:29:38 +00001396 }
Misha Brukman12c29d12003-09-22 23:38:23 +00001397}
1398
Reid Spencer04cde2c2004-07-04 11:33:49 +00001399/// Parse the constant pool.
Misha Brukman8a96c532005-04-21 21:44:41 +00001400void BytecodeReader::ParseConstantPool(ValueTable &Tab,
Reid Spencer04cde2c2004-07-04 11:33:49 +00001401 TypeListTy &TypeTab,
Reid Spencer46b002c2004-07-11 17:28:43 +00001402 bool isFunction) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001403 if (Handler) Handler->handleGlobalConstantsBegin();
1404
1405 /// In LLVM 1.3 Type does not derive from Value so the types
1406 /// do not occupy a plane. Consequently, we read the types
1407 /// first in the constant pool.
Reid Spencerd798a512006-11-14 04:47:22 +00001408 if (isFunction) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001409 unsigned NumEntries = read_vbr_uint();
Reid Spencer46b002c2004-07-11 17:28:43 +00001410 ParseTypes(TypeTab, NumEntries);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001411 }
1412
Reid Spencer46b002c2004-07-11 17:28:43 +00001413 while (moreInBlock()) {
Reid Spencer060d25d2004-06-29 23:29:38 +00001414 unsigned NumEntries = read_vbr_uint();
Reid Spencerd798a512006-11-14 04:47:22 +00001415 unsigned Typ = read_vbr_uint();
Reid Spencer04cde2c2004-07-04 11:33:49 +00001416
Reid Spencerd798a512006-11-14 04:47:22 +00001417 if (Typ == Type::VoidTyID) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001418 /// Use of Type::VoidTyID is a misnomer. It actually means
1419 /// that the following plane is constant strings
Reid Spencer060d25d2004-06-29 23:29:38 +00001420 assert(&Tab == &ModuleValues && "Cannot read strings in functions!");
1421 ParseStringConstants(NumEntries, Tab);
1422 } else {
1423 for (unsigned i = 0; i < NumEntries; ++i) {
Chris Lattner3bc5a602006-01-25 23:08:15 +00001424 Value *V = ParseConstantPoolValue(Typ);
1425 assert(V && "ParseConstantPoolValue returned NULL!");
1426 unsigned Slot = insertValue(V, Typ, Tab);
Chris Lattner29b789b2003-11-19 17:27:18 +00001427
Reid Spencer060d25d2004-06-29 23:29:38 +00001428 // If we are reading a function constant table, make sure that we adjust
1429 // the slot number to be the real global constant number.
1430 //
1431 if (&Tab != &ModuleValues && Typ < ModuleValues.size() &&
1432 ModuleValues[Typ])
1433 Slot += ModuleValues[Typ]->size();
Chris Lattner3bc5a602006-01-25 23:08:15 +00001434 if (Constant *C = dyn_cast<Constant>(V))
1435 ResolveReferencesToConstant(C, Typ, Slot);
Reid Spencer060d25d2004-06-29 23:29:38 +00001436 }
1437 }
1438 }
Chris Lattner02dce162004-12-04 05:28:27 +00001439
1440 // After we have finished parsing the constant pool, we had better not have
1441 // any dangling references left.
Reid Spencer3c391272004-12-04 22:19:53 +00001442 if (!ConstantFwdRefs.empty()) {
Reid Spencer3c391272004-12-04 22:19:53 +00001443 ConstantRefsType::const_iterator I = ConstantFwdRefs.begin();
Reid Spencer3c391272004-12-04 22:19:53 +00001444 Constant* missingConst = I->second;
Misha Brukman8a96c532005-04-21 21:44:41 +00001445 error(utostr(ConstantFwdRefs.size()) +
1446 " unresolved constant reference exist. First one is '" +
1447 missingConst->getName() + "' of type '" +
Chris Lattner389bd042004-12-09 06:19:44 +00001448 missingConst->getType()->getDescription() + "'.");
Reid Spencer3c391272004-12-04 22:19:53 +00001449 }
Chris Lattner02dce162004-12-04 05:28:27 +00001450
Reid Spencer060d25d2004-06-29 23:29:38 +00001451 checkPastBlockEnd("Constant Pool");
Reid Spencer04cde2c2004-07-04 11:33:49 +00001452 if (Handler) Handler->handleGlobalConstantsEnd();
Reid Spencer060d25d2004-06-29 23:29:38 +00001453}
Chris Lattner00950542001-06-06 20:29:01 +00001454
Reid Spencer04cde2c2004-07-04 11:33:49 +00001455/// Parse the contents of a function. Note that this function can be
1456/// called lazily by materializeFunction
1457/// @see materializeFunction
Reid Spencer46b002c2004-07-11 17:28:43 +00001458void BytecodeReader::ParseFunctionBody(Function* F) {
Reid Spencer060d25d2004-06-29 23:29:38 +00001459
1460 unsigned FuncSize = BlockEnd - At;
Chris Lattnere3869c82003-04-16 21:16:05 +00001461 GlobalValue::LinkageTypes Linkage = GlobalValue::ExternalLinkage;
Anton Korobeynikov7f705592007-01-12 19:20:47 +00001462 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
Chris Lattnere3869c82003-04-16 21:16:05 +00001463
Anton Korobeynikov7f705592007-01-12 19:20:47 +00001464 unsigned rWord = read_vbr_uint();
1465 unsigned LinkageID = rWord & 65535;
1466 unsigned VisibilityID = rWord >> 16;
1467 switch (LinkageID) {
Chris Lattnerc08912f2004-01-14 16:44:44 +00001468 case 0: Linkage = GlobalValue::ExternalLinkage; break;
1469 case 1: Linkage = GlobalValue::WeakLinkage; break;
1470 case 2: Linkage = GlobalValue::AppendingLinkage; break;
1471 case 3: Linkage = GlobalValue::InternalLinkage; break;
1472 case 4: Linkage = GlobalValue::LinkOnceLinkage; break;
Anton Korobeynikovb74ed072006-09-14 18:23:27 +00001473 case 5: Linkage = GlobalValue::DLLImportLinkage; break;
1474 case 6: Linkage = GlobalValue::DLLExportLinkage; break;
1475 case 7: Linkage = GlobalValue::ExternalWeakLinkage; break;
Reid Spencer060d25d2004-06-29 23:29:38 +00001476 default:
Reid Spencer24399722004-07-09 22:21:33 +00001477 error("Invalid linkage type for Function.");
Reid Spencer060d25d2004-06-29 23:29:38 +00001478 Linkage = GlobalValue::InternalLinkage;
1479 break;
Chris Lattnere3869c82003-04-16 21:16:05 +00001480 }
Anton Korobeynikov7f705592007-01-12 19:20:47 +00001481 switch (VisibilityID) {
1482 case 0: Visibility = GlobalValue::DefaultVisibility; break;
1483 case 1: Visibility = GlobalValue::HiddenVisibility; break;
1484 default:
1485 error("Unknown visibility type: " + utostr(VisibilityID));
1486 Visibility = GlobalValue::DefaultVisibility;
1487 break;
1488 }
Chris Lattnerd23b1d32001-11-26 18:56:10 +00001489
Reid Spencer46b002c2004-07-11 17:28:43 +00001490 F->setLinkage(Linkage);
Anton Korobeynikov7f705592007-01-12 19:20:47 +00001491 F->setVisibility(Visibility);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001492 if (Handler) Handler->handleFunctionBegin(F,FuncSize);
Chris Lattner00950542001-06-06 20:29:01 +00001493
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001494 // Keep track of how many basic blocks we have read in...
1495 unsigned BlockNum = 0;
Chris Lattner89e02532004-01-18 21:08:15 +00001496 bool InsertedArguments = false;
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001497
Reid Spencer060d25d2004-06-29 23:29:38 +00001498 BufPtr MyEnd = BlockEnd;
Reid Spencer46b002c2004-07-11 17:28:43 +00001499 while (At < MyEnd) {
Chris Lattner00950542001-06-06 20:29:01 +00001500 unsigned Type, Size;
Reid Spencer060d25d2004-06-29 23:29:38 +00001501 BufPtr OldAt = At;
1502 read_block(Type, Size);
Chris Lattner00950542001-06-06 20:29:01 +00001503
1504 switch (Type) {
Reid Spencerad89bd62004-07-25 18:07:36 +00001505 case BytecodeFormat::ConstantPoolBlockID:
Chris Lattner89e02532004-01-18 21:08:15 +00001506 if (!InsertedArguments) {
1507 // Insert arguments into the value table before we parse the first basic
Reid Spencerd2bb8872007-01-30 19:36:46 +00001508 // block in the function
Reid Spencer04cde2c2004-07-04 11:33:49 +00001509 insertArguments(F);
Chris Lattner89e02532004-01-18 21:08:15 +00001510 InsertedArguments = true;
1511 }
1512
Reid Spencer04cde2c2004-07-04 11:33:49 +00001513 ParseConstantPool(FunctionValues, FunctionTypes, true);
Chris Lattner00950542001-06-06 20:29:01 +00001514 break;
1515
Reid Spencerad89bd62004-07-25 18:07:36 +00001516 case BytecodeFormat::InstructionListBlockID: {
Chris Lattner89e02532004-01-18 21:08:15 +00001517 // Insert arguments into the value table before we parse the instruction
Reid Spencerd2bb8872007-01-30 19:36:46 +00001518 // list for the function
Chris Lattner89e02532004-01-18 21:08:15 +00001519 if (!InsertedArguments) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001520 insertArguments(F);
Chris Lattner89e02532004-01-18 21:08:15 +00001521 InsertedArguments = true;
1522 }
1523
Misha Brukman8a96c532005-04-21 21:44:41 +00001524 if (BlockNum)
Reid Spencer24399722004-07-09 22:21:33 +00001525 error("Already parsed basic blocks!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001526 BlockNum = ParseInstructionList(F);
Chris Lattner8d1dbd22003-12-01 07:05:31 +00001527 break;
1528 }
1529
Reid Spencer78d033e2007-01-06 07:24:44 +00001530 case BytecodeFormat::ValueSymbolTableBlockID:
1531 ParseValueSymbolTable(F, &F->getValueSymbolTable());
1532 break;
1533
1534 case BytecodeFormat::TypeSymbolTableBlockID:
1535 error("Functions don't have type symbol tables");
Chris Lattner00950542001-06-06 20:29:01 +00001536 break;
1537
1538 default:
Reid Spencer060d25d2004-06-29 23:29:38 +00001539 At += Size;
Misha Brukman8a96c532005-04-21 21:44:41 +00001540 if (OldAt > At)
Reid Spencer24399722004-07-09 22:21:33 +00001541 error("Wrapped around reading bytecode.");
Chris Lattner00950542001-06-06 20:29:01 +00001542 break;
1543 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001544 BlockEnd = MyEnd;
Chris Lattner00950542001-06-06 20:29:01 +00001545 }
1546
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001547 // Make sure there were no references to non-existant basic blocks.
1548 if (BlockNum != ParsedBasicBlocks.size())
Reid Spencer24399722004-07-09 22:21:33 +00001549 error("Illegal basic block operand reference");
Reid Spencer060d25d2004-06-29 23:29:38 +00001550
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001551 ParsedBasicBlocks.clear();
1552
Chris Lattner97330cf2003-10-09 23:10:14 +00001553 // Resolve forward references. Replace any uses of a forward reference value
1554 // with the real value.
Chris Lattner8eb10ce2003-10-09 06:05:40 +00001555 while (!ForwardReferences.empty()) {
Chris Lattnerc4d69162004-12-09 04:51:50 +00001556 std::map<std::pair<unsigned,unsigned>, Value*>::iterator
1557 I = ForwardReferences.begin();
1558 Value *V = getValue(I->first.first, I->first.second, false);
Chris Lattner8eb10ce2003-10-09 06:05:40 +00001559 Value *PlaceHolder = I->second;
Chris Lattnerc4d69162004-12-09 04:51:50 +00001560 PlaceHolder->replaceAllUsesWith(V);
Chris Lattner8eb10ce2003-10-09 06:05:40 +00001561 ForwardReferences.erase(I);
Chris Lattner8eb10ce2003-10-09 06:05:40 +00001562 delete PlaceHolder;
Chris Lattner6e448022003-10-08 21:51:46 +00001563 }
Chris Lattner00950542001-06-06 20:29:01 +00001564
Misha Brukman12c29d12003-09-22 23:38:23 +00001565 // Clear out function-level types...
Reid Spencer060d25d2004-06-29 23:29:38 +00001566 FunctionTypes.clear();
Reid Spencer060d25d2004-06-29 23:29:38 +00001567 freeTable(FunctionValues);
1568
Reid Spencer04cde2c2004-07-04 11:33:49 +00001569 if (Handler) Handler->handleFunctionEnd(F);
Chris Lattner00950542001-06-06 20:29:01 +00001570}
1571
Reid Spencer04cde2c2004-07-04 11:33:49 +00001572/// This function parses LLVM functions lazily. It obtains the type of the
1573/// function and records where the body of the function is in the bytecode
Misha Brukman8a96c532005-04-21 21:44:41 +00001574/// buffer. The caller can then use the ParseNextFunction and
Reid Spencer04cde2c2004-07-04 11:33:49 +00001575/// ParseAllFunctionBodies to get handler events for the functions.
Reid Spencer060d25d2004-06-29 23:29:38 +00001576void BytecodeReader::ParseFunctionLazily() {
1577 if (FunctionSignatureList.empty())
Reid Spencer24399722004-07-09 22:21:33 +00001578 error("FunctionSignatureList empty!");
Chris Lattner89e02532004-01-18 21:08:15 +00001579
Reid Spencer060d25d2004-06-29 23:29:38 +00001580 Function *Func = FunctionSignatureList.back();
1581 FunctionSignatureList.pop_back();
Chris Lattner24102432004-01-18 22:35:34 +00001582
Reid Spencer060d25d2004-06-29 23:29:38 +00001583 // Save the information for future reading of the function
1584 LazyFunctionLoadMap[Func] = LazyFunctionInfo(BlockStart, BlockEnd);
Chris Lattner89e02532004-01-18 21:08:15 +00001585
Misha Brukmana3e6ad62004-11-14 21:02:55 +00001586 // This function has a body but it's not loaded so it appears `External'.
1587 // Mark it as a `Ghost' instead to notify the users that it has a body.
1588 Func->setLinkage(GlobalValue::GhostLinkage);
1589
Reid Spencer060d25d2004-06-29 23:29:38 +00001590 // Pretend we've `parsed' this function
1591 At = BlockEnd;
1592}
Chris Lattner89e02532004-01-18 21:08:15 +00001593
Misha Brukman8a96c532005-04-21 21:44:41 +00001594/// The ParserFunction method lazily parses one function. Use this method to
1595/// casue the parser to parse a specific function in the module. Note that
1596/// this will remove the function from what is to be included by
Reid Spencer04cde2c2004-07-04 11:33:49 +00001597/// ParseAllFunctionBodies.
1598/// @see ParseAllFunctionBodies
1599/// @see ParseBytecode
Reid Spencer99655e12006-08-25 19:54:53 +00001600bool BytecodeReader::ParseFunction(Function* Func, std::string* ErrMsg) {
1601
Reid Spencer9b84ad12006-12-15 19:49:23 +00001602 if (setjmp(context)) {
1603 // Set caller's error message, if requested
1604 if (ErrMsg)
1605 *ErrMsg = ErrorMsg;
1606 // Indicate an error occurred
Reid Spencer99655e12006-08-25 19:54:53 +00001607 return true;
Reid Spencer9b84ad12006-12-15 19:49:23 +00001608 }
Reid Spencer99655e12006-08-25 19:54:53 +00001609
Reid Spencer060d25d2004-06-29 23:29:38 +00001610 // Find {start, end} pointers and slot in the map. If not there, we're done.
1611 LazyFunctionMap::iterator Fi = LazyFunctionLoadMap.find(Func);
Chris Lattner89e02532004-01-18 21:08:15 +00001612
Reid Spencer060d25d2004-06-29 23:29:38 +00001613 // Make sure we found it
Reid Spencer46b002c2004-07-11 17:28:43 +00001614 if (Fi == LazyFunctionLoadMap.end()) {
Reid Spencer24399722004-07-09 22:21:33 +00001615 error("Unrecognized function of type " + Func->getType()->getDescription());
Reid Spencer99655e12006-08-25 19:54:53 +00001616 return true;
Chris Lattner89e02532004-01-18 21:08:15 +00001617 }
1618
Reid Spencer060d25d2004-06-29 23:29:38 +00001619 BlockStart = At = Fi->second.Buf;
1620 BlockEnd = Fi->second.EndBuf;
Reid Spencer24399722004-07-09 22:21:33 +00001621 assert(Fi->first == Func && "Found wrong function?");
Reid Spencer060d25d2004-06-29 23:29:38 +00001622
1623 LazyFunctionLoadMap.erase(Fi);
1624
Reid Spencer46b002c2004-07-11 17:28:43 +00001625 this->ParseFunctionBody(Func);
Reid Spencer99655e12006-08-25 19:54:53 +00001626 return false;
Chris Lattner89e02532004-01-18 21:08:15 +00001627}
1628
Reid Spencer04cde2c2004-07-04 11:33:49 +00001629/// The ParseAllFunctionBodies method parses through all the previously
1630/// unparsed functions in the bytecode file. If you want to completely parse
1631/// a bytecode file, this method should be called after Parsebytecode because
1632/// Parsebytecode only records the locations in the bytecode file of where
1633/// the function definitions are located. This function uses that information
1634/// to materialize the functions.
1635/// @see ParseBytecode
Reid Spencer99655e12006-08-25 19:54:53 +00001636bool BytecodeReader::ParseAllFunctionBodies(std::string* ErrMsg) {
Reid Spencer9b84ad12006-12-15 19:49:23 +00001637 if (setjmp(context)) {
1638 // Set caller's error message, if requested
1639 if (ErrMsg)
1640 *ErrMsg = ErrorMsg;
1641 // Indicate an error occurred
Reid Spencer99655e12006-08-25 19:54:53 +00001642 return true;
Reid Spencer9b84ad12006-12-15 19:49:23 +00001643 }
Reid Spencer99655e12006-08-25 19:54:53 +00001644
Reid Spencer060d25d2004-06-29 23:29:38 +00001645 LazyFunctionMap::iterator Fi = LazyFunctionLoadMap.begin();
1646 LazyFunctionMap::iterator Fe = LazyFunctionLoadMap.end();
Chris Lattner89e02532004-01-18 21:08:15 +00001647
Reid Spencer46b002c2004-07-11 17:28:43 +00001648 while (Fi != Fe) {
Reid Spencer060d25d2004-06-29 23:29:38 +00001649 Function* Func = Fi->first;
1650 BlockStart = At = Fi->second.Buf;
1651 BlockEnd = Fi->second.EndBuf;
Chris Lattnerb52f1c22005-02-13 17:48:18 +00001652 ParseFunctionBody(Func);
Reid Spencer060d25d2004-06-29 23:29:38 +00001653 ++Fi;
1654 }
Chris Lattnerb52f1c22005-02-13 17:48:18 +00001655 LazyFunctionLoadMap.clear();
Reid Spencer99655e12006-08-25 19:54:53 +00001656 return false;
Reid Spencer060d25d2004-06-29 23:29:38 +00001657}
Chris Lattner89e02532004-01-18 21:08:15 +00001658
Reid Spencer04cde2c2004-07-04 11:33:49 +00001659/// Parse the global type list
Reid Spencer060d25d2004-06-29 23:29:38 +00001660void BytecodeReader::ParseGlobalTypes() {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001661 // Read the number of types
1662 unsigned NumEntries = read_vbr_uint();
Reid Spencer46b002c2004-07-11 17:28:43 +00001663 ParseTypes(ModuleTypes, NumEntries);
Reid Spencer060d25d2004-06-29 23:29:38 +00001664}
1665
Reid Spencer04cde2c2004-07-04 11:33:49 +00001666/// Parse the Global info (types, global vars, constants)
Reid Spencer060d25d2004-06-29 23:29:38 +00001667void BytecodeReader::ParseModuleGlobalInfo() {
1668
Reid Spencer04cde2c2004-07-04 11:33:49 +00001669 if (Handler) Handler->handleModuleGlobalsBegin();
Chris Lattner00950542001-06-06 20:29:01 +00001670
Chris Lattner404cddf2005-11-12 01:33:40 +00001671 // SectionID - If a global has an explicit section specified, this map
1672 // remembers the ID until we can translate it into a string.
1673 std::map<GlobalValue*, unsigned> SectionID;
1674
Chris Lattner70cc3392001-09-10 07:58:01 +00001675 // Read global variables...
Reid Spencer060d25d2004-06-29 23:29:38 +00001676 unsigned VarType = read_vbr_uint();
Chris Lattner70cc3392001-09-10 07:58:01 +00001677 while (VarType != Type::VoidTyID) { // List is terminated by Void
Chris Lattner9dd87702004-04-03 23:43:42 +00001678 // VarType Fields: bit0 = isConstant, bit1 = hasInitializer, bit2,3,4 =
1679 // Linkage, bit4+ = slot#
1680 unsigned SlotNo = VarType >> 5;
1681 unsigned LinkageID = (VarType >> 2) & 7;
Anton Korobeynikov7f705592007-01-12 19:20:47 +00001682 unsigned VisibilityID = 0;
Reid Spencer060d25d2004-06-29 23:29:38 +00001683 bool isConstant = VarType & 1;
Chris Lattnerce5e04e2005-11-06 08:23:17 +00001684 bool hasInitializer = (VarType & 2) != 0;
Chris Lattner8eb52dd2005-11-06 07:11:04 +00001685 unsigned Alignment = 0;
Chris Lattner404cddf2005-11-12 01:33:40 +00001686 unsigned GlobalSectionID = 0;
Chris Lattner8eb52dd2005-11-06 07:11:04 +00001687
1688 // An extension word is present when linkage = 3 (internal) and hasinit = 0.
1689 if (LinkageID == 3 && !hasInitializer) {
1690 unsigned ExtWord = read_vbr_uint();
1691 // The extension word has this format: bit 0 = has initializer, bit 1-3 =
Anton Korobeynikov7f705592007-01-12 19:20:47 +00001692 // linkage, bit 4-8 = alignment (log2), bit 9 = has section,
1693 // bits 10-12 = visibility, bits 13+ = future use.
Chris Lattner8eb52dd2005-11-06 07:11:04 +00001694 hasInitializer = ExtWord & 1;
1695 LinkageID = (ExtWord >> 1) & 7;
1696 Alignment = (1 << ((ExtWord >> 4) & 31)) >> 1;
Anton Korobeynikov7f705592007-01-12 19:20:47 +00001697 VisibilityID = (ExtWord >> 10) & 7;
Chris Lattner404cddf2005-11-12 01:33:40 +00001698
1699 if (ExtWord & (1 << 9)) // Has a section ID.
1700 GlobalSectionID = read_vbr_uint();
Chris Lattner8eb52dd2005-11-06 07:11:04 +00001701 }
Chris Lattnere3869c82003-04-16 21:16:05 +00001702
Chris Lattnerce5e04e2005-11-06 08:23:17 +00001703 GlobalValue::LinkageTypes Linkage;
Chris Lattnerc08912f2004-01-14 16:44:44 +00001704 switch (LinkageID) {
Chris Lattnerc08912f2004-01-14 16:44:44 +00001705 case 0: Linkage = GlobalValue::ExternalLinkage; break;
1706 case 1: Linkage = GlobalValue::WeakLinkage; break;
1707 case 2: Linkage = GlobalValue::AppendingLinkage; break;
1708 case 3: Linkage = GlobalValue::InternalLinkage; break;
1709 case 4: Linkage = GlobalValue::LinkOnceLinkage; break;
Anton Korobeynikovb74ed072006-09-14 18:23:27 +00001710 case 5: Linkage = GlobalValue::DLLImportLinkage; break;
1711 case 6: Linkage = GlobalValue::DLLExportLinkage; break;
1712 case 7: Linkage = GlobalValue::ExternalWeakLinkage; break;
Misha Brukman8a96c532005-04-21 21:44:41 +00001713 default:
Reid Spencer24399722004-07-09 22:21:33 +00001714 error("Unknown linkage type: " + utostr(LinkageID));
Reid Spencer060d25d2004-06-29 23:29:38 +00001715 Linkage = GlobalValue::InternalLinkage;
1716 break;
Chris Lattnere3869c82003-04-16 21:16:05 +00001717 }
Anton Korobeynikov7f705592007-01-12 19:20:47 +00001718 GlobalValue::VisibilityTypes Visibility;
1719 switch (VisibilityID) {
1720 case 0: Visibility = GlobalValue::DefaultVisibility; break;
1721 case 1: Visibility = GlobalValue::HiddenVisibility; break;
1722 default:
1723 error("Unknown visibility type: " + utostr(VisibilityID));
1724 Visibility = GlobalValue::DefaultVisibility;
1725 break;
1726 }
1727
Chris Lattnere3869c82003-04-16 21:16:05 +00001728 const Type *Ty = getType(SlotNo);
Chris Lattnere73bd452005-11-06 07:43:39 +00001729 if (!Ty)
Reid Spencer24399722004-07-09 22:21:33 +00001730 error("Global has no type! SlotNo=" + utostr(SlotNo));
Reid Spencer060d25d2004-06-29 23:29:38 +00001731
Chris Lattnere73bd452005-11-06 07:43:39 +00001732 if (!isa<PointerType>(Ty))
Reid Spencer24399722004-07-09 22:21:33 +00001733 error("Global not a pointer type! Ty= " + Ty->getDescription());
Chris Lattner70cc3392001-09-10 07:58:01 +00001734
Chris Lattner52e20b02003-03-19 20:54:26 +00001735 const Type *ElTy = cast<PointerType>(Ty)->getElementType();
Chris Lattnerd70684f2001-09-18 04:01:05 +00001736
Chris Lattner70cc3392001-09-10 07:58:01 +00001737 // Create the global variable...
Reid Spencer060d25d2004-06-29 23:29:38 +00001738 GlobalVariable *GV = new GlobalVariable(ElTy, isConstant, Linkage,
Chris Lattner52e20b02003-03-19 20:54:26 +00001739 0, "", TheModule);
Chris Lattner8eb52dd2005-11-06 07:11:04 +00001740 GV->setAlignment(Alignment);
Anton Korobeynikov7f705592007-01-12 19:20:47 +00001741 GV->setVisibility(Visibility);
Chris Lattner29b789b2003-11-19 17:27:18 +00001742 insertValue(GV, SlotNo, ModuleValues);
Chris Lattner05950c32001-10-13 06:47:01 +00001743
Chris Lattner404cddf2005-11-12 01:33:40 +00001744 if (GlobalSectionID != 0)
1745 SectionID[GV] = GlobalSectionID;
1746
Reid Spencer060d25d2004-06-29 23:29:38 +00001747 unsigned initSlot = 0;
Misha Brukman8a96c532005-04-21 21:44:41 +00001748 if (hasInitializer) {
Reid Spencer060d25d2004-06-29 23:29:38 +00001749 initSlot = read_vbr_uint();
1750 GlobalInits.push_back(std::make_pair(GV, initSlot));
1751 }
1752
1753 // Notify handler about the global value.
Chris Lattner4a242b32004-10-14 01:39:18 +00001754 if (Handler)
Anton Korobeynikov7f705592007-01-12 19:20:47 +00001755 Handler->handleGlobalVariable(ElTy, isConstant, Linkage, Visibility,
1756 SlotNo, initSlot);
Reid Spencer060d25d2004-06-29 23:29:38 +00001757
1758 // Get next item
1759 VarType = read_vbr_uint();
Chris Lattner70cc3392001-09-10 07:58:01 +00001760 }
1761
Chris Lattner52e20b02003-03-19 20:54:26 +00001762 // Read the function objects for all of the functions that are coming
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001763 unsigned FnSignature = read_vbr_uint();
Reid Spencer24399722004-07-09 22:21:33 +00001764
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001765 // List is terminated by VoidTy.
Chris Lattnere73bd452005-11-06 07:43:39 +00001766 while (((FnSignature & (~0U >> 1)) >> 5) != Type::VoidTyID) {
1767 const Type *Ty = getType((FnSignature & (~0U >> 1)) >> 5);
Chris Lattner927b1852003-10-09 20:22:47 +00001768 if (!isa<PointerType>(Ty) ||
Reid Spencer060d25d2004-06-29 23:29:38 +00001769 !isa<FunctionType>(cast<PointerType>(Ty)->getElementType())) {
Misha Brukman8a96c532005-04-21 21:44:41 +00001770 error("Function not a pointer to function type! Ty = " +
Reid Spencer46b002c2004-07-11 17:28:43 +00001771 Ty->getDescription());
Reid Spencer060d25d2004-06-29 23:29:38 +00001772 }
Chris Lattner8cdc6b72002-10-23 00:51:54 +00001773
Chris Lattner2a7b6ba2003-03-06 17:15:19 +00001774 // We create functions by passing the underlying FunctionType to create...
Misha Brukman8a96c532005-04-21 21:44:41 +00001775 const FunctionType* FTy =
Reid Spencer060d25d2004-06-29 23:29:38 +00001776 cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
Chris Lattner00950542001-06-06 20:29:01 +00001777
Chris Lattner18549c22004-11-15 21:43:03 +00001778 // Insert the place holder.
Chris Lattner404cddf2005-11-12 01:33:40 +00001779 Function *Func = new Function(FTy, GlobalValue::ExternalLinkage,
Reid Spencer04cde2c2004-07-04 11:33:49 +00001780 "", TheModule);
Reid Spencere1e96c02006-01-19 07:02:16 +00001781
Chris Lattnere73bd452005-11-06 07:43:39 +00001782 insertValue(Func, (FnSignature & (~0U >> 1)) >> 5, ModuleValues);
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001783
1784 // Flags are not used yet.
Chris Lattner97fbc502004-11-15 22:38:52 +00001785 unsigned Flags = FnSignature & 31;
Chris Lattner00950542001-06-06 20:29:01 +00001786
Chris Lattner97fbc502004-11-15 22:38:52 +00001787 // Save this for later so we know type of lazily instantiated functions.
1788 // Note that known-external functions do not have FunctionInfo blocks, so we
1789 // do not add them to the FunctionSignatureList.
1790 if ((Flags & (1 << 4)) == 0)
1791 FunctionSignatureList.push_back(Func);
Chris Lattner52e20b02003-03-19 20:54:26 +00001792
Chris Lattnere73bd452005-11-06 07:43:39 +00001793 // Get the calling convention from the low bits.
1794 unsigned CC = Flags & 15;
1795 unsigned Alignment = 0;
1796 if (FnSignature & (1 << 31)) { // Has extension word?
1797 unsigned ExtWord = read_vbr_uint();
1798 Alignment = (1 << (ExtWord & 31)) >> 1;
1799 CC |= ((ExtWord >> 5) & 15) << 4;
Chris Lattner404cddf2005-11-12 01:33:40 +00001800
1801 if (ExtWord & (1 << 10)) // Has a section ID.
1802 SectionID[Func] = read_vbr_uint();
Anton Korobeynikovb74ed072006-09-14 18:23:27 +00001803
1804 // Parse external declaration linkage
1805 switch ((ExtWord >> 11) & 3) {
1806 case 0: break;
1807 case 1: Func->setLinkage(Function::DLLImportLinkage); break;
1808 case 2: Func->setLinkage(Function::ExternalWeakLinkage); break;
1809 default: assert(0 && "Unsupported external linkage");
1810 }
Chris Lattnere73bd452005-11-06 07:43:39 +00001811 }
1812
Chris Lattner54b369e2005-11-06 07:46:13 +00001813 Func->setCallingConv(CC-1);
Chris Lattnere73bd452005-11-06 07:43:39 +00001814 Func->setAlignment(Alignment);
Chris Lattner479ffeb2005-05-06 20:42:57 +00001815
Reid Spencer04cde2c2004-07-04 11:33:49 +00001816 if (Handler) Handler->handleFunctionDeclaration(Func);
Reid Spencer060d25d2004-06-29 23:29:38 +00001817
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001818 // Get the next function signature.
1819 FnSignature = read_vbr_uint();
Chris Lattner00950542001-06-06 20:29:01 +00001820 }
1821
Misha Brukman8a96c532005-04-21 21:44:41 +00001822 // Now that the function signature list is set up, reverse it so that we can
Chris Lattner74734132002-08-17 22:01:27 +00001823 // remove elements efficiently from the back of the vector.
1824 std::reverse(FunctionSignatureList.begin(), FunctionSignatureList.end());
Chris Lattner00950542001-06-06 20:29:01 +00001825
Chris Lattner404cddf2005-11-12 01:33:40 +00001826 /// SectionNames - This contains the list of section names encoded in the
1827 /// moduleinfoblock. Functions and globals with an explicit section index
1828 /// into this to get their section name.
1829 std::vector<std::string> SectionNames;
1830
Reid Spencerd798a512006-11-14 04:47:22 +00001831 // Read in the dependent library information.
1832 unsigned num_dep_libs = read_vbr_uint();
1833 std::string dep_lib;
1834 while (num_dep_libs--) {
1835 dep_lib = read_str();
1836 TheModule->addLibrary(dep_lib);
Reid Spencer5b472d92004-08-21 20:49:23 +00001837 if (Handler)
Reid Spencerd798a512006-11-14 04:47:22 +00001838 Handler->handleDependentLibrary(dep_lib);
Reid Spencerad89bd62004-07-25 18:07:36 +00001839 }
1840
Reid Spencerd798a512006-11-14 04:47:22 +00001841 // Read target triple and place into the module.
1842 std::string triple = read_str();
1843 TheModule->setTargetTriple(triple);
1844 if (Handler)
1845 Handler->handleTargetTriple(triple);
1846
Reid Spenceraacc35a2007-01-26 08:10:24 +00001847 // Read the data layout string and place into the module.
1848 std::string datalayout = read_str();
1849 TheModule->setDataLayout(datalayout);
1850 // FIXME: Implement
1851 // if (Handler)
1852 // Handler->handleDataLayout(datalayout);
1853
Reid Spencerd798a512006-11-14 04:47:22 +00001854 if (At != BlockEnd) {
1855 // If the file has section info in it, read the section names now.
1856 unsigned NumSections = read_vbr_uint();
1857 while (NumSections--)
1858 SectionNames.push_back(read_str());
1859 }
1860
1861 // If the file has module-level inline asm, read it now.
1862 if (At != BlockEnd)
1863 TheModule->setModuleInlineAsm(read_str());
1864
Chris Lattner404cddf2005-11-12 01:33:40 +00001865 // If any globals are in specified sections, assign them now.
1866 for (std::map<GlobalValue*, unsigned>::iterator I = SectionID.begin(), E =
1867 SectionID.end(); I != E; ++I)
1868 if (I->second) {
1869 if (I->second > SectionID.size())
1870 error("SectionID out of range for global!");
1871 I->first->setSection(SectionNames[I->second-1]);
1872 }
Reid Spencerad89bd62004-07-25 18:07:36 +00001873
Chris Lattner00950542001-06-06 20:29:01 +00001874 // This is for future proofing... in the future extra fields may be added that
1875 // we don't understand, so we transparently ignore them.
1876 //
Reid Spencer060d25d2004-06-29 23:29:38 +00001877 At = BlockEnd;
1878
Reid Spencer04cde2c2004-07-04 11:33:49 +00001879 if (Handler) Handler->handleModuleGlobalsEnd();
Chris Lattner00950542001-06-06 20:29:01 +00001880}
1881
Reid Spencer04cde2c2004-07-04 11:33:49 +00001882/// Parse the version information and decode it by setting flags on the
1883/// Reader that enable backward compatibility of the reader.
Reid Spencer060d25d2004-06-29 23:29:38 +00001884void BytecodeReader::ParseVersionInfo() {
Reid Spenceraacc35a2007-01-26 08:10:24 +00001885 unsigned RevisionNum = read_vbr_uint();
Chris Lattnere3869c82003-04-16 21:16:05 +00001886
Reid Spencer3795ad12006-12-03 05:47:10 +00001887 // We don't provide backwards compatibility in the Reader any more. To
1888 // upgrade, the user should use llvm-upgrade.
1889 if (RevisionNum < 7)
1890 error("Bytecode formats < 7 are no longer supported. Use llvm-upgrade.");
Chris Lattner036b8aa2003-03-06 17:55:45 +00001891
Reid Spenceraacc35a2007-01-26 08:10:24 +00001892 if (Handler) Handler->handleVersionInfo(RevisionNum);
Chris Lattner036b8aa2003-03-06 17:55:45 +00001893}
1894
Reid Spencer04cde2c2004-07-04 11:33:49 +00001895/// Parse a whole module.
Reid Spencer060d25d2004-06-29 23:29:38 +00001896void BytecodeReader::ParseModule() {
Chris Lattner00950542001-06-06 20:29:01 +00001897 unsigned Type, Size;
Chris Lattner00950542001-06-06 20:29:01 +00001898
Reid Spencer060d25d2004-06-29 23:29:38 +00001899 FunctionSignatureList.clear(); // Just in case...
Chris Lattner00950542001-06-06 20:29:01 +00001900
1901 // Read into instance variables...
Reid Spencer060d25d2004-06-29 23:29:38 +00001902 ParseVersionInfo();
Chris Lattner00950542001-06-06 20:29:01 +00001903
Reid Spencer060d25d2004-06-29 23:29:38 +00001904 bool SeenModuleGlobalInfo = false;
1905 bool SeenGlobalTypePlane = false;
1906 BufPtr MyEnd = BlockEnd;
1907 while (At < MyEnd) {
1908 BufPtr OldAt = At;
1909 read_block(Type, Size);
1910
Chris Lattner00950542001-06-06 20:29:01 +00001911 switch (Type) {
Reid Spencer060d25d2004-06-29 23:29:38 +00001912
Reid Spencerad89bd62004-07-25 18:07:36 +00001913 case BytecodeFormat::GlobalTypePlaneBlockID:
Reid Spencer46b002c2004-07-11 17:28:43 +00001914 if (SeenGlobalTypePlane)
Reid Spencer24399722004-07-09 22:21:33 +00001915 error("Two GlobalTypePlane Blocks Encountered!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001916
Reid Spencer5b472d92004-08-21 20:49:23 +00001917 if (Size > 0)
1918 ParseGlobalTypes();
Reid Spencer060d25d2004-06-29 23:29:38 +00001919 SeenGlobalTypePlane = true;
Chris Lattner52e20b02003-03-19 20:54:26 +00001920 break;
1921
Misha Brukman8a96c532005-04-21 21:44:41 +00001922 case BytecodeFormat::ModuleGlobalInfoBlockID:
Reid Spencer46b002c2004-07-11 17:28:43 +00001923 if (SeenModuleGlobalInfo)
Reid Spencer24399722004-07-09 22:21:33 +00001924 error("Two ModuleGlobalInfo Blocks Encountered!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001925 ParseModuleGlobalInfo();
1926 SeenModuleGlobalInfo = true;
Chris Lattner52e20b02003-03-19 20:54:26 +00001927 break;
1928
Reid Spencerad89bd62004-07-25 18:07:36 +00001929 case BytecodeFormat::ConstantPoolBlockID:
Reid Spencer04cde2c2004-07-04 11:33:49 +00001930 ParseConstantPool(ModuleValues, ModuleTypes,false);
Chris Lattner00950542001-06-06 20:29:01 +00001931 break;
1932
Reid Spencerad89bd62004-07-25 18:07:36 +00001933 case BytecodeFormat::FunctionBlockID:
Reid Spencer060d25d2004-06-29 23:29:38 +00001934 ParseFunctionLazily();
Chris Lattner00950542001-06-06 20:29:01 +00001935 break;
Chris Lattner00950542001-06-06 20:29:01 +00001936
Reid Spencer78d033e2007-01-06 07:24:44 +00001937 case BytecodeFormat::ValueSymbolTableBlockID:
1938 ParseValueSymbolTable(0, &TheModule->getValueSymbolTable());
1939 break;
1940
1941 case BytecodeFormat::TypeSymbolTableBlockID:
1942 ParseTypeSymbolTable(&TheModule->getTypeSymbolTable());
Chris Lattner00950542001-06-06 20:29:01 +00001943 break;
Reid Spencer060d25d2004-06-29 23:29:38 +00001944
Chris Lattner00950542001-06-06 20:29:01 +00001945 default:
Reid Spencer060d25d2004-06-29 23:29:38 +00001946 At += Size;
1947 if (OldAt > At) {
Reid Spencer46b002c2004-07-11 17:28:43 +00001948 error("Unexpected Block of Type #" + utostr(Type) + " encountered!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001949 }
Chris Lattner00950542001-06-06 20:29:01 +00001950 break;
1951 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001952 BlockEnd = MyEnd;
Chris Lattner00950542001-06-06 20:29:01 +00001953 }
1954
Chris Lattner52e20b02003-03-19 20:54:26 +00001955 // After the module constant pool has been read, we can safely initialize
1956 // global variables...
1957 while (!GlobalInits.empty()) {
1958 GlobalVariable *GV = GlobalInits.back().first;
1959 unsigned Slot = GlobalInits.back().second;
1960 GlobalInits.pop_back();
1961
1962 // Look up the initializer value...
Chris Lattner29b789b2003-11-19 17:27:18 +00001963 // FIXME: Preserve this type ID!
Reid Spencer060d25d2004-06-29 23:29:38 +00001964
1965 const llvm::PointerType* GVType = GV->getType();
1966 unsigned TypeSlot = getTypeSlot(GVType->getElementType());
Chris Lattner93361992004-01-15 18:45:25 +00001967 if (Constant *CV = getConstantValue(TypeSlot, Slot)) {
Misha Brukman8a96c532005-04-21 21:44:41 +00001968 if (GV->hasInitializer())
Reid Spencer24399722004-07-09 22:21:33 +00001969 error("Global *already* has an initializer?!");
Reid Spencer04cde2c2004-07-04 11:33:49 +00001970 if (Handler) Handler->handleGlobalInitializer(GV,CV);
Chris Lattner93361992004-01-15 18:45:25 +00001971 GV->setInitializer(CV);
Chris Lattner52e20b02003-03-19 20:54:26 +00001972 } else
Reid Spencer24399722004-07-09 22:21:33 +00001973 error("Cannot find initializer value.");
Chris Lattner52e20b02003-03-19 20:54:26 +00001974 }
1975
Chris Lattneraba5ff52005-05-05 20:57:00 +00001976 if (!ConstantFwdRefs.empty())
1977 error("Use of undefined constants in a module");
1978
Reid Spencer060d25d2004-06-29 23:29:38 +00001979 /// Make sure we pulled them all out. If we didn't then there's a declaration
1980 /// but a missing body. That's not allowed.
Misha Brukman12c29d12003-09-22 23:38:23 +00001981 if (!FunctionSignatureList.empty())
Reid Spencer24399722004-07-09 22:21:33 +00001982 error("Function declared, but bytecode stream ended before definition");
Chris Lattner00950542001-06-06 20:29:01 +00001983}
1984
Reid Spencer04cde2c2004-07-04 11:33:49 +00001985/// This function completely parses a bytecode buffer given by the \p Buf
1986/// and \p Length parameters.
Anton Korobeynikov7d515442006-09-01 20:35:17 +00001987bool BytecodeReader::ParseBytecode(volatile BufPtr Buf, unsigned Length,
Reid Spencer233fe722006-08-22 16:09:19 +00001988 const std::string &ModuleID,
1989 std::string* ErrMsg) {
Misha Brukmane0dd0d42003-09-23 16:15:29 +00001990
Reid Spencer233fe722006-08-22 16:09:19 +00001991 /// We handle errors by
1992 if (setjmp(context)) {
1993 // Cleanup after error
1994 if (Handler) Handler->handleError(ErrorMsg);
Reid Spencer060d25d2004-06-29 23:29:38 +00001995 freeState();
Chris Lattner2a7b6ba2003-03-06 17:15:19 +00001996 delete TheModule;
1997 TheModule = 0;
Chris Lattner3bdad692004-11-15 21:55:33 +00001998 if (decompressedBlock != 0 ) {
Reid Spencer61aaf2e2004-11-14 21:59:21 +00001999 ::free(decompressedBlock);
Chris Lattner3bdad692004-11-15 21:55:33 +00002000 decompressedBlock = 0;
2001 }
Reid Spencer233fe722006-08-22 16:09:19 +00002002 // Set caller's error message, if requested
2003 if (ErrMsg)
2004 *ErrMsg = ErrorMsg;
2005 // Indicate an error occurred
2006 return true;
Chris Lattner2a7b6ba2003-03-06 17:15:19 +00002007 }
Reid Spencer233fe722006-08-22 16:09:19 +00002008
2009 RevisionNum = 0;
2010 At = MemStart = BlockStart = Buf;
2011 MemEnd = BlockEnd = Buf + Length;
2012
2013 // Create the module
2014 TheModule = new Module(ModuleID);
2015
2016 if (Handler) Handler->handleStart(TheModule, Length);
2017
2018 // Read the four bytes of the signature.
2019 unsigned Sig = read_uint();
2020
2021 // If this is a compressed file
2022 if (Sig == ('l' | ('l' << 8) | ('v' << 16) | ('c' << 24))) {
2023
2024 // Invoke the decompression of the bytecode. Note that we have to skip the
2025 // file's magic number which is not part of the compressed block. Hence,
2026 // the Buf+4 and Length-4. The result goes into decompressedBlock, a data
2027 // member for retention until BytecodeReader is destructed.
2028 unsigned decompressedLength = Compressor::decompressToNewBuffer(
2029 (char*)Buf+4,Length-4,decompressedBlock);
2030
2031 // We must adjust the buffer pointers used by the bytecode reader to point
2032 // into the new decompressed block. After decompression, the
2033 // decompressedBlock will point to a contiguous memory area that has
2034 // the decompressed data.
2035 At = MemStart = BlockStart = Buf = (BufPtr) decompressedBlock;
2036 MemEnd = BlockEnd = Buf + decompressedLength;
2037
2038 // else if this isn't a regular (uncompressed) bytecode file, then its
2039 // and error, generate that now.
2040 } else if (Sig != ('l' | ('l' << 8) | ('v' << 16) | ('m' << 24))) {
2041 error("Invalid bytecode signature: " + utohexstr(Sig));
2042 }
2043
2044 // Tell the handler we're starting a module
2045 if (Handler) Handler->handleModuleBegin(ModuleID);
2046
2047 // Get the module block and size and verify. This is handled specially
2048 // because the module block/size is always written in long format. Other
2049 // blocks are written in short format so the read_block method is used.
2050 unsigned Type, Size;
2051 Type = read_uint();
2052 Size = read_uint();
2053 if (Type != BytecodeFormat::ModuleBlockID) {
2054 error("Expected Module Block! Type:" + utostr(Type) + ", Size:"
2055 + utostr(Size));
2056 }
2057
2058 // It looks like the darwin ranlib program is broken, and adds trailing
2059 // garbage to the end of some bytecode files. This hack allows the bc
2060 // reader to ignore trailing garbage on bytecode files.
2061 if (At + Size < MemEnd)
2062 MemEnd = BlockEnd = At+Size;
2063
2064 if (At + Size != MemEnd)
2065 error("Invalid Top Level Block Length! Type:" + utostr(Type)
2066 + ", Size:" + utostr(Size));
2067
2068 // Parse the module contents
2069 this->ParseModule();
2070
2071 // Check for missing functions
2072 if (hasFunctions())
2073 error("Function expected, but bytecode stream ended!");
2074
Reid Spencer233fe722006-08-22 16:09:19 +00002075 // Tell the handler we're done with the module
2076 if (Handler)
2077 Handler->handleModuleEnd(ModuleID);
2078
2079 // Tell the handler we're finished the parse
2080 if (Handler) Handler->handleFinish();
2081
2082 return false;
2083
Chris Lattner00950542001-06-06 20:29:01 +00002084}
Reid Spencer060d25d2004-06-29 23:29:38 +00002085
2086//===----------------------------------------------------------------------===//
2087//=== Default Implementations of Handler Methods
2088//===----------------------------------------------------------------------===//
2089
2090BytecodeHandler::~BytecodeHandler() {}
Reid Spencer060d25d2004-06-29 23:29:38 +00002091