blob: 82b1888e6aa390b3c626248458f690be98f1a892 [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"
Jim Laskeycb6682f2005-08-17 19:34:49 +000030#include "llvm/Support/MathExtras.h"
Chris Lattner4c3d3a92007-01-31 19:56:15 +000031#include "llvm/ADT/SmallVector.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000032#include "llvm/ADT/StringExtras.h"
Reid Spencer060d25d2004-06-29 23:29:38 +000033#include <sstream>
Alkis Evlogimenos20aa4742004-09-03 18:19:51 +000034#include <algorithm>
Chris Lattner29b789b2003-11-19 17:27:18 +000035using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000036
Reid Spencer46b002c2004-07-11 17:28:43 +000037namespace {
Chris Lattnercad28bd2005-01-29 00:36:19 +000038 /// @brief A class for maintaining the slot number definition
39 /// as a placeholder for the actual definition for forward constants defs.
40 class ConstantPlaceHolder : public ConstantExpr {
41 ConstantPlaceHolder(); // DO NOT IMPLEMENT
42 void operator=(const ConstantPlaceHolder &); // DO NOT IMPLEMENT
43 public:
Chris Lattner61323322005-01-31 01:11:13 +000044 Use Op;
Misha Brukman8a96c532005-04-21 21:44:41 +000045 ConstantPlaceHolder(const Type *Ty)
Chris Lattner61323322005-01-31 01:11:13 +000046 : ConstantExpr(Ty, Instruction::UserOp1, &Op, 1),
Reid Spencer88cfda22006-12-31 05:44:24 +000047 Op(UndefValue::get(Type::Int32Ty), this) {
Chris Lattner61323322005-01-31 01:11:13 +000048 }
Chris Lattnercad28bd2005-01-29 00:36:19 +000049 };
Reid Spencer46b002c2004-07-11 17:28:43 +000050}
Reid Spencer060d25d2004-06-29 23:29:38 +000051
Reid Spencer24399722004-07-09 22:21:33 +000052// Provide some details on error
Reid Spencer233fe722006-08-22 16:09:19 +000053inline void BytecodeReader::error(const std::string& err) {
54 ErrorMsg = err + " (Vers=" + itostr(RevisionNum) + ", Pos="
55 + itostr(At-MemStart) + ")";
Reid Spenceref9b9a72007-02-05 20:47:22 +000056 if (Handler) Handler->handleError(ErrorMsg);
Reid Spencer233fe722006-08-22 16:09:19 +000057 longjmp(context,1);
Reid Spencer24399722004-07-09 22:21:33 +000058}
59
Reid Spencer060d25d2004-06-29 23:29:38 +000060//===----------------------------------------------------------------------===//
61// Bytecode Reading Methods
62//===----------------------------------------------------------------------===//
63
Reid Spencer04cde2c2004-07-04 11:33:49 +000064/// Determine if the current block being read contains any more data.
Reid Spencer060d25d2004-06-29 23:29:38 +000065inline bool BytecodeReader::moreInBlock() {
66 return At < BlockEnd;
Chris Lattner00950542001-06-06 20:29:01 +000067}
68
Reid Spencer04cde2c2004-07-04 11:33:49 +000069/// Throw an error if we've read past the end of the current block
Reid Spencer060d25d2004-06-29 23:29:38 +000070inline void BytecodeReader::checkPastBlockEnd(const char * block_name) {
Reid Spencer46b002c2004-07-11 17:28:43 +000071 if (At > BlockEnd)
Chris Lattnera79e7cc2004-10-16 18:18:16 +000072 error(std::string("Attempt to read past the end of ") + block_name +
73 " block.");
Reid Spencer060d25d2004-06-29 23:29:38 +000074}
Chris Lattner36392bc2003-10-08 21:18:57 +000075
Reid Spencer04cde2c2004-07-04 11:33:49 +000076/// Read a whole unsigned integer
Reid Spencer060d25d2004-06-29 23:29:38 +000077inline unsigned BytecodeReader::read_uint() {
Misha Brukman8a96c532005-04-21 21:44:41 +000078 if (At+4 > BlockEnd)
Reid Spencer24399722004-07-09 22:21:33 +000079 error("Ran out of data reading uint!");
Reid Spencer060d25d2004-06-29 23:29:38 +000080 At += 4;
81 return At[-4] | (At[-3] << 8) | (At[-2] << 16) | (At[-1] << 24);
82}
83
Reid Spencer04cde2c2004-07-04 11:33:49 +000084/// Read a variable-bit-rate encoded unsigned integer
Reid Spencer060d25d2004-06-29 23:29:38 +000085inline unsigned BytecodeReader::read_vbr_uint() {
86 unsigned Shift = 0;
87 unsigned Result = 0;
Misha Brukman8a96c532005-04-21 21:44:41 +000088
Reid Spencer060d25d2004-06-29 23:29:38 +000089 do {
Misha Brukman8a96c532005-04-21 21:44:41 +000090 if (At == BlockEnd)
Reid Spencer24399722004-07-09 22:21:33 +000091 error("Ran out of data reading vbr_uint!");
Reid Spencer060d25d2004-06-29 23:29:38 +000092 Result |= (unsigned)((*At++) & 0x7F) << Shift;
93 Shift += 7;
94 } while (At[-1] & 0x80);
Reid Spencer060d25d2004-06-29 23:29:38 +000095 return Result;
96}
97
Reid Spencer04cde2c2004-07-04 11:33:49 +000098/// Read a variable-bit-rate encoded unsigned 64-bit integer.
Reid Spencer060d25d2004-06-29 23:29:38 +000099inline uint64_t BytecodeReader::read_vbr_uint64() {
100 unsigned Shift = 0;
101 uint64_t Result = 0;
Misha Brukman8a96c532005-04-21 21:44:41 +0000102
Reid Spencer060d25d2004-06-29 23:29:38 +0000103 do {
Misha Brukman8a96c532005-04-21 21:44:41 +0000104 if (At == BlockEnd)
Reid Spencer24399722004-07-09 22:21:33 +0000105 error("Ran out of data reading vbr_uint64!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000106 Result |= (uint64_t)((*At++) & 0x7F) << Shift;
107 Shift += 7;
108 } while (At[-1] & 0x80);
Reid Spencer060d25d2004-06-29 23:29:38 +0000109 return Result;
110}
111
Reid Spencer04cde2c2004-07-04 11:33:49 +0000112/// Read a variable-bit-rate encoded signed 64-bit integer.
Reid Spencer060d25d2004-06-29 23:29:38 +0000113inline int64_t BytecodeReader::read_vbr_int64() {
114 uint64_t R = read_vbr_uint64();
115 if (R & 1) {
116 if (R != 1)
117 return -(int64_t)(R >> 1);
118 else // There is no such thing as -0 with integers. "-0" really means
119 // 0x8000000000000000.
120 return 1LL << 63;
121 } else
122 return (int64_t)(R >> 1);
123}
124
Reid Spencer04cde2c2004-07-04 11:33:49 +0000125/// Read a pascal-style string (length followed by text)
Reid Spencer060d25d2004-06-29 23:29:38 +0000126inline std::string BytecodeReader::read_str() {
127 unsigned Size = read_vbr_uint();
128 const unsigned char *OldAt = At;
129 At += Size;
130 if (At > BlockEnd) // Size invalid?
Reid Spencer24399722004-07-09 22:21:33 +0000131 error("Ran out of data reading a string!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000132 return std::string((char*)OldAt, Size);
133}
134
Chris Lattnerdd8cec52007-02-12 18:53:43 +0000135void BytecodeReader::read_str(SmallVectorImpl<char> &StrData) {
136 StrData.clear();
137 unsigned Size = read_vbr_uint();
138 const unsigned char *OldAt = At;
139 At += Size;
140 if (At > BlockEnd) // Size invalid?
141 error("Ran out of data reading a string!");
142 StrData.append(OldAt, At);
143}
144
145
Reid Spencer04cde2c2004-07-04 11:33:49 +0000146/// Read an arbitrary block of data
Reid Spencer060d25d2004-06-29 23:29:38 +0000147inline void BytecodeReader::read_data(void *Ptr, void *End) {
148 unsigned char *Start = (unsigned char *)Ptr;
149 unsigned Amount = (unsigned char *)End - Start;
Misha Brukman8a96c532005-04-21 21:44:41 +0000150 if (At+Amount > BlockEnd)
Reid Spencer24399722004-07-09 22:21:33 +0000151 error("Ran out of data!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000152 std::copy(At, At+Amount, Start);
153 At += Amount;
154}
155
Reid Spencer46b002c2004-07-11 17:28:43 +0000156/// Read a float value in little-endian order
157inline void BytecodeReader::read_float(float& FloatVal) {
Reid Spencerada16182004-07-25 21:36:26 +0000158 /// FIXME: This isn't optimal, it has size problems on some platforms
159 /// where FP is not IEEE.
Jim Laskeycb6682f2005-08-17 19:34:49 +0000160 FloatVal = BitsToFloat(At[0] | (At[1] << 8) | (At[2] << 16) | (At[3] << 24));
Reid Spencerada16182004-07-25 21:36:26 +0000161 At+=sizeof(uint32_t);
Reid Spencer46b002c2004-07-11 17:28:43 +0000162}
163
164/// Read a double value in little-endian order
165inline void BytecodeReader::read_double(double& DoubleVal) {
Reid Spencerada16182004-07-25 21:36:26 +0000166 /// FIXME: This isn't optimal, it has size problems on some platforms
167 /// where FP is not IEEE.
Jim Laskeycb6682f2005-08-17 19:34:49 +0000168 DoubleVal = BitsToDouble((uint64_t(At[0]) << 0) | (uint64_t(At[1]) << 8) |
169 (uint64_t(At[2]) << 16) | (uint64_t(At[3]) << 24) |
170 (uint64_t(At[4]) << 32) | (uint64_t(At[5]) << 40) |
171 (uint64_t(At[6]) << 48) | (uint64_t(At[7]) << 56));
Reid Spencerada16182004-07-25 21:36:26 +0000172 At+=sizeof(uint64_t);
Reid Spencer46b002c2004-07-11 17:28:43 +0000173}
174
Reid Spencer04cde2c2004-07-04 11:33:49 +0000175/// Read a block header and obtain its type and size
Reid Spencer060d25d2004-06-29 23:29:38 +0000176inline void BytecodeReader::read_block(unsigned &Type, unsigned &Size) {
Reid Spencerd798a512006-11-14 04:47:22 +0000177 Size = read_uint(); // Read the header
178 Type = Size & 0x1F; // mask low order five bits to get type
179 Size >>= 5; // high order 27 bits is the size
Reid Spencer060d25d2004-06-29 23:29:38 +0000180 BlockStart = At;
Reid Spencer46b002c2004-07-11 17:28:43 +0000181 if (At + Size > BlockEnd)
Reid Spencer24399722004-07-09 22:21:33 +0000182 error("Attempt to size a block past end of memory");
Reid Spencer060d25d2004-06-29 23:29:38 +0000183 BlockEnd = At + Size;
Reid Spencer46b002c2004-07-11 17:28:43 +0000184 if (Handler) Handler->handleBlock(Type, BlockStart, Size);
Reid Spencer04cde2c2004-07-04 11:33:49 +0000185}
186
Reid Spencer060d25d2004-06-29 23:29:38 +0000187//===----------------------------------------------------------------------===//
188// IR Lookup Methods
189//===----------------------------------------------------------------------===//
190
Reid Spencer04cde2c2004-07-04 11:33:49 +0000191/// Determine if a type id has an implicit null value
Reid Spencer46b002c2004-07-11 17:28:43 +0000192inline bool BytecodeReader::hasImplicitNull(unsigned TyID) {
Reid Spencerd798a512006-11-14 04:47:22 +0000193 return TyID != Type::LabelTyID && TyID != Type::VoidTyID;
Reid Spencer060d25d2004-06-29 23:29:38 +0000194}
195
Reid Spencerd2bb8872007-01-30 19:36:46 +0000196/// Obtain a type given a typeid and account for things like function level vs
197/// module level, and the offsetting for the primitive types.
Reid Spencer060d25d2004-06-29 23:29:38 +0000198const Type *BytecodeReader::getType(unsigned ID) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000199 if (ID <= Type::LastPrimitiveTyID)
Chris Lattnerf70c22b2004-06-17 18:19:28 +0000200 if (const Type *T = Type::getPrimitiveType((Type::TypeID)ID))
Chris Lattner927b1852003-10-09 20:22:47 +0000201 return T; // Asked for a primitive type...
Chris Lattner36392bc2003-10-08 21:18:57 +0000202
203 // Otherwise, derived types need offset...
Chris Lattner89e02532004-01-18 21:08:15 +0000204 ID -= Type::FirstDerivedTyID;
205
Chris Lattner36392bc2003-10-08 21:18:57 +0000206 // Is it a module-level type?
Reid Spencer46b002c2004-07-11 17:28:43 +0000207 if (ID < ModuleTypes.size())
208 return ModuleTypes[ID].get();
Chris Lattner36392bc2003-10-08 21:18:57 +0000209
Reid Spencer46b002c2004-07-11 17:28:43 +0000210 // Nope, is it a function-level type?
211 ID -= ModuleTypes.size();
212 if (ID < FunctionTypes.size())
213 return FunctionTypes[ID].get();
Chris Lattner36392bc2003-10-08 21:18:57 +0000214
Reid Spencer46b002c2004-07-11 17:28:43 +0000215 error("Illegal type reference!");
216 return Type::VoidTy;
Chris Lattner00950542001-06-06 20:29:01 +0000217}
218
Reid Spencer3795ad12006-12-03 05:47:10 +0000219/// This method just saves some coding. It uses read_vbr_uint to read in a
220/// type id, errors that its not the type type, and then calls getType to
221/// return the type value.
Reid Spencerd798a512006-11-14 04:47:22 +0000222inline const Type* BytecodeReader::readType() {
223 return getType(read_vbr_uint());
Reid Spencer04cde2c2004-07-04 11:33:49 +0000224}
225
226/// Get the slot number associated with a type accounting for primitive
Reid Spencerd2bb8872007-01-30 19:36:46 +0000227/// types and function level vs module level.
Reid Spencer060d25d2004-06-29 23:29:38 +0000228unsigned BytecodeReader::getTypeSlot(const Type *Ty) {
229 if (Ty->isPrimitiveType())
230 return Ty->getTypeID();
231
Reid Spencer060d25d2004-06-29 23:29:38 +0000232 // Check the function level types first...
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000233 TypeListTy::iterator I = std::find(FunctionTypes.begin(),
234 FunctionTypes.end(), Ty);
Reid Spencer060d25d2004-06-29 23:29:38 +0000235
236 if (I != FunctionTypes.end())
Misha Brukman8a96c532005-04-21 21:44:41 +0000237 return Type::FirstDerivedTyID + ModuleTypes.size() +
Reid Spencer46b002c2004-07-11 17:28:43 +0000238 (&*I - &FunctionTypes[0]);
Reid Spencer060d25d2004-06-29 23:29:38 +0000239
Chris Lattnereebac5f2005-10-03 21:26:53 +0000240 // If we don't have our cache yet, build it now.
241 if (ModuleTypeIDCache.empty()) {
242 unsigned N = 0;
243 ModuleTypeIDCache.reserve(ModuleTypes.size());
244 for (TypeListTy::iterator I = ModuleTypes.begin(), E = ModuleTypes.end();
245 I != E; ++I, ++N)
246 ModuleTypeIDCache.push_back(std::make_pair(*I, N));
247
248 std::sort(ModuleTypeIDCache.begin(), ModuleTypeIDCache.end());
249 }
250
251 // Binary search the cache for the entry.
252 std::vector<std::pair<const Type*, unsigned> >::iterator IT =
253 std::lower_bound(ModuleTypeIDCache.begin(), ModuleTypeIDCache.end(),
254 std::make_pair(Ty, 0U));
255 if (IT == ModuleTypeIDCache.end() || IT->first != Ty)
Reid Spencer24399722004-07-09 22:21:33 +0000256 error("Didn't find type in ModuleTypes.");
Chris Lattnereebac5f2005-10-03 21:26:53 +0000257
258 return Type::FirstDerivedTyID + IT->second;
Chris Lattner80b97342004-01-17 23:25:43 +0000259}
260
Misha Brukman8a96c532005-04-21 21:44:41 +0000261/// Retrieve a value of a given type and slot number, possibly creating
262/// it if it doesn't already exist.
Reid Spencer060d25d2004-06-29 23:29:38 +0000263Value * BytecodeReader::getValue(unsigned type, unsigned oNum, bool Create) {
Chris Lattner4ee8ef22003-10-08 22:52:54 +0000264 assert(type != Type::LabelTyID && "getValue() cannot get blocks!");
Chris Lattner00950542001-06-06 20:29:01 +0000265 unsigned Num = oNum;
Chris Lattner00950542001-06-06 20:29:01 +0000266
Reid Spencerd2bb8872007-01-30 19:36:46 +0000267 // By default, the global type id is the type id passed in
268 unsigned GlobalTyID = type;
Reid Spencer060d25d2004-06-29 23:29:38 +0000269
Reid Spencerd2bb8872007-01-30 19:36:46 +0000270 if (hasImplicitNull(GlobalTyID)) {
271 const Type *Ty = getType(type);
272 if (!isa<OpaqueType>(Ty)) {
273 if (Num == 0)
274 return Constant::getNullValue(Ty);
275 --Num;
Chris Lattner89e02532004-01-18 21:08:15 +0000276 }
Reid Spencerd2bb8872007-01-30 19:36:46 +0000277 }
Chris Lattner89e02532004-01-18 21:08:15 +0000278
Reid Spencer8dd4f532007-04-08 23:58:41 +0000279 if (GlobalTyID < ModuleValues.size())
280 if (ValueList *Globals = ModuleValues[GlobalTyID]) {
281 if (Num < Globals->size())
282 return Globals->getOperand(Num);
283 Num -= Globals->size();
284 }
Chris Lattner52e20b02003-03-19 20:54:26 +0000285
Reid Spencer8dd4f532007-04-08 23:58:41 +0000286 if (type < FunctionValues.size())
287 if (ValueList *Locals = FunctionValues[type])
288 if (Num < Locals->size())
289 return Locals->getOperand(Num);
Chris Lattner00950542001-06-06 20:29:01 +0000290
Chris Lattner74734132002-08-17 22:01:27 +0000291 if (!Create) return 0; // Do not create a placeholder?
Chris Lattner00950542001-06-06 20:29:01 +0000292
Reid Spencer551ccae2004-09-01 22:55:40 +0000293 // Did we already create a place holder?
Chris Lattner8eb10ce2003-10-09 06:05:40 +0000294 std::pair<unsigned,unsigned> KeyValue(type, oNum);
Reid Spencer060d25d2004-06-29 23:29:38 +0000295 ForwardReferenceMap::iterator I = ForwardReferences.lower_bound(KeyValue);
Chris Lattner8eb10ce2003-10-09 06:05:40 +0000296 if (I != ForwardReferences.end() && I->first == KeyValue)
297 return I->second; // We have already created this placeholder
298
Reid Spencer551ccae2004-09-01 22:55:40 +0000299 // If the type exists (it should)
300 if (const Type* Ty = getType(type)) {
301 // Create the place holder
302 Value *Val = new Argument(Ty);
303 ForwardReferences.insert(I, std::make_pair(KeyValue, Val));
304 return Val;
305 }
Reid Spencer233fe722006-08-22 16:09:19 +0000306 error("Can't create placeholder for value of type slot #" + utostr(type));
307 return 0; // just silence warning, error calls longjmp
Chris Lattner00950542001-06-06 20:29:01 +0000308}
309
Reid Spencer060d25d2004-06-29 23:29:38 +0000310
Reid Spencer04cde2c2004-07-04 11:33:49 +0000311/// Just like getValue, except that it returns a null pointer
312/// only on error. It always returns a constant (meaning that if the value is
313/// defined, but is not a constant, that is an error). If the specified
Misha Brukman8a96c532005-04-21 21:44:41 +0000314/// constant hasn't been parsed yet, a placeholder is defined and used.
Reid Spencer04cde2c2004-07-04 11:33:49 +0000315/// Later, after the real value is parsed, the placeholder is eliminated.
Reid Spencer060d25d2004-06-29 23:29:38 +0000316Constant* BytecodeReader::getConstantValue(unsigned TypeSlot, unsigned Slot) {
317 if (Value *V = getValue(TypeSlot, Slot, false))
318 if (Constant *C = dyn_cast<Constant>(V))
319 return C; // If we already have the value parsed, just return it
Reid Spencer060d25d2004-06-29 23:29:38 +0000320 else
Misha Brukman8a96c532005-04-21 21:44:41 +0000321 error("Value for slot " + utostr(Slot) +
Reid Spencera86037e2004-07-18 00:12:03 +0000322 " is expected to be a constant!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000323
Chris Lattner389bd042004-12-09 06:19:44 +0000324 std::pair<unsigned, unsigned> Key(TypeSlot, Slot);
Reid Spencer060d25d2004-06-29 23:29:38 +0000325 ConstantRefsType::iterator I = ConstantFwdRefs.lower_bound(Key);
326
327 if (I != ConstantFwdRefs.end() && I->first == Key) {
328 return I->second;
329 } else {
330 // Create a placeholder for the constant reference and
331 // keep track of the fact that we have a forward ref to recycle it
Chris Lattner389bd042004-12-09 06:19:44 +0000332 Constant *C = new ConstantPlaceHolder(getType(TypeSlot));
Misha Brukman8a96c532005-04-21 21:44:41 +0000333
Reid Spencer060d25d2004-06-29 23:29:38 +0000334 // Keep track of the fact that we have a forward ref to recycle it
335 ConstantFwdRefs.insert(I, std::make_pair(Key, C));
336 return C;
337 }
338}
339
340//===----------------------------------------------------------------------===//
341// IR Construction Methods
342//===----------------------------------------------------------------------===//
343
Reid Spencer04cde2c2004-07-04 11:33:49 +0000344/// As values are created, they are inserted into the appropriate place
345/// with this method. The ValueTable argument must be one of ModuleValues
346/// or FunctionValues data members of this class.
Misha Brukman8a96c532005-04-21 21:44:41 +0000347unsigned BytecodeReader::insertValue(Value *Val, unsigned type,
Reid Spencer46b002c2004-07-11 17:28:43 +0000348 ValueTable &ValueTab) {
Reid Spencer060d25d2004-06-29 23:29:38 +0000349 if (ValueTab.size() <= type)
350 ValueTab.resize(type+1);
351
352 if (!ValueTab[type]) ValueTab[type] = new ValueList();
353
354 ValueTab[type]->push_back(Val);
355
Chris Lattneraba5ff52005-05-05 20:57:00 +0000356 bool HasOffset = hasImplicitNull(type) && !isa<OpaqueType>(Val->getType());
Reid Spencer060d25d2004-06-29 23:29:38 +0000357 return ValueTab[type]->size()-1 + HasOffset;
358}
359
Reid Spencer04cde2c2004-07-04 11:33:49 +0000360/// Insert the arguments of a function as new values in the reader.
Reid Spencer46b002c2004-07-11 17:28:43 +0000361void BytecodeReader::insertArguments(Function* F) {
Reid Spencer060d25d2004-06-29 23:29:38 +0000362 const FunctionType *FT = F->getFunctionType();
Chris Lattnere4d5c442005-03-15 04:54:21 +0000363 Function::arg_iterator AI = F->arg_begin();
Reid Spencer060d25d2004-06-29 23:29:38 +0000364 for (FunctionType::param_iterator It = FT->param_begin();
365 It != FT->param_end(); ++It, ++AI)
366 insertValue(AI, getTypeSlot(AI->getType()), FunctionValues);
367}
368
369//===----------------------------------------------------------------------===//
370// Bytecode Parsing Methods
371//===----------------------------------------------------------------------===//
372
Reid Spencer04cde2c2004-07-04 11:33:49 +0000373/// This method parses a single instruction. The instruction is
374/// inserted at the end of the \p BB provided. The arguments of
Misha Brukman44666b12004-09-28 16:57:46 +0000375/// the instruction are provided in the \p Oprnds vector.
Chris Lattner63cf59e2007-02-07 05:08:39 +0000376void BytecodeReader::ParseInstruction(SmallVector<unsigned, 8> &Oprnds,
Reid Spencer46b002c2004-07-11 17:28:43 +0000377 BasicBlock* BB) {
Reid Spencer060d25d2004-06-29 23:29:38 +0000378 BufPtr SaveAt = At;
379
380 // Clear instruction data
381 Oprnds.clear();
382 unsigned iType = 0;
383 unsigned Opcode = 0;
384 unsigned Op = read_uint();
385
386 // bits Instruction format: Common to all formats
387 // --------------------------
388 // 01-00: Opcode type, fixed to 1.
389 // 07-02: Opcode
390 Opcode = (Op >> 2) & 63;
391 Oprnds.resize((Op >> 0) & 03);
392
393 // Extract the operands
394 switch (Oprnds.size()) {
395 case 1:
396 // bits Instruction format:
397 // --------------------------
398 // 19-08: Resulting type plane
399 // 31-20: Operand #1 (if set to (2^12-1), then zero operands)
400 //
401 iType = (Op >> 8) & 4095;
402 Oprnds[0] = (Op >> 20) & 4095;
403 if (Oprnds[0] == 4095) // Handle special encoding for 0 operands...
404 Oprnds.resize(0);
405 break;
406 case 2:
407 // bits Instruction format:
408 // --------------------------
409 // 15-08: Resulting type plane
410 // 23-16: Operand #1
Misha Brukman8a96c532005-04-21 21:44:41 +0000411 // 31-24: Operand #2
Reid Spencer060d25d2004-06-29 23:29:38 +0000412 //
413 iType = (Op >> 8) & 255;
414 Oprnds[0] = (Op >> 16) & 255;
415 Oprnds[1] = (Op >> 24) & 255;
416 break;
417 case 3:
418 // bits Instruction format:
419 // --------------------------
420 // 13-08: Resulting type plane
421 // 19-14: Operand #1
422 // 25-20: Operand #2
423 // 31-26: Operand #3
424 //
425 iType = (Op >> 8) & 63;
426 Oprnds[0] = (Op >> 14) & 63;
427 Oprnds[1] = (Op >> 20) & 63;
428 Oprnds[2] = (Op >> 26) & 63;
429 break;
430 case 0:
431 At -= 4; // Hrm, try this again...
432 Opcode = read_vbr_uint();
433 Opcode >>= 2;
434 iType = read_vbr_uint();
435
436 unsigned NumOprnds = read_vbr_uint();
437 Oprnds.resize(NumOprnds);
438
439 if (NumOprnds == 0)
Reid Spencer24399722004-07-09 22:21:33 +0000440 error("Zero-argument instruction found; this is invalid.");
Reid Spencer060d25d2004-06-29 23:29:38 +0000441
442 for (unsigned i = 0; i != NumOprnds; ++i)
443 Oprnds[i] = read_vbr_uint();
Reid Spencer060d25d2004-06-29 23:29:38 +0000444 break;
445 }
446
Reid Spencerd798a512006-11-14 04:47:22 +0000447 const Type *InstTy = getType(iType);
Reid Spencer060d25d2004-06-29 23:29:38 +0000448
Reid Spencer1628cec2006-10-26 06:15:43 +0000449 // Make the necessary adjustments for dealing with backwards compatibility
450 // of opcodes.
Reid Spencer3795ad12006-12-03 05:47:10 +0000451 Instruction* Result = 0;
Reid Spencer1628cec2006-10-26 06:15:43 +0000452
Reid Spencer3795ad12006-12-03 05:47:10 +0000453 // First, handle the easy binary operators case
454 if (Opcode >= Instruction::BinaryOpsBegin &&
Reid Spencerc8dab492006-12-03 06:28:54 +0000455 Opcode < Instruction::BinaryOpsEnd && Oprnds.size() == 2) {
Reid Spencer3795ad12006-12-03 05:47:10 +0000456 Result = BinaryOperator::create(Instruction::BinaryOps(Opcode),
457 getValue(iType, Oprnds[0]),
458 getValue(iType, Oprnds[1]));
Reid Spencerc8dab492006-12-03 06:28:54 +0000459 } else {
Reid Spencer1628cec2006-10-26 06:15:43 +0000460 // Indicate that we don't think this is a call instruction (yet).
461 // Process based on the Opcode read
462 switch (Opcode) {
463 default: // There was an error, this shouldn't happen.
464 if (Result == 0)
465 error("Illegal instruction read!");
466 break;
467 case Instruction::VAArg:
468 if (Oprnds.size() != 2)
469 error("Invalid VAArg instruction!");
470 Result = new VAArgInst(getValue(iType, Oprnds[0]),
Reid Spencerd798a512006-11-14 04:47:22 +0000471 getType(Oprnds[1]));
Reid Spencer1628cec2006-10-26 06:15:43 +0000472 break;
473 case Instruction::ExtractElement: {
474 if (Oprnds.size() != 2)
475 error("Invalid extractelement instruction!");
476 Value *V1 = getValue(iType, Oprnds[0]);
Reid Spencera54b7cb2007-01-12 07:05:14 +0000477 Value *V2 = getValue(Int32TySlot, Oprnds[1]);
Chris Lattner59fecec2006-04-08 04:09:19 +0000478
Reid Spencer1628cec2006-10-26 06:15:43 +0000479 if (!ExtractElementInst::isValidOperands(V1, V2))
480 error("Invalid extractelement instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000481
Reid Spencer1628cec2006-10-26 06:15:43 +0000482 Result = new ExtractElementInst(V1, V2);
483 break;
Chris Lattnera65371e2006-05-26 18:42:34 +0000484 }
Reid Spencer1628cec2006-10-26 06:15:43 +0000485 case Instruction::InsertElement: {
Reid Spencerac9dcb92007-02-15 03:39:18 +0000486 const VectorType *VectorTy = dyn_cast<VectorType>(InstTy);
487 if (!VectorTy || Oprnds.size() != 3)
Reid Spencer1628cec2006-10-26 06:15:43 +0000488 error("Invalid insertelement instruction!");
489
490 Value *V1 = getValue(iType, Oprnds[0]);
Reid Spencerac9dcb92007-02-15 03:39:18 +0000491 Value *V2 = getValue(getTypeSlot(VectorTy->getElementType()),Oprnds[1]);
Reid Spencera54b7cb2007-01-12 07:05:14 +0000492 Value *V3 = getValue(Int32TySlot, Oprnds[2]);
Reid Spencer1628cec2006-10-26 06:15:43 +0000493
494 if (!InsertElementInst::isValidOperands(V1, V2, V3))
495 error("Invalid insertelement instruction!");
496 Result = new InsertElementInst(V1, V2, V3);
497 break;
498 }
499 case Instruction::ShuffleVector: {
Reid Spencerac9dcb92007-02-15 03:39:18 +0000500 const VectorType *VectorTy = dyn_cast<VectorType>(InstTy);
501 if (!VectorTy || Oprnds.size() != 3)
Reid Spencer1628cec2006-10-26 06:15:43 +0000502 error("Invalid shufflevector instruction!");
503 Value *V1 = getValue(iType, Oprnds[0]);
504 Value *V2 = getValue(iType, Oprnds[1]);
Reid Spencer9d6565a2007-02-15 02:26:10 +0000505 const VectorType *EltTy =
Reid Spencerac9dcb92007-02-15 03:39:18 +0000506 VectorType::get(Type::Int32Ty, VectorTy->getNumElements());
Reid Spencer1628cec2006-10-26 06:15:43 +0000507 Value *V3 = getValue(getTypeSlot(EltTy), Oprnds[2]);
508 if (!ShuffleVectorInst::isValidOperands(V1, V2, V3))
509 error("Invalid shufflevector instruction!");
510 Result = new ShuffleVectorInst(V1, V2, V3);
511 break;
512 }
Reid Spencer3da59db2006-11-27 01:05:10 +0000513 case Instruction::Trunc:
514 if (Oprnds.size() != 2)
515 error("Invalid cast instruction!");
516 Result = new TruncInst(getValue(iType, Oprnds[0]),
517 getType(Oprnds[1]));
518 break;
519 case Instruction::ZExt:
520 if (Oprnds.size() != 2)
521 error("Invalid cast instruction!");
522 Result = new ZExtInst(getValue(iType, Oprnds[0]),
523 getType(Oprnds[1]));
524 break;
525 case Instruction::SExt:
Reid Spencer1628cec2006-10-26 06:15:43 +0000526 if (Oprnds.size() != 2)
527 error("Invalid Cast instruction!");
Reid Spencer3da59db2006-11-27 01:05:10 +0000528 Result = new SExtInst(getValue(iType, Oprnds[0]),
Reid Spencerd798a512006-11-14 04:47:22 +0000529 getType(Oprnds[1]));
Reid Spencer1628cec2006-10-26 06:15:43 +0000530 break;
Reid Spencer3da59db2006-11-27 01:05:10 +0000531 case Instruction::FPTrunc:
532 if (Oprnds.size() != 2)
533 error("Invalid cast instruction!");
534 Result = new FPTruncInst(getValue(iType, Oprnds[0]),
535 getType(Oprnds[1]));
536 break;
537 case Instruction::FPExt:
538 if (Oprnds.size() != 2)
539 error("Invalid cast instruction!");
540 Result = new FPExtInst(getValue(iType, Oprnds[0]),
541 getType(Oprnds[1]));
542 break;
543 case Instruction::UIToFP:
544 if (Oprnds.size() != 2)
545 error("Invalid cast instruction!");
546 Result = new UIToFPInst(getValue(iType, Oprnds[0]),
547 getType(Oprnds[1]));
548 break;
549 case Instruction::SIToFP:
550 if (Oprnds.size() != 2)
551 error("Invalid cast instruction!");
552 Result = new SIToFPInst(getValue(iType, Oprnds[0]),
553 getType(Oprnds[1]));
554 break;
555 case Instruction::FPToUI:
556 if (Oprnds.size() != 2)
557 error("Invalid cast instruction!");
558 Result = new FPToUIInst(getValue(iType, Oprnds[0]),
559 getType(Oprnds[1]));
560 break;
561 case Instruction::FPToSI:
562 if (Oprnds.size() != 2)
563 error("Invalid cast instruction!");
564 Result = new FPToSIInst(getValue(iType, Oprnds[0]),
565 getType(Oprnds[1]));
566 break;
567 case Instruction::IntToPtr:
568 if (Oprnds.size() != 2)
569 error("Invalid cast instruction!");
570 Result = new IntToPtrInst(getValue(iType, Oprnds[0]),
571 getType(Oprnds[1]));
572 break;
573 case Instruction::PtrToInt:
574 if (Oprnds.size() != 2)
575 error("Invalid cast instruction!");
576 Result = new PtrToIntInst(getValue(iType, Oprnds[0]),
577 getType(Oprnds[1]));
578 break;
579 case Instruction::BitCast:
580 if (Oprnds.size() != 2)
581 error("Invalid cast instruction!");
582 Result = new BitCastInst(getValue(iType, Oprnds[0]),
583 getType(Oprnds[1]));
584 break;
Reid Spencer1628cec2006-10-26 06:15:43 +0000585 case Instruction::Select:
586 if (Oprnds.size() != 3)
587 error("Invalid Select instruction!");
Reid Spencera54b7cb2007-01-12 07:05:14 +0000588 Result = new SelectInst(getValue(BoolTySlot, Oprnds[0]),
Reid Spencer1628cec2006-10-26 06:15:43 +0000589 getValue(iType, Oprnds[1]),
590 getValue(iType, Oprnds[2]));
591 break;
592 case Instruction::PHI: {
593 if (Oprnds.size() == 0 || (Oprnds.size() & 1))
594 error("Invalid phi node encountered!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000595
Reid Spencer1628cec2006-10-26 06:15:43 +0000596 PHINode *PN = new PHINode(InstTy);
597 PN->reserveOperandSpace(Oprnds.size());
598 for (unsigned i = 0, e = Oprnds.size(); i != e; i += 2)
599 PN->addIncoming(
600 getValue(iType, Oprnds[i]), getBasicBlock(Oprnds[i+1]));
601 Result = PN;
602 break;
603 }
Reid Spencerc8dab492006-12-03 06:28:54 +0000604 case Instruction::ICmp:
605 case Instruction::FCmp:
Reid Spencer9f132762006-12-03 17:17:02 +0000606 if (Oprnds.size() != 3)
607 error("Cmp instructions requires 3 operands");
Reid Spencerc8dab492006-12-03 06:28:54 +0000608 // These instructions encode the comparison predicate as the 3rd operand.
609 Result = CmpInst::create(Instruction::OtherOps(Opcode),
610 static_cast<unsigned short>(Oprnds[2]),
611 getValue(iType, Oprnds[0]), getValue(iType, Oprnds[1]));
612 break;
Reid Spencer1628cec2006-10-26 06:15:43 +0000613 case Instruction::Ret:
614 if (Oprnds.size() == 0)
615 Result = new ReturnInst();
616 else if (Oprnds.size() == 1)
617 Result = new ReturnInst(getValue(iType, Oprnds[0]));
618 else
619 error("Unrecognized instruction!");
620 break;
621
622 case Instruction::Br:
623 if (Oprnds.size() == 1)
624 Result = new BranchInst(getBasicBlock(Oprnds[0]));
625 else if (Oprnds.size() == 3)
626 Result = new BranchInst(getBasicBlock(Oprnds[0]),
Reid Spencera54b7cb2007-01-12 07:05:14 +0000627 getBasicBlock(Oprnds[1]), getValue(BoolTySlot, Oprnds[2]));
Reid Spencer1628cec2006-10-26 06:15:43 +0000628 else
629 error("Invalid number of operands for a 'br' instruction!");
630 break;
631 case Instruction::Switch: {
632 if (Oprnds.size() & 1)
633 error("Switch statement with odd number of arguments!");
634
635 SwitchInst *I = new SwitchInst(getValue(iType, Oprnds[0]),
636 getBasicBlock(Oprnds[1]),
637 Oprnds.size()/2-1);
638 for (unsigned i = 2, e = Oprnds.size(); i != e; i += 2)
639 I->addCase(cast<ConstantInt>(getValue(iType, Oprnds[i])),
640 getBasicBlock(Oprnds[i+1]));
641 Result = I;
642 break;
643 }
644 case 58: // Call with extra operand for calling conv
645 case 59: // tail call, Fast CC
646 case 60: // normal call, Fast CC
647 case 61: // tail call, C Calling Conv
648 case Instruction::Call: { // Normal Call, C Calling Convention
649 if (Oprnds.size() == 0)
650 error("Invalid call instruction encountered!");
Reid Spencer1628cec2006-10-26 06:15:43 +0000651 Value *F = getValue(iType, Oprnds[0]);
652
653 unsigned CallingConv = CallingConv::C;
654 bool isTailCall = false;
655
656 if (Opcode == 61 || Opcode == 59)
657 isTailCall = true;
658
659 if (Opcode == 58) {
660 isTailCall = Oprnds.back() & 1;
661 CallingConv = Oprnds.back() >> 1;
662 Oprnds.pop_back();
663 } else if (Opcode == 59 || Opcode == 60) {
664 CallingConv = CallingConv::Fast;
665 }
666
667 // Check to make sure we have a pointer to function type
668 const PointerType *PTy = dyn_cast<PointerType>(F->getType());
669 if (PTy == 0) error("Call to non function pointer value!");
670 const FunctionType *FTy = dyn_cast<FunctionType>(PTy->getElementType());
671 if (FTy == 0) error("Call to non function pointer value!");
672
Chris Lattnerd0e44c22007-02-13 06:30:42 +0000673 SmallVector<Value *, 8> Params;
Reid Spencer1628cec2006-10-26 06:15:43 +0000674 if (!FTy->isVarArg()) {
675 FunctionType::param_iterator It = FTy->param_begin();
676
677 for (unsigned i = 1, e = Oprnds.size(); i != e; ++i) {
678 if (It == FTy->param_end())
679 error("Invalid call instruction!");
680 Params.push_back(getValue(getTypeSlot(*It++), Oprnds[i]));
681 }
682 if (It != FTy->param_end())
Reid Spencer24399722004-07-09 22:21:33 +0000683 error("Invalid call instruction!");
Reid Spencer1628cec2006-10-26 06:15:43 +0000684 } else {
685 Oprnds.erase(Oprnds.begin(), Oprnds.begin()+1);
686
687 unsigned FirstVariableOperand;
688 if (Oprnds.size() < FTy->getNumParams())
689 error("Call instruction missing operands!");
690
691 // Read all of the fixed arguments
692 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
693 Params.push_back(
694 getValue(getTypeSlot(FTy->getParamType(i)),Oprnds[i]));
695
696 FirstVariableOperand = FTy->getNumParams();
697
698 if ((Oprnds.size()-FirstVariableOperand) & 1)
699 error("Invalid call instruction!"); // Must be pairs of type/value
700
701 for (unsigned i = FirstVariableOperand, e = Oprnds.size();
702 i != e; i += 2)
703 Params.push_back(getValue(Oprnds[i], Oprnds[i+1]));
Reid Spencer060d25d2004-06-29 23:29:38 +0000704 }
Reid Spencer060d25d2004-06-29 23:29:38 +0000705
Chris Lattnere4339192007-02-13 01:53:54 +0000706 Result = new CallInst(F, &Params[0], Params.size());
Reid Spencer1628cec2006-10-26 06:15:43 +0000707 if (isTailCall) cast<CallInst>(Result)->setTailCall();
708 if (CallingConv) cast<CallInst>(Result)->setCallingConv(CallingConv);
709 break;
Reid Spencer060d25d2004-06-29 23:29:38 +0000710 }
Reid Spencer1628cec2006-10-26 06:15:43 +0000711 case Instruction::Invoke: { // Invoke C CC
712 if (Oprnds.size() < 3)
713 error("Invalid invoke instruction!");
714 Value *F = getValue(iType, Oprnds[0]);
Reid Spencer060d25d2004-06-29 23:29:38 +0000715
Reid Spencer1628cec2006-10-26 06:15:43 +0000716 // Check to make sure we have a pointer to function type
717 const PointerType *PTy = dyn_cast<PointerType>(F->getType());
718 if (PTy == 0)
719 error("Invoke to non function pointer value!");
720 const FunctionType *FTy = dyn_cast<FunctionType>(PTy->getElementType());
721 if (FTy == 0)
722 error("Invoke to non function pointer value!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000723
Chris Lattnerd0e44c22007-02-13 06:30:42 +0000724 SmallVector<Value *, 8> Params;
Reid Spencer1628cec2006-10-26 06:15:43 +0000725 BasicBlock *Normal, *Except;
Reid Spencer3da59db2006-11-27 01:05:10 +0000726 unsigned CallingConv = Oprnds.back();
727 Oprnds.pop_back();
Chris Lattnerdee199f2005-05-06 22:34:01 +0000728
Reid Spencer1628cec2006-10-26 06:15:43 +0000729 if (!FTy->isVarArg()) {
730 Normal = getBasicBlock(Oprnds[1]);
731 Except = getBasicBlock(Oprnds[2]);
Reid Spencer060d25d2004-06-29 23:29:38 +0000732
Reid Spencer1628cec2006-10-26 06:15:43 +0000733 FunctionType::param_iterator It = FTy->param_begin();
734 for (unsigned i = 3, e = Oprnds.size(); i != e; ++i) {
735 if (It == FTy->param_end())
736 error("Invalid invoke instruction!");
737 Params.push_back(getValue(getTypeSlot(*It++), Oprnds[i]));
738 }
739 if (It != FTy->param_end())
Reid Spencer24399722004-07-09 22:21:33 +0000740 error("Invalid invoke instruction!");
Reid Spencer1628cec2006-10-26 06:15:43 +0000741 } else {
742 Oprnds.erase(Oprnds.begin(), Oprnds.begin()+1);
743
744 Normal = getBasicBlock(Oprnds[0]);
745 Except = getBasicBlock(Oprnds[1]);
746
747 unsigned FirstVariableArgument = FTy->getNumParams()+2;
748 for (unsigned i = 2; i != FirstVariableArgument; ++i)
749 Params.push_back(getValue(getTypeSlot(FTy->getParamType(i-2)),
750 Oprnds[i]));
751
752 // Must be type/value pairs. If not, error out.
753 if (Oprnds.size()-FirstVariableArgument & 1)
754 error("Invalid invoke instruction!");
755
756 for (unsigned i = FirstVariableArgument; i < Oprnds.size(); i += 2)
757 Params.push_back(getValue(Oprnds[i], Oprnds[i+1]));
Reid Spencer060d25d2004-06-29 23:29:38 +0000758 }
Reid Spencer060d25d2004-06-29 23:29:38 +0000759
Chris Lattnere4339192007-02-13 01:53:54 +0000760 Result = new InvokeInst(F, Normal, Except, &Params[0], Params.size());
Reid Spencer1628cec2006-10-26 06:15:43 +0000761 if (CallingConv) cast<InvokeInst>(Result)->setCallingConv(CallingConv);
762 break;
Reid Spencer060d25d2004-06-29 23:29:38 +0000763 }
Reid Spencer1628cec2006-10-26 06:15:43 +0000764 case Instruction::Malloc: {
765 unsigned Align = 0;
766 if (Oprnds.size() == 2)
767 Align = (1 << Oprnds[1]) >> 1;
768 else if (Oprnds.size() > 2)
769 error("Invalid malloc instruction!");
770 if (!isa<PointerType>(InstTy))
771 error("Invalid malloc instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000772
Reid Spencer1628cec2006-10-26 06:15:43 +0000773 Result = new MallocInst(cast<PointerType>(InstTy)->getElementType(),
Reid Spencera54b7cb2007-01-12 07:05:14 +0000774 getValue(Int32TySlot, Oprnds[0]), Align);
Reid Spencer1628cec2006-10-26 06:15:43 +0000775 break;
776 }
777 case Instruction::Alloca: {
778 unsigned Align = 0;
779 if (Oprnds.size() == 2)
780 Align = (1 << Oprnds[1]) >> 1;
781 else if (Oprnds.size() > 2)
782 error("Invalid alloca instruction!");
783 if (!isa<PointerType>(InstTy))
784 error("Invalid alloca instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000785
Reid Spencer1628cec2006-10-26 06:15:43 +0000786 Result = new AllocaInst(cast<PointerType>(InstTy)->getElementType(),
Reid Spencera54b7cb2007-01-12 07:05:14 +0000787 getValue(Int32TySlot, Oprnds[0]), Align);
Reid Spencer1628cec2006-10-26 06:15:43 +0000788 break;
789 }
790 case Instruction::Free:
791 if (!isa<PointerType>(InstTy))
792 error("Invalid free instruction!");
793 Result = new FreeInst(getValue(iType, Oprnds[0]));
794 break;
795 case Instruction::GetElementPtr: {
796 if (Oprnds.size() == 0 || !isa<PointerType>(InstTy))
Misha Brukman8a96c532005-04-21 21:44:41 +0000797 error("Invalid getelementptr instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000798
Chris Lattner4c3d3a92007-01-31 19:56:15 +0000799 SmallVector<Value*, 8> Idx;
Reid Spencer1628cec2006-10-26 06:15:43 +0000800
801 const Type *NextTy = InstTy;
802 for (unsigned i = 1, e = Oprnds.size(); i != e; ++i) {
803 const CompositeType *TopTy = dyn_cast_or_null<CompositeType>(NextTy);
804 if (!TopTy)
805 error("Invalid getelementptr instruction!");
806
807 unsigned ValIdx = Oprnds[i];
808 unsigned IdxTy = 0;
Reid Spencerd798a512006-11-14 04:47:22 +0000809 // Struct indices are always uints, sequential type indices can be
810 // any of the 32 or 64-bit integer types. The actual choice of
Reid Spencer88cfda22006-12-31 05:44:24 +0000811 // type is encoded in the low bit of the slot number.
Reid Spencerd798a512006-11-14 04:47:22 +0000812 if (isa<StructType>(TopTy))
Reid Spencera54b7cb2007-01-12 07:05:14 +0000813 IdxTy = Int32TySlot;
Reid Spencerd798a512006-11-14 04:47:22 +0000814 else {
Reid Spencer88cfda22006-12-31 05:44:24 +0000815 switch (ValIdx & 1) {
Reid Spencerd798a512006-11-14 04:47:22 +0000816 default:
Reid Spencera54b7cb2007-01-12 07:05:14 +0000817 case 0: IdxTy = Int32TySlot; break;
818 case 1: IdxTy = Int64TySlot; break;
Reid Spencer060d25d2004-06-29 23:29:38 +0000819 }
Reid Spencer88cfda22006-12-31 05:44:24 +0000820 ValIdx >>= 1;
Reid Spencer060d25d2004-06-29 23:29:38 +0000821 }
Reid Spencer1628cec2006-10-26 06:15:43 +0000822 Idx.push_back(getValue(IdxTy, ValIdx));
Chris Lattner4c3d3a92007-01-31 19:56:15 +0000823 NextTy = GetElementPtrInst::getIndexedType(InstTy, &Idx[0], Idx.size(),
824 true);
Reid Spencer060d25d2004-06-29 23:29:38 +0000825 }
826
Chris Lattner4c3d3a92007-01-31 19:56:15 +0000827 Result = new GetElementPtrInst(getValue(iType, Oprnds[0]),
828 &Idx[0], Idx.size());
Reid Spencer1628cec2006-10-26 06:15:43 +0000829 break;
Reid Spencer060d25d2004-06-29 23:29:38 +0000830 }
Reid Spencer1628cec2006-10-26 06:15:43 +0000831 case 62: // volatile load
832 case Instruction::Load:
833 if (Oprnds.size() != 1 || !isa<PointerType>(InstTy))
834 error("Invalid load instruction!");
835 Result = new LoadInst(getValue(iType, Oprnds[0]), "", Opcode == 62);
836 break;
837 case 63: // volatile store
838 case Instruction::Store: {
839 if (!isa<PointerType>(InstTy) || Oprnds.size() != 2)
840 error("Invalid store instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000841
Reid Spencer1628cec2006-10-26 06:15:43 +0000842 Value *Ptr = getValue(iType, Oprnds[1]);
843 const Type *ValTy = cast<PointerType>(Ptr->getType())->getElementType();
844 Result = new StoreInst(getValue(getTypeSlot(ValTy), Oprnds[0]), Ptr,
845 Opcode == 63);
846 break;
847 }
848 case Instruction::Unwind:
849 if (Oprnds.size() != 0) error("Invalid unwind instruction!");
850 Result = new UnwindInst();
851 break;
852 case Instruction::Unreachable:
853 if (Oprnds.size() != 0) error("Invalid unreachable instruction!");
854 Result = new UnreachableInst();
855 break;
856 } // end switch(Opcode)
Reid Spencer3795ad12006-12-03 05:47:10 +0000857 } // end if !Result
Reid Spencer060d25d2004-06-29 23:29:38 +0000858
Reid Spencere1e96c02006-01-19 07:02:16 +0000859 BB->getInstList().push_back(Result);
860
Reid Spencer060d25d2004-06-29 23:29:38 +0000861 unsigned TypeSlot;
862 if (Result->getType() == InstTy)
863 TypeSlot = iType;
864 else
865 TypeSlot = getTypeSlot(Result->getType());
866
Reid Spenceref9b9a72007-02-05 20:47:22 +0000867 // We have enough info to inform the handler now.
868 if (Handler)
Chris Lattner63cf59e2007-02-07 05:08:39 +0000869 Handler->handleInstruction(Opcode, InstTy, &Oprnds[0], Oprnds.size(),
870 Result, At-SaveAt);
Reid Spenceref9b9a72007-02-05 20:47:22 +0000871
Reid Spencer060d25d2004-06-29 23:29:38 +0000872 insertValue(Result, TypeSlot, FunctionValues);
Reid Spencer060d25d2004-06-29 23:29:38 +0000873}
874
Reid Spencer04cde2c2004-07-04 11:33:49 +0000875/// Get a particular numbered basic block, which might be a forward reference.
Reid Spencerd798a512006-11-14 04:47:22 +0000876/// This works together with ParseInstructionList to handle these forward
877/// references in a clean manner. This function is used when constructing
878/// phi, br, switch, and other instructions that reference basic blocks.
879/// Blocks are numbered sequentially as they appear in the function.
Reid Spencer060d25d2004-06-29 23:29:38 +0000880BasicBlock *BytecodeReader::getBasicBlock(unsigned ID) {
Chris Lattner4ee8ef22003-10-08 22:52:54 +0000881 // Make sure there is room in the table...
882 if (ParsedBasicBlocks.size() <= ID) ParsedBasicBlocks.resize(ID+1);
883
Reid Spencerd798a512006-11-14 04:47:22 +0000884 // First check to see if this is a backwards reference, i.e. this block
885 // has already been created, or if the forward reference has already
Chris Lattner4ee8ef22003-10-08 22:52:54 +0000886 // been created.
887 if (ParsedBasicBlocks[ID])
888 return ParsedBasicBlocks[ID];
889
890 // Otherwise, the basic block has not yet been created. Do so and add it to
891 // the ParsedBasicBlocks list.
892 return ParsedBasicBlocks[ID] = new BasicBlock();
893}
894
Reid Spencer04cde2c2004-07-04 11:33:49 +0000895/// Parse all of the BasicBlock's & Instruction's in the body of a function.
Misha Brukman8a96c532005-04-21 21:44:41 +0000896/// In post 1.0 bytecode files, we no longer emit basic block individually,
Reid Spencer04cde2c2004-07-04 11:33:49 +0000897/// in order to avoid per-basic-block overhead.
Reid Spencerd798a512006-11-14 04:47:22 +0000898/// @returns the number of basic blocks encountered.
Reid Spencer060d25d2004-06-29 23:29:38 +0000899unsigned BytecodeReader::ParseInstructionList(Function* F) {
Chris Lattner8d1dbd22003-12-01 07:05:31 +0000900 unsigned BlockNo = 0;
Chris Lattner63cf59e2007-02-07 05:08:39 +0000901 SmallVector<unsigned, 8> Args;
Chris Lattner8d1dbd22003-12-01 07:05:31 +0000902
Reid Spencer46b002c2004-07-11 17:28:43 +0000903 while (moreInBlock()) {
904 if (Handler) Handler->handleBasicBlockBegin(BlockNo);
Chris Lattner8d1dbd22003-12-01 07:05:31 +0000905 BasicBlock *BB;
906 if (ParsedBasicBlocks.size() == BlockNo)
907 ParsedBasicBlocks.push_back(BB = new BasicBlock());
908 else if (ParsedBasicBlocks[BlockNo] == 0)
909 BB = ParsedBasicBlocks[BlockNo] = new BasicBlock();
910 else
911 BB = ParsedBasicBlocks[BlockNo];
912 ++BlockNo;
913 F->getBasicBlockList().push_back(BB);
914
915 // Read instructions into this basic block until we get to a terminator
Reid Spencer46b002c2004-07-11 17:28:43 +0000916 while (moreInBlock() && !BB->getTerminator())
Reid Spencer060d25d2004-06-29 23:29:38 +0000917 ParseInstruction(Args, BB);
Chris Lattner8d1dbd22003-12-01 07:05:31 +0000918
919 if (!BB->getTerminator())
Reid Spencer24399722004-07-09 22:21:33 +0000920 error("Non-terminated basic block found!");
Reid Spencer5c15fe52004-07-05 00:57:50 +0000921
Reid Spencer46b002c2004-07-11 17:28:43 +0000922 if (Handler) Handler->handleBasicBlockEnd(BlockNo-1);
Chris Lattner8d1dbd22003-12-01 07:05:31 +0000923 }
924
925 return BlockNo;
926}
927
Reid Spencer78d033e2007-01-06 07:24:44 +0000928/// Parse a type symbol table.
929void BytecodeReader::ParseTypeSymbolTable(TypeSymbolTable *TST) {
930 // Type Symtab block header: [num entries]
931 unsigned NumEntries = read_vbr_uint();
932 for (unsigned i = 0; i < NumEntries; ++i) {
933 // Symtab entry: [type slot #][name]
934 unsigned slot = read_vbr_uint();
935 std::string Name = read_str();
936 const Type* T = getType(slot);
937 TST->insert(Name, T);
938 }
939}
940
941/// Parse a value symbol table. This works for both module level and function
Reid Spencer04cde2c2004-07-04 11:33:49 +0000942/// level symbol tables. For function level symbol tables, the CurrentFunction
943/// parameter must be non-zero and the ST parameter must correspond to
944/// CurrentFunction's symbol table. For Module level symbol tables, the
945/// CurrentFunction argument must be zero.
Reid Spencer78d033e2007-01-06 07:24:44 +0000946void BytecodeReader::ParseValueSymbolTable(Function *CurrentFunction,
Reid Spenceref9b9a72007-02-05 20:47:22 +0000947 ValueSymbolTable *VST) {
Reid Spencer78d033e2007-01-06 07:24:44 +0000948
Reid Spenceref9b9a72007-02-05 20:47:22 +0000949 if (Handler) Handler->handleValueSymbolTableBegin(CurrentFunction,VST);
Reid Spencer060d25d2004-06-29 23:29:38 +0000950
Chris Lattner39cacce2003-10-10 05:43:47 +0000951 // Allow efficient basic block lookup by number.
Chris Lattner63cf59e2007-02-07 05:08:39 +0000952 SmallVector<BasicBlock*, 32> BBMap;
Chris Lattner39cacce2003-10-10 05:43:47 +0000953 if (CurrentFunction)
954 for (Function::iterator I = CurrentFunction->begin(),
955 E = CurrentFunction->end(); I != E; ++I)
956 BBMap.push_back(I);
957
Chris Lattnerdd8cec52007-02-12 18:53:43 +0000958 SmallVector<char, 32> NameStr;
959
Reid Spencer46b002c2004-07-11 17:28:43 +0000960 while (moreInBlock()) {
Chris Lattner00950542001-06-06 20:29:01 +0000961 // Symtab block header: [num entries][type id number]
Reid Spencer060d25d2004-06-29 23:29:38 +0000962 unsigned NumEntries = read_vbr_uint();
Reid Spencerd798a512006-11-14 04:47:22 +0000963 unsigned Typ = read_vbr_uint();
Chris Lattner1d670cc2001-09-07 16:37:43 +0000964
Chris Lattner7dc3a2e2003-10-13 14:57:53 +0000965 for (unsigned i = 0; i != NumEntries; ++i) {
Chris Lattner00950542001-06-06 20:29:01 +0000966 // Symtab entry: [def slot #][name]
Reid Spencer060d25d2004-06-29 23:29:38 +0000967 unsigned slot = read_vbr_uint();
Chris Lattnerdd8cec52007-02-12 18:53:43 +0000968 read_str(NameStr);
Reid Spencerd798a512006-11-14 04:47:22 +0000969 Value *V = 0;
Reid Spencera54b7cb2007-01-12 07:05:14 +0000970 if (Typ == LabelTySlot) {
Chris Lattnerdd8cec52007-02-12 18:53:43 +0000971 V = (slot < BBMap.size()) ? BBMap[slot] : 0;
Chris Lattner39cacce2003-10-10 05:43:47 +0000972 } else {
Chris Lattnerdd8cec52007-02-12 18:53:43 +0000973 V = getValue(Typ, slot, false); // Find mapping.
Chris Lattner39cacce2003-10-10 05:43:47 +0000974 }
Chris Lattnerdd8cec52007-02-12 18:53:43 +0000975 if (Handler) Handler->handleSymbolTableValue(Typ, slot,
976 &NameStr[0], NameStr.size());
Reid Spencerd798a512006-11-14 04:47:22 +0000977 if (V == 0)
Chris Lattnerdd8cec52007-02-12 18:53:43 +0000978 error("Failed value look-up for name '" +
979 std::string(NameStr.begin(), NameStr.end()) + "', type #" +
Reid Spenceref9b9a72007-02-05 20:47:22 +0000980 utostr(Typ) + " slot #" + utostr(slot));
Chris Lattnerdd8cec52007-02-12 18:53:43 +0000981 V->setName(&NameStr[0], NameStr.size());
982
983 NameStr.clear();
Chris Lattner00950542001-06-06 20:29:01 +0000984 }
985 }
Reid Spencer060d25d2004-06-29 23:29:38 +0000986 checkPastBlockEnd("Symbol Table");
Reid Spenceref9b9a72007-02-05 20:47:22 +0000987 if (Handler) Handler->handleValueSymbolTableEnd();
Chris Lattner00950542001-06-06 20:29:01 +0000988}
989
Reid Spencer46b002c2004-07-11 17:28:43 +0000990// Parse a single type. The typeid is read in first. If its a primitive type
991// then nothing else needs to be read, we know how to instantiate it. If its
Misha Brukman8a96c532005-04-21 21:44:41 +0000992// a derived type, then additional data is read to fill out the type
Reid Spencer46b002c2004-07-11 17:28:43 +0000993// definition.
994const Type *BytecodeReader::ParseType() {
Reid Spencerd798a512006-11-14 04:47:22 +0000995 unsigned PrimType = read_vbr_uint();
Reid Spencer060d25d2004-06-29 23:29:38 +0000996 const Type *Result = 0;
997 if ((Result = Type::getPrimitiveType((Type::TypeID)PrimType)))
998 return Result;
Misha Brukman8a96c532005-04-21 21:44:41 +0000999
Reid Spencer060d25d2004-06-29 23:29:38 +00001000 switch (PrimType) {
Reid Spencera54b7cb2007-01-12 07:05:14 +00001001 case Type::IntegerTyID: {
1002 unsigned NumBits = read_vbr_uint();
1003 Result = IntegerType::get(NumBits);
1004 break;
1005 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001006 case Type::FunctionTyID: {
Reid Spencerd798a512006-11-14 04:47:22 +00001007 const Type *RetType = readType();
Reid Spencer88cfda22006-12-31 05:44:24 +00001008 unsigned RetAttr = read_vbr_uint();
Reid Spencer060d25d2004-06-29 23:29:38 +00001009
1010 unsigned NumParams = read_vbr_uint();
1011
1012 std::vector<const Type*> Params;
Reid Spencer88cfda22006-12-31 05:44:24 +00001013 std::vector<FunctionType::ParameterAttributes> Attrs;
1014 Attrs.push_back(FunctionType::ParameterAttributes(RetAttr));
1015 while (NumParams--) {
Reid Spencerd798a512006-11-14 04:47:22 +00001016 Params.push_back(readType());
Reid Spencer88cfda22006-12-31 05:44:24 +00001017 if (Params.back() != Type::VoidTy)
1018 Attrs.push_back(FunctionType::ParameterAttributes(read_vbr_uint()));
1019 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001020
1021 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1022 if (isVarArg) Params.pop_back();
1023
Reid Spencer88cfda22006-12-31 05:44:24 +00001024 Result = FunctionType::get(RetType, Params, isVarArg, Attrs);
Reid Spencer060d25d2004-06-29 23:29:38 +00001025 break;
1026 }
1027 case Type::ArrayTyID: {
Reid Spencerd798a512006-11-14 04:47:22 +00001028 const Type *ElementType = readType();
Reid Spencer060d25d2004-06-29 23:29:38 +00001029 unsigned NumElements = read_vbr_uint();
Reid Spencer060d25d2004-06-29 23:29:38 +00001030 Result = ArrayType::get(ElementType, NumElements);
1031 break;
1032 }
Reid Spencer9d6565a2007-02-15 02:26:10 +00001033 case Type::VectorTyID: {
Reid Spencerd798a512006-11-14 04:47:22 +00001034 const Type *ElementType = readType();
Brian Gaeke715c90b2004-08-20 06:00:58 +00001035 unsigned NumElements = read_vbr_uint();
Reid Spencer9d6565a2007-02-15 02:26:10 +00001036 Result = VectorType::get(ElementType, NumElements);
Brian Gaeke715c90b2004-08-20 06:00:58 +00001037 break;
1038 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001039 case Type::StructTyID: {
1040 std::vector<const Type*> Elements;
Reid Spencerd798a512006-11-14 04:47:22 +00001041 unsigned Typ = read_vbr_uint();
Reid Spencer060d25d2004-06-29 23:29:38 +00001042 while (Typ) { // List is terminated by void/0 typeid
1043 Elements.push_back(getType(Typ));
Reid Spencerd798a512006-11-14 04:47:22 +00001044 Typ = read_vbr_uint();
Reid Spencer060d25d2004-06-29 23:29:38 +00001045 }
1046
Andrew Lenharth38ecbf12006-12-08 18:06:16 +00001047 Result = StructType::get(Elements, false);
1048 break;
1049 }
Reid Spencera54b7cb2007-01-12 07:05:14 +00001050 case Type::PackedStructTyID: {
Andrew Lenharth38ecbf12006-12-08 18:06:16 +00001051 std::vector<const Type*> Elements;
1052 unsigned Typ = read_vbr_uint();
1053 while (Typ) { // List is terminated by void/0 typeid
1054 Elements.push_back(getType(Typ));
1055 Typ = read_vbr_uint();
1056 }
1057
1058 Result = StructType::get(Elements, true);
Reid Spencer060d25d2004-06-29 23:29:38 +00001059 break;
1060 }
1061 case Type::PointerTyID: {
Reid Spencerd798a512006-11-14 04:47:22 +00001062 Result = PointerType::get(readType());
Reid Spencer060d25d2004-06-29 23:29:38 +00001063 break;
1064 }
1065
1066 case Type::OpaqueTyID: {
1067 Result = OpaqueType::get();
1068 break;
1069 }
1070
1071 default:
Reid Spencer24399722004-07-09 22:21:33 +00001072 error("Don't know how to deserialize primitive type " + utostr(PrimType));
Reid Spencer060d25d2004-06-29 23:29:38 +00001073 break;
1074 }
Reid Spencer46b002c2004-07-11 17:28:43 +00001075 if (Handler) Handler->handleType(Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001076 return Result;
1077}
1078
Reid Spencer5b472d92004-08-21 20:49:23 +00001079// ParseTypes - We have to use this weird code to handle recursive
Reid Spencer060d25d2004-06-29 23:29:38 +00001080// types. We know that recursive types will only reference the current slab of
1081// values in the type plane, but they can forward reference types before they
1082// have been read. For example, Type #0 might be '{ Ty#1 }' and Type #1 might
1083// be 'Ty#0*'. When reading Type #0, type number one doesn't exist. To fix
1084// this ugly problem, we pessimistically insert an opaque type for each type we
1085// are about to read. This means that forward references will resolve to
1086// something and when we reread the type later, we can replace the opaque type
1087// with a new resolved concrete type.
1088//
Reid Spencer46b002c2004-07-11 17:28:43 +00001089void BytecodeReader::ParseTypes(TypeListTy &Tab, unsigned NumEntries){
Reid Spencer060d25d2004-06-29 23:29:38 +00001090 assert(Tab.size() == 0 && "should not have read type constants in before!");
1091
1092 // Insert a bunch of opaque types to be resolved later...
1093 Tab.reserve(NumEntries);
1094 for (unsigned i = 0; i != NumEntries; ++i)
1095 Tab.push_back(OpaqueType::get());
1096
Misha Brukman8a96c532005-04-21 21:44:41 +00001097 if (Handler)
Reid Spencer5b472d92004-08-21 20:49:23 +00001098 Handler->handleTypeList(NumEntries);
1099
Chris Lattnereebac5f2005-10-03 21:26:53 +00001100 // If we are about to resolve types, make sure the type cache is clear.
1101 if (NumEntries)
1102 ModuleTypeIDCache.clear();
1103
Reid Spencer060d25d2004-06-29 23:29:38 +00001104 // Loop through reading all of the types. Forward types will make use of the
1105 // opaque types just inserted.
1106 //
1107 for (unsigned i = 0; i != NumEntries; ++i) {
Reid Spencer46b002c2004-07-11 17:28:43 +00001108 const Type* NewTy = ParseType();
Reid Spencer04cde2c2004-07-04 11:33:49 +00001109 const Type* OldTy = Tab[i].get();
Misha Brukman8a96c532005-04-21 21:44:41 +00001110 if (NewTy == 0)
Reid Spencer24399722004-07-09 22:21:33 +00001111 error("Couldn't parse type!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001112
Misha Brukman8a96c532005-04-21 21:44:41 +00001113 // Don't directly push the new type on the Tab. Instead we want to replace
Reid Spencer060d25d2004-06-29 23:29:38 +00001114 // the opaque type we previously inserted with the new concrete value. This
1115 // approach helps with forward references to types. The refinement from the
1116 // abstract (opaque) type to the new type causes all uses of the abstract
1117 // type to use the concrete type (NewTy). This will also cause the opaque
1118 // type to be deleted.
1119 cast<DerivedType>(const_cast<Type*>(OldTy))->refineAbstractTypeTo(NewTy);
1120
1121 // This should have replaced the old opaque type with the new type in the
1122 // value table... or with a preexisting type that was already in the system.
1123 // Let's just make sure it did.
1124 assert(Tab[i] != OldTy && "refineAbstractType didn't work!");
1125 }
1126}
1127
Reid Spencer04cde2c2004-07-04 11:33:49 +00001128/// Parse a single constant value
Chris Lattner3bc5a602006-01-25 23:08:15 +00001129Value *BytecodeReader::ParseConstantPoolValue(unsigned TypeID) {
Reid Spencer060d25d2004-06-29 23:29:38 +00001130 // We must check for a ConstantExpr before switching by type because
1131 // a ConstantExpr can be of any type, and has no explicit value.
Misha Brukman8a96c532005-04-21 21:44:41 +00001132 //
Reid Spencer060d25d2004-06-29 23:29:38 +00001133 // 0 if not expr; numArgs if is expr
1134 unsigned isExprNumArgs = read_vbr_uint();
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001135
Reid Spencer060d25d2004-06-29 23:29:38 +00001136 if (isExprNumArgs) {
Reid Spencerd798a512006-11-14 04:47:22 +00001137 // 'undef' is encoded with 'exprnumargs' == 1.
1138 if (isExprNumArgs == 1)
1139 return UndefValue::get(getType(TypeID));
Misha Brukman8a96c532005-04-21 21:44:41 +00001140
Reid Spencerd798a512006-11-14 04:47:22 +00001141 // Inline asm is encoded with exprnumargs == ~0U.
1142 if (isExprNumArgs == ~0U) {
1143 std::string AsmStr = read_str();
1144 std::string ConstraintStr = read_str();
1145 unsigned Flags = read_vbr_uint();
Chris Lattner3bc5a602006-01-25 23:08:15 +00001146
Reid Spencerd798a512006-11-14 04:47:22 +00001147 const PointerType *PTy = dyn_cast<PointerType>(getType(TypeID));
1148 const FunctionType *FTy =
1149 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
1150
1151 if (!FTy || !InlineAsm::Verify(FTy, ConstraintStr))
1152 error("Invalid constraints for inline asm");
1153 if (Flags & ~1U)
1154 error("Invalid flags for inline asm");
1155 bool HasSideEffects = Flags & 1;
1156 return InlineAsm::get(FTy, AsmStr, ConstraintStr, HasSideEffects);
Chris Lattner3bc5a602006-01-25 23:08:15 +00001157 }
Reid Spencerd798a512006-11-14 04:47:22 +00001158
1159 --isExprNumArgs;
Chris Lattner3bc5a602006-01-25 23:08:15 +00001160
Reid Spencer060d25d2004-06-29 23:29:38 +00001161 // FIXME: Encoding of constant exprs could be much more compact!
Chris Lattner670ccfe2007-02-07 05:15:28 +00001162 SmallVector<Constant*, 8> ArgVec;
Reid Spencer060d25d2004-06-29 23:29:38 +00001163 ArgVec.reserve(isExprNumArgs);
1164 unsigned Opcode = read_vbr_uint();
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001165
Reid Spencer060d25d2004-06-29 23:29:38 +00001166 // Read the slot number and types of each of the arguments
1167 for (unsigned i = 0; i != isExprNumArgs; ++i) {
1168 unsigned ArgValSlot = read_vbr_uint();
Reid Spencerd798a512006-11-14 04:47:22 +00001169 unsigned ArgTypeSlot = read_vbr_uint();
Misha Brukman8a96c532005-04-21 21:44:41 +00001170
Reid Spencer060d25d2004-06-29 23:29:38 +00001171 // Get the arg value from its slot if it exists, otherwise a placeholder
1172 ArgVec.push_back(getConstantValue(ArgTypeSlot, ArgValSlot));
1173 }
Misha Brukman8a96c532005-04-21 21:44:41 +00001174
Reid Spencer060d25d2004-06-29 23:29:38 +00001175 // Construct a ConstantExpr of the appropriate kind
1176 if (isExprNumArgs == 1) { // All one-operand expressions
Reid Spencer3da59db2006-11-27 01:05:10 +00001177 if (!Instruction::isCast(Opcode))
Chris Lattner02dce162004-12-04 05:28:27 +00001178 error("Only cast instruction has one argument for ConstantExpr");
Reid Spencer46b002c2004-07-11 17:28:43 +00001179
Reid Spencera77fa7e2006-12-11 23:20:20 +00001180 Constant *Result = ConstantExpr::getCast(Opcode, ArgVec[0],
1181 getType(TypeID));
Chris Lattner63cf59e2007-02-07 05:08:39 +00001182 if (Handler) Handler->handleConstantExpression(Opcode, &ArgVec[0],
1183 ArgVec.size(), Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001184 return Result;
1185 } else if (Opcode == Instruction::GetElementPtr) { // GetElementPtr
Chris Lattnere0135402007-01-31 04:43:46 +00001186 Constant *Result = ConstantExpr::getGetElementPtr(ArgVec[0], &ArgVec[1],
1187 ArgVec.size()-1);
Chris Lattner63cf59e2007-02-07 05:08:39 +00001188 if (Handler) Handler->handleConstantExpression(Opcode, &ArgVec[0],
1189 ArgVec.size(), Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001190 return Result;
1191 } else if (Opcode == Instruction::Select) {
Reid Spencer46b002c2004-07-11 17:28:43 +00001192 if (ArgVec.size() != 3)
1193 error("Select instruction must have three arguments.");
Misha Brukman8a96c532005-04-21 21:44:41 +00001194 Constant* Result = ConstantExpr::getSelect(ArgVec[0], ArgVec[1],
Reid Spencer04cde2c2004-07-04 11:33:49 +00001195 ArgVec[2]);
Chris Lattner63cf59e2007-02-07 05:08:39 +00001196 if (Handler) Handler->handleConstantExpression(Opcode, &ArgVec[0],
1197 ArgVec.size(), Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001198 return Result;
Robert Bocchinofee31b32006-01-10 19:04:39 +00001199 } else if (Opcode == Instruction::ExtractElement) {
Chris Lattner59fecec2006-04-08 04:09:19 +00001200 if (ArgVec.size() != 2 ||
1201 !ExtractElementInst::isValidOperands(ArgVec[0], ArgVec[1]))
1202 error("Invalid extractelement constand expr arguments");
Robert Bocchinofee31b32006-01-10 19:04:39 +00001203 Constant* Result = ConstantExpr::getExtractElement(ArgVec[0], ArgVec[1]);
Chris Lattner63cf59e2007-02-07 05:08:39 +00001204 if (Handler) Handler->handleConstantExpression(Opcode, &ArgVec[0],
1205 ArgVec.size(), Result);
Robert Bocchinofee31b32006-01-10 19:04:39 +00001206 return Result;
Robert Bocchinob1f240b2006-01-17 20:06:35 +00001207 } else if (Opcode == Instruction::InsertElement) {
Chris Lattner59fecec2006-04-08 04:09:19 +00001208 if (ArgVec.size() != 3 ||
1209 !InsertElementInst::isValidOperands(ArgVec[0], ArgVec[1], ArgVec[2]))
1210 error("Invalid insertelement constand expr arguments");
1211
1212 Constant *Result =
Robert Bocchinob1f240b2006-01-17 20:06:35 +00001213 ConstantExpr::getInsertElement(ArgVec[0], ArgVec[1], ArgVec[2]);
Chris Lattner63cf59e2007-02-07 05:08:39 +00001214 if (Handler) Handler->handleConstantExpression(Opcode, &ArgVec[0],
1215 ArgVec.size(), Result);
Robert Bocchinob1f240b2006-01-17 20:06:35 +00001216 return Result;
Chris Lattner30b44b62006-04-08 01:17:59 +00001217 } else if (Opcode == Instruction::ShuffleVector) {
1218 if (ArgVec.size() != 3 ||
1219 !ShuffleVectorInst::isValidOperands(ArgVec[0], ArgVec[1], ArgVec[2]))
Chris Lattner59fecec2006-04-08 04:09:19 +00001220 error("Invalid shufflevector constant expr arguments.");
Chris Lattner30b44b62006-04-08 01:17:59 +00001221 Constant *Result =
1222 ConstantExpr::getShuffleVector(ArgVec[0], ArgVec[1], ArgVec[2]);
Chris Lattner63cf59e2007-02-07 05:08:39 +00001223 if (Handler) Handler->handleConstantExpression(Opcode, &ArgVec[0],
1224 ArgVec.size(), Result);
Chris Lattner30b44b62006-04-08 01:17:59 +00001225 return Result;
Reid Spencer9f132762006-12-03 17:17:02 +00001226 } else if (Opcode == Instruction::ICmp) {
1227 if (ArgVec.size() != 2)
Reid Spencer595b4772006-12-04 05:23:49 +00001228 error("Invalid ICmp constant expr arguments.");
1229 unsigned predicate = read_vbr_uint();
1230 Constant *Result = ConstantExpr::getICmp(predicate, ArgVec[0], ArgVec[1]);
Chris Lattner63cf59e2007-02-07 05:08:39 +00001231 if (Handler) Handler->handleConstantExpression(Opcode, &ArgVec[0],
1232 ArgVec.size(), Result);
Reid Spencer595b4772006-12-04 05:23:49 +00001233 return Result;
Reid Spencer9f132762006-12-03 17:17:02 +00001234 } else if (Opcode == Instruction::FCmp) {
1235 if (ArgVec.size() != 2)
Reid Spencer595b4772006-12-04 05:23:49 +00001236 error("Invalid FCmp constant expr arguments.");
1237 unsigned predicate = read_vbr_uint();
1238 Constant *Result = ConstantExpr::getFCmp(predicate, ArgVec[0], ArgVec[1]);
Chris Lattner63cf59e2007-02-07 05:08:39 +00001239 if (Handler) Handler->handleConstantExpression(Opcode, &ArgVec[0],
1240 ArgVec.size(), Result);
Reid Spencer595b4772006-12-04 05:23:49 +00001241 return Result;
Reid Spencer060d25d2004-06-29 23:29:38 +00001242 } else { // All other 2-operand expressions
1243 Constant* Result = ConstantExpr::get(Opcode, ArgVec[0], ArgVec[1]);
Chris Lattner63cf59e2007-02-07 05:08:39 +00001244 if (Handler) Handler->handleConstantExpression(Opcode, &ArgVec[0],
1245 ArgVec.size(), Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001246 return Result;
1247 }
1248 }
Misha Brukman8a96c532005-04-21 21:44:41 +00001249
Reid Spencer060d25d2004-06-29 23:29:38 +00001250 // Ok, not an ConstantExpr. We now know how to read the given type...
1251 const Type *Ty = getType(TypeID);
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001252 Constant *Result = 0;
Reid Spencer060d25d2004-06-29 23:29:38 +00001253 switch (Ty->getTypeID()) {
Reid Spencera54b7cb2007-01-12 07:05:14 +00001254 case Type::IntegerTyID: {
1255 const IntegerType *IT = cast<IntegerType>(Ty);
1256 if (IT->getBitWidth() <= 32) {
1257 uint32_t Val = read_vbr_uint();
Reid Spencerb61c1ce2007-01-13 00:09:12 +00001258 if (!ConstantInt::isValueValidForType(Ty, uint64_t(Val)))
1259 error("Integer value read is invalid for type.");
1260 Result = ConstantInt::get(IT, Val);
1261 if (Handler) Handler->handleConstantValue(Result);
Reid Spencera54b7cb2007-01-12 07:05:14 +00001262 } else if (IT->getBitWidth() <= 64) {
1263 uint64_t Val = read_vbr_uint64();
1264 if (!ConstantInt::isValueValidForType(Ty, Val))
1265 error("Invalid constant integer read.");
1266 Result = ConstantInt::get(IT, Val);
1267 if (Handler) Handler->handleConstantValue(Result);
Reid Spencerfa1353c2007-02-28 02:25:48 +00001268 } else {
1269 uint32_t numWords = read_vbr_uint();
1270 uint64_t *data = new uint64_t[numWords];
1271 for (uint32_t i = 0; i < numWords; ++i)
1272 data[i] = read_vbr_uint64();
Reid Spencere2a6acd2007-03-01 20:25:31 +00001273 Result = ConstantInt::get(APInt(IT->getBitWidth(), numWords, data));
Reid Spencerfa1353c2007-02-28 02:25:48 +00001274 if (Handler) Handler->handleConstantValue(Result);
1275 }
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001276 break;
Reid Spencer060d25d2004-06-29 23:29:38 +00001277 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001278 case Type::FloatTyID: {
Reid Spencer46b002c2004-07-11 17:28:43 +00001279 float Val;
1280 read_float(Val);
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001281 Result = ConstantFP::get(Ty, Val);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001282 if (Handler) Handler->handleConstantValue(Result);
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001283 break;
Reid Spencer060d25d2004-06-29 23:29:38 +00001284 }
1285
1286 case Type::DoubleTyID: {
1287 double Val;
Reid Spencer46b002c2004-07-11 17:28:43 +00001288 read_double(Val);
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001289 Result = ConstantFP::get(Ty, Val);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001290 if (Handler) Handler->handleConstantValue(Result);
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001291 break;
Reid Spencer060d25d2004-06-29 23:29:38 +00001292 }
1293
Reid Spencer060d25d2004-06-29 23:29:38 +00001294 case Type::ArrayTyID: {
1295 const ArrayType *AT = cast<ArrayType>(Ty);
1296 unsigned NumElements = AT->getNumElements();
1297 unsigned TypeSlot = getTypeSlot(AT->getElementType());
1298 std::vector<Constant*> Elements;
1299 Elements.reserve(NumElements);
1300 while (NumElements--) // Read all of the elements of the constant.
1301 Elements.push_back(getConstantValue(TypeSlot,
1302 read_vbr_uint()));
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001303 Result = ConstantArray::get(AT, Elements);
Chris Lattner63cf59e2007-02-07 05:08:39 +00001304 if (Handler) Handler->handleConstantArray(AT, &Elements[0], Elements.size(),
1305 TypeSlot, Result);
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001306 break;
Reid Spencer060d25d2004-06-29 23:29:38 +00001307 }
1308
1309 case Type::StructTyID: {
1310 const StructType *ST = cast<StructType>(Ty);
1311
1312 std::vector<Constant *> Elements;
1313 Elements.reserve(ST->getNumElements());
1314 for (unsigned i = 0; i != ST->getNumElements(); ++i)
1315 Elements.push_back(getConstantValue(ST->getElementType(i),
1316 read_vbr_uint()));
1317
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001318 Result = ConstantStruct::get(ST, Elements);
Chris Lattner63cf59e2007-02-07 05:08:39 +00001319 if (Handler) Handler->handleConstantStruct(ST, &Elements[0],Elements.size(),
1320 Result);
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001321 break;
Misha Brukman8a96c532005-04-21 21:44:41 +00001322 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001323
Reid Spencer9d6565a2007-02-15 02:26:10 +00001324 case Type::VectorTyID: {
1325 const VectorType *PT = cast<VectorType>(Ty);
Brian Gaeke715c90b2004-08-20 06:00:58 +00001326 unsigned NumElements = PT->getNumElements();
1327 unsigned TypeSlot = getTypeSlot(PT->getElementType());
1328 std::vector<Constant*> Elements;
1329 Elements.reserve(NumElements);
1330 while (NumElements--) // Read all of the elements of the constant.
1331 Elements.push_back(getConstantValue(TypeSlot,
1332 read_vbr_uint()));
Reid Spencer9d6565a2007-02-15 02:26:10 +00001333 Result = ConstantVector::get(PT, Elements);
1334 if (Handler) Handler->handleConstantVector(PT, &Elements[0],Elements.size(),
Chris Lattner63cf59e2007-02-07 05:08:39 +00001335 TypeSlot, Result);
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001336 break;
Brian Gaeke715c90b2004-08-20 06:00:58 +00001337 }
1338
Chris Lattner638c3812004-11-19 16:24:05 +00001339 case Type::PointerTyID: { // ConstantPointerRef value (backwards compat).
Reid Spencer060d25d2004-06-29 23:29:38 +00001340 const PointerType *PT = cast<PointerType>(Ty);
1341 unsigned Slot = read_vbr_uint();
Misha Brukman8a96c532005-04-21 21:44:41 +00001342
Reid Spencer060d25d2004-06-29 23:29:38 +00001343 // Check to see if we have already read this global variable...
1344 Value *Val = getValue(TypeID, Slot, false);
Reid Spencer060d25d2004-06-29 23:29:38 +00001345 if (Val) {
Chris Lattnerbcb11cf2004-07-27 02:34:49 +00001346 GlobalValue *GV = dyn_cast<GlobalValue>(Val);
1347 if (!GV) error("GlobalValue not in ValueTable!");
1348 if (Handler) Handler->handleConstantPointer(PT, Slot, GV);
1349 return GV;
Reid Spencer060d25d2004-06-29 23:29:38 +00001350 } else {
Reid Spencer24399722004-07-09 22:21:33 +00001351 error("Forward references are not allowed here.");
Reid Spencer060d25d2004-06-29 23:29:38 +00001352 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001353 }
1354
1355 default:
Reid Spencer24399722004-07-09 22:21:33 +00001356 error("Don't know how to deserialize constant value of type '" +
Reid Spencer060d25d2004-06-29 23:29:38 +00001357 Ty->getDescription());
1358 break;
1359 }
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001360
1361 // Check that we didn't read a null constant if they are implicit for this
1362 // type plane. Do not do this check for constantexprs, as they may be folded
1363 // to a null value in a way that isn't predicted when a .bc file is initially
1364 // produced.
1365 assert((!isa<Constant>(Result) || !cast<Constant>(Result)->isNullValue()) ||
Reid Spencerfa1353c2007-02-28 02:25:48 +00001366 !hasImplicitNull(TypeID) && "Cannot read null values from bytecode!");
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001367 return Result;
Reid Spencer060d25d2004-06-29 23:29:38 +00001368}
1369
Misha Brukman8a96c532005-04-21 21:44:41 +00001370/// Resolve references for constants. This function resolves the forward
1371/// referenced constants in the ConstantFwdRefs map. It uses the
Reid Spencer04cde2c2004-07-04 11:33:49 +00001372/// replaceAllUsesWith method of Value class to substitute the placeholder
1373/// instance with the actual instance.
Chris Lattner389bd042004-12-09 06:19:44 +00001374void BytecodeReader::ResolveReferencesToConstant(Constant *NewV, unsigned Typ,
1375 unsigned Slot) {
Chris Lattner29b789b2003-11-19 17:27:18 +00001376 ConstantRefsType::iterator I =
Chris Lattner389bd042004-12-09 06:19:44 +00001377 ConstantFwdRefs.find(std::make_pair(Typ, Slot));
Chris Lattner29b789b2003-11-19 17:27:18 +00001378 if (I == ConstantFwdRefs.end()) return; // Never forward referenced?
Chris Lattner00950542001-06-06 20:29:01 +00001379
Chris Lattner29b789b2003-11-19 17:27:18 +00001380 Value *PH = I->second; // Get the placeholder...
1381 PH->replaceAllUsesWith(NewV);
1382 delete PH; // Delete the old placeholder
1383 ConstantFwdRefs.erase(I); // Remove the map entry for it
Vikram S. Advec1e4a812002-07-14 23:04:18 +00001384}
1385
Reid Spencer04cde2c2004-07-04 11:33:49 +00001386/// Parse the constant strings section.
Reid Spencer060d25d2004-06-29 23:29:38 +00001387void BytecodeReader::ParseStringConstants(unsigned NumEntries, ValueTable &Tab){
1388 for (; NumEntries; --NumEntries) {
Reid Spencerd798a512006-11-14 04:47:22 +00001389 unsigned Typ = read_vbr_uint();
Reid Spencer060d25d2004-06-29 23:29:38 +00001390 const Type *Ty = getType(Typ);
1391 if (!isa<ArrayType>(Ty))
Reid Spencer24399722004-07-09 22:21:33 +00001392 error("String constant data invalid!");
Misha Brukman8a96c532005-04-21 21:44:41 +00001393
Reid Spencer060d25d2004-06-29 23:29:38 +00001394 const ArrayType *ATy = cast<ArrayType>(Ty);
Reid Spencer88cfda22006-12-31 05:44:24 +00001395 if (ATy->getElementType() != Type::Int8Ty &&
1396 ATy->getElementType() != Type::Int8Ty)
Reid Spencer24399722004-07-09 22:21:33 +00001397 error("String constant data invalid!");
Misha Brukman8a96c532005-04-21 21:44:41 +00001398
Reid Spencer060d25d2004-06-29 23:29:38 +00001399 // Read character data. The type tells us how long the string is.
Misha Brukman8a96c532005-04-21 21:44:41 +00001400 char *Data = reinterpret_cast<char *>(alloca(ATy->getNumElements()));
Reid Spencer060d25d2004-06-29 23:29:38 +00001401 read_data(Data, Data+ATy->getNumElements());
Chris Lattner52e20b02003-03-19 20:54:26 +00001402
Reid Spencer060d25d2004-06-29 23:29:38 +00001403 std::vector<Constant*> Elements(ATy->getNumElements());
Reid Spencerb83eb642006-10-20 07:07:24 +00001404 const Type* ElemType = ATy->getElementType();
1405 for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
1406 Elements[i] = ConstantInt::get(ElemType, (unsigned char)Data[i]);
Misha Brukman12c29d12003-09-22 23:38:23 +00001407
Reid Spencer060d25d2004-06-29 23:29:38 +00001408 // Create the constant, inserting it as needed.
1409 Constant *C = ConstantArray::get(ATy, Elements);
1410 unsigned Slot = insertValue(C, Typ, Tab);
Chris Lattner389bd042004-12-09 06:19:44 +00001411 ResolveReferencesToConstant(C, Typ, Slot);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001412 if (Handler) Handler->handleConstantString(cast<ConstantArray>(C));
Reid Spencer060d25d2004-06-29 23:29:38 +00001413 }
Misha Brukman12c29d12003-09-22 23:38:23 +00001414}
1415
Reid Spencer04cde2c2004-07-04 11:33:49 +00001416/// Parse the constant pool.
Misha Brukman8a96c532005-04-21 21:44:41 +00001417void BytecodeReader::ParseConstantPool(ValueTable &Tab,
Reid Spencer04cde2c2004-07-04 11:33:49 +00001418 TypeListTy &TypeTab,
Reid Spencer46b002c2004-07-11 17:28:43 +00001419 bool isFunction) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001420 if (Handler) Handler->handleGlobalConstantsBegin();
1421
1422 /// In LLVM 1.3 Type does not derive from Value so the types
1423 /// do not occupy a plane. Consequently, we read the types
1424 /// first in the constant pool.
Reid Spencerd798a512006-11-14 04:47:22 +00001425 if (isFunction) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001426 unsigned NumEntries = read_vbr_uint();
Reid Spencer46b002c2004-07-11 17:28:43 +00001427 ParseTypes(TypeTab, NumEntries);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001428 }
1429
Reid Spencer46b002c2004-07-11 17:28:43 +00001430 while (moreInBlock()) {
Reid Spencer060d25d2004-06-29 23:29:38 +00001431 unsigned NumEntries = read_vbr_uint();
Reid Spencerd798a512006-11-14 04:47:22 +00001432 unsigned Typ = read_vbr_uint();
Reid Spencer04cde2c2004-07-04 11:33:49 +00001433
Reid Spencerd798a512006-11-14 04:47:22 +00001434 if (Typ == Type::VoidTyID) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001435 /// Use of Type::VoidTyID is a misnomer. It actually means
1436 /// that the following plane is constant strings
Reid Spencer060d25d2004-06-29 23:29:38 +00001437 assert(&Tab == &ModuleValues && "Cannot read strings in functions!");
1438 ParseStringConstants(NumEntries, Tab);
1439 } else {
1440 for (unsigned i = 0; i < NumEntries; ++i) {
Chris Lattner3bc5a602006-01-25 23:08:15 +00001441 Value *V = ParseConstantPoolValue(Typ);
1442 assert(V && "ParseConstantPoolValue returned NULL!");
1443 unsigned Slot = insertValue(V, Typ, Tab);
Chris Lattner29b789b2003-11-19 17:27:18 +00001444
Reid Spencer060d25d2004-06-29 23:29:38 +00001445 // If we are reading a function constant table, make sure that we adjust
1446 // the slot number to be the real global constant number.
1447 //
1448 if (&Tab != &ModuleValues && Typ < ModuleValues.size() &&
1449 ModuleValues[Typ])
1450 Slot += ModuleValues[Typ]->size();
Chris Lattner3bc5a602006-01-25 23:08:15 +00001451 if (Constant *C = dyn_cast<Constant>(V))
1452 ResolveReferencesToConstant(C, Typ, Slot);
Reid Spencer060d25d2004-06-29 23:29:38 +00001453 }
1454 }
1455 }
Chris Lattner02dce162004-12-04 05:28:27 +00001456
1457 // After we have finished parsing the constant pool, we had better not have
1458 // any dangling references left.
Reid Spencer3c391272004-12-04 22:19:53 +00001459 if (!ConstantFwdRefs.empty()) {
Reid Spencer3c391272004-12-04 22:19:53 +00001460 ConstantRefsType::const_iterator I = ConstantFwdRefs.begin();
Reid Spencer3c391272004-12-04 22:19:53 +00001461 Constant* missingConst = I->second;
Misha Brukman8a96c532005-04-21 21:44:41 +00001462 error(utostr(ConstantFwdRefs.size()) +
1463 " unresolved constant reference exist. First one is '" +
1464 missingConst->getName() + "' of type '" +
Chris Lattner389bd042004-12-09 06:19:44 +00001465 missingConst->getType()->getDescription() + "'.");
Reid Spencer3c391272004-12-04 22:19:53 +00001466 }
Chris Lattner02dce162004-12-04 05:28:27 +00001467
Reid Spencer060d25d2004-06-29 23:29:38 +00001468 checkPastBlockEnd("Constant Pool");
Reid Spencer04cde2c2004-07-04 11:33:49 +00001469 if (Handler) Handler->handleGlobalConstantsEnd();
Reid Spencer060d25d2004-06-29 23:29:38 +00001470}
Chris Lattner00950542001-06-06 20:29:01 +00001471
Reid Spencer04cde2c2004-07-04 11:33:49 +00001472/// Parse the contents of a function. Note that this function can be
1473/// called lazily by materializeFunction
1474/// @see materializeFunction
Reid Spencer46b002c2004-07-11 17:28:43 +00001475void BytecodeReader::ParseFunctionBody(Function* F) {
Reid Spencer060d25d2004-06-29 23:29:38 +00001476
1477 unsigned FuncSize = BlockEnd - At;
Chris Lattnere3869c82003-04-16 21:16:05 +00001478 GlobalValue::LinkageTypes Linkage = GlobalValue::ExternalLinkage;
Anton Korobeynikov7f705592007-01-12 19:20:47 +00001479 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
Chris Lattnere3869c82003-04-16 21:16:05 +00001480
Anton Korobeynikov7f705592007-01-12 19:20:47 +00001481 unsigned rWord = read_vbr_uint();
1482 unsigned LinkageID = rWord & 65535;
1483 unsigned VisibilityID = rWord >> 16;
1484 switch (LinkageID) {
Chris Lattnerc08912f2004-01-14 16:44:44 +00001485 case 0: Linkage = GlobalValue::ExternalLinkage; break;
1486 case 1: Linkage = GlobalValue::WeakLinkage; break;
1487 case 2: Linkage = GlobalValue::AppendingLinkage; break;
1488 case 3: Linkage = GlobalValue::InternalLinkage; break;
1489 case 4: Linkage = GlobalValue::LinkOnceLinkage; break;
Anton Korobeynikovb74ed072006-09-14 18:23:27 +00001490 case 5: Linkage = GlobalValue::DLLImportLinkage; break;
1491 case 6: Linkage = GlobalValue::DLLExportLinkage; break;
1492 case 7: Linkage = GlobalValue::ExternalWeakLinkage; break;
Reid Spencer060d25d2004-06-29 23:29:38 +00001493 default:
Reid Spencer24399722004-07-09 22:21:33 +00001494 error("Invalid linkage type for Function.");
Reid Spencer060d25d2004-06-29 23:29:38 +00001495 Linkage = GlobalValue::InternalLinkage;
1496 break;
Chris Lattnere3869c82003-04-16 21:16:05 +00001497 }
Anton Korobeynikov7f705592007-01-12 19:20:47 +00001498 switch (VisibilityID) {
1499 case 0: Visibility = GlobalValue::DefaultVisibility; break;
1500 case 1: Visibility = GlobalValue::HiddenVisibility; break;
1501 default:
1502 error("Unknown visibility type: " + utostr(VisibilityID));
1503 Visibility = GlobalValue::DefaultVisibility;
1504 break;
1505 }
Chris Lattnerd23b1d32001-11-26 18:56:10 +00001506
Reid Spencer46b002c2004-07-11 17:28:43 +00001507 F->setLinkage(Linkage);
Anton Korobeynikov7f705592007-01-12 19:20:47 +00001508 F->setVisibility(Visibility);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001509 if (Handler) Handler->handleFunctionBegin(F,FuncSize);
Chris Lattner00950542001-06-06 20:29:01 +00001510
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001511 // Keep track of how many basic blocks we have read in...
1512 unsigned BlockNum = 0;
Chris Lattner89e02532004-01-18 21:08:15 +00001513 bool InsertedArguments = false;
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001514
Reid Spencer060d25d2004-06-29 23:29:38 +00001515 BufPtr MyEnd = BlockEnd;
Reid Spencer46b002c2004-07-11 17:28:43 +00001516 while (At < MyEnd) {
Chris Lattner00950542001-06-06 20:29:01 +00001517 unsigned Type, Size;
Reid Spencer060d25d2004-06-29 23:29:38 +00001518 BufPtr OldAt = At;
1519 read_block(Type, Size);
Chris Lattner00950542001-06-06 20:29:01 +00001520
1521 switch (Type) {
Reid Spencerad89bd62004-07-25 18:07:36 +00001522 case BytecodeFormat::ConstantPoolBlockID:
Chris Lattner89e02532004-01-18 21:08:15 +00001523 if (!InsertedArguments) {
1524 // Insert arguments into the value table before we parse the first basic
Reid Spencerd2bb8872007-01-30 19:36:46 +00001525 // block in the function
Reid Spencer04cde2c2004-07-04 11:33:49 +00001526 insertArguments(F);
Chris Lattner89e02532004-01-18 21:08:15 +00001527 InsertedArguments = true;
1528 }
1529
Reid Spencer04cde2c2004-07-04 11:33:49 +00001530 ParseConstantPool(FunctionValues, FunctionTypes, true);
Chris Lattner00950542001-06-06 20:29:01 +00001531 break;
1532
Reid Spencerad89bd62004-07-25 18:07:36 +00001533 case BytecodeFormat::InstructionListBlockID: {
Chris Lattner89e02532004-01-18 21:08:15 +00001534 // Insert arguments into the value table before we parse the instruction
Reid Spencerd2bb8872007-01-30 19:36:46 +00001535 // list for the function
Chris Lattner89e02532004-01-18 21:08:15 +00001536 if (!InsertedArguments) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001537 insertArguments(F);
Chris Lattner89e02532004-01-18 21:08:15 +00001538 InsertedArguments = true;
1539 }
1540
Misha Brukman8a96c532005-04-21 21:44:41 +00001541 if (BlockNum)
Reid Spencer24399722004-07-09 22:21:33 +00001542 error("Already parsed basic blocks!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001543 BlockNum = ParseInstructionList(F);
Chris Lattner8d1dbd22003-12-01 07:05:31 +00001544 break;
1545 }
1546
Reid Spencer78d033e2007-01-06 07:24:44 +00001547 case BytecodeFormat::ValueSymbolTableBlockID:
1548 ParseValueSymbolTable(F, &F->getValueSymbolTable());
1549 break;
1550
1551 case BytecodeFormat::TypeSymbolTableBlockID:
1552 error("Functions don't have type symbol tables");
Chris Lattner00950542001-06-06 20:29:01 +00001553 break;
1554
1555 default:
Reid Spencer060d25d2004-06-29 23:29:38 +00001556 At += Size;
Misha Brukman8a96c532005-04-21 21:44:41 +00001557 if (OldAt > At)
Reid Spencer24399722004-07-09 22:21:33 +00001558 error("Wrapped around reading bytecode.");
Chris Lattner00950542001-06-06 20:29:01 +00001559 break;
1560 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001561 BlockEnd = MyEnd;
Chris Lattner00950542001-06-06 20:29:01 +00001562 }
1563
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001564 // Make sure there were no references to non-existant basic blocks.
1565 if (BlockNum != ParsedBasicBlocks.size())
Reid Spencer24399722004-07-09 22:21:33 +00001566 error("Illegal basic block operand reference");
Reid Spencer060d25d2004-06-29 23:29:38 +00001567
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001568 ParsedBasicBlocks.clear();
1569
Chris Lattner97330cf2003-10-09 23:10:14 +00001570 // Resolve forward references. Replace any uses of a forward reference value
1571 // with the real value.
Chris Lattner8eb10ce2003-10-09 06:05:40 +00001572 while (!ForwardReferences.empty()) {
Chris Lattnerc4d69162004-12-09 04:51:50 +00001573 std::map<std::pair<unsigned,unsigned>, Value*>::iterator
1574 I = ForwardReferences.begin();
1575 Value *V = getValue(I->first.first, I->first.second, false);
Chris Lattner8eb10ce2003-10-09 06:05:40 +00001576 Value *PlaceHolder = I->second;
Chris Lattnerc4d69162004-12-09 04:51:50 +00001577 PlaceHolder->replaceAllUsesWith(V);
Chris Lattner8eb10ce2003-10-09 06:05:40 +00001578 ForwardReferences.erase(I);
Chris Lattner8eb10ce2003-10-09 06:05:40 +00001579 delete PlaceHolder;
Chris Lattner6e448022003-10-08 21:51:46 +00001580 }
Chris Lattner00950542001-06-06 20:29:01 +00001581
Misha Brukman12c29d12003-09-22 23:38:23 +00001582 // Clear out function-level types...
Reid Spencer060d25d2004-06-29 23:29:38 +00001583 FunctionTypes.clear();
Reid Spencer060d25d2004-06-29 23:29:38 +00001584 freeTable(FunctionValues);
1585
Reid Spencer04cde2c2004-07-04 11:33:49 +00001586 if (Handler) Handler->handleFunctionEnd(F);
Chris Lattner00950542001-06-06 20:29:01 +00001587}
1588
Reid Spencer04cde2c2004-07-04 11:33:49 +00001589/// This function parses LLVM functions lazily. It obtains the type of the
1590/// function and records where the body of the function is in the bytecode
Misha Brukman8a96c532005-04-21 21:44:41 +00001591/// buffer. The caller can then use the ParseNextFunction and
Reid Spencer04cde2c2004-07-04 11:33:49 +00001592/// ParseAllFunctionBodies to get handler events for the functions.
Reid Spencer060d25d2004-06-29 23:29:38 +00001593void BytecodeReader::ParseFunctionLazily() {
1594 if (FunctionSignatureList.empty())
Reid Spencer24399722004-07-09 22:21:33 +00001595 error("FunctionSignatureList empty!");
Chris Lattner89e02532004-01-18 21:08:15 +00001596
Reid Spencer060d25d2004-06-29 23:29:38 +00001597 Function *Func = FunctionSignatureList.back();
1598 FunctionSignatureList.pop_back();
Chris Lattner24102432004-01-18 22:35:34 +00001599
Reid Spencer060d25d2004-06-29 23:29:38 +00001600 // Save the information for future reading of the function
1601 LazyFunctionLoadMap[Func] = LazyFunctionInfo(BlockStart, BlockEnd);
Chris Lattner89e02532004-01-18 21:08:15 +00001602
Misha Brukmana3e6ad62004-11-14 21:02:55 +00001603 // This function has a body but it's not loaded so it appears `External'.
1604 // Mark it as a `Ghost' instead to notify the users that it has a body.
1605 Func->setLinkage(GlobalValue::GhostLinkage);
1606
Reid Spencer060d25d2004-06-29 23:29:38 +00001607 // Pretend we've `parsed' this function
1608 At = BlockEnd;
1609}
Chris Lattner89e02532004-01-18 21:08:15 +00001610
Misha Brukman8a96c532005-04-21 21:44:41 +00001611/// The ParserFunction method lazily parses one function. Use this method to
1612/// casue the parser to parse a specific function in the module. Note that
1613/// this will remove the function from what is to be included by
Reid Spencer04cde2c2004-07-04 11:33:49 +00001614/// ParseAllFunctionBodies.
1615/// @see ParseAllFunctionBodies
1616/// @see ParseBytecode
Reid Spencer99655e12006-08-25 19:54:53 +00001617bool BytecodeReader::ParseFunction(Function* Func, std::string* ErrMsg) {
1618
Reid Spencer9b84ad12006-12-15 19:49:23 +00001619 if (setjmp(context)) {
1620 // Set caller's error message, if requested
1621 if (ErrMsg)
1622 *ErrMsg = ErrorMsg;
1623 // Indicate an error occurred
Reid Spencer99655e12006-08-25 19:54:53 +00001624 return true;
Reid Spencer9b84ad12006-12-15 19:49:23 +00001625 }
Reid Spencer99655e12006-08-25 19:54:53 +00001626
Reid Spencer060d25d2004-06-29 23:29:38 +00001627 // Find {start, end} pointers and slot in the map. If not there, we're done.
1628 LazyFunctionMap::iterator Fi = LazyFunctionLoadMap.find(Func);
Chris Lattner89e02532004-01-18 21:08:15 +00001629
Reid Spencer060d25d2004-06-29 23:29:38 +00001630 // Make sure we found it
Reid Spencer46b002c2004-07-11 17:28:43 +00001631 if (Fi == LazyFunctionLoadMap.end()) {
Reid Spencer24399722004-07-09 22:21:33 +00001632 error("Unrecognized function of type " + Func->getType()->getDescription());
Reid Spencer99655e12006-08-25 19:54:53 +00001633 return true;
Chris Lattner89e02532004-01-18 21:08:15 +00001634 }
1635
Reid Spencer060d25d2004-06-29 23:29:38 +00001636 BlockStart = At = Fi->second.Buf;
1637 BlockEnd = Fi->second.EndBuf;
Reid Spencer24399722004-07-09 22:21:33 +00001638 assert(Fi->first == Func && "Found wrong function?");
Reid Spencer060d25d2004-06-29 23:29:38 +00001639
Reid Spencer46b002c2004-07-11 17:28:43 +00001640 this->ParseFunctionBody(Func);
Reid Spencer99655e12006-08-25 19:54:53 +00001641 return false;
Chris Lattner89e02532004-01-18 21:08:15 +00001642}
1643
Reid Spencer04cde2c2004-07-04 11:33:49 +00001644/// The ParseAllFunctionBodies method parses through all the previously
1645/// unparsed functions in the bytecode file. If you want to completely parse
1646/// a bytecode file, this method should be called after Parsebytecode because
1647/// Parsebytecode only records the locations in the bytecode file of where
1648/// the function definitions are located. This function uses that information
1649/// to materialize the functions.
1650/// @see ParseBytecode
Reid Spencer99655e12006-08-25 19:54:53 +00001651bool BytecodeReader::ParseAllFunctionBodies(std::string* ErrMsg) {
Reid Spencer9b84ad12006-12-15 19:49:23 +00001652 if (setjmp(context)) {
1653 // Set caller's error message, if requested
1654 if (ErrMsg)
1655 *ErrMsg = ErrorMsg;
1656 // Indicate an error occurred
Reid Spencer99655e12006-08-25 19:54:53 +00001657 return true;
Reid Spencer9b84ad12006-12-15 19:49:23 +00001658 }
Reid Spencer99655e12006-08-25 19:54:53 +00001659
Reid Spencer060d25d2004-06-29 23:29:38 +00001660 LazyFunctionMap::iterator Fi = LazyFunctionLoadMap.begin();
1661 LazyFunctionMap::iterator Fe = LazyFunctionLoadMap.end();
Chris Lattner89e02532004-01-18 21:08:15 +00001662
Reid Spencer46b002c2004-07-11 17:28:43 +00001663 while (Fi != Fe) {
Reid Spencer060d25d2004-06-29 23:29:38 +00001664 Function* Func = Fi->first;
1665 BlockStart = At = Fi->second.Buf;
1666 BlockEnd = Fi->second.EndBuf;
Chris Lattnerb52f1c22005-02-13 17:48:18 +00001667 ParseFunctionBody(Func);
Reid Spencer060d25d2004-06-29 23:29:38 +00001668 ++Fi;
1669 }
Reid Spencer99655e12006-08-25 19:54:53 +00001670 return false;
Reid Spencer060d25d2004-06-29 23:29:38 +00001671}
Chris Lattner89e02532004-01-18 21:08:15 +00001672
Reid Spencer04cde2c2004-07-04 11:33:49 +00001673/// Parse the global type list
Reid Spencer060d25d2004-06-29 23:29:38 +00001674void BytecodeReader::ParseGlobalTypes() {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001675 // Read the number of types
1676 unsigned NumEntries = read_vbr_uint();
Reid Spencer46b002c2004-07-11 17:28:43 +00001677 ParseTypes(ModuleTypes, NumEntries);
Reid Spencer060d25d2004-06-29 23:29:38 +00001678}
1679
Reid Spencer04cde2c2004-07-04 11:33:49 +00001680/// Parse the Global info (types, global vars, constants)
Reid Spencer060d25d2004-06-29 23:29:38 +00001681void BytecodeReader::ParseModuleGlobalInfo() {
1682
Reid Spencer04cde2c2004-07-04 11:33:49 +00001683 if (Handler) Handler->handleModuleGlobalsBegin();
Chris Lattner00950542001-06-06 20:29:01 +00001684
Chris Lattner404cddf2005-11-12 01:33:40 +00001685 // SectionID - If a global has an explicit section specified, this map
1686 // remembers the ID until we can translate it into a string.
1687 std::map<GlobalValue*, unsigned> SectionID;
1688
Chris Lattner70cc3392001-09-10 07:58:01 +00001689 // Read global variables...
Reid Spencer060d25d2004-06-29 23:29:38 +00001690 unsigned VarType = read_vbr_uint();
Chris Lattner70cc3392001-09-10 07:58:01 +00001691 while (VarType != Type::VoidTyID) { // List is terminated by Void
Chris Lattner9dd87702004-04-03 23:43:42 +00001692 // VarType Fields: bit0 = isConstant, bit1 = hasInitializer, bit2,3,4 =
1693 // Linkage, bit4+ = slot#
1694 unsigned SlotNo = VarType >> 5;
1695 unsigned LinkageID = (VarType >> 2) & 7;
Anton Korobeynikov7f705592007-01-12 19:20:47 +00001696 unsigned VisibilityID = 0;
Reid Spencer060d25d2004-06-29 23:29:38 +00001697 bool isConstant = VarType & 1;
Chris Lattnerce5e04e2005-11-06 08:23:17 +00001698 bool hasInitializer = (VarType & 2) != 0;
Chris Lattner8eb52dd2005-11-06 07:11:04 +00001699 unsigned Alignment = 0;
Chris Lattner404cddf2005-11-12 01:33:40 +00001700 unsigned GlobalSectionID = 0;
Chris Lattner8eb52dd2005-11-06 07:11:04 +00001701
1702 // An extension word is present when linkage = 3 (internal) and hasinit = 0.
1703 if (LinkageID == 3 && !hasInitializer) {
1704 unsigned ExtWord = read_vbr_uint();
1705 // The extension word has this format: bit 0 = has initializer, bit 1-3 =
Anton Korobeynikov7f705592007-01-12 19:20:47 +00001706 // linkage, bit 4-8 = alignment (log2), bit 9 = has section,
1707 // bits 10-12 = visibility, bits 13+ = future use.
Chris Lattner8eb52dd2005-11-06 07:11:04 +00001708 hasInitializer = ExtWord & 1;
1709 LinkageID = (ExtWord >> 1) & 7;
1710 Alignment = (1 << ((ExtWord >> 4) & 31)) >> 1;
Anton Korobeynikov7f705592007-01-12 19:20:47 +00001711 VisibilityID = (ExtWord >> 10) & 7;
Chris Lattner404cddf2005-11-12 01:33:40 +00001712
1713 if (ExtWord & (1 << 9)) // Has a section ID.
1714 GlobalSectionID = read_vbr_uint();
Chris Lattner8eb52dd2005-11-06 07:11:04 +00001715 }
Chris Lattnere3869c82003-04-16 21:16:05 +00001716
Chris Lattnerce5e04e2005-11-06 08:23:17 +00001717 GlobalValue::LinkageTypes Linkage;
Chris Lattnerc08912f2004-01-14 16:44:44 +00001718 switch (LinkageID) {
Chris Lattnerc08912f2004-01-14 16:44:44 +00001719 case 0: Linkage = GlobalValue::ExternalLinkage; break;
1720 case 1: Linkage = GlobalValue::WeakLinkage; break;
1721 case 2: Linkage = GlobalValue::AppendingLinkage; break;
1722 case 3: Linkage = GlobalValue::InternalLinkage; break;
1723 case 4: Linkage = GlobalValue::LinkOnceLinkage; break;
Anton Korobeynikovb74ed072006-09-14 18:23:27 +00001724 case 5: Linkage = GlobalValue::DLLImportLinkage; break;
1725 case 6: Linkage = GlobalValue::DLLExportLinkage; break;
1726 case 7: Linkage = GlobalValue::ExternalWeakLinkage; break;
Misha Brukman8a96c532005-04-21 21:44:41 +00001727 default:
Reid Spencer24399722004-07-09 22:21:33 +00001728 error("Unknown linkage type: " + utostr(LinkageID));
Reid Spencer060d25d2004-06-29 23:29:38 +00001729 Linkage = GlobalValue::InternalLinkage;
1730 break;
Chris Lattnere3869c82003-04-16 21:16:05 +00001731 }
Anton Korobeynikov7f705592007-01-12 19:20:47 +00001732 GlobalValue::VisibilityTypes Visibility;
1733 switch (VisibilityID) {
1734 case 0: Visibility = GlobalValue::DefaultVisibility; break;
1735 case 1: Visibility = GlobalValue::HiddenVisibility; break;
1736 default:
1737 error("Unknown visibility type: " + utostr(VisibilityID));
1738 Visibility = GlobalValue::DefaultVisibility;
1739 break;
1740 }
1741
Chris Lattnere3869c82003-04-16 21:16:05 +00001742 const Type *Ty = getType(SlotNo);
Chris Lattnere73bd452005-11-06 07:43:39 +00001743 if (!Ty)
Reid Spencer24399722004-07-09 22:21:33 +00001744 error("Global has no type! SlotNo=" + utostr(SlotNo));
Reid Spencer060d25d2004-06-29 23:29:38 +00001745
Chris Lattnere73bd452005-11-06 07:43:39 +00001746 if (!isa<PointerType>(Ty))
Reid Spencer24399722004-07-09 22:21:33 +00001747 error("Global not a pointer type! Ty= " + Ty->getDescription());
Chris Lattner70cc3392001-09-10 07:58:01 +00001748
Chris Lattner52e20b02003-03-19 20:54:26 +00001749 const Type *ElTy = cast<PointerType>(Ty)->getElementType();
Chris Lattnerd70684f2001-09-18 04:01:05 +00001750
Chris Lattner70cc3392001-09-10 07:58:01 +00001751 // Create the global variable...
Reid Spencer060d25d2004-06-29 23:29:38 +00001752 GlobalVariable *GV = new GlobalVariable(ElTy, isConstant, Linkage,
Chris Lattner52e20b02003-03-19 20:54:26 +00001753 0, "", TheModule);
Chris Lattner8eb52dd2005-11-06 07:11:04 +00001754 GV->setAlignment(Alignment);
Anton Korobeynikov7f705592007-01-12 19:20:47 +00001755 GV->setVisibility(Visibility);
Chris Lattner29b789b2003-11-19 17:27:18 +00001756 insertValue(GV, SlotNo, ModuleValues);
Chris Lattner05950c32001-10-13 06:47:01 +00001757
Chris Lattner404cddf2005-11-12 01:33:40 +00001758 if (GlobalSectionID != 0)
1759 SectionID[GV] = GlobalSectionID;
1760
Reid Spencer060d25d2004-06-29 23:29:38 +00001761 unsigned initSlot = 0;
Misha Brukman8a96c532005-04-21 21:44:41 +00001762 if (hasInitializer) {
Reid Spencer060d25d2004-06-29 23:29:38 +00001763 initSlot = read_vbr_uint();
1764 GlobalInits.push_back(std::make_pair(GV, initSlot));
1765 }
1766
1767 // Notify handler about the global value.
Chris Lattner4a242b32004-10-14 01:39:18 +00001768 if (Handler)
Anton Korobeynikov7f705592007-01-12 19:20:47 +00001769 Handler->handleGlobalVariable(ElTy, isConstant, Linkage, Visibility,
1770 SlotNo, initSlot);
Reid Spencer060d25d2004-06-29 23:29:38 +00001771
1772 // Get next item
1773 VarType = read_vbr_uint();
Chris Lattner70cc3392001-09-10 07:58:01 +00001774 }
1775
Chris Lattner52e20b02003-03-19 20:54:26 +00001776 // Read the function objects for all of the functions that are coming
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001777 unsigned FnSignature = read_vbr_uint();
Reid Spencer24399722004-07-09 22:21:33 +00001778
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001779 // List is terminated by VoidTy.
Chris Lattnere73bd452005-11-06 07:43:39 +00001780 while (((FnSignature & (~0U >> 1)) >> 5) != Type::VoidTyID) {
1781 const Type *Ty = getType((FnSignature & (~0U >> 1)) >> 5);
Chris Lattner927b1852003-10-09 20:22:47 +00001782 if (!isa<PointerType>(Ty) ||
Reid Spencer060d25d2004-06-29 23:29:38 +00001783 !isa<FunctionType>(cast<PointerType>(Ty)->getElementType())) {
Misha Brukman8a96c532005-04-21 21:44:41 +00001784 error("Function not a pointer to function type! Ty = " +
Reid Spencer46b002c2004-07-11 17:28:43 +00001785 Ty->getDescription());
Reid Spencer060d25d2004-06-29 23:29:38 +00001786 }
Chris Lattner8cdc6b72002-10-23 00:51:54 +00001787
Chris Lattner2a7b6ba2003-03-06 17:15:19 +00001788 // We create functions by passing the underlying FunctionType to create...
Misha Brukman8a96c532005-04-21 21:44:41 +00001789 const FunctionType* FTy =
Reid Spencer060d25d2004-06-29 23:29:38 +00001790 cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
Chris Lattner00950542001-06-06 20:29:01 +00001791
Chris Lattner18549c22004-11-15 21:43:03 +00001792 // Insert the place holder.
Chris Lattner404cddf2005-11-12 01:33:40 +00001793 Function *Func = new Function(FTy, GlobalValue::ExternalLinkage,
Reid Spencer04cde2c2004-07-04 11:33:49 +00001794 "", TheModule);
Reid Spencere1e96c02006-01-19 07:02:16 +00001795
Chris Lattnere73bd452005-11-06 07:43:39 +00001796 insertValue(Func, (FnSignature & (~0U >> 1)) >> 5, ModuleValues);
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001797
1798 // Flags are not used yet.
Chris Lattner97fbc502004-11-15 22:38:52 +00001799 unsigned Flags = FnSignature & 31;
Chris Lattner00950542001-06-06 20:29:01 +00001800
Chris Lattner97fbc502004-11-15 22:38:52 +00001801 // Save this for later so we know type of lazily instantiated functions.
1802 // Note that known-external functions do not have FunctionInfo blocks, so we
1803 // do not add them to the FunctionSignatureList.
1804 if ((Flags & (1 << 4)) == 0)
1805 FunctionSignatureList.push_back(Func);
Chris Lattner52e20b02003-03-19 20:54:26 +00001806
Chris Lattnere73bd452005-11-06 07:43:39 +00001807 // Get the calling convention from the low bits.
1808 unsigned CC = Flags & 15;
1809 unsigned Alignment = 0;
1810 if (FnSignature & (1 << 31)) { // Has extension word?
1811 unsigned ExtWord = read_vbr_uint();
1812 Alignment = (1 << (ExtWord & 31)) >> 1;
1813 CC |= ((ExtWord >> 5) & 15) << 4;
Chris Lattner404cddf2005-11-12 01:33:40 +00001814
1815 if (ExtWord & (1 << 10)) // Has a section ID.
1816 SectionID[Func] = read_vbr_uint();
Anton Korobeynikovb74ed072006-09-14 18:23:27 +00001817
1818 // Parse external declaration linkage
1819 switch ((ExtWord >> 11) & 3) {
1820 case 0: break;
1821 case 1: Func->setLinkage(Function::DLLImportLinkage); break;
1822 case 2: Func->setLinkage(Function::ExternalWeakLinkage); break;
1823 default: assert(0 && "Unsupported external linkage");
1824 }
Chris Lattnere73bd452005-11-06 07:43:39 +00001825 }
1826
Chris Lattner54b369e2005-11-06 07:46:13 +00001827 Func->setCallingConv(CC-1);
Chris Lattnere73bd452005-11-06 07:43:39 +00001828 Func->setAlignment(Alignment);
Chris Lattner479ffeb2005-05-06 20:42:57 +00001829
Reid Spencer04cde2c2004-07-04 11:33:49 +00001830 if (Handler) Handler->handleFunctionDeclaration(Func);
Reid Spencer060d25d2004-06-29 23:29:38 +00001831
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001832 // Get the next function signature.
1833 FnSignature = read_vbr_uint();
Chris Lattner00950542001-06-06 20:29:01 +00001834 }
1835
Misha Brukman8a96c532005-04-21 21:44:41 +00001836 // Now that the function signature list is set up, reverse it so that we can
Chris Lattner74734132002-08-17 22:01:27 +00001837 // remove elements efficiently from the back of the vector.
1838 std::reverse(FunctionSignatureList.begin(), FunctionSignatureList.end());
Chris Lattner00950542001-06-06 20:29:01 +00001839
Chris Lattner404cddf2005-11-12 01:33:40 +00001840 /// SectionNames - This contains the list of section names encoded in the
1841 /// moduleinfoblock. Functions and globals with an explicit section index
1842 /// into this to get their section name.
1843 std::vector<std::string> SectionNames;
1844
Reid Spencerd798a512006-11-14 04:47:22 +00001845 // Read in the dependent library information.
1846 unsigned num_dep_libs = read_vbr_uint();
1847 std::string dep_lib;
1848 while (num_dep_libs--) {
1849 dep_lib = read_str();
1850 TheModule->addLibrary(dep_lib);
Reid Spencer5b472d92004-08-21 20:49:23 +00001851 if (Handler)
Reid Spencerd798a512006-11-14 04:47:22 +00001852 Handler->handleDependentLibrary(dep_lib);
Reid Spencerad89bd62004-07-25 18:07:36 +00001853 }
1854
Reid Spencerd798a512006-11-14 04:47:22 +00001855 // Read target triple and place into the module.
1856 std::string triple = read_str();
1857 TheModule->setTargetTriple(triple);
1858 if (Handler)
1859 Handler->handleTargetTriple(triple);
1860
Reid Spenceraacc35a2007-01-26 08:10:24 +00001861 // Read the data layout string and place into the module.
1862 std::string datalayout = read_str();
1863 TheModule->setDataLayout(datalayout);
1864 // FIXME: Implement
1865 // if (Handler)
1866 // Handler->handleDataLayout(datalayout);
1867
Reid Spencerd798a512006-11-14 04:47:22 +00001868 if (At != BlockEnd) {
1869 // If the file has section info in it, read the section names now.
1870 unsigned NumSections = read_vbr_uint();
1871 while (NumSections--)
1872 SectionNames.push_back(read_str());
1873 }
1874
1875 // If the file has module-level inline asm, read it now.
1876 if (At != BlockEnd)
1877 TheModule->setModuleInlineAsm(read_str());
1878
Chris Lattner404cddf2005-11-12 01:33:40 +00001879 // If any globals are in specified sections, assign them now.
1880 for (std::map<GlobalValue*, unsigned>::iterator I = SectionID.begin(), E =
1881 SectionID.end(); I != E; ++I)
1882 if (I->second) {
1883 if (I->second > SectionID.size())
1884 error("SectionID out of range for global!");
1885 I->first->setSection(SectionNames[I->second-1]);
1886 }
Reid Spencerad89bd62004-07-25 18:07:36 +00001887
Chris Lattner00950542001-06-06 20:29:01 +00001888 // This is for future proofing... in the future extra fields may be added that
1889 // we don't understand, so we transparently ignore them.
1890 //
Reid Spencer060d25d2004-06-29 23:29:38 +00001891 At = BlockEnd;
1892
Reid Spencer04cde2c2004-07-04 11:33:49 +00001893 if (Handler) Handler->handleModuleGlobalsEnd();
Chris Lattner00950542001-06-06 20:29:01 +00001894}
1895
Reid Spencer04cde2c2004-07-04 11:33:49 +00001896/// Parse the version information and decode it by setting flags on the
1897/// Reader that enable backward compatibility of the reader.
Reid Spencer060d25d2004-06-29 23:29:38 +00001898void BytecodeReader::ParseVersionInfo() {
Reid Spenceraacc35a2007-01-26 08:10:24 +00001899 unsigned RevisionNum = read_vbr_uint();
Chris Lattnere3869c82003-04-16 21:16:05 +00001900
Reid Spencer3795ad12006-12-03 05:47:10 +00001901 // We don't provide backwards compatibility in the Reader any more. To
1902 // upgrade, the user should use llvm-upgrade.
1903 if (RevisionNum < 7)
1904 error("Bytecode formats < 7 are no longer supported. Use llvm-upgrade.");
Chris Lattner036b8aa2003-03-06 17:55:45 +00001905
Reid Spenceraacc35a2007-01-26 08:10:24 +00001906 if (Handler) Handler->handleVersionInfo(RevisionNum);
Chris Lattner036b8aa2003-03-06 17:55:45 +00001907}
1908
Reid Spencer04cde2c2004-07-04 11:33:49 +00001909/// Parse a whole module.
Reid Spencer060d25d2004-06-29 23:29:38 +00001910void BytecodeReader::ParseModule() {
Chris Lattner00950542001-06-06 20:29:01 +00001911 unsigned Type, Size;
Chris Lattner00950542001-06-06 20:29:01 +00001912
Reid Spencer060d25d2004-06-29 23:29:38 +00001913 FunctionSignatureList.clear(); // Just in case...
Chris Lattner00950542001-06-06 20:29:01 +00001914
1915 // Read into instance variables...
Reid Spencer060d25d2004-06-29 23:29:38 +00001916 ParseVersionInfo();
Chris Lattner00950542001-06-06 20:29:01 +00001917
Reid Spencer060d25d2004-06-29 23:29:38 +00001918 bool SeenModuleGlobalInfo = false;
1919 bool SeenGlobalTypePlane = false;
1920 BufPtr MyEnd = BlockEnd;
1921 while (At < MyEnd) {
1922 BufPtr OldAt = At;
1923 read_block(Type, Size);
1924
Chris Lattner00950542001-06-06 20:29:01 +00001925 switch (Type) {
Reid Spencer060d25d2004-06-29 23:29:38 +00001926
Reid Spencerad89bd62004-07-25 18:07:36 +00001927 case BytecodeFormat::GlobalTypePlaneBlockID:
Reid Spencer46b002c2004-07-11 17:28:43 +00001928 if (SeenGlobalTypePlane)
Reid Spencer24399722004-07-09 22:21:33 +00001929 error("Two GlobalTypePlane Blocks Encountered!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001930
Reid Spencer5b472d92004-08-21 20:49:23 +00001931 if (Size > 0)
1932 ParseGlobalTypes();
Reid Spencer060d25d2004-06-29 23:29:38 +00001933 SeenGlobalTypePlane = true;
Chris Lattner52e20b02003-03-19 20:54:26 +00001934 break;
1935
Misha Brukman8a96c532005-04-21 21:44:41 +00001936 case BytecodeFormat::ModuleGlobalInfoBlockID:
Reid Spencer46b002c2004-07-11 17:28:43 +00001937 if (SeenModuleGlobalInfo)
Reid Spencer24399722004-07-09 22:21:33 +00001938 error("Two ModuleGlobalInfo Blocks Encountered!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001939 ParseModuleGlobalInfo();
1940 SeenModuleGlobalInfo = true;
Chris Lattner52e20b02003-03-19 20:54:26 +00001941 break;
1942
Reid Spencerad89bd62004-07-25 18:07:36 +00001943 case BytecodeFormat::ConstantPoolBlockID:
Reid Spencer04cde2c2004-07-04 11:33:49 +00001944 ParseConstantPool(ModuleValues, ModuleTypes,false);
Chris Lattner00950542001-06-06 20:29:01 +00001945 break;
1946
Reid Spencerad89bd62004-07-25 18:07:36 +00001947 case BytecodeFormat::FunctionBlockID:
Reid Spencer060d25d2004-06-29 23:29:38 +00001948 ParseFunctionLazily();
Chris Lattner00950542001-06-06 20:29:01 +00001949 break;
Chris Lattner00950542001-06-06 20:29:01 +00001950
Reid Spencer78d033e2007-01-06 07:24:44 +00001951 case BytecodeFormat::ValueSymbolTableBlockID:
1952 ParseValueSymbolTable(0, &TheModule->getValueSymbolTable());
1953 break;
1954
1955 case BytecodeFormat::TypeSymbolTableBlockID:
1956 ParseTypeSymbolTable(&TheModule->getTypeSymbolTable());
Chris Lattner00950542001-06-06 20:29:01 +00001957 break;
Reid Spencer060d25d2004-06-29 23:29:38 +00001958
Chris Lattner00950542001-06-06 20:29:01 +00001959 default:
Reid Spencer060d25d2004-06-29 23:29:38 +00001960 At += Size;
1961 if (OldAt > At) {
Reid Spencer46b002c2004-07-11 17:28:43 +00001962 error("Unexpected Block of Type #" + utostr(Type) + " encountered!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001963 }
Chris Lattner00950542001-06-06 20:29:01 +00001964 break;
1965 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001966 BlockEnd = MyEnd;
Chris Lattner00950542001-06-06 20:29:01 +00001967 }
1968
Chris Lattner52e20b02003-03-19 20:54:26 +00001969 // After the module constant pool has been read, we can safely initialize
1970 // global variables...
1971 while (!GlobalInits.empty()) {
1972 GlobalVariable *GV = GlobalInits.back().first;
1973 unsigned Slot = GlobalInits.back().second;
1974 GlobalInits.pop_back();
1975
1976 // Look up the initializer value...
Chris Lattner29b789b2003-11-19 17:27:18 +00001977 // FIXME: Preserve this type ID!
Reid Spencer060d25d2004-06-29 23:29:38 +00001978
1979 const llvm::PointerType* GVType = GV->getType();
1980 unsigned TypeSlot = getTypeSlot(GVType->getElementType());
Chris Lattner93361992004-01-15 18:45:25 +00001981 if (Constant *CV = getConstantValue(TypeSlot, Slot)) {
Misha Brukman8a96c532005-04-21 21:44:41 +00001982 if (GV->hasInitializer())
Reid Spencer24399722004-07-09 22:21:33 +00001983 error("Global *already* has an initializer?!");
Reid Spencer04cde2c2004-07-04 11:33:49 +00001984 if (Handler) Handler->handleGlobalInitializer(GV,CV);
Chris Lattner93361992004-01-15 18:45:25 +00001985 GV->setInitializer(CV);
Chris Lattner52e20b02003-03-19 20:54:26 +00001986 } else
Reid Spencer24399722004-07-09 22:21:33 +00001987 error("Cannot find initializer value.");
Chris Lattner52e20b02003-03-19 20:54:26 +00001988 }
1989
Chris Lattneraba5ff52005-05-05 20:57:00 +00001990 if (!ConstantFwdRefs.empty())
1991 error("Use of undefined constants in a module");
1992
Reid Spencer060d25d2004-06-29 23:29:38 +00001993 /// Make sure we pulled them all out. If we didn't then there's a declaration
1994 /// but a missing body. That's not allowed.
Misha Brukman12c29d12003-09-22 23:38:23 +00001995 if (!FunctionSignatureList.empty())
Reid Spencer24399722004-07-09 22:21:33 +00001996 error("Function declared, but bytecode stream ended before definition");
Chris Lattner00950542001-06-06 20:29:01 +00001997}
1998
Reid Spencer04cde2c2004-07-04 11:33:49 +00001999/// This function completely parses a bytecode buffer given by the \p Buf
2000/// and \p Length parameters.
Anton Korobeynikov7d515442006-09-01 20:35:17 +00002001bool BytecodeReader::ParseBytecode(volatile BufPtr Buf, unsigned Length,
Reid Spencer233fe722006-08-22 16:09:19 +00002002 const std::string &ModuleID,
Chris Lattnerf2e292c2007-02-07 21:41:02 +00002003 BCDecompressor_t *Decompressor,
Reid Spencer233fe722006-08-22 16:09:19 +00002004 std::string* ErrMsg) {
Misha Brukmane0dd0d42003-09-23 16:15:29 +00002005
Reid Spencer233fe722006-08-22 16:09:19 +00002006 /// We handle errors by
2007 if (setjmp(context)) {
2008 // Cleanup after error
2009 if (Handler) Handler->handleError(ErrorMsg);
Reid Spencer060d25d2004-06-29 23:29:38 +00002010 freeState();
Chris Lattner2a7b6ba2003-03-06 17:15:19 +00002011 delete TheModule;
2012 TheModule = 0;
Chris Lattner3bdad692004-11-15 21:55:33 +00002013 if (decompressedBlock != 0 ) {
Reid Spencer61aaf2e2004-11-14 21:59:21 +00002014 ::free(decompressedBlock);
Chris Lattner3bdad692004-11-15 21:55:33 +00002015 decompressedBlock = 0;
2016 }
Reid Spencer233fe722006-08-22 16:09:19 +00002017 // Set caller's error message, if requested
2018 if (ErrMsg)
2019 *ErrMsg = ErrorMsg;
2020 // Indicate an error occurred
2021 return true;
Chris Lattner2a7b6ba2003-03-06 17:15:19 +00002022 }
Reid Spencer233fe722006-08-22 16:09:19 +00002023
2024 RevisionNum = 0;
2025 At = MemStart = BlockStart = Buf;
2026 MemEnd = BlockEnd = Buf + Length;
2027
2028 // Create the module
2029 TheModule = new Module(ModuleID);
2030
2031 if (Handler) Handler->handleStart(TheModule, Length);
2032
2033 // Read the four bytes of the signature.
2034 unsigned Sig = read_uint();
2035
2036 // If this is a compressed file
2037 if (Sig == ('l' | ('l' << 8) | ('v' << 16) | ('c' << 24))) {
Chris Lattnerf2e292c2007-02-07 21:41:02 +00002038 if (!Decompressor) {
2039 error("Compressed bytecode found, but not decompressor available");
2040 }
Reid Spencer233fe722006-08-22 16:09:19 +00002041
2042 // Invoke the decompression of the bytecode. Note that we have to skip the
2043 // file's magic number which is not part of the compressed block. Hence,
2044 // the Buf+4 and Length-4. The result goes into decompressedBlock, a data
2045 // member for retention until BytecodeReader is destructed.
Chris Lattner0d3382a2007-02-07 19:49:01 +00002046 unsigned decompressedLength =
2047 Decompressor((char*)Buf+4,Length-4,decompressedBlock, 0);
Reid Spencer233fe722006-08-22 16:09:19 +00002048
2049 // We must adjust the buffer pointers used by the bytecode reader to point
2050 // into the new decompressed block. After decompression, the
2051 // decompressedBlock will point to a contiguous memory area that has
2052 // the decompressed data.
2053 At = MemStart = BlockStart = Buf = (BufPtr) decompressedBlock;
2054 MemEnd = BlockEnd = Buf + decompressedLength;
2055
2056 // else if this isn't a regular (uncompressed) bytecode file, then its
2057 // and error, generate that now.
2058 } else if (Sig != ('l' | ('l' << 8) | ('v' << 16) | ('m' << 24))) {
2059 error("Invalid bytecode signature: " + utohexstr(Sig));
2060 }
2061
2062 // Tell the handler we're starting a module
2063 if (Handler) Handler->handleModuleBegin(ModuleID);
2064
2065 // Get the module block and size and verify. This is handled specially
2066 // because the module block/size is always written in long format. Other
2067 // blocks are written in short format so the read_block method is used.
2068 unsigned Type, Size;
2069 Type = read_uint();
2070 Size = read_uint();
2071 if (Type != BytecodeFormat::ModuleBlockID) {
2072 error("Expected Module Block! Type:" + utostr(Type) + ", Size:"
2073 + utostr(Size));
2074 }
2075
2076 // It looks like the darwin ranlib program is broken, and adds trailing
2077 // garbage to the end of some bytecode files. This hack allows the bc
2078 // reader to ignore trailing garbage on bytecode files.
2079 if (At + Size < MemEnd)
2080 MemEnd = BlockEnd = At+Size;
2081
2082 if (At + Size != MemEnd)
2083 error("Invalid Top Level Block Length! Type:" + utostr(Type)
2084 + ", Size:" + utostr(Size));
2085
2086 // Parse the module contents
2087 this->ParseModule();
2088
2089 // Check for missing functions
2090 if (hasFunctions())
2091 error("Function expected, but bytecode stream ended!");
2092
Reid Spencer233fe722006-08-22 16:09:19 +00002093 // Tell the handler we're done with the module
2094 if (Handler)
2095 Handler->handleModuleEnd(ModuleID);
2096
2097 // Tell the handler we're finished the parse
2098 if (Handler) Handler->handleFinish();
2099
2100 return false;
2101
Chris Lattner00950542001-06-06 20:29:01 +00002102}
Reid Spencer060d25d2004-06-29 23:29:38 +00002103
2104//===----------------------------------------------------------------------===//
2105//=== Default Implementations of Handler Methods
2106//===----------------------------------------------------------------------===//
2107
2108BytecodeHandler::~BytecodeHandler() {}
Reid Spencer060d25d2004-06-29 23:29:38 +00002109