blob: 59c69d7c496ba7541c1be2aafce2191b6af5d754 [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 Spencer91ac04a2007-04-09 06:14:31 +000026#include "llvm/ParameterAttributes.h"
Reid Spencer78d033e2007-01-06 07:24:44 +000027#include "llvm/TypeSymbolTable.h"
Chris Lattner00950542001-06-06 20:29:01 +000028#include "llvm/Bytecode/Format.h"
Chris Lattnerdee199f2005-05-06 22:34:01 +000029#include "llvm/Config/alloca.h"
Reid Spencer060d25d2004-06-29 23:29:38 +000030#include "llvm/Support/GetElementPtrTypeIterator.h"
Jim Laskeycb6682f2005-08-17 19:34:49 +000031#include "llvm/Support/MathExtras.h"
Chris Lattner4c3d3a92007-01-31 19:56:15 +000032#include "llvm/ADT/SmallVector.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000033#include "llvm/ADT/StringExtras.h"
Reid Spencer060d25d2004-06-29 23:29:38 +000034#include <sstream>
Alkis Evlogimenos20aa4742004-09-03 18:19:51 +000035#include <algorithm>
Chris Lattner29b789b2003-11-19 17:27:18 +000036using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000037
Reid Spencer46b002c2004-07-11 17:28:43 +000038namespace {
Chris Lattnercad28bd2005-01-29 00:36:19 +000039 /// @brief A class for maintaining the slot number definition
40 /// as a placeholder for the actual definition for forward constants defs.
41 class ConstantPlaceHolder : public ConstantExpr {
42 ConstantPlaceHolder(); // DO NOT IMPLEMENT
43 void operator=(const ConstantPlaceHolder &); // DO NOT IMPLEMENT
44 public:
Chris Lattner61323322005-01-31 01:11:13 +000045 Use Op;
Misha Brukman8a96c532005-04-21 21:44:41 +000046 ConstantPlaceHolder(const Type *Ty)
Chris Lattner61323322005-01-31 01:11:13 +000047 : ConstantExpr(Ty, Instruction::UserOp1, &Op, 1),
Reid Spencer88cfda22006-12-31 05:44:24 +000048 Op(UndefValue::get(Type::Int32Ty), this) {
Chris Lattner61323322005-01-31 01:11:13 +000049 }
Chris Lattnercad28bd2005-01-29 00:36:19 +000050 };
Reid Spencer46b002c2004-07-11 17:28:43 +000051}
Reid Spencer060d25d2004-06-29 23:29:38 +000052
Reid Spencer24399722004-07-09 22:21:33 +000053// Provide some details on error
Reid Spencer233fe722006-08-22 16:09:19 +000054inline void BytecodeReader::error(const std::string& err) {
55 ErrorMsg = err + " (Vers=" + itostr(RevisionNum) + ", Pos="
56 + itostr(At-MemStart) + ")";
Reid Spenceref9b9a72007-02-05 20:47:22 +000057 if (Handler) Handler->handleError(ErrorMsg);
Reid Spencer233fe722006-08-22 16:09:19 +000058 longjmp(context,1);
Reid Spencer24399722004-07-09 22:21:33 +000059}
60
Reid Spencer060d25d2004-06-29 23:29:38 +000061//===----------------------------------------------------------------------===//
62// Bytecode Reading Methods
63//===----------------------------------------------------------------------===//
64
Reid Spencer04cde2c2004-07-04 11:33:49 +000065/// Determine if the current block being read contains any more data.
Reid Spencer060d25d2004-06-29 23:29:38 +000066inline bool BytecodeReader::moreInBlock() {
67 return At < BlockEnd;
Chris Lattner00950542001-06-06 20:29:01 +000068}
69
Reid Spencer04cde2c2004-07-04 11:33:49 +000070/// Throw an error if we've read past the end of the current block
Reid Spencer060d25d2004-06-29 23:29:38 +000071inline void BytecodeReader::checkPastBlockEnd(const char * block_name) {
Reid Spencer46b002c2004-07-11 17:28:43 +000072 if (At > BlockEnd)
Chris Lattnera79e7cc2004-10-16 18:18:16 +000073 error(std::string("Attempt to read past the end of ") + block_name +
74 " block.");
Reid Spencer060d25d2004-06-29 23:29:38 +000075}
Chris Lattner36392bc2003-10-08 21:18:57 +000076
Reid Spencer04cde2c2004-07-04 11:33:49 +000077/// Read a whole unsigned integer
Reid Spencer060d25d2004-06-29 23:29:38 +000078inline unsigned BytecodeReader::read_uint() {
Misha Brukman8a96c532005-04-21 21:44:41 +000079 if (At+4 > BlockEnd)
Reid Spencer24399722004-07-09 22:21:33 +000080 error("Ran out of data reading uint!");
Reid Spencer060d25d2004-06-29 23:29:38 +000081 At += 4;
82 return At[-4] | (At[-3] << 8) | (At[-2] << 16) | (At[-1] << 24);
83}
84
Reid Spencer04cde2c2004-07-04 11:33:49 +000085/// Read a variable-bit-rate encoded unsigned integer
Reid Spencer060d25d2004-06-29 23:29:38 +000086inline unsigned BytecodeReader::read_vbr_uint() {
87 unsigned Shift = 0;
88 unsigned Result = 0;
Misha Brukman8a96c532005-04-21 21:44:41 +000089
Reid Spencer060d25d2004-06-29 23:29:38 +000090 do {
Misha Brukman8a96c532005-04-21 21:44:41 +000091 if (At == BlockEnd)
Reid Spencer24399722004-07-09 22:21:33 +000092 error("Ran out of data reading vbr_uint!");
Reid Spencer060d25d2004-06-29 23:29:38 +000093 Result |= (unsigned)((*At++) & 0x7F) << Shift;
94 Shift += 7;
95 } while (At[-1] & 0x80);
Reid Spencer060d25d2004-06-29 23:29:38 +000096 return Result;
97}
98
Reid Spencer04cde2c2004-07-04 11:33:49 +000099/// Read a variable-bit-rate encoded unsigned 64-bit integer.
Reid Spencer060d25d2004-06-29 23:29:38 +0000100inline uint64_t BytecodeReader::read_vbr_uint64() {
101 unsigned Shift = 0;
102 uint64_t Result = 0;
Misha Brukman8a96c532005-04-21 21:44:41 +0000103
Reid Spencer060d25d2004-06-29 23:29:38 +0000104 do {
Misha Brukman8a96c532005-04-21 21:44:41 +0000105 if (At == BlockEnd)
Reid Spencer24399722004-07-09 22:21:33 +0000106 error("Ran out of data reading vbr_uint64!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000107 Result |= (uint64_t)((*At++) & 0x7F) << Shift;
108 Shift += 7;
109 } while (At[-1] & 0x80);
Reid Spencer060d25d2004-06-29 23:29:38 +0000110 return Result;
111}
112
Reid Spencer04cde2c2004-07-04 11:33:49 +0000113/// Read a variable-bit-rate encoded signed 64-bit integer.
Reid Spencer060d25d2004-06-29 23:29:38 +0000114inline int64_t BytecodeReader::read_vbr_int64() {
115 uint64_t R = read_vbr_uint64();
116 if (R & 1) {
117 if (R != 1)
118 return -(int64_t)(R >> 1);
119 else // There is no such thing as -0 with integers. "-0" really means
120 // 0x8000000000000000.
121 return 1LL << 63;
122 } else
123 return (int64_t)(R >> 1);
124}
125
Reid Spencer04cde2c2004-07-04 11:33:49 +0000126/// Read a pascal-style string (length followed by text)
Reid Spencer060d25d2004-06-29 23:29:38 +0000127inline std::string BytecodeReader::read_str() {
128 unsigned Size = read_vbr_uint();
129 const unsigned char *OldAt = At;
130 At += Size;
131 if (At > BlockEnd) // Size invalid?
Reid Spencer24399722004-07-09 22:21:33 +0000132 error("Ran out of data reading a string!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000133 return std::string((char*)OldAt, Size);
134}
135
Chris Lattnerdd8cec52007-02-12 18:53:43 +0000136void BytecodeReader::read_str(SmallVectorImpl<char> &StrData) {
137 StrData.clear();
138 unsigned Size = read_vbr_uint();
139 const unsigned char *OldAt = At;
140 At += Size;
141 if (At > BlockEnd) // Size invalid?
142 error("Ran out of data reading a string!");
143 StrData.append(OldAt, At);
144}
145
146
Reid Spencer04cde2c2004-07-04 11:33:49 +0000147/// Read an arbitrary block of data
Reid Spencer060d25d2004-06-29 23:29:38 +0000148inline void BytecodeReader::read_data(void *Ptr, void *End) {
149 unsigned char *Start = (unsigned char *)Ptr;
150 unsigned Amount = (unsigned char *)End - Start;
Misha Brukman8a96c532005-04-21 21:44:41 +0000151 if (At+Amount > BlockEnd)
Reid Spencer24399722004-07-09 22:21:33 +0000152 error("Ran out of data!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000153 std::copy(At, At+Amount, Start);
154 At += Amount;
155}
156
Reid Spencer46b002c2004-07-11 17:28:43 +0000157/// Read a float value in little-endian order
158inline void BytecodeReader::read_float(float& FloatVal) {
Reid Spencerada16182004-07-25 21:36:26 +0000159 /// FIXME: This isn't optimal, it has size problems on some platforms
160 /// where FP is not IEEE.
Jim Laskeycb6682f2005-08-17 19:34:49 +0000161 FloatVal = BitsToFloat(At[0] | (At[1] << 8) | (At[2] << 16) | (At[3] << 24));
Reid Spencerada16182004-07-25 21:36:26 +0000162 At+=sizeof(uint32_t);
Reid Spencer46b002c2004-07-11 17:28:43 +0000163}
164
165/// Read a double value in little-endian order
166inline void BytecodeReader::read_double(double& DoubleVal) {
Reid Spencerada16182004-07-25 21:36:26 +0000167 /// FIXME: This isn't optimal, it has size problems on some platforms
168 /// where FP is not IEEE.
Jim Laskeycb6682f2005-08-17 19:34:49 +0000169 DoubleVal = BitsToDouble((uint64_t(At[0]) << 0) | (uint64_t(At[1]) << 8) |
170 (uint64_t(At[2]) << 16) | (uint64_t(At[3]) << 24) |
171 (uint64_t(At[4]) << 32) | (uint64_t(At[5]) << 40) |
172 (uint64_t(At[6]) << 48) | (uint64_t(At[7]) << 56));
Reid Spencerada16182004-07-25 21:36:26 +0000173 At+=sizeof(uint64_t);
Reid Spencer46b002c2004-07-11 17:28:43 +0000174}
175
Reid Spencer04cde2c2004-07-04 11:33:49 +0000176/// Read a block header and obtain its type and size
Reid Spencer060d25d2004-06-29 23:29:38 +0000177inline void BytecodeReader::read_block(unsigned &Type, unsigned &Size) {
Reid Spencerd798a512006-11-14 04:47:22 +0000178 Size = read_uint(); // Read the header
179 Type = Size & 0x1F; // mask low order five bits to get type
180 Size >>= 5; // high order 27 bits is the size
Reid Spencer060d25d2004-06-29 23:29:38 +0000181 BlockStart = At;
Reid Spencer46b002c2004-07-11 17:28:43 +0000182 if (At + Size > BlockEnd)
Reid Spencer24399722004-07-09 22:21:33 +0000183 error("Attempt to size a block past end of memory");
Reid Spencer060d25d2004-06-29 23:29:38 +0000184 BlockEnd = At + Size;
Reid Spencer46b002c2004-07-11 17:28:43 +0000185 if (Handler) Handler->handleBlock(Type, BlockStart, Size);
Reid Spencer04cde2c2004-07-04 11:33:49 +0000186}
187
Reid Spencer060d25d2004-06-29 23:29:38 +0000188//===----------------------------------------------------------------------===//
189// IR Lookup Methods
190//===----------------------------------------------------------------------===//
191
Reid Spencer04cde2c2004-07-04 11:33:49 +0000192/// Determine if a type id has an implicit null value
Reid Spencer46b002c2004-07-11 17:28:43 +0000193inline bool BytecodeReader::hasImplicitNull(unsigned TyID) {
Reid Spencerd798a512006-11-14 04:47:22 +0000194 return TyID != Type::LabelTyID && TyID != Type::VoidTyID;
Reid Spencer060d25d2004-06-29 23:29:38 +0000195}
196
Reid Spencerd2bb8872007-01-30 19:36:46 +0000197/// Obtain a type given a typeid and account for things like function level vs
198/// module level, and the offsetting for the primitive types.
Reid Spencer060d25d2004-06-29 23:29:38 +0000199const Type *BytecodeReader::getType(unsigned ID) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000200 if (ID <= Type::LastPrimitiveTyID)
Chris Lattnerf70c22b2004-06-17 18:19:28 +0000201 if (const Type *T = Type::getPrimitiveType((Type::TypeID)ID))
Chris Lattner927b1852003-10-09 20:22:47 +0000202 return T; // Asked for a primitive type...
Chris Lattner36392bc2003-10-08 21:18:57 +0000203
204 // Otherwise, derived types need offset...
Chris Lattner89e02532004-01-18 21:08:15 +0000205 ID -= Type::FirstDerivedTyID;
206
Chris Lattner36392bc2003-10-08 21:18:57 +0000207 // Is it a module-level type?
Reid Spencer46b002c2004-07-11 17:28:43 +0000208 if (ID < ModuleTypes.size())
209 return ModuleTypes[ID].get();
Chris Lattner36392bc2003-10-08 21:18:57 +0000210
Reid Spencer46b002c2004-07-11 17:28:43 +0000211 // Nope, is it a function-level type?
212 ID -= ModuleTypes.size();
213 if (ID < FunctionTypes.size())
214 return FunctionTypes[ID].get();
Chris Lattner36392bc2003-10-08 21:18:57 +0000215
Reid Spencer46b002c2004-07-11 17:28:43 +0000216 error("Illegal type reference!");
217 return Type::VoidTy;
Chris Lattner00950542001-06-06 20:29:01 +0000218}
219
Reid Spencer3795ad12006-12-03 05:47:10 +0000220/// This method just saves some coding. It uses read_vbr_uint to read in a
221/// type id, errors that its not the type type, and then calls getType to
222/// return the type value.
Reid Spencerd798a512006-11-14 04:47:22 +0000223inline const Type* BytecodeReader::readType() {
224 return getType(read_vbr_uint());
Reid Spencer04cde2c2004-07-04 11:33:49 +0000225}
226
227/// Get the slot number associated with a type accounting for primitive
Reid Spencerd2bb8872007-01-30 19:36:46 +0000228/// types and function level vs module level.
Reid Spencer060d25d2004-06-29 23:29:38 +0000229unsigned BytecodeReader::getTypeSlot(const Type *Ty) {
230 if (Ty->isPrimitiveType())
231 return Ty->getTypeID();
232
Reid Spencer060d25d2004-06-29 23:29:38 +0000233 // Check the function level types first...
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000234 TypeListTy::iterator I = std::find(FunctionTypes.begin(),
235 FunctionTypes.end(), Ty);
Reid Spencer060d25d2004-06-29 23:29:38 +0000236
237 if (I != FunctionTypes.end())
Misha Brukman8a96c532005-04-21 21:44:41 +0000238 return Type::FirstDerivedTyID + ModuleTypes.size() +
Reid Spencer46b002c2004-07-11 17:28:43 +0000239 (&*I - &FunctionTypes[0]);
Reid Spencer060d25d2004-06-29 23:29:38 +0000240
Chris Lattnereebac5f2005-10-03 21:26:53 +0000241 // If we don't have our cache yet, build it now.
242 if (ModuleTypeIDCache.empty()) {
243 unsigned N = 0;
244 ModuleTypeIDCache.reserve(ModuleTypes.size());
245 for (TypeListTy::iterator I = ModuleTypes.begin(), E = ModuleTypes.end();
246 I != E; ++I, ++N)
247 ModuleTypeIDCache.push_back(std::make_pair(*I, N));
248
249 std::sort(ModuleTypeIDCache.begin(), ModuleTypeIDCache.end());
250 }
251
252 // Binary search the cache for the entry.
253 std::vector<std::pair<const Type*, unsigned> >::iterator IT =
254 std::lower_bound(ModuleTypeIDCache.begin(), ModuleTypeIDCache.end(),
255 std::make_pair(Ty, 0U));
256 if (IT == ModuleTypeIDCache.end() || IT->first != Ty)
Reid Spencer24399722004-07-09 22:21:33 +0000257 error("Didn't find type in ModuleTypes.");
Chris Lattnereebac5f2005-10-03 21:26:53 +0000258
259 return Type::FirstDerivedTyID + IT->second;
Chris Lattner80b97342004-01-17 23:25:43 +0000260}
261
Misha Brukman8a96c532005-04-21 21:44:41 +0000262/// Retrieve a value of a given type and slot number, possibly creating
263/// it if it doesn't already exist.
Reid Spencer060d25d2004-06-29 23:29:38 +0000264Value * BytecodeReader::getValue(unsigned type, unsigned oNum, bool Create) {
Chris Lattner4ee8ef22003-10-08 22:52:54 +0000265 assert(type != Type::LabelTyID && "getValue() cannot get blocks!");
Chris Lattner00950542001-06-06 20:29:01 +0000266 unsigned Num = oNum;
Chris Lattner00950542001-06-06 20:29:01 +0000267
Reid Spencerd2bb8872007-01-30 19:36:46 +0000268 // By default, the global type id is the type id passed in
269 unsigned GlobalTyID = type;
Reid Spencer060d25d2004-06-29 23:29:38 +0000270
Reid Spencerd2bb8872007-01-30 19:36:46 +0000271 if (hasImplicitNull(GlobalTyID)) {
272 const Type *Ty = getType(type);
273 if (!isa<OpaqueType>(Ty)) {
274 if (Num == 0)
275 return Constant::getNullValue(Ty);
276 --Num;
Chris Lattner89e02532004-01-18 21:08:15 +0000277 }
Reid Spencerd2bb8872007-01-30 19:36:46 +0000278 }
Chris Lattner89e02532004-01-18 21:08:15 +0000279
Reid Spencer8dd4f532007-04-08 23:58:41 +0000280 if (GlobalTyID < ModuleValues.size())
281 if (ValueList *Globals = ModuleValues[GlobalTyID]) {
282 if (Num < Globals->size())
283 return Globals->getOperand(Num);
284 Num -= Globals->size();
285 }
Chris Lattner52e20b02003-03-19 20:54:26 +0000286
Reid Spencer8dd4f532007-04-08 23:58:41 +0000287 if (type < FunctionValues.size())
288 if (ValueList *Locals = FunctionValues[type])
289 if (Num < Locals->size())
290 return Locals->getOperand(Num);
Chris Lattner00950542001-06-06 20:29:01 +0000291
Reid Spencer91ac04a2007-04-09 06:14:31 +0000292 // We did not find the value.
293
Chris Lattner74734132002-08-17 22:01:27 +0000294 if (!Create) return 0; // Do not create a placeholder?
Chris Lattner00950542001-06-06 20:29:01 +0000295
Reid Spencer551ccae2004-09-01 22:55:40 +0000296 // Did we already create a place holder?
Chris Lattner8eb10ce2003-10-09 06:05:40 +0000297 std::pair<unsigned,unsigned> KeyValue(type, oNum);
Reid Spencer060d25d2004-06-29 23:29:38 +0000298 ForwardReferenceMap::iterator I = ForwardReferences.lower_bound(KeyValue);
Chris Lattner8eb10ce2003-10-09 06:05:40 +0000299 if (I != ForwardReferences.end() && I->first == KeyValue)
300 return I->second; // We have already created this placeholder
301
Reid Spencer551ccae2004-09-01 22:55:40 +0000302 // If the type exists (it should)
303 if (const Type* Ty = getType(type)) {
304 // Create the place holder
305 Value *Val = new Argument(Ty);
306 ForwardReferences.insert(I, std::make_pair(KeyValue, Val));
307 return Val;
308 }
Reid Spencer233fe722006-08-22 16:09:19 +0000309 error("Can't create placeholder for value of type slot #" + utostr(type));
310 return 0; // just silence warning, error calls longjmp
Chris Lattner00950542001-06-06 20:29:01 +0000311}
312
Reid Spencer060d25d2004-06-29 23:29:38 +0000313
Reid Spencer04cde2c2004-07-04 11:33:49 +0000314/// Just like getValue, except that it returns a null pointer
315/// only on error. It always returns a constant (meaning that if the value is
316/// defined, but is not a constant, that is an error). If the specified
Misha Brukman8a96c532005-04-21 21:44:41 +0000317/// constant hasn't been parsed yet, a placeholder is defined and used.
Reid Spencer04cde2c2004-07-04 11:33:49 +0000318/// Later, after the real value is parsed, the placeholder is eliminated.
Reid Spencer060d25d2004-06-29 23:29:38 +0000319Constant* BytecodeReader::getConstantValue(unsigned TypeSlot, unsigned Slot) {
320 if (Value *V = getValue(TypeSlot, Slot, false))
321 if (Constant *C = dyn_cast<Constant>(V))
322 return C; // If we already have the value parsed, just return it
Reid Spencer060d25d2004-06-29 23:29:38 +0000323 else
Misha Brukman8a96c532005-04-21 21:44:41 +0000324 error("Value for slot " + utostr(Slot) +
Reid Spencera86037e2004-07-18 00:12:03 +0000325 " is expected to be a constant!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000326
Chris Lattner389bd042004-12-09 06:19:44 +0000327 std::pair<unsigned, unsigned> Key(TypeSlot, Slot);
Reid Spencer060d25d2004-06-29 23:29:38 +0000328 ConstantRefsType::iterator I = ConstantFwdRefs.lower_bound(Key);
329
330 if (I != ConstantFwdRefs.end() && I->first == Key) {
331 return I->second;
332 } else {
333 // Create a placeholder for the constant reference and
334 // keep track of the fact that we have a forward ref to recycle it
Chris Lattner389bd042004-12-09 06:19:44 +0000335 Constant *C = new ConstantPlaceHolder(getType(TypeSlot));
Misha Brukman8a96c532005-04-21 21:44:41 +0000336
Reid Spencer060d25d2004-06-29 23:29:38 +0000337 // Keep track of the fact that we have a forward ref to recycle it
338 ConstantFwdRefs.insert(I, std::make_pair(Key, C));
339 return C;
340 }
341}
342
343//===----------------------------------------------------------------------===//
344// IR Construction Methods
345//===----------------------------------------------------------------------===//
346
Reid Spencer04cde2c2004-07-04 11:33:49 +0000347/// As values are created, they are inserted into the appropriate place
348/// with this method. The ValueTable argument must be one of ModuleValues
349/// or FunctionValues data members of this class.
Misha Brukman8a96c532005-04-21 21:44:41 +0000350unsigned BytecodeReader::insertValue(Value *Val, unsigned type,
Reid Spencer46b002c2004-07-11 17:28:43 +0000351 ValueTable &ValueTab) {
Reid Spencer060d25d2004-06-29 23:29:38 +0000352 if (ValueTab.size() <= type)
353 ValueTab.resize(type+1);
354
355 if (!ValueTab[type]) ValueTab[type] = new ValueList();
356
357 ValueTab[type]->push_back(Val);
358
Chris Lattneraba5ff52005-05-05 20:57:00 +0000359 bool HasOffset = hasImplicitNull(type) && !isa<OpaqueType>(Val->getType());
Reid Spencer060d25d2004-06-29 23:29:38 +0000360 return ValueTab[type]->size()-1 + HasOffset;
361}
362
Reid Spencer04cde2c2004-07-04 11:33:49 +0000363/// Insert the arguments of a function as new values in the reader.
Reid Spencer46b002c2004-07-11 17:28:43 +0000364void BytecodeReader::insertArguments(Function* F) {
Reid Spencer060d25d2004-06-29 23:29:38 +0000365 const FunctionType *FT = F->getFunctionType();
Chris Lattnere4d5c442005-03-15 04:54:21 +0000366 Function::arg_iterator AI = F->arg_begin();
Reid Spencer060d25d2004-06-29 23:29:38 +0000367 for (FunctionType::param_iterator It = FT->param_begin();
368 It != FT->param_end(); ++It, ++AI)
369 insertValue(AI, getTypeSlot(AI->getType()), FunctionValues);
370}
371
372//===----------------------------------------------------------------------===//
373// Bytecode Parsing Methods
374//===----------------------------------------------------------------------===//
375
Reid Spencer04cde2c2004-07-04 11:33:49 +0000376/// This method parses a single instruction. The instruction is
377/// inserted at the end of the \p BB provided. The arguments of
Misha Brukman44666b12004-09-28 16:57:46 +0000378/// the instruction are provided in the \p Oprnds vector.
Chris Lattner63cf59e2007-02-07 05:08:39 +0000379void BytecodeReader::ParseInstruction(SmallVector<unsigned, 8> &Oprnds,
Reid Spencer46b002c2004-07-11 17:28:43 +0000380 BasicBlock* BB) {
Reid Spencer060d25d2004-06-29 23:29:38 +0000381 BufPtr SaveAt = At;
382
383 // Clear instruction data
384 Oprnds.clear();
385 unsigned iType = 0;
386 unsigned Opcode = 0;
387 unsigned Op = read_uint();
388
389 // bits Instruction format: Common to all formats
390 // --------------------------
391 // 01-00: Opcode type, fixed to 1.
392 // 07-02: Opcode
393 Opcode = (Op >> 2) & 63;
394 Oprnds.resize((Op >> 0) & 03);
395
396 // Extract the operands
397 switch (Oprnds.size()) {
398 case 1:
399 // bits Instruction format:
400 // --------------------------
401 // 19-08: Resulting type plane
402 // 31-20: Operand #1 (if set to (2^12-1), then zero operands)
403 //
404 iType = (Op >> 8) & 4095;
405 Oprnds[0] = (Op >> 20) & 4095;
406 if (Oprnds[0] == 4095) // Handle special encoding for 0 operands...
407 Oprnds.resize(0);
408 break;
409 case 2:
410 // bits Instruction format:
411 // --------------------------
412 // 15-08: Resulting type plane
413 // 23-16: Operand #1
Misha Brukman8a96c532005-04-21 21:44:41 +0000414 // 31-24: Operand #2
Reid Spencer060d25d2004-06-29 23:29:38 +0000415 //
416 iType = (Op >> 8) & 255;
417 Oprnds[0] = (Op >> 16) & 255;
418 Oprnds[1] = (Op >> 24) & 255;
419 break;
420 case 3:
421 // bits Instruction format:
422 // --------------------------
423 // 13-08: Resulting type plane
424 // 19-14: Operand #1
425 // 25-20: Operand #2
426 // 31-26: Operand #3
427 //
428 iType = (Op >> 8) & 63;
429 Oprnds[0] = (Op >> 14) & 63;
430 Oprnds[1] = (Op >> 20) & 63;
431 Oprnds[2] = (Op >> 26) & 63;
432 break;
433 case 0:
434 At -= 4; // Hrm, try this again...
435 Opcode = read_vbr_uint();
436 Opcode >>= 2;
437 iType = read_vbr_uint();
438
439 unsigned NumOprnds = read_vbr_uint();
440 Oprnds.resize(NumOprnds);
441
442 if (NumOprnds == 0)
Reid Spencer24399722004-07-09 22:21:33 +0000443 error("Zero-argument instruction found; this is invalid.");
Reid Spencer060d25d2004-06-29 23:29:38 +0000444
445 for (unsigned i = 0; i != NumOprnds; ++i)
446 Oprnds[i] = read_vbr_uint();
Reid Spencer060d25d2004-06-29 23:29:38 +0000447 break;
448 }
449
Reid Spencerd798a512006-11-14 04:47:22 +0000450 const Type *InstTy = getType(iType);
Reid Spencer060d25d2004-06-29 23:29:38 +0000451
Reid Spencer1628cec2006-10-26 06:15:43 +0000452 // Make the necessary adjustments for dealing with backwards compatibility
453 // of opcodes.
Reid Spencer3795ad12006-12-03 05:47:10 +0000454 Instruction* Result = 0;
Reid Spencer1628cec2006-10-26 06:15:43 +0000455
Reid Spencer3795ad12006-12-03 05:47:10 +0000456 // First, handle the easy binary operators case
457 if (Opcode >= Instruction::BinaryOpsBegin &&
Reid Spencerc8dab492006-12-03 06:28:54 +0000458 Opcode < Instruction::BinaryOpsEnd && Oprnds.size() == 2) {
Reid Spencer3795ad12006-12-03 05:47:10 +0000459 Result = BinaryOperator::create(Instruction::BinaryOps(Opcode),
460 getValue(iType, Oprnds[0]),
461 getValue(iType, Oprnds[1]));
Reid Spencerc8dab492006-12-03 06:28:54 +0000462 } else {
Reid Spencer1628cec2006-10-26 06:15:43 +0000463 // Indicate that we don't think this is a call instruction (yet).
464 // Process based on the Opcode read
465 switch (Opcode) {
466 default: // There was an error, this shouldn't happen.
467 if (Result == 0)
468 error("Illegal instruction read!");
469 break;
470 case Instruction::VAArg:
471 if (Oprnds.size() != 2)
472 error("Invalid VAArg instruction!");
473 Result = new VAArgInst(getValue(iType, Oprnds[0]),
Reid Spencerd798a512006-11-14 04:47:22 +0000474 getType(Oprnds[1]));
Reid Spencer1628cec2006-10-26 06:15:43 +0000475 break;
476 case Instruction::ExtractElement: {
477 if (Oprnds.size() != 2)
478 error("Invalid extractelement instruction!");
479 Value *V1 = getValue(iType, Oprnds[0]);
Reid Spencera54b7cb2007-01-12 07:05:14 +0000480 Value *V2 = getValue(Int32TySlot, Oprnds[1]);
Chris Lattner59fecec2006-04-08 04:09:19 +0000481
Reid Spencer1628cec2006-10-26 06:15:43 +0000482 if (!ExtractElementInst::isValidOperands(V1, V2))
483 error("Invalid extractelement instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000484
Reid Spencer1628cec2006-10-26 06:15:43 +0000485 Result = new ExtractElementInst(V1, V2);
486 break;
Chris Lattnera65371e2006-05-26 18:42:34 +0000487 }
Reid Spencer1628cec2006-10-26 06:15:43 +0000488 case Instruction::InsertElement: {
Reid Spencerac9dcb92007-02-15 03:39:18 +0000489 const VectorType *VectorTy = dyn_cast<VectorType>(InstTy);
490 if (!VectorTy || Oprnds.size() != 3)
Reid Spencer1628cec2006-10-26 06:15:43 +0000491 error("Invalid insertelement instruction!");
492
493 Value *V1 = getValue(iType, Oprnds[0]);
Reid Spencerac9dcb92007-02-15 03:39:18 +0000494 Value *V2 = getValue(getTypeSlot(VectorTy->getElementType()),Oprnds[1]);
Reid Spencera54b7cb2007-01-12 07:05:14 +0000495 Value *V3 = getValue(Int32TySlot, Oprnds[2]);
Reid Spencer1628cec2006-10-26 06:15:43 +0000496
497 if (!InsertElementInst::isValidOperands(V1, V2, V3))
498 error("Invalid insertelement instruction!");
499 Result = new InsertElementInst(V1, V2, V3);
500 break;
501 }
502 case Instruction::ShuffleVector: {
Reid Spencerac9dcb92007-02-15 03:39:18 +0000503 const VectorType *VectorTy = dyn_cast<VectorType>(InstTy);
504 if (!VectorTy || Oprnds.size() != 3)
Reid Spencer1628cec2006-10-26 06:15:43 +0000505 error("Invalid shufflevector instruction!");
506 Value *V1 = getValue(iType, Oprnds[0]);
507 Value *V2 = getValue(iType, Oprnds[1]);
Reid Spencer9d6565a2007-02-15 02:26:10 +0000508 const VectorType *EltTy =
Reid Spencerac9dcb92007-02-15 03:39:18 +0000509 VectorType::get(Type::Int32Ty, VectorTy->getNumElements());
Reid Spencer1628cec2006-10-26 06:15:43 +0000510 Value *V3 = getValue(getTypeSlot(EltTy), Oprnds[2]);
511 if (!ShuffleVectorInst::isValidOperands(V1, V2, V3))
512 error("Invalid shufflevector instruction!");
513 Result = new ShuffleVectorInst(V1, V2, V3);
514 break;
515 }
Reid Spencer3da59db2006-11-27 01:05:10 +0000516 case Instruction::Trunc:
517 if (Oprnds.size() != 2)
518 error("Invalid cast instruction!");
519 Result = new TruncInst(getValue(iType, Oprnds[0]),
520 getType(Oprnds[1]));
521 break;
522 case Instruction::ZExt:
523 if (Oprnds.size() != 2)
524 error("Invalid cast instruction!");
525 Result = new ZExtInst(getValue(iType, Oprnds[0]),
526 getType(Oprnds[1]));
527 break;
528 case Instruction::SExt:
Reid Spencer1628cec2006-10-26 06:15:43 +0000529 if (Oprnds.size() != 2)
530 error("Invalid Cast instruction!");
Reid Spencer3da59db2006-11-27 01:05:10 +0000531 Result = new SExtInst(getValue(iType, Oprnds[0]),
Reid Spencerd798a512006-11-14 04:47:22 +0000532 getType(Oprnds[1]));
Reid Spencer1628cec2006-10-26 06:15:43 +0000533 break;
Reid Spencer3da59db2006-11-27 01:05:10 +0000534 case Instruction::FPTrunc:
535 if (Oprnds.size() != 2)
536 error("Invalid cast instruction!");
537 Result = new FPTruncInst(getValue(iType, Oprnds[0]),
538 getType(Oprnds[1]));
539 break;
540 case Instruction::FPExt:
541 if (Oprnds.size() != 2)
542 error("Invalid cast instruction!");
543 Result = new FPExtInst(getValue(iType, Oprnds[0]),
544 getType(Oprnds[1]));
545 break;
546 case Instruction::UIToFP:
547 if (Oprnds.size() != 2)
548 error("Invalid cast instruction!");
549 Result = new UIToFPInst(getValue(iType, Oprnds[0]),
550 getType(Oprnds[1]));
551 break;
552 case Instruction::SIToFP:
553 if (Oprnds.size() != 2)
554 error("Invalid cast instruction!");
555 Result = new SIToFPInst(getValue(iType, Oprnds[0]),
556 getType(Oprnds[1]));
557 break;
558 case Instruction::FPToUI:
559 if (Oprnds.size() != 2)
560 error("Invalid cast instruction!");
561 Result = new FPToUIInst(getValue(iType, Oprnds[0]),
562 getType(Oprnds[1]));
563 break;
564 case Instruction::FPToSI:
565 if (Oprnds.size() != 2)
566 error("Invalid cast instruction!");
567 Result = new FPToSIInst(getValue(iType, Oprnds[0]),
568 getType(Oprnds[1]));
569 break;
570 case Instruction::IntToPtr:
571 if (Oprnds.size() != 2)
572 error("Invalid cast instruction!");
573 Result = new IntToPtrInst(getValue(iType, Oprnds[0]),
574 getType(Oprnds[1]));
575 break;
576 case Instruction::PtrToInt:
577 if (Oprnds.size() != 2)
578 error("Invalid cast instruction!");
579 Result = new PtrToIntInst(getValue(iType, Oprnds[0]),
580 getType(Oprnds[1]));
581 break;
582 case Instruction::BitCast:
583 if (Oprnds.size() != 2)
584 error("Invalid cast instruction!");
585 Result = new BitCastInst(getValue(iType, Oprnds[0]),
586 getType(Oprnds[1]));
587 break;
Reid Spencer1628cec2006-10-26 06:15:43 +0000588 case Instruction::Select:
589 if (Oprnds.size() != 3)
590 error("Invalid Select instruction!");
Reid Spencera54b7cb2007-01-12 07:05:14 +0000591 Result = new SelectInst(getValue(BoolTySlot, Oprnds[0]),
Reid Spencer1628cec2006-10-26 06:15:43 +0000592 getValue(iType, Oprnds[1]),
593 getValue(iType, Oprnds[2]));
594 break;
595 case Instruction::PHI: {
596 if (Oprnds.size() == 0 || (Oprnds.size() & 1))
597 error("Invalid phi node encountered!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000598
Reid Spencer1628cec2006-10-26 06:15:43 +0000599 PHINode *PN = new PHINode(InstTy);
600 PN->reserveOperandSpace(Oprnds.size());
601 for (unsigned i = 0, e = Oprnds.size(); i != e; i += 2)
602 PN->addIncoming(
603 getValue(iType, Oprnds[i]), getBasicBlock(Oprnds[i+1]));
604 Result = PN;
605 break;
606 }
Reid Spencerc8dab492006-12-03 06:28:54 +0000607 case Instruction::ICmp:
608 case Instruction::FCmp:
Reid Spencer9f132762006-12-03 17:17:02 +0000609 if (Oprnds.size() != 3)
610 error("Cmp instructions requires 3 operands");
Reid Spencerc8dab492006-12-03 06:28:54 +0000611 // These instructions encode the comparison predicate as the 3rd operand.
612 Result = CmpInst::create(Instruction::OtherOps(Opcode),
613 static_cast<unsigned short>(Oprnds[2]),
614 getValue(iType, Oprnds[0]), getValue(iType, Oprnds[1]));
615 break;
Reid Spencer1628cec2006-10-26 06:15:43 +0000616 case Instruction::Ret:
617 if (Oprnds.size() == 0)
618 Result = new ReturnInst();
619 else if (Oprnds.size() == 1)
620 Result = new ReturnInst(getValue(iType, Oprnds[0]));
621 else
622 error("Unrecognized instruction!");
623 break;
624
625 case Instruction::Br:
626 if (Oprnds.size() == 1)
627 Result = new BranchInst(getBasicBlock(Oprnds[0]));
628 else if (Oprnds.size() == 3)
629 Result = new BranchInst(getBasicBlock(Oprnds[0]),
Reid Spencera54b7cb2007-01-12 07:05:14 +0000630 getBasicBlock(Oprnds[1]), getValue(BoolTySlot, Oprnds[2]));
Reid Spencer1628cec2006-10-26 06:15:43 +0000631 else
632 error("Invalid number of operands for a 'br' instruction!");
633 break;
634 case Instruction::Switch: {
635 if (Oprnds.size() & 1)
636 error("Switch statement with odd number of arguments!");
637
638 SwitchInst *I = new SwitchInst(getValue(iType, Oprnds[0]),
639 getBasicBlock(Oprnds[1]),
640 Oprnds.size()/2-1);
641 for (unsigned i = 2, e = Oprnds.size(); i != e; i += 2)
642 I->addCase(cast<ConstantInt>(getValue(iType, Oprnds[i])),
643 getBasicBlock(Oprnds[i+1]));
644 Result = I;
645 break;
646 }
647 case 58: // Call with extra operand for calling conv
648 case 59: // tail call, Fast CC
649 case 60: // normal call, Fast CC
650 case 61: // tail call, C Calling Conv
651 case Instruction::Call: { // Normal Call, C Calling Convention
652 if (Oprnds.size() == 0)
653 error("Invalid call instruction encountered!");
Reid Spencer1628cec2006-10-26 06:15:43 +0000654 Value *F = getValue(iType, Oprnds[0]);
655
656 unsigned CallingConv = CallingConv::C;
657 bool isTailCall = false;
658
659 if (Opcode == 61 || Opcode == 59)
660 isTailCall = true;
661
662 if (Opcode == 58) {
663 isTailCall = Oprnds.back() & 1;
664 CallingConv = Oprnds.back() >> 1;
665 Oprnds.pop_back();
666 } else if (Opcode == 59 || Opcode == 60) {
667 CallingConv = CallingConv::Fast;
668 }
669
670 // Check to make sure we have a pointer to function type
671 const PointerType *PTy = dyn_cast<PointerType>(F->getType());
672 if (PTy == 0) error("Call to non function pointer value!");
673 const FunctionType *FTy = dyn_cast<FunctionType>(PTy->getElementType());
674 if (FTy == 0) error("Call to non function pointer value!");
675
Chris Lattnerd0e44c22007-02-13 06:30:42 +0000676 SmallVector<Value *, 8> Params;
Reid Spencer1628cec2006-10-26 06:15:43 +0000677 if (!FTy->isVarArg()) {
678 FunctionType::param_iterator It = FTy->param_begin();
679
680 for (unsigned i = 1, e = Oprnds.size(); i != e; ++i) {
681 if (It == FTy->param_end())
682 error("Invalid call instruction!");
683 Params.push_back(getValue(getTypeSlot(*It++), Oprnds[i]));
684 }
685 if (It != FTy->param_end())
Reid Spencer24399722004-07-09 22:21:33 +0000686 error("Invalid call instruction!");
Reid Spencer1628cec2006-10-26 06:15:43 +0000687 } else {
688 Oprnds.erase(Oprnds.begin(), Oprnds.begin()+1);
689
690 unsigned FirstVariableOperand;
691 if (Oprnds.size() < FTy->getNumParams())
692 error("Call instruction missing operands!");
693
694 // Read all of the fixed arguments
695 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
696 Params.push_back(
697 getValue(getTypeSlot(FTy->getParamType(i)),Oprnds[i]));
698
699 FirstVariableOperand = FTy->getNumParams();
700
701 if ((Oprnds.size()-FirstVariableOperand) & 1)
702 error("Invalid call instruction!"); // Must be pairs of type/value
703
704 for (unsigned i = FirstVariableOperand, e = Oprnds.size();
705 i != e; i += 2)
706 Params.push_back(getValue(Oprnds[i], Oprnds[i+1]));
Reid Spencer060d25d2004-06-29 23:29:38 +0000707 }
Reid Spencer060d25d2004-06-29 23:29:38 +0000708
Chris Lattnere4339192007-02-13 01:53:54 +0000709 Result = new CallInst(F, &Params[0], Params.size());
Reid Spencer1628cec2006-10-26 06:15:43 +0000710 if (isTailCall) cast<CallInst>(Result)->setTailCall();
711 if (CallingConv) cast<CallInst>(Result)->setCallingConv(CallingConv);
712 break;
Reid Spencer060d25d2004-06-29 23:29:38 +0000713 }
Reid Spencer1628cec2006-10-26 06:15:43 +0000714 case Instruction::Invoke: { // Invoke C CC
715 if (Oprnds.size() < 3)
716 error("Invalid invoke instruction!");
717 Value *F = getValue(iType, Oprnds[0]);
Reid Spencer060d25d2004-06-29 23:29:38 +0000718
Reid Spencer1628cec2006-10-26 06:15:43 +0000719 // Check to make sure we have a pointer to function type
720 const PointerType *PTy = dyn_cast<PointerType>(F->getType());
721 if (PTy == 0)
722 error("Invoke to non function pointer value!");
723 const FunctionType *FTy = dyn_cast<FunctionType>(PTy->getElementType());
724 if (FTy == 0)
725 error("Invoke to non function pointer value!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000726
Chris Lattnerd0e44c22007-02-13 06:30:42 +0000727 SmallVector<Value *, 8> Params;
Reid Spencer1628cec2006-10-26 06:15:43 +0000728 BasicBlock *Normal, *Except;
Reid Spencer3da59db2006-11-27 01:05:10 +0000729 unsigned CallingConv = Oprnds.back();
730 Oprnds.pop_back();
Chris Lattnerdee199f2005-05-06 22:34:01 +0000731
Reid Spencer1628cec2006-10-26 06:15:43 +0000732 if (!FTy->isVarArg()) {
733 Normal = getBasicBlock(Oprnds[1]);
734 Except = getBasicBlock(Oprnds[2]);
Reid Spencer060d25d2004-06-29 23:29:38 +0000735
Reid Spencer1628cec2006-10-26 06:15:43 +0000736 FunctionType::param_iterator It = FTy->param_begin();
737 for (unsigned i = 3, e = Oprnds.size(); i != e; ++i) {
738 if (It == FTy->param_end())
739 error("Invalid invoke instruction!");
740 Params.push_back(getValue(getTypeSlot(*It++), Oprnds[i]));
741 }
742 if (It != FTy->param_end())
Reid Spencer24399722004-07-09 22:21:33 +0000743 error("Invalid invoke instruction!");
Reid Spencer1628cec2006-10-26 06:15:43 +0000744 } else {
745 Oprnds.erase(Oprnds.begin(), Oprnds.begin()+1);
746
747 Normal = getBasicBlock(Oprnds[0]);
748 Except = getBasicBlock(Oprnds[1]);
749
750 unsigned FirstVariableArgument = FTy->getNumParams()+2;
751 for (unsigned i = 2; i != FirstVariableArgument; ++i)
752 Params.push_back(getValue(getTypeSlot(FTy->getParamType(i-2)),
753 Oprnds[i]));
754
755 // Must be type/value pairs. If not, error out.
756 if (Oprnds.size()-FirstVariableArgument & 1)
757 error("Invalid invoke instruction!");
758
759 for (unsigned i = FirstVariableArgument; i < Oprnds.size(); i += 2)
760 Params.push_back(getValue(Oprnds[i], Oprnds[i+1]));
Reid Spencer060d25d2004-06-29 23:29:38 +0000761 }
Reid Spencer060d25d2004-06-29 23:29:38 +0000762
Chris Lattnere4339192007-02-13 01:53:54 +0000763 Result = new InvokeInst(F, Normal, Except, &Params[0], Params.size());
Reid Spencer1628cec2006-10-26 06:15:43 +0000764 if (CallingConv) cast<InvokeInst>(Result)->setCallingConv(CallingConv);
765 break;
Reid Spencer060d25d2004-06-29 23:29:38 +0000766 }
Reid Spencer1628cec2006-10-26 06:15:43 +0000767 case Instruction::Malloc: {
768 unsigned Align = 0;
769 if (Oprnds.size() == 2)
770 Align = (1 << Oprnds[1]) >> 1;
771 else if (Oprnds.size() > 2)
772 error("Invalid malloc instruction!");
773 if (!isa<PointerType>(InstTy))
774 error("Invalid malloc instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000775
Reid Spencer1628cec2006-10-26 06:15:43 +0000776 Result = new MallocInst(cast<PointerType>(InstTy)->getElementType(),
Reid Spencera54b7cb2007-01-12 07:05:14 +0000777 getValue(Int32TySlot, Oprnds[0]), Align);
Reid Spencer1628cec2006-10-26 06:15:43 +0000778 break;
779 }
780 case Instruction::Alloca: {
781 unsigned Align = 0;
782 if (Oprnds.size() == 2)
783 Align = (1 << Oprnds[1]) >> 1;
784 else if (Oprnds.size() > 2)
785 error("Invalid alloca instruction!");
786 if (!isa<PointerType>(InstTy))
787 error("Invalid alloca instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000788
Reid Spencer1628cec2006-10-26 06:15:43 +0000789 Result = new AllocaInst(cast<PointerType>(InstTy)->getElementType(),
Reid Spencera54b7cb2007-01-12 07:05:14 +0000790 getValue(Int32TySlot, Oprnds[0]), Align);
Reid Spencer1628cec2006-10-26 06:15:43 +0000791 break;
792 }
793 case Instruction::Free:
794 if (!isa<PointerType>(InstTy))
795 error("Invalid free instruction!");
796 Result = new FreeInst(getValue(iType, Oprnds[0]));
797 break;
798 case Instruction::GetElementPtr: {
799 if (Oprnds.size() == 0 || !isa<PointerType>(InstTy))
Misha Brukman8a96c532005-04-21 21:44:41 +0000800 error("Invalid getelementptr instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000801
Chris Lattner4c3d3a92007-01-31 19:56:15 +0000802 SmallVector<Value*, 8> Idx;
Reid Spencer1628cec2006-10-26 06:15:43 +0000803
804 const Type *NextTy = InstTy;
805 for (unsigned i = 1, e = Oprnds.size(); i != e; ++i) {
806 const CompositeType *TopTy = dyn_cast_or_null<CompositeType>(NextTy);
807 if (!TopTy)
808 error("Invalid getelementptr instruction!");
809
810 unsigned ValIdx = Oprnds[i];
811 unsigned IdxTy = 0;
Reid Spencerd798a512006-11-14 04:47:22 +0000812 // Struct indices are always uints, sequential type indices can be
813 // any of the 32 or 64-bit integer types. The actual choice of
Reid Spencer88cfda22006-12-31 05:44:24 +0000814 // type is encoded in the low bit of the slot number.
Reid Spencerd798a512006-11-14 04:47:22 +0000815 if (isa<StructType>(TopTy))
Reid Spencera54b7cb2007-01-12 07:05:14 +0000816 IdxTy = Int32TySlot;
Reid Spencerd798a512006-11-14 04:47:22 +0000817 else {
Reid Spencer88cfda22006-12-31 05:44:24 +0000818 switch (ValIdx & 1) {
Reid Spencerd798a512006-11-14 04:47:22 +0000819 default:
Reid Spencera54b7cb2007-01-12 07:05:14 +0000820 case 0: IdxTy = Int32TySlot; break;
821 case 1: IdxTy = Int64TySlot; break;
Reid Spencer060d25d2004-06-29 23:29:38 +0000822 }
Reid Spencer88cfda22006-12-31 05:44:24 +0000823 ValIdx >>= 1;
Reid Spencer060d25d2004-06-29 23:29:38 +0000824 }
Reid Spencer1628cec2006-10-26 06:15:43 +0000825 Idx.push_back(getValue(IdxTy, ValIdx));
Chris Lattner4c3d3a92007-01-31 19:56:15 +0000826 NextTy = GetElementPtrInst::getIndexedType(InstTy, &Idx[0], Idx.size(),
827 true);
Reid Spencer060d25d2004-06-29 23:29:38 +0000828 }
829
Chris Lattner4c3d3a92007-01-31 19:56:15 +0000830 Result = new GetElementPtrInst(getValue(iType, Oprnds[0]),
831 &Idx[0], Idx.size());
Reid Spencer1628cec2006-10-26 06:15:43 +0000832 break;
Reid Spencer060d25d2004-06-29 23:29:38 +0000833 }
Christopher Lamb2330e4d2007-04-21 08:16:25 +0000834 case 62: { // attributed load
835 if (Oprnds.size() != 2 || !isa<PointerType>(InstTy))
836 error("Invalid attributed load instruction!");
837 signed Log2AlignVal = ((Oprnds[1]>>1)-1);
838 Result = new LoadInst(getValue(iType, Oprnds[0]), "", (Oprnds[1] & 1),
839 ((Log2AlignVal < 0) ? 0 : 1<<Log2AlignVal));
840 break;
841 }
Reid Spencer1628cec2006-10-26 06:15:43 +0000842 case Instruction::Load:
843 if (Oprnds.size() != 1 || !isa<PointerType>(InstTy))
844 error("Invalid load instruction!");
Christopher Lamb2330e4d2007-04-21 08:16:25 +0000845 Result = new LoadInst(getValue(iType, Oprnds[0]), "");
Reid Spencer1628cec2006-10-26 06:15:43 +0000846 break;
Christopher Lamb2330e4d2007-04-21 08:16:25 +0000847 case 63: { // attributed store
848 if (!isa<PointerType>(InstTy) || Oprnds.size() != 3)
849 error("Invalid store instruction!");
850
851 Value *Ptr = getValue(iType, Oprnds[1]);
852 const Type *ValTy = cast<PointerType>(Ptr->getType())->getElementType();
853 signed Log2AlignVal = ((Oprnds[2]>>1)-1);
854 Result = new StoreInst(getValue(getTypeSlot(ValTy), Oprnds[0]), Ptr,
855 (Oprnds[2] & 1),
856 ((Log2AlignVal < 0) ? 0 : 1<<Log2AlignVal));
857 break;
858 }
Reid Spencer1628cec2006-10-26 06:15:43 +0000859 case Instruction::Store: {
860 if (!isa<PointerType>(InstTy) || Oprnds.size() != 2)
861 error("Invalid store instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000862
Reid Spencer1628cec2006-10-26 06:15:43 +0000863 Value *Ptr = getValue(iType, Oprnds[1]);
864 const Type *ValTy = cast<PointerType>(Ptr->getType())->getElementType();
865 Result = new StoreInst(getValue(getTypeSlot(ValTy), Oprnds[0]), Ptr,
866 Opcode == 63);
867 break;
868 }
869 case Instruction::Unwind:
870 if (Oprnds.size() != 0) error("Invalid unwind instruction!");
871 Result = new UnwindInst();
872 break;
873 case Instruction::Unreachable:
874 if (Oprnds.size() != 0) error("Invalid unreachable instruction!");
875 Result = new UnreachableInst();
876 break;
877 } // end switch(Opcode)
Reid Spencer3795ad12006-12-03 05:47:10 +0000878 } // end if !Result
Reid Spencer060d25d2004-06-29 23:29:38 +0000879
Reid Spencere1e96c02006-01-19 07:02:16 +0000880 BB->getInstList().push_back(Result);
881
Reid Spencer060d25d2004-06-29 23:29:38 +0000882 unsigned TypeSlot;
883 if (Result->getType() == InstTy)
884 TypeSlot = iType;
885 else
886 TypeSlot = getTypeSlot(Result->getType());
887
Reid Spenceref9b9a72007-02-05 20:47:22 +0000888 // We have enough info to inform the handler now.
889 if (Handler)
Chris Lattner63cf59e2007-02-07 05:08:39 +0000890 Handler->handleInstruction(Opcode, InstTy, &Oprnds[0], Oprnds.size(),
891 Result, At-SaveAt);
Reid Spenceref9b9a72007-02-05 20:47:22 +0000892
Reid Spencer060d25d2004-06-29 23:29:38 +0000893 insertValue(Result, TypeSlot, FunctionValues);
Reid Spencer060d25d2004-06-29 23:29:38 +0000894}
895
Reid Spencer04cde2c2004-07-04 11:33:49 +0000896/// Get a particular numbered basic block, which might be a forward reference.
Reid Spencerd798a512006-11-14 04:47:22 +0000897/// This works together with ParseInstructionList to handle these forward
898/// references in a clean manner. This function is used when constructing
899/// phi, br, switch, and other instructions that reference basic blocks.
900/// Blocks are numbered sequentially as they appear in the function.
Reid Spencer060d25d2004-06-29 23:29:38 +0000901BasicBlock *BytecodeReader::getBasicBlock(unsigned ID) {
Chris Lattner4ee8ef22003-10-08 22:52:54 +0000902 // Make sure there is room in the table...
903 if (ParsedBasicBlocks.size() <= ID) ParsedBasicBlocks.resize(ID+1);
904
Reid Spencerd798a512006-11-14 04:47:22 +0000905 // First check to see if this is a backwards reference, i.e. this block
906 // has already been created, or if the forward reference has already
Chris Lattner4ee8ef22003-10-08 22:52:54 +0000907 // been created.
908 if (ParsedBasicBlocks[ID])
909 return ParsedBasicBlocks[ID];
910
911 // Otherwise, the basic block has not yet been created. Do so and add it to
912 // the ParsedBasicBlocks list.
913 return ParsedBasicBlocks[ID] = new BasicBlock();
914}
915
Reid Spencer04cde2c2004-07-04 11:33:49 +0000916/// Parse all of the BasicBlock's & Instruction's in the body of a function.
Misha Brukman8a96c532005-04-21 21:44:41 +0000917/// In post 1.0 bytecode files, we no longer emit basic block individually,
Reid Spencer04cde2c2004-07-04 11:33:49 +0000918/// in order to avoid per-basic-block overhead.
Reid Spencerd798a512006-11-14 04:47:22 +0000919/// @returns the number of basic blocks encountered.
Reid Spencer060d25d2004-06-29 23:29:38 +0000920unsigned BytecodeReader::ParseInstructionList(Function* F) {
Chris Lattner8d1dbd22003-12-01 07:05:31 +0000921 unsigned BlockNo = 0;
Chris Lattner63cf59e2007-02-07 05:08:39 +0000922 SmallVector<unsigned, 8> Args;
Chris Lattner8d1dbd22003-12-01 07:05:31 +0000923
Reid Spencer46b002c2004-07-11 17:28:43 +0000924 while (moreInBlock()) {
925 if (Handler) Handler->handleBasicBlockBegin(BlockNo);
Chris Lattner8d1dbd22003-12-01 07:05:31 +0000926 BasicBlock *BB;
927 if (ParsedBasicBlocks.size() == BlockNo)
928 ParsedBasicBlocks.push_back(BB = new BasicBlock());
929 else if (ParsedBasicBlocks[BlockNo] == 0)
930 BB = ParsedBasicBlocks[BlockNo] = new BasicBlock();
931 else
932 BB = ParsedBasicBlocks[BlockNo];
933 ++BlockNo;
934 F->getBasicBlockList().push_back(BB);
935
936 // Read instructions into this basic block until we get to a terminator
Reid Spencer46b002c2004-07-11 17:28:43 +0000937 while (moreInBlock() && !BB->getTerminator())
Reid Spencer060d25d2004-06-29 23:29:38 +0000938 ParseInstruction(Args, BB);
Chris Lattner8d1dbd22003-12-01 07:05:31 +0000939
940 if (!BB->getTerminator())
Reid Spencer24399722004-07-09 22:21:33 +0000941 error("Non-terminated basic block found!");
Reid Spencer5c15fe52004-07-05 00:57:50 +0000942
Reid Spencer46b002c2004-07-11 17:28:43 +0000943 if (Handler) Handler->handleBasicBlockEnd(BlockNo-1);
Chris Lattner8d1dbd22003-12-01 07:05:31 +0000944 }
945
946 return BlockNo;
947}
948
Reid Spencer78d033e2007-01-06 07:24:44 +0000949/// Parse a type symbol table.
950void BytecodeReader::ParseTypeSymbolTable(TypeSymbolTable *TST) {
951 // Type Symtab block header: [num entries]
952 unsigned NumEntries = read_vbr_uint();
953 for (unsigned i = 0; i < NumEntries; ++i) {
954 // Symtab entry: [type slot #][name]
955 unsigned slot = read_vbr_uint();
956 std::string Name = read_str();
957 const Type* T = getType(slot);
958 TST->insert(Name, T);
959 }
960}
961
962/// Parse a value symbol table. This works for both module level and function
Reid Spencer04cde2c2004-07-04 11:33:49 +0000963/// level symbol tables. For function level symbol tables, the CurrentFunction
964/// parameter must be non-zero and the ST parameter must correspond to
965/// CurrentFunction's symbol table. For Module level symbol tables, the
966/// CurrentFunction argument must be zero.
Reid Spencer78d033e2007-01-06 07:24:44 +0000967void BytecodeReader::ParseValueSymbolTable(Function *CurrentFunction,
Reid Spenceref9b9a72007-02-05 20:47:22 +0000968 ValueSymbolTable *VST) {
Reid Spencer78d033e2007-01-06 07:24:44 +0000969
Reid Spenceref9b9a72007-02-05 20:47:22 +0000970 if (Handler) Handler->handleValueSymbolTableBegin(CurrentFunction,VST);
Reid Spencer060d25d2004-06-29 23:29:38 +0000971
Chris Lattner39cacce2003-10-10 05:43:47 +0000972 // Allow efficient basic block lookup by number.
Chris Lattner63cf59e2007-02-07 05:08:39 +0000973 SmallVector<BasicBlock*, 32> BBMap;
Chris Lattner39cacce2003-10-10 05:43:47 +0000974 if (CurrentFunction)
975 for (Function::iterator I = CurrentFunction->begin(),
976 E = CurrentFunction->end(); I != E; ++I)
977 BBMap.push_back(I);
978
Chris Lattnerdd8cec52007-02-12 18:53:43 +0000979 SmallVector<char, 32> NameStr;
980
Reid Spencer46b002c2004-07-11 17:28:43 +0000981 while (moreInBlock()) {
Chris Lattner00950542001-06-06 20:29:01 +0000982 // Symtab block header: [num entries][type id number]
Reid Spencer060d25d2004-06-29 23:29:38 +0000983 unsigned NumEntries = read_vbr_uint();
Reid Spencerd798a512006-11-14 04:47:22 +0000984 unsigned Typ = read_vbr_uint();
Chris Lattner1d670cc2001-09-07 16:37:43 +0000985
Chris Lattner7dc3a2e2003-10-13 14:57:53 +0000986 for (unsigned i = 0; i != NumEntries; ++i) {
Chris Lattner00950542001-06-06 20:29:01 +0000987 // Symtab entry: [def slot #][name]
Reid Spencer060d25d2004-06-29 23:29:38 +0000988 unsigned slot = read_vbr_uint();
Chris Lattnerdd8cec52007-02-12 18:53:43 +0000989 read_str(NameStr);
Reid Spencerd798a512006-11-14 04:47:22 +0000990 Value *V = 0;
Reid Spencera54b7cb2007-01-12 07:05:14 +0000991 if (Typ == LabelTySlot) {
Chris Lattnerdd8cec52007-02-12 18:53:43 +0000992 V = (slot < BBMap.size()) ? BBMap[slot] : 0;
Chris Lattner39cacce2003-10-10 05:43:47 +0000993 } else {
Chris Lattnerdd8cec52007-02-12 18:53:43 +0000994 V = getValue(Typ, slot, false); // Find mapping.
Chris Lattner39cacce2003-10-10 05:43:47 +0000995 }
Chris Lattnerdd8cec52007-02-12 18:53:43 +0000996 if (Handler) Handler->handleSymbolTableValue(Typ, slot,
997 &NameStr[0], NameStr.size());
Reid Spencerd798a512006-11-14 04:47:22 +0000998 if (V == 0)
Chris Lattnerdd8cec52007-02-12 18:53:43 +0000999 error("Failed value look-up for name '" +
1000 std::string(NameStr.begin(), NameStr.end()) + "', type #" +
Reid Spenceref9b9a72007-02-05 20:47:22 +00001001 utostr(Typ) + " slot #" + utostr(slot));
Chris Lattnerdd8cec52007-02-12 18:53:43 +00001002 V->setName(&NameStr[0], NameStr.size());
1003
1004 NameStr.clear();
Chris Lattner00950542001-06-06 20:29:01 +00001005 }
1006 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001007 checkPastBlockEnd("Symbol Table");
Reid Spenceref9b9a72007-02-05 20:47:22 +00001008 if (Handler) Handler->handleValueSymbolTableEnd();
Chris Lattner00950542001-06-06 20:29:01 +00001009}
1010
Reid Spencer46b002c2004-07-11 17:28:43 +00001011// Parse a single type. The typeid is read in first. If its a primitive type
1012// then nothing else needs to be read, we know how to instantiate it. If its
Misha Brukman8a96c532005-04-21 21:44:41 +00001013// a derived type, then additional data is read to fill out the type
Reid Spencer46b002c2004-07-11 17:28:43 +00001014// definition.
1015const Type *BytecodeReader::ParseType() {
Reid Spencerd798a512006-11-14 04:47:22 +00001016 unsigned PrimType = read_vbr_uint();
Reid Spencer060d25d2004-06-29 23:29:38 +00001017 const Type *Result = 0;
1018 if ((Result = Type::getPrimitiveType((Type::TypeID)PrimType)))
1019 return Result;
Misha Brukman8a96c532005-04-21 21:44:41 +00001020
Reid Spencer060d25d2004-06-29 23:29:38 +00001021 switch (PrimType) {
Reid Spencera54b7cb2007-01-12 07:05:14 +00001022 case Type::IntegerTyID: {
1023 unsigned NumBits = read_vbr_uint();
1024 Result = IntegerType::get(NumBits);
1025 break;
1026 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001027 case Type::FunctionTyID: {
Reid Spencerd798a512006-11-14 04:47:22 +00001028 const Type *RetType = readType();
Reid Spencer060d25d2004-06-29 23:29:38 +00001029 unsigned NumParams = read_vbr_uint();
1030
1031 std::vector<const Type*> Params;
Reid Spencer88cfda22006-12-31 05:44:24 +00001032 while (NumParams--) {
Reid Spencerd798a512006-11-14 04:47:22 +00001033 Params.push_back(readType());
Reid Spencer88cfda22006-12-31 05:44:24 +00001034 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001035
1036 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
Reid Spencer91ac04a2007-04-09 06:14:31 +00001037 if (isVarArg)
1038 Params.pop_back();
1039
1040 ParamAttrsList *Attrs = ParseParamAttrsList();
Reid Spencer060d25d2004-06-29 23:29:38 +00001041
Reid Spencer88cfda22006-12-31 05:44:24 +00001042 Result = FunctionType::get(RetType, Params, isVarArg, Attrs);
Reid Spencer060d25d2004-06-29 23:29:38 +00001043 break;
1044 }
1045 case Type::ArrayTyID: {
Reid Spencerd798a512006-11-14 04:47:22 +00001046 const Type *ElementType = readType();
Reid Spencer060d25d2004-06-29 23:29:38 +00001047 unsigned NumElements = read_vbr_uint();
Reid Spencer060d25d2004-06-29 23:29:38 +00001048 Result = ArrayType::get(ElementType, NumElements);
1049 break;
1050 }
Reid Spencer9d6565a2007-02-15 02:26:10 +00001051 case Type::VectorTyID: {
Reid Spencerd798a512006-11-14 04:47:22 +00001052 const Type *ElementType = readType();
Brian Gaeke715c90b2004-08-20 06:00:58 +00001053 unsigned NumElements = read_vbr_uint();
Reid Spencer9d6565a2007-02-15 02:26:10 +00001054 Result = VectorType::get(ElementType, NumElements);
Brian Gaeke715c90b2004-08-20 06:00:58 +00001055 break;
1056 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001057 case Type::StructTyID: {
1058 std::vector<const Type*> Elements;
Reid Spencerd798a512006-11-14 04:47:22 +00001059 unsigned Typ = read_vbr_uint();
Reid Spencer060d25d2004-06-29 23:29:38 +00001060 while (Typ) { // List is terminated by void/0 typeid
1061 Elements.push_back(getType(Typ));
Reid Spencerd798a512006-11-14 04:47:22 +00001062 Typ = read_vbr_uint();
Reid Spencer060d25d2004-06-29 23:29:38 +00001063 }
1064
Andrew Lenharth38ecbf12006-12-08 18:06:16 +00001065 Result = StructType::get(Elements, false);
1066 break;
1067 }
Reid Spencera54b7cb2007-01-12 07:05:14 +00001068 case Type::PackedStructTyID: {
Andrew Lenharth38ecbf12006-12-08 18:06:16 +00001069 std::vector<const Type*> Elements;
1070 unsigned Typ = read_vbr_uint();
1071 while (Typ) { // List is terminated by void/0 typeid
1072 Elements.push_back(getType(Typ));
1073 Typ = read_vbr_uint();
1074 }
1075
1076 Result = StructType::get(Elements, true);
Reid Spencer060d25d2004-06-29 23:29:38 +00001077 break;
1078 }
1079 case Type::PointerTyID: {
Reid Spencerd798a512006-11-14 04:47:22 +00001080 Result = PointerType::get(readType());
Reid Spencer060d25d2004-06-29 23:29:38 +00001081 break;
1082 }
1083
1084 case Type::OpaqueTyID: {
1085 Result = OpaqueType::get();
1086 break;
1087 }
1088
1089 default:
Reid Spencer24399722004-07-09 22:21:33 +00001090 error("Don't know how to deserialize primitive type " + utostr(PrimType));
Reid Spencer060d25d2004-06-29 23:29:38 +00001091 break;
1092 }
Reid Spencer46b002c2004-07-11 17:28:43 +00001093 if (Handler) Handler->handleType(Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001094 return Result;
1095}
1096
Reid Spencer91ac04a2007-04-09 06:14:31 +00001097ParamAttrsList *BytecodeReader::ParseParamAttrsList() {
1098 unsigned NumAttrs = read_vbr_uint();
1099 ParamAttrsList *Attrs = 0;
1100 if (NumAttrs) {
1101 Attrs = new ParamAttrsList();
1102 while (NumAttrs--) {
1103 uint16_t index = read_vbr_uint();
1104 uint16_t attrs = read_vbr_uint();
1105 Attrs->addAttributes(index, attrs);
1106 }
1107 }
1108 return Attrs;
1109}
1110
1111
Reid Spencer5b472d92004-08-21 20:49:23 +00001112// ParseTypes - We have to use this weird code to handle recursive
Reid Spencer060d25d2004-06-29 23:29:38 +00001113// types. We know that recursive types will only reference the current slab of
1114// values in the type plane, but they can forward reference types before they
1115// have been read. For example, Type #0 might be '{ Ty#1 }' and Type #1 might
1116// be 'Ty#0*'. When reading Type #0, type number one doesn't exist. To fix
1117// this ugly problem, we pessimistically insert an opaque type for each type we
1118// are about to read. This means that forward references will resolve to
1119// something and when we reread the type later, we can replace the opaque type
1120// with a new resolved concrete type.
1121//
Reid Spencer46b002c2004-07-11 17:28:43 +00001122void BytecodeReader::ParseTypes(TypeListTy &Tab, unsigned NumEntries){
Reid Spencer060d25d2004-06-29 23:29:38 +00001123 assert(Tab.size() == 0 && "should not have read type constants in before!");
1124
1125 // Insert a bunch of opaque types to be resolved later...
1126 Tab.reserve(NumEntries);
1127 for (unsigned i = 0; i != NumEntries; ++i)
1128 Tab.push_back(OpaqueType::get());
1129
Misha Brukman8a96c532005-04-21 21:44:41 +00001130 if (Handler)
Reid Spencer5b472d92004-08-21 20:49:23 +00001131 Handler->handleTypeList(NumEntries);
1132
Chris Lattnereebac5f2005-10-03 21:26:53 +00001133 // If we are about to resolve types, make sure the type cache is clear.
1134 if (NumEntries)
1135 ModuleTypeIDCache.clear();
1136
Reid Spencer060d25d2004-06-29 23:29:38 +00001137 // Loop through reading all of the types. Forward types will make use of the
1138 // opaque types just inserted.
1139 //
1140 for (unsigned i = 0; i != NumEntries; ++i) {
Reid Spencer46b002c2004-07-11 17:28:43 +00001141 const Type* NewTy = ParseType();
Reid Spencer04cde2c2004-07-04 11:33:49 +00001142 const Type* OldTy = Tab[i].get();
Misha Brukman8a96c532005-04-21 21:44:41 +00001143 if (NewTy == 0)
Reid Spencer24399722004-07-09 22:21:33 +00001144 error("Couldn't parse type!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001145
Misha Brukman8a96c532005-04-21 21:44:41 +00001146 // Don't directly push the new type on the Tab. Instead we want to replace
Reid Spencer060d25d2004-06-29 23:29:38 +00001147 // the opaque type we previously inserted with the new concrete value. This
1148 // approach helps with forward references to types. The refinement from the
1149 // abstract (opaque) type to the new type causes all uses of the abstract
1150 // type to use the concrete type (NewTy). This will also cause the opaque
1151 // type to be deleted.
1152 cast<DerivedType>(const_cast<Type*>(OldTy))->refineAbstractTypeTo(NewTy);
1153
1154 // This should have replaced the old opaque type with the new type in the
1155 // value table... or with a preexisting type that was already in the system.
1156 // Let's just make sure it did.
1157 assert(Tab[i] != OldTy && "refineAbstractType didn't work!");
1158 }
1159}
1160
Reid Spencer04cde2c2004-07-04 11:33:49 +00001161/// Parse a single constant value
Chris Lattner3bc5a602006-01-25 23:08:15 +00001162Value *BytecodeReader::ParseConstantPoolValue(unsigned TypeID) {
Reid Spencer060d25d2004-06-29 23:29:38 +00001163 // We must check for a ConstantExpr before switching by type because
1164 // a ConstantExpr can be of any type, and has no explicit value.
Misha Brukman8a96c532005-04-21 21:44:41 +00001165 //
Reid Spencer060d25d2004-06-29 23:29:38 +00001166 // 0 if not expr; numArgs if is expr
1167 unsigned isExprNumArgs = read_vbr_uint();
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001168
Reid Spencer060d25d2004-06-29 23:29:38 +00001169 if (isExprNumArgs) {
Reid Spencerd798a512006-11-14 04:47:22 +00001170 // 'undef' is encoded with 'exprnumargs' == 1.
1171 if (isExprNumArgs == 1)
1172 return UndefValue::get(getType(TypeID));
Misha Brukman8a96c532005-04-21 21:44:41 +00001173
Reid Spencerd798a512006-11-14 04:47:22 +00001174 // Inline asm is encoded with exprnumargs == ~0U.
1175 if (isExprNumArgs == ~0U) {
1176 std::string AsmStr = read_str();
1177 std::string ConstraintStr = read_str();
1178 unsigned Flags = read_vbr_uint();
Chris Lattner3bc5a602006-01-25 23:08:15 +00001179
Reid Spencerd798a512006-11-14 04:47:22 +00001180 const PointerType *PTy = dyn_cast<PointerType>(getType(TypeID));
1181 const FunctionType *FTy =
1182 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
1183
1184 if (!FTy || !InlineAsm::Verify(FTy, ConstraintStr))
1185 error("Invalid constraints for inline asm");
1186 if (Flags & ~1U)
1187 error("Invalid flags for inline asm");
1188 bool HasSideEffects = Flags & 1;
1189 return InlineAsm::get(FTy, AsmStr, ConstraintStr, HasSideEffects);
Chris Lattner3bc5a602006-01-25 23:08:15 +00001190 }
Reid Spencerd798a512006-11-14 04:47:22 +00001191
1192 --isExprNumArgs;
Chris Lattner3bc5a602006-01-25 23:08:15 +00001193
Reid Spencer060d25d2004-06-29 23:29:38 +00001194 // FIXME: Encoding of constant exprs could be much more compact!
Chris Lattner670ccfe2007-02-07 05:15:28 +00001195 SmallVector<Constant*, 8> ArgVec;
Reid Spencer060d25d2004-06-29 23:29:38 +00001196 ArgVec.reserve(isExprNumArgs);
1197 unsigned Opcode = read_vbr_uint();
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001198
Reid Spencer060d25d2004-06-29 23:29:38 +00001199 // Read the slot number and types of each of the arguments
1200 for (unsigned i = 0; i != isExprNumArgs; ++i) {
1201 unsigned ArgValSlot = read_vbr_uint();
Reid Spencerd798a512006-11-14 04:47:22 +00001202 unsigned ArgTypeSlot = read_vbr_uint();
Misha Brukman8a96c532005-04-21 21:44:41 +00001203
Reid Spencer060d25d2004-06-29 23:29:38 +00001204 // Get the arg value from its slot if it exists, otherwise a placeholder
1205 ArgVec.push_back(getConstantValue(ArgTypeSlot, ArgValSlot));
1206 }
Misha Brukman8a96c532005-04-21 21:44:41 +00001207
Reid Spencer060d25d2004-06-29 23:29:38 +00001208 // Construct a ConstantExpr of the appropriate kind
1209 if (isExprNumArgs == 1) { // All one-operand expressions
Reid Spencer3da59db2006-11-27 01:05:10 +00001210 if (!Instruction::isCast(Opcode))
Chris Lattner02dce162004-12-04 05:28:27 +00001211 error("Only cast instruction has one argument for ConstantExpr");
Reid Spencer46b002c2004-07-11 17:28:43 +00001212
Reid Spencera77fa7e2006-12-11 23:20:20 +00001213 Constant *Result = ConstantExpr::getCast(Opcode, ArgVec[0],
1214 getType(TypeID));
Chris Lattner63cf59e2007-02-07 05:08:39 +00001215 if (Handler) Handler->handleConstantExpression(Opcode, &ArgVec[0],
1216 ArgVec.size(), Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001217 return Result;
1218 } else if (Opcode == Instruction::GetElementPtr) { // GetElementPtr
Chris Lattnere0135402007-01-31 04:43:46 +00001219 Constant *Result = ConstantExpr::getGetElementPtr(ArgVec[0], &ArgVec[1],
1220 ArgVec.size()-1);
Chris Lattner63cf59e2007-02-07 05:08:39 +00001221 if (Handler) Handler->handleConstantExpression(Opcode, &ArgVec[0],
1222 ArgVec.size(), Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001223 return Result;
1224 } else if (Opcode == Instruction::Select) {
Reid Spencer46b002c2004-07-11 17:28:43 +00001225 if (ArgVec.size() != 3)
1226 error("Select instruction must have three arguments.");
Misha Brukman8a96c532005-04-21 21:44:41 +00001227 Constant* Result = ConstantExpr::getSelect(ArgVec[0], ArgVec[1],
Reid Spencer04cde2c2004-07-04 11:33:49 +00001228 ArgVec[2]);
Chris Lattner63cf59e2007-02-07 05:08:39 +00001229 if (Handler) Handler->handleConstantExpression(Opcode, &ArgVec[0],
1230 ArgVec.size(), Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001231 return Result;
Robert Bocchinofee31b32006-01-10 19:04:39 +00001232 } else if (Opcode == Instruction::ExtractElement) {
Chris Lattner59fecec2006-04-08 04:09:19 +00001233 if (ArgVec.size() != 2 ||
1234 !ExtractElementInst::isValidOperands(ArgVec[0], ArgVec[1]))
1235 error("Invalid extractelement constand expr arguments");
Robert Bocchinofee31b32006-01-10 19:04:39 +00001236 Constant* Result = ConstantExpr::getExtractElement(ArgVec[0], ArgVec[1]);
Chris Lattner63cf59e2007-02-07 05:08:39 +00001237 if (Handler) Handler->handleConstantExpression(Opcode, &ArgVec[0],
1238 ArgVec.size(), Result);
Robert Bocchinofee31b32006-01-10 19:04:39 +00001239 return Result;
Robert Bocchinob1f240b2006-01-17 20:06:35 +00001240 } else if (Opcode == Instruction::InsertElement) {
Chris Lattner59fecec2006-04-08 04:09:19 +00001241 if (ArgVec.size() != 3 ||
1242 !InsertElementInst::isValidOperands(ArgVec[0], ArgVec[1], ArgVec[2]))
1243 error("Invalid insertelement constand expr arguments");
1244
1245 Constant *Result =
Robert Bocchinob1f240b2006-01-17 20:06:35 +00001246 ConstantExpr::getInsertElement(ArgVec[0], ArgVec[1], ArgVec[2]);
Chris Lattner63cf59e2007-02-07 05:08:39 +00001247 if (Handler) Handler->handleConstantExpression(Opcode, &ArgVec[0],
1248 ArgVec.size(), Result);
Robert Bocchinob1f240b2006-01-17 20:06:35 +00001249 return Result;
Chris Lattner30b44b62006-04-08 01:17:59 +00001250 } else if (Opcode == Instruction::ShuffleVector) {
1251 if (ArgVec.size() != 3 ||
1252 !ShuffleVectorInst::isValidOperands(ArgVec[0], ArgVec[1], ArgVec[2]))
Chris Lattner59fecec2006-04-08 04:09:19 +00001253 error("Invalid shufflevector constant expr arguments.");
Chris Lattner30b44b62006-04-08 01:17:59 +00001254 Constant *Result =
1255 ConstantExpr::getShuffleVector(ArgVec[0], ArgVec[1], ArgVec[2]);
Chris Lattner63cf59e2007-02-07 05:08:39 +00001256 if (Handler) Handler->handleConstantExpression(Opcode, &ArgVec[0],
1257 ArgVec.size(), Result);
Chris Lattner30b44b62006-04-08 01:17:59 +00001258 return Result;
Reid Spencer9f132762006-12-03 17:17:02 +00001259 } else if (Opcode == Instruction::ICmp) {
1260 if (ArgVec.size() != 2)
Reid Spencer595b4772006-12-04 05:23:49 +00001261 error("Invalid ICmp constant expr arguments.");
1262 unsigned predicate = read_vbr_uint();
1263 Constant *Result = ConstantExpr::getICmp(predicate, ArgVec[0], ArgVec[1]);
Chris Lattner63cf59e2007-02-07 05:08:39 +00001264 if (Handler) Handler->handleConstantExpression(Opcode, &ArgVec[0],
1265 ArgVec.size(), Result);
Reid Spencer595b4772006-12-04 05:23:49 +00001266 return Result;
Reid Spencer9f132762006-12-03 17:17:02 +00001267 } else if (Opcode == Instruction::FCmp) {
1268 if (ArgVec.size() != 2)
Reid Spencer595b4772006-12-04 05:23:49 +00001269 error("Invalid FCmp constant expr arguments.");
1270 unsigned predicate = read_vbr_uint();
1271 Constant *Result = ConstantExpr::getFCmp(predicate, ArgVec[0], ArgVec[1]);
Chris Lattner63cf59e2007-02-07 05:08:39 +00001272 if (Handler) Handler->handleConstantExpression(Opcode, &ArgVec[0],
1273 ArgVec.size(), Result);
Reid Spencer595b4772006-12-04 05:23:49 +00001274 return Result;
Reid Spencer060d25d2004-06-29 23:29:38 +00001275 } else { // All other 2-operand expressions
1276 Constant* Result = ConstantExpr::get(Opcode, ArgVec[0], ArgVec[1]);
Chris Lattner63cf59e2007-02-07 05:08:39 +00001277 if (Handler) Handler->handleConstantExpression(Opcode, &ArgVec[0],
1278 ArgVec.size(), Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001279 return Result;
1280 }
1281 }
Misha Brukman8a96c532005-04-21 21:44:41 +00001282
Reid Spencer060d25d2004-06-29 23:29:38 +00001283 // Ok, not an ConstantExpr. We now know how to read the given type...
1284 const Type *Ty = getType(TypeID);
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001285 Constant *Result = 0;
Reid Spencer060d25d2004-06-29 23:29:38 +00001286 switch (Ty->getTypeID()) {
Reid Spencera54b7cb2007-01-12 07:05:14 +00001287 case Type::IntegerTyID: {
1288 const IntegerType *IT = cast<IntegerType>(Ty);
1289 if (IT->getBitWidth() <= 32) {
1290 uint32_t Val = read_vbr_uint();
Reid Spencerb61c1ce2007-01-13 00:09:12 +00001291 if (!ConstantInt::isValueValidForType(Ty, uint64_t(Val)))
1292 error("Integer value read is invalid for type.");
1293 Result = ConstantInt::get(IT, Val);
1294 if (Handler) Handler->handleConstantValue(Result);
Reid Spencera54b7cb2007-01-12 07:05:14 +00001295 } else if (IT->getBitWidth() <= 64) {
1296 uint64_t Val = read_vbr_uint64();
1297 if (!ConstantInt::isValueValidForType(Ty, Val))
1298 error("Invalid constant integer read.");
1299 Result = ConstantInt::get(IT, Val);
1300 if (Handler) Handler->handleConstantValue(Result);
Reid Spencerfa1353c2007-02-28 02:25:48 +00001301 } else {
1302 uint32_t numWords = read_vbr_uint();
1303 uint64_t *data = new uint64_t[numWords];
1304 for (uint32_t i = 0; i < numWords; ++i)
1305 data[i] = read_vbr_uint64();
Reid Spencere2a6acd2007-03-01 20:25:31 +00001306 Result = ConstantInt::get(APInt(IT->getBitWidth(), numWords, data));
Reid Spencerfa1353c2007-02-28 02:25:48 +00001307 if (Handler) Handler->handleConstantValue(Result);
1308 }
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001309 break;
Reid Spencer060d25d2004-06-29 23:29:38 +00001310 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001311 case Type::FloatTyID: {
Reid Spencer46b002c2004-07-11 17:28:43 +00001312 float Val;
1313 read_float(Val);
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001314 Result = ConstantFP::get(Ty, Val);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001315 if (Handler) Handler->handleConstantValue(Result);
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001316 break;
Reid Spencer060d25d2004-06-29 23:29:38 +00001317 }
1318
1319 case Type::DoubleTyID: {
1320 double Val;
Reid Spencer46b002c2004-07-11 17:28:43 +00001321 read_double(Val);
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001322 Result = ConstantFP::get(Ty, Val);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001323 if (Handler) Handler->handleConstantValue(Result);
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001324 break;
Reid Spencer060d25d2004-06-29 23:29:38 +00001325 }
1326
Reid Spencer060d25d2004-06-29 23:29:38 +00001327 case Type::ArrayTyID: {
1328 const ArrayType *AT = cast<ArrayType>(Ty);
1329 unsigned NumElements = AT->getNumElements();
1330 unsigned TypeSlot = getTypeSlot(AT->getElementType());
1331 std::vector<Constant*> Elements;
1332 Elements.reserve(NumElements);
1333 while (NumElements--) // Read all of the elements of the constant.
1334 Elements.push_back(getConstantValue(TypeSlot,
1335 read_vbr_uint()));
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001336 Result = ConstantArray::get(AT, Elements);
Chris Lattner63cf59e2007-02-07 05:08:39 +00001337 if (Handler) Handler->handleConstantArray(AT, &Elements[0], Elements.size(),
1338 TypeSlot, Result);
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001339 break;
Reid Spencer060d25d2004-06-29 23:29:38 +00001340 }
1341
1342 case Type::StructTyID: {
1343 const StructType *ST = cast<StructType>(Ty);
1344
1345 std::vector<Constant *> Elements;
1346 Elements.reserve(ST->getNumElements());
1347 for (unsigned i = 0; i != ST->getNumElements(); ++i)
1348 Elements.push_back(getConstantValue(ST->getElementType(i),
1349 read_vbr_uint()));
1350
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001351 Result = ConstantStruct::get(ST, Elements);
Chris Lattner63cf59e2007-02-07 05:08:39 +00001352 if (Handler) Handler->handleConstantStruct(ST, &Elements[0],Elements.size(),
1353 Result);
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001354 break;
Misha Brukman8a96c532005-04-21 21:44:41 +00001355 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001356
Reid Spencer9d6565a2007-02-15 02:26:10 +00001357 case Type::VectorTyID: {
1358 const VectorType *PT = cast<VectorType>(Ty);
Brian Gaeke715c90b2004-08-20 06:00:58 +00001359 unsigned NumElements = PT->getNumElements();
1360 unsigned TypeSlot = getTypeSlot(PT->getElementType());
1361 std::vector<Constant*> Elements;
1362 Elements.reserve(NumElements);
1363 while (NumElements--) // Read all of the elements of the constant.
1364 Elements.push_back(getConstantValue(TypeSlot,
1365 read_vbr_uint()));
Reid Spencer9d6565a2007-02-15 02:26:10 +00001366 Result = ConstantVector::get(PT, Elements);
1367 if (Handler) Handler->handleConstantVector(PT, &Elements[0],Elements.size(),
Chris Lattner63cf59e2007-02-07 05:08:39 +00001368 TypeSlot, Result);
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001369 break;
Brian Gaeke715c90b2004-08-20 06:00:58 +00001370 }
1371
Chris Lattner638c3812004-11-19 16:24:05 +00001372 case Type::PointerTyID: { // ConstantPointerRef value (backwards compat).
Reid Spencer060d25d2004-06-29 23:29:38 +00001373 const PointerType *PT = cast<PointerType>(Ty);
1374 unsigned Slot = read_vbr_uint();
Misha Brukman8a96c532005-04-21 21:44:41 +00001375
Reid Spencer060d25d2004-06-29 23:29:38 +00001376 // Check to see if we have already read this global variable...
1377 Value *Val = getValue(TypeID, Slot, false);
Reid Spencer060d25d2004-06-29 23:29:38 +00001378 if (Val) {
Chris Lattnerbcb11cf2004-07-27 02:34:49 +00001379 GlobalValue *GV = dyn_cast<GlobalValue>(Val);
1380 if (!GV) error("GlobalValue not in ValueTable!");
1381 if (Handler) Handler->handleConstantPointer(PT, Slot, GV);
1382 return GV;
Reid Spencer060d25d2004-06-29 23:29:38 +00001383 } else {
Reid Spencer24399722004-07-09 22:21:33 +00001384 error("Forward references are not allowed here.");
Reid Spencer060d25d2004-06-29 23:29:38 +00001385 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001386 }
1387
1388 default:
Reid Spencer24399722004-07-09 22:21:33 +00001389 error("Don't know how to deserialize constant value of type '" +
Reid Spencer060d25d2004-06-29 23:29:38 +00001390 Ty->getDescription());
1391 break;
1392 }
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001393
1394 // Check that we didn't read a null constant if they are implicit for this
1395 // type plane. Do not do this check for constantexprs, as they may be folded
1396 // to a null value in a way that isn't predicted when a .bc file is initially
1397 // produced.
1398 assert((!isa<Constant>(Result) || !cast<Constant>(Result)->isNullValue()) ||
Reid Spencerfa1353c2007-02-28 02:25:48 +00001399 !hasImplicitNull(TypeID) && "Cannot read null values from bytecode!");
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001400 return Result;
Reid Spencer060d25d2004-06-29 23:29:38 +00001401}
1402
Misha Brukman8a96c532005-04-21 21:44:41 +00001403/// Resolve references for constants. This function resolves the forward
1404/// referenced constants in the ConstantFwdRefs map. It uses the
Reid Spencer04cde2c2004-07-04 11:33:49 +00001405/// replaceAllUsesWith method of Value class to substitute the placeholder
1406/// instance with the actual instance.
Chris Lattner389bd042004-12-09 06:19:44 +00001407void BytecodeReader::ResolveReferencesToConstant(Constant *NewV, unsigned Typ,
1408 unsigned Slot) {
Chris Lattner29b789b2003-11-19 17:27:18 +00001409 ConstantRefsType::iterator I =
Chris Lattner389bd042004-12-09 06:19:44 +00001410 ConstantFwdRefs.find(std::make_pair(Typ, Slot));
Chris Lattner29b789b2003-11-19 17:27:18 +00001411 if (I == ConstantFwdRefs.end()) return; // Never forward referenced?
Chris Lattner00950542001-06-06 20:29:01 +00001412
Chris Lattner29b789b2003-11-19 17:27:18 +00001413 Value *PH = I->second; // Get the placeholder...
1414 PH->replaceAllUsesWith(NewV);
1415 delete PH; // Delete the old placeholder
1416 ConstantFwdRefs.erase(I); // Remove the map entry for it
Vikram S. Advec1e4a812002-07-14 23:04:18 +00001417}
1418
Reid Spencer04cde2c2004-07-04 11:33:49 +00001419/// Parse the constant strings section.
Reid Spencer060d25d2004-06-29 23:29:38 +00001420void BytecodeReader::ParseStringConstants(unsigned NumEntries, ValueTable &Tab){
1421 for (; NumEntries; --NumEntries) {
Reid Spencerd798a512006-11-14 04:47:22 +00001422 unsigned Typ = read_vbr_uint();
Reid Spencer060d25d2004-06-29 23:29:38 +00001423 const Type *Ty = getType(Typ);
1424 if (!isa<ArrayType>(Ty))
Reid Spencer24399722004-07-09 22:21:33 +00001425 error("String constant data invalid!");
Misha Brukman8a96c532005-04-21 21:44:41 +00001426
Reid Spencer060d25d2004-06-29 23:29:38 +00001427 const ArrayType *ATy = cast<ArrayType>(Ty);
Reid Spencer88cfda22006-12-31 05:44:24 +00001428 if (ATy->getElementType() != Type::Int8Ty &&
1429 ATy->getElementType() != Type::Int8Ty)
Reid Spencer24399722004-07-09 22:21:33 +00001430 error("String constant data invalid!");
Misha Brukman8a96c532005-04-21 21:44:41 +00001431
Reid Spencer060d25d2004-06-29 23:29:38 +00001432 // Read character data. The type tells us how long the string is.
Misha Brukman8a96c532005-04-21 21:44:41 +00001433 char *Data = reinterpret_cast<char *>(alloca(ATy->getNumElements()));
Reid Spencer060d25d2004-06-29 23:29:38 +00001434 read_data(Data, Data+ATy->getNumElements());
Chris Lattner52e20b02003-03-19 20:54:26 +00001435
Reid Spencer060d25d2004-06-29 23:29:38 +00001436 std::vector<Constant*> Elements(ATy->getNumElements());
Reid Spencerb83eb642006-10-20 07:07:24 +00001437 const Type* ElemType = ATy->getElementType();
1438 for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
1439 Elements[i] = ConstantInt::get(ElemType, (unsigned char)Data[i]);
Misha Brukman12c29d12003-09-22 23:38:23 +00001440
Reid Spencer060d25d2004-06-29 23:29:38 +00001441 // Create the constant, inserting it as needed.
1442 Constant *C = ConstantArray::get(ATy, Elements);
1443 unsigned Slot = insertValue(C, Typ, Tab);
Chris Lattner389bd042004-12-09 06:19:44 +00001444 ResolveReferencesToConstant(C, Typ, Slot);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001445 if (Handler) Handler->handleConstantString(cast<ConstantArray>(C));
Reid Spencer060d25d2004-06-29 23:29:38 +00001446 }
Misha Brukman12c29d12003-09-22 23:38:23 +00001447}
1448
Reid Spencer04cde2c2004-07-04 11:33:49 +00001449/// Parse the constant pool.
Misha Brukman8a96c532005-04-21 21:44:41 +00001450void BytecodeReader::ParseConstantPool(ValueTable &Tab,
Reid Spencer04cde2c2004-07-04 11:33:49 +00001451 TypeListTy &TypeTab,
Reid Spencer46b002c2004-07-11 17:28:43 +00001452 bool isFunction) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001453 if (Handler) Handler->handleGlobalConstantsBegin();
1454
1455 /// In LLVM 1.3 Type does not derive from Value so the types
1456 /// do not occupy a plane. Consequently, we read the types
1457 /// first in the constant pool.
Reid Spencerd798a512006-11-14 04:47:22 +00001458 if (isFunction) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001459 unsigned NumEntries = read_vbr_uint();
Reid Spencer46b002c2004-07-11 17:28:43 +00001460 ParseTypes(TypeTab, NumEntries);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001461 }
1462
Reid Spencer46b002c2004-07-11 17:28:43 +00001463 while (moreInBlock()) {
Reid Spencer060d25d2004-06-29 23:29:38 +00001464 unsigned NumEntries = read_vbr_uint();
Reid Spencerd798a512006-11-14 04:47:22 +00001465 unsigned Typ = read_vbr_uint();
Reid Spencer04cde2c2004-07-04 11:33:49 +00001466
Reid Spencerd798a512006-11-14 04:47:22 +00001467 if (Typ == Type::VoidTyID) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001468 /// Use of Type::VoidTyID is a misnomer. It actually means
1469 /// that the following plane is constant strings
Reid Spencer060d25d2004-06-29 23:29:38 +00001470 assert(&Tab == &ModuleValues && "Cannot read strings in functions!");
1471 ParseStringConstants(NumEntries, Tab);
1472 } else {
1473 for (unsigned i = 0; i < NumEntries; ++i) {
Chris Lattner3bc5a602006-01-25 23:08:15 +00001474 Value *V = ParseConstantPoolValue(Typ);
1475 assert(V && "ParseConstantPoolValue returned NULL!");
1476 unsigned Slot = insertValue(V, Typ, Tab);
Chris Lattner29b789b2003-11-19 17:27:18 +00001477
Reid Spencer060d25d2004-06-29 23:29:38 +00001478 // If we are reading a function constant table, make sure that we adjust
1479 // the slot number to be the real global constant number.
1480 //
1481 if (&Tab != &ModuleValues && Typ < ModuleValues.size() &&
1482 ModuleValues[Typ])
1483 Slot += ModuleValues[Typ]->size();
Chris Lattner3bc5a602006-01-25 23:08:15 +00001484 if (Constant *C = dyn_cast<Constant>(V))
1485 ResolveReferencesToConstant(C, Typ, Slot);
Reid Spencer060d25d2004-06-29 23:29:38 +00001486 }
1487 }
1488 }
Chris Lattner02dce162004-12-04 05:28:27 +00001489
1490 // After we have finished parsing the constant pool, we had better not have
1491 // any dangling references left.
Reid Spencer3c391272004-12-04 22:19:53 +00001492 if (!ConstantFwdRefs.empty()) {
Reid Spencer3c391272004-12-04 22:19:53 +00001493 ConstantRefsType::const_iterator I = ConstantFwdRefs.begin();
Reid Spencer3c391272004-12-04 22:19:53 +00001494 Constant* missingConst = I->second;
Misha Brukman8a96c532005-04-21 21:44:41 +00001495 error(utostr(ConstantFwdRefs.size()) +
1496 " unresolved constant reference exist. First one is '" +
1497 missingConst->getName() + "' of type '" +
Chris Lattner389bd042004-12-09 06:19:44 +00001498 missingConst->getType()->getDescription() + "'.");
Reid Spencer3c391272004-12-04 22:19:53 +00001499 }
Chris Lattner02dce162004-12-04 05:28:27 +00001500
Reid Spencer060d25d2004-06-29 23:29:38 +00001501 checkPastBlockEnd("Constant Pool");
Reid Spencer04cde2c2004-07-04 11:33:49 +00001502 if (Handler) Handler->handleGlobalConstantsEnd();
Reid Spencer060d25d2004-06-29 23:29:38 +00001503}
Chris Lattner00950542001-06-06 20:29:01 +00001504
Reid Spencer04cde2c2004-07-04 11:33:49 +00001505/// Parse the contents of a function. Note that this function can be
1506/// called lazily by materializeFunction
1507/// @see materializeFunction
Reid Spencer46b002c2004-07-11 17:28:43 +00001508void BytecodeReader::ParseFunctionBody(Function* F) {
Reid Spencer060d25d2004-06-29 23:29:38 +00001509
1510 unsigned FuncSize = BlockEnd - At;
Chris Lattnere3869c82003-04-16 21:16:05 +00001511 GlobalValue::LinkageTypes Linkage = GlobalValue::ExternalLinkage;
Anton Korobeynikov7f705592007-01-12 19:20:47 +00001512 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
Chris Lattnere3869c82003-04-16 21:16:05 +00001513
Anton Korobeynikov7f705592007-01-12 19:20:47 +00001514 unsigned rWord = read_vbr_uint();
1515 unsigned LinkageID = rWord & 65535;
1516 unsigned VisibilityID = rWord >> 16;
1517 switch (LinkageID) {
Chris Lattnerc08912f2004-01-14 16:44:44 +00001518 case 0: Linkage = GlobalValue::ExternalLinkage; break;
1519 case 1: Linkage = GlobalValue::WeakLinkage; break;
1520 case 2: Linkage = GlobalValue::AppendingLinkage; break;
1521 case 3: Linkage = GlobalValue::InternalLinkage; break;
1522 case 4: Linkage = GlobalValue::LinkOnceLinkage; break;
Anton Korobeynikovb74ed072006-09-14 18:23:27 +00001523 case 5: Linkage = GlobalValue::DLLImportLinkage; break;
1524 case 6: Linkage = GlobalValue::DLLExportLinkage; break;
1525 case 7: Linkage = GlobalValue::ExternalWeakLinkage; break;
Reid Spencer060d25d2004-06-29 23:29:38 +00001526 default:
Reid Spencer24399722004-07-09 22:21:33 +00001527 error("Invalid linkage type for Function.");
Reid Spencer060d25d2004-06-29 23:29:38 +00001528 Linkage = GlobalValue::InternalLinkage;
1529 break;
Chris Lattnere3869c82003-04-16 21:16:05 +00001530 }
Anton Korobeynikov7f705592007-01-12 19:20:47 +00001531 switch (VisibilityID) {
1532 case 0: Visibility = GlobalValue::DefaultVisibility; break;
1533 case 1: Visibility = GlobalValue::HiddenVisibility; break;
1534 default:
1535 error("Unknown visibility type: " + utostr(VisibilityID));
1536 Visibility = GlobalValue::DefaultVisibility;
1537 break;
1538 }
Chris Lattnerd23b1d32001-11-26 18:56:10 +00001539
Reid Spencer46b002c2004-07-11 17:28:43 +00001540 F->setLinkage(Linkage);
Anton Korobeynikov7f705592007-01-12 19:20:47 +00001541 F->setVisibility(Visibility);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001542 if (Handler) Handler->handleFunctionBegin(F,FuncSize);
Chris Lattner00950542001-06-06 20:29:01 +00001543
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001544 // Keep track of how many basic blocks we have read in...
1545 unsigned BlockNum = 0;
Chris Lattner89e02532004-01-18 21:08:15 +00001546 bool InsertedArguments = false;
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001547
Reid Spencer060d25d2004-06-29 23:29:38 +00001548 BufPtr MyEnd = BlockEnd;
Reid Spencer46b002c2004-07-11 17:28:43 +00001549 while (At < MyEnd) {
Chris Lattner00950542001-06-06 20:29:01 +00001550 unsigned Type, Size;
Reid Spencer060d25d2004-06-29 23:29:38 +00001551 BufPtr OldAt = At;
1552 read_block(Type, Size);
Chris Lattner00950542001-06-06 20:29:01 +00001553
1554 switch (Type) {
Reid Spencerad89bd62004-07-25 18:07:36 +00001555 case BytecodeFormat::ConstantPoolBlockID:
Chris Lattner89e02532004-01-18 21:08:15 +00001556 if (!InsertedArguments) {
1557 // Insert arguments into the value table before we parse the first basic
Reid Spencerd2bb8872007-01-30 19:36:46 +00001558 // block in the function
Reid Spencer04cde2c2004-07-04 11:33:49 +00001559 insertArguments(F);
Chris Lattner89e02532004-01-18 21:08:15 +00001560 InsertedArguments = true;
1561 }
1562
Reid Spencer04cde2c2004-07-04 11:33:49 +00001563 ParseConstantPool(FunctionValues, FunctionTypes, true);
Chris Lattner00950542001-06-06 20:29:01 +00001564 break;
1565
Reid Spencerad89bd62004-07-25 18:07:36 +00001566 case BytecodeFormat::InstructionListBlockID: {
Chris Lattner89e02532004-01-18 21:08:15 +00001567 // Insert arguments into the value table before we parse the instruction
Reid Spencerd2bb8872007-01-30 19:36:46 +00001568 // list for the function
Chris Lattner89e02532004-01-18 21:08:15 +00001569 if (!InsertedArguments) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001570 insertArguments(F);
Chris Lattner89e02532004-01-18 21:08:15 +00001571 InsertedArguments = true;
1572 }
1573
Misha Brukman8a96c532005-04-21 21:44:41 +00001574 if (BlockNum)
Reid Spencer24399722004-07-09 22:21:33 +00001575 error("Already parsed basic blocks!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001576 BlockNum = ParseInstructionList(F);
Chris Lattner8d1dbd22003-12-01 07:05:31 +00001577 break;
1578 }
1579
Reid Spencer78d033e2007-01-06 07:24:44 +00001580 case BytecodeFormat::ValueSymbolTableBlockID:
1581 ParseValueSymbolTable(F, &F->getValueSymbolTable());
1582 break;
1583
1584 case BytecodeFormat::TypeSymbolTableBlockID:
1585 error("Functions don't have type symbol tables");
Chris Lattner00950542001-06-06 20:29:01 +00001586 break;
1587
1588 default:
Reid Spencer060d25d2004-06-29 23:29:38 +00001589 At += Size;
Misha Brukman8a96c532005-04-21 21:44:41 +00001590 if (OldAt > At)
Reid Spencer24399722004-07-09 22:21:33 +00001591 error("Wrapped around reading bytecode.");
Chris Lattner00950542001-06-06 20:29:01 +00001592 break;
1593 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001594 BlockEnd = MyEnd;
Chris Lattner00950542001-06-06 20:29:01 +00001595 }
1596
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001597 // Make sure there were no references to non-existant basic blocks.
1598 if (BlockNum != ParsedBasicBlocks.size())
Reid Spencer24399722004-07-09 22:21:33 +00001599 error("Illegal basic block operand reference");
Reid Spencer060d25d2004-06-29 23:29:38 +00001600
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001601 ParsedBasicBlocks.clear();
1602
Chris Lattner97330cf2003-10-09 23:10:14 +00001603 // Resolve forward references. Replace any uses of a forward reference value
1604 // with the real value.
Chris Lattner8eb10ce2003-10-09 06:05:40 +00001605 while (!ForwardReferences.empty()) {
Chris Lattnerc4d69162004-12-09 04:51:50 +00001606 std::map<std::pair<unsigned,unsigned>, Value*>::iterator
1607 I = ForwardReferences.begin();
1608 Value *V = getValue(I->first.first, I->first.second, false);
Chris Lattner8eb10ce2003-10-09 06:05:40 +00001609 Value *PlaceHolder = I->second;
Chris Lattnerc4d69162004-12-09 04:51:50 +00001610 PlaceHolder->replaceAllUsesWith(V);
Chris Lattner8eb10ce2003-10-09 06:05:40 +00001611 ForwardReferences.erase(I);
Chris Lattner8eb10ce2003-10-09 06:05:40 +00001612 delete PlaceHolder;
Chris Lattner6e448022003-10-08 21:51:46 +00001613 }
Chris Lattner00950542001-06-06 20:29:01 +00001614
Misha Brukman12c29d12003-09-22 23:38:23 +00001615 // Clear out function-level types...
Reid Spencer060d25d2004-06-29 23:29:38 +00001616 FunctionTypes.clear();
Reid Spencer060d25d2004-06-29 23:29:38 +00001617 freeTable(FunctionValues);
1618
Reid Spencer04cde2c2004-07-04 11:33:49 +00001619 if (Handler) Handler->handleFunctionEnd(F);
Chris Lattner00950542001-06-06 20:29:01 +00001620}
1621
Reid Spencer04cde2c2004-07-04 11:33:49 +00001622/// This function parses LLVM functions lazily. It obtains the type of the
1623/// function and records where the body of the function is in the bytecode
Misha Brukman8a96c532005-04-21 21:44:41 +00001624/// buffer. The caller can then use the ParseNextFunction and
Reid Spencer04cde2c2004-07-04 11:33:49 +00001625/// ParseAllFunctionBodies to get handler events for the functions.
Reid Spencer060d25d2004-06-29 23:29:38 +00001626void BytecodeReader::ParseFunctionLazily() {
1627 if (FunctionSignatureList.empty())
Reid Spencer24399722004-07-09 22:21:33 +00001628 error("FunctionSignatureList empty!");
Chris Lattner89e02532004-01-18 21:08:15 +00001629
Reid Spencer060d25d2004-06-29 23:29:38 +00001630 Function *Func = FunctionSignatureList.back();
1631 FunctionSignatureList.pop_back();
Chris Lattner24102432004-01-18 22:35:34 +00001632
Reid Spencer060d25d2004-06-29 23:29:38 +00001633 // Save the information for future reading of the function
1634 LazyFunctionLoadMap[Func] = LazyFunctionInfo(BlockStart, BlockEnd);
Chris Lattner89e02532004-01-18 21:08:15 +00001635
Misha Brukmana3e6ad62004-11-14 21:02:55 +00001636 // This function has a body but it's not loaded so it appears `External'.
1637 // Mark it as a `Ghost' instead to notify the users that it has a body.
1638 Func->setLinkage(GlobalValue::GhostLinkage);
1639
Reid Spencer060d25d2004-06-29 23:29:38 +00001640 // Pretend we've `parsed' this function
1641 At = BlockEnd;
1642}
Chris Lattner89e02532004-01-18 21:08:15 +00001643
Misha Brukman8a96c532005-04-21 21:44:41 +00001644/// The ParserFunction method lazily parses one function. Use this method to
1645/// casue the parser to parse a specific function in the module. Note that
1646/// this will remove the function from what is to be included by
Reid Spencer04cde2c2004-07-04 11:33:49 +00001647/// ParseAllFunctionBodies.
1648/// @see ParseAllFunctionBodies
1649/// @see ParseBytecode
Reid Spencer99655e12006-08-25 19:54:53 +00001650bool BytecodeReader::ParseFunction(Function* Func, std::string* ErrMsg) {
1651
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 // Find {start, end} pointers and slot in the map. If not there, we're done.
1661 LazyFunctionMap::iterator Fi = LazyFunctionLoadMap.find(Func);
Chris Lattner89e02532004-01-18 21:08:15 +00001662
Reid Spencer060d25d2004-06-29 23:29:38 +00001663 // Make sure we found it
Reid Spencer46b002c2004-07-11 17:28:43 +00001664 if (Fi == LazyFunctionLoadMap.end()) {
Reid Spencer24399722004-07-09 22:21:33 +00001665 error("Unrecognized function of type " + Func->getType()->getDescription());
Reid Spencer99655e12006-08-25 19:54:53 +00001666 return true;
Chris Lattner89e02532004-01-18 21:08:15 +00001667 }
1668
Reid Spencer060d25d2004-06-29 23:29:38 +00001669 BlockStart = At = Fi->second.Buf;
1670 BlockEnd = Fi->second.EndBuf;
Reid Spencer24399722004-07-09 22:21:33 +00001671 assert(Fi->first == Func && "Found wrong function?");
Reid Spencer060d25d2004-06-29 23:29:38 +00001672
Reid Spencer46b002c2004-07-11 17:28:43 +00001673 this->ParseFunctionBody(Func);
Reid Spencer99655e12006-08-25 19:54:53 +00001674 return false;
Chris Lattner89e02532004-01-18 21:08:15 +00001675}
1676
Reid Spencer04cde2c2004-07-04 11:33:49 +00001677/// The ParseAllFunctionBodies method parses through all the previously
1678/// unparsed functions in the bytecode file. If you want to completely parse
1679/// a bytecode file, this method should be called after Parsebytecode because
1680/// Parsebytecode only records the locations in the bytecode file of where
1681/// the function definitions are located. This function uses that information
1682/// to materialize the functions.
1683/// @see ParseBytecode
Reid Spencer99655e12006-08-25 19:54:53 +00001684bool BytecodeReader::ParseAllFunctionBodies(std::string* ErrMsg) {
Reid Spencer9b84ad12006-12-15 19:49:23 +00001685 if (setjmp(context)) {
1686 // Set caller's error message, if requested
1687 if (ErrMsg)
1688 *ErrMsg = ErrorMsg;
1689 // Indicate an error occurred
Reid Spencer99655e12006-08-25 19:54:53 +00001690 return true;
Reid Spencer9b84ad12006-12-15 19:49:23 +00001691 }
Reid Spencer99655e12006-08-25 19:54:53 +00001692
Chris Lattner24e90d32007-04-09 20:28:40 +00001693 for (LazyFunctionMap::iterator I = LazyFunctionLoadMap.begin(),
1694 E = LazyFunctionLoadMap.end(); I != E; ++I) {
1695 Function *Func = I->first;
1696 if (Func->hasNotBeenReadFromBytecode()) {
1697 BlockStart = At = I->second.Buf;
1698 BlockEnd = I->second.EndBuf;
1699 ParseFunctionBody(Func);
1700 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001701 }
Reid Spencer99655e12006-08-25 19:54:53 +00001702 return false;
Reid Spencer060d25d2004-06-29 23:29:38 +00001703}
Chris Lattner89e02532004-01-18 21:08:15 +00001704
Reid Spencer04cde2c2004-07-04 11:33:49 +00001705/// Parse the global type list
Reid Spencer060d25d2004-06-29 23:29:38 +00001706void BytecodeReader::ParseGlobalTypes() {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001707 // Read the number of types
1708 unsigned NumEntries = read_vbr_uint();
Reid Spencer46b002c2004-07-11 17:28:43 +00001709 ParseTypes(ModuleTypes, NumEntries);
Reid Spencer060d25d2004-06-29 23:29:38 +00001710}
1711
Reid Spencer04cde2c2004-07-04 11:33:49 +00001712/// Parse the Global info (types, global vars, constants)
Reid Spencer060d25d2004-06-29 23:29:38 +00001713void BytecodeReader::ParseModuleGlobalInfo() {
1714
Reid Spencer04cde2c2004-07-04 11:33:49 +00001715 if (Handler) Handler->handleModuleGlobalsBegin();
Chris Lattner00950542001-06-06 20:29:01 +00001716
Chris Lattner404cddf2005-11-12 01:33:40 +00001717 // SectionID - If a global has an explicit section specified, this map
1718 // remembers the ID until we can translate it into a string.
1719 std::map<GlobalValue*, unsigned> SectionID;
1720
Chris Lattner70cc3392001-09-10 07:58:01 +00001721 // Read global variables...
Reid Spencer060d25d2004-06-29 23:29:38 +00001722 unsigned VarType = read_vbr_uint();
Chris Lattner70cc3392001-09-10 07:58:01 +00001723 while (VarType != Type::VoidTyID) { // List is terminated by Void
Chris Lattner9dd87702004-04-03 23:43:42 +00001724 // VarType Fields: bit0 = isConstant, bit1 = hasInitializer, bit2,3,4 =
Lauro Ramos Venancioc7635522007-04-12 18:32:50 +00001725 // Linkage, bit5 = isThreadLocal, bit6+ = slot#
1726 unsigned SlotNo = VarType >> 6;
Chris Lattner9dd87702004-04-03 23:43:42 +00001727 unsigned LinkageID = (VarType >> 2) & 7;
Anton Korobeynikov7f705592007-01-12 19:20:47 +00001728 unsigned VisibilityID = 0;
Reid Spencer060d25d2004-06-29 23:29:38 +00001729 bool isConstant = VarType & 1;
Lauro Ramos Venancioc7635522007-04-12 18:32:50 +00001730 bool isThreadLocal = (VarType >> 5) & 1;
Chris Lattnerce5e04e2005-11-06 08:23:17 +00001731 bool hasInitializer = (VarType & 2) != 0;
Chris Lattner8eb52dd2005-11-06 07:11:04 +00001732 unsigned Alignment = 0;
Chris Lattner404cddf2005-11-12 01:33:40 +00001733 unsigned GlobalSectionID = 0;
Chris Lattner8eb52dd2005-11-06 07:11:04 +00001734
1735 // An extension word is present when linkage = 3 (internal) and hasinit = 0.
1736 if (LinkageID == 3 && !hasInitializer) {
1737 unsigned ExtWord = read_vbr_uint();
1738 // The extension word has this format: bit 0 = has initializer, bit 1-3 =
Anton Korobeynikov7f705592007-01-12 19:20:47 +00001739 // linkage, bit 4-8 = alignment (log2), bit 9 = has section,
1740 // bits 10-12 = visibility, bits 13+ = future use.
Chris Lattner8eb52dd2005-11-06 07:11:04 +00001741 hasInitializer = ExtWord & 1;
1742 LinkageID = (ExtWord >> 1) & 7;
1743 Alignment = (1 << ((ExtWord >> 4) & 31)) >> 1;
Anton Korobeynikov7f705592007-01-12 19:20:47 +00001744 VisibilityID = (ExtWord >> 10) & 7;
Chris Lattner404cddf2005-11-12 01:33:40 +00001745
1746 if (ExtWord & (1 << 9)) // Has a section ID.
1747 GlobalSectionID = read_vbr_uint();
Chris Lattner8eb52dd2005-11-06 07:11:04 +00001748 }
Chris Lattnere3869c82003-04-16 21:16:05 +00001749
Chris Lattnerce5e04e2005-11-06 08:23:17 +00001750 GlobalValue::LinkageTypes Linkage;
Chris Lattnerc08912f2004-01-14 16:44:44 +00001751 switch (LinkageID) {
Chris Lattnerc08912f2004-01-14 16:44:44 +00001752 case 0: Linkage = GlobalValue::ExternalLinkage; break;
1753 case 1: Linkage = GlobalValue::WeakLinkage; break;
1754 case 2: Linkage = GlobalValue::AppendingLinkage; break;
1755 case 3: Linkage = GlobalValue::InternalLinkage; break;
1756 case 4: Linkage = GlobalValue::LinkOnceLinkage; break;
Anton Korobeynikovb74ed072006-09-14 18:23:27 +00001757 case 5: Linkage = GlobalValue::DLLImportLinkage; break;
1758 case 6: Linkage = GlobalValue::DLLExportLinkage; break;
1759 case 7: Linkage = GlobalValue::ExternalWeakLinkage; break;
Misha Brukman8a96c532005-04-21 21:44:41 +00001760 default:
Reid Spencer24399722004-07-09 22:21:33 +00001761 error("Unknown linkage type: " + utostr(LinkageID));
Reid Spencer060d25d2004-06-29 23:29:38 +00001762 Linkage = GlobalValue::InternalLinkage;
1763 break;
Chris Lattnere3869c82003-04-16 21:16:05 +00001764 }
Anton Korobeynikov7f705592007-01-12 19:20:47 +00001765 GlobalValue::VisibilityTypes Visibility;
1766 switch (VisibilityID) {
1767 case 0: Visibility = GlobalValue::DefaultVisibility; break;
1768 case 1: Visibility = GlobalValue::HiddenVisibility; break;
1769 default:
1770 error("Unknown visibility type: " + utostr(VisibilityID));
1771 Visibility = GlobalValue::DefaultVisibility;
1772 break;
1773 }
1774
Chris Lattnere3869c82003-04-16 21:16:05 +00001775 const Type *Ty = getType(SlotNo);
Chris Lattnere73bd452005-11-06 07:43:39 +00001776 if (!Ty)
Reid Spencer24399722004-07-09 22:21:33 +00001777 error("Global has no type! SlotNo=" + utostr(SlotNo));
Reid Spencer060d25d2004-06-29 23:29:38 +00001778
Chris Lattnere73bd452005-11-06 07:43:39 +00001779 if (!isa<PointerType>(Ty))
Reid Spencer24399722004-07-09 22:21:33 +00001780 error("Global not a pointer type! Ty= " + Ty->getDescription());
Chris Lattner70cc3392001-09-10 07:58:01 +00001781
Chris Lattner52e20b02003-03-19 20:54:26 +00001782 const Type *ElTy = cast<PointerType>(Ty)->getElementType();
Chris Lattnerd70684f2001-09-18 04:01:05 +00001783
Chris Lattner70cc3392001-09-10 07:58:01 +00001784 // Create the global variable...
Reid Spencer060d25d2004-06-29 23:29:38 +00001785 GlobalVariable *GV = new GlobalVariable(ElTy, isConstant, Linkage,
Lauro Ramos Venancioc7635522007-04-12 18:32:50 +00001786 0, "", TheModule, isThreadLocal);
Chris Lattner8eb52dd2005-11-06 07:11:04 +00001787 GV->setAlignment(Alignment);
Anton Korobeynikov7f705592007-01-12 19:20:47 +00001788 GV->setVisibility(Visibility);
Chris Lattner29b789b2003-11-19 17:27:18 +00001789 insertValue(GV, SlotNo, ModuleValues);
Chris Lattner05950c32001-10-13 06:47:01 +00001790
Chris Lattner404cddf2005-11-12 01:33:40 +00001791 if (GlobalSectionID != 0)
1792 SectionID[GV] = GlobalSectionID;
1793
Reid Spencer060d25d2004-06-29 23:29:38 +00001794 unsigned initSlot = 0;
Misha Brukman8a96c532005-04-21 21:44:41 +00001795 if (hasInitializer) {
Reid Spencer060d25d2004-06-29 23:29:38 +00001796 initSlot = read_vbr_uint();
1797 GlobalInits.push_back(std::make_pair(GV, initSlot));
1798 }
1799
1800 // Notify handler about the global value.
Chris Lattner4a242b32004-10-14 01:39:18 +00001801 if (Handler)
Anton Korobeynikov7f705592007-01-12 19:20:47 +00001802 Handler->handleGlobalVariable(ElTy, isConstant, Linkage, Visibility,
Lauro Ramos Venancioc7635522007-04-12 18:32:50 +00001803 SlotNo, initSlot, isThreadLocal);
Reid Spencer060d25d2004-06-29 23:29:38 +00001804
1805 // Get next item
1806 VarType = read_vbr_uint();
Chris Lattner70cc3392001-09-10 07:58:01 +00001807 }
1808
Chris Lattner52e20b02003-03-19 20:54:26 +00001809 // Read the function objects for all of the functions that are coming
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001810 unsigned FnSignature = read_vbr_uint();
Reid Spencer24399722004-07-09 22:21:33 +00001811
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001812 // List is terminated by VoidTy.
Chris Lattnere73bd452005-11-06 07:43:39 +00001813 while (((FnSignature & (~0U >> 1)) >> 5) != Type::VoidTyID) {
1814 const Type *Ty = getType((FnSignature & (~0U >> 1)) >> 5);
Chris Lattner927b1852003-10-09 20:22:47 +00001815 if (!isa<PointerType>(Ty) ||
Reid Spencer060d25d2004-06-29 23:29:38 +00001816 !isa<FunctionType>(cast<PointerType>(Ty)->getElementType())) {
Misha Brukman8a96c532005-04-21 21:44:41 +00001817 error("Function not a pointer to function type! Ty = " +
Reid Spencer46b002c2004-07-11 17:28:43 +00001818 Ty->getDescription());
Reid Spencer060d25d2004-06-29 23:29:38 +00001819 }
Chris Lattner8cdc6b72002-10-23 00:51:54 +00001820
Chris Lattner2a7b6ba2003-03-06 17:15:19 +00001821 // We create functions by passing the underlying FunctionType to create...
Misha Brukman8a96c532005-04-21 21:44:41 +00001822 const FunctionType* FTy =
Reid Spencer060d25d2004-06-29 23:29:38 +00001823 cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
Chris Lattner00950542001-06-06 20:29:01 +00001824
Chris Lattner18549c22004-11-15 21:43:03 +00001825 // Insert the place holder.
Chris Lattner404cddf2005-11-12 01:33:40 +00001826 Function *Func = new Function(FTy, GlobalValue::ExternalLinkage,
Reid Spencer04cde2c2004-07-04 11:33:49 +00001827 "", TheModule);
Reid Spencere1e96c02006-01-19 07:02:16 +00001828
Chris Lattnere73bd452005-11-06 07:43:39 +00001829 insertValue(Func, (FnSignature & (~0U >> 1)) >> 5, ModuleValues);
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001830
1831 // Flags are not used yet.
Chris Lattner97fbc502004-11-15 22:38:52 +00001832 unsigned Flags = FnSignature & 31;
Chris Lattner00950542001-06-06 20:29:01 +00001833
Chris Lattner97fbc502004-11-15 22:38:52 +00001834 // Save this for later so we know type of lazily instantiated functions.
1835 // Note that known-external functions do not have FunctionInfo blocks, so we
1836 // do not add them to the FunctionSignatureList.
1837 if ((Flags & (1 << 4)) == 0)
1838 FunctionSignatureList.push_back(Func);
Chris Lattner52e20b02003-03-19 20:54:26 +00001839
Chris Lattnere73bd452005-11-06 07:43:39 +00001840 // Get the calling convention from the low bits.
1841 unsigned CC = Flags & 15;
1842 unsigned Alignment = 0;
1843 if (FnSignature & (1 << 31)) { // Has extension word?
1844 unsigned ExtWord = read_vbr_uint();
1845 Alignment = (1 << (ExtWord & 31)) >> 1;
1846 CC |= ((ExtWord >> 5) & 15) << 4;
Chris Lattner404cddf2005-11-12 01:33:40 +00001847
1848 if (ExtWord & (1 << 10)) // Has a section ID.
1849 SectionID[Func] = read_vbr_uint();
Anton Korobeynikovb74ed072006-09-14 18:23:27 +00001850
1851 // Parse external declaration linkage
1852 switch ((ExtWord >> 11) & 3) {
1853 case 0: break;
1854 case 1: Func->setLinkage(Function::DLLImportLinkage); break;
1855 case 2: Func->setLinkage(Function::ExternalWeakLinkage); break;
1856 default: assert(0 && "Unsupported external linkage");
1857 }
Chris Lattnere73bd452005-11-06 07:43:39 +00001858 }
1859
Chris Lattner54b369e2005-11-06 07:46:13 +00001860 Func->setCallingConv(CC-1);
Chris Lattnere73bd452005-11-06 07:43:39 +00001861 Func->setAlignment(Alignment);
Chris Lattner479ffeb2005-05-06 20:42:57 +00001862
Reid Spencer04cde2c2004-07-04 11:33:49 +00001863 if (Handler) Handler->handleFunctionDeclaration(Func);
Reid Spencer060d25d2004-06-29 23:29:38 +00001864
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001865 // Get the next function signature.
1866 FnSignature = read_vbr_uint();
Chris Lattner00950542001-06-06 20:29:01 +00001867 }
1868
Misha Brukman8a96c532005-04-21 21:44:41 +00001869 // Now that the function signature list is set up, reverse it so that we can
Chris Lattner74734132002-08-17 22:01:27 +00001870 // remove elements efficiently from the back of the vector.
1871 std::reverse(FunctionSignatureList.begin(), FunctionSignatureList.end());
Chris Lattner00950542001-06-06 20:29:01 +00001872
Chris Lattner404cddf2005-11-12 01:33:40 +00001873 /// SectionNames - This contains the list of section names encoded in the
1874 /// moduleinfoblock. Functions and globals with an explicit section index
1875 /// into this to get their section name.
1876 std::vector<std::string> SectionNames;
1877
Reid Spencerd798a512006-11-14 04:47:22 +00001878 // Read in the dependent library information.
1879 unsigned num_dep_libs = read_vbr_uint();
1880 std::string dep_lib;
1881 while (num_dep_libs--) {
1882 dep_lib = read_str();
1883 TheModule->addLibrary(dep_lib);
Reid Spencer5b472d92004-08-21 20:49:23 +00001884 if (Handler)
Reid Spencerd798a512006-11-14 04:47:22 +00001885 Handler->handleDependentLibrary(dep_lib);
Reid Spencerad89bd62004-07-25 18:07:36 +00001886 }
1887
Reid Spencerd798a512006-11-14 04:47:22 +00001888 // Read target triple and place into the module.
1889 std::string triple = read_str();
1890 TheModule->setTargetTriple(triple);
1891 if (Handler)
1892 Handler->handleTargetTriple(triple);
1893
Reid Spenceraacc35a2007-01-26 08:10:24 +00001894 // Read the data layout string and place into the module.
1895 std::string datalayout = read_str();
1896 TheModule->setDataLayout(datalayout);
1897 // FIXME: Implement
1898 // if (Handler)
1899 // Handler->handleDataLayout(datalayout);
1900
Reid Spencerd798a512006-11-14 04:47:22 +00001901 if (At != BlockEnd) {
1902 // If the file has section info in it, read the section names now.
1903 unsigned NumSections = read_vbr_uint();
1904 while (NumSections--)
1905 SectionNames.push_back(read_str());
1906 }
1907
1908 // If the file has module-level inline asm, read it now.
1909 if (At != BlockEnd)
1910 TheModule->setModuleInlineAsm(read_str());
1911
Chris Lattner404cddf2005-11-12 01:33:40 +00001912 // If any globals are in specified sections, assign them now.
1913 for (std::map<GlobalValue*, unsigned>::iterator I = SectionID.begin(), E =
1914 SectionID.end(); I != E; ++I)
1915 if (I->second) {
1916 if (I->second > SectionID.size())
1917 error("SectionID out of range for global!");
1918 I->first->setSection(SectionNames[I->second-1]);
1919 }
Reid Spencerad89bd62004-07-25 18:07:36 +00001920
Chris Lattner00950542001-06-06 20:29:01 +00001921 // This is for future proofing... in the future extra fields may be added that
1922 // we don't understand, so we transparently ignore them.
1923 //
Reid Spencer060d25d2004-06-29 23:29:38 +00001924 At = BlockEnd;
1925
Reid Spencer04cde2c2004-07-04 11:33:49 +00001926 if (Handler) Handler->handleModuleGlobalsEnd();
Chris Lattner00950542001-06-06 20:29:01 +00001927}
1928
Reid Spencer04cde2c2004-07-04 11:33:49 +00001929/// Parse the version information and decode it by setting flags on the
1930/// Reader that enable backward compatibility of the reader.
Reid Spencer060d25d2004-06-29 23:29:38 +00001931void BytecodeReader::ParseVersionInfo() {
Reid Spenceraacc35a2007-01-26 08:10:24 +00001932 unsigned RevisionNum = read_vbr_uint();
Chris Lattnere3869c82003-04-16 21:16:05 +00001933
Reid Spencer3795ad12006-12-03 05:47:10 +00001934 // We don't provide backwards compatibility in the Reader any more. To
1935 // upgrade, the user should use llvm-upgrade.
1936 if (RevisionNum < 7)
1937 error("Bytecode formats < 7 are no longer supported. Use llvm-upgrade.");
Chris Lattner036b8aa2003-03-06 17:55:45 +00001938
Reid Spenceraacc35a2007-01-26 08:10:24 +00001939 if (Handler) Handler->handleVersionInfo(RevisionNum);
Chris Lattner036b8aa2003-03-06 17:55:45 +00001940}
1941
Reid Spencer04cde2c2004-07-04 11:33:49 +00001942/// Parse a whole module.
Reid Spencer060d25d2004-06-29 23:29:38 +00001943void BytecodeReader::ParseModule() {
Chris Lattner00950542001-06-06 20:29:01 +00001944 unsigned Type, Size;
Chris Lattner00950542001-06-06 20:29:01 +00001945
Reid Spencer060d25d2004-06-29 23:29:38 +00001946 FunctionSignatureList.clear(); // Just in case...
Chris Lattner00950542001-06-06 20:29:01 +00001947
1948 // Read into instance variables...
Reid Spencer060d25d2004-06-29 23:29:38 +00001949 ParseVersionInfo();
Chris Lattner00950542001-06-06 20:29:01 +00001950
Reid Spencer060d25d2004-06-29 23:29:38 +00001951 bool SeenModuleGlobalInfo = false;
1952 bool SeenGlobalTypePlane = false;
1953 BufPtr MyEnd = BlockEnd;
1954 while (At < MyEnd) {
1955 BufPtr OldAt = At;
1956 read_block(Type, Size);
1957
Chris Lattner00950542001-06-06 20:29:01 +00001958 switch (Type) {
Reid Spencer060d25d2004-06-29 23:29:38 +00001959
Reid Spencerad89bd62004-07-25 18:07:36 +00001960 case BytecodeFormat::GlobalTypePlaneBlockID:
Reid Spencer46b002c2004-07-11 17:28:43 +00001961 if (SeenGlobalTypePlane)
Reid Spencer24399722004-07-09 22:21:33 +00001962 error("Two GlobalTypePlane Blocks Encountered!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001963
Reid Spencer5b472d92004-08-21 20:49:23 +00001964 if (Size > 0)
1965 ParseGlobalTypes();
Reid Spencer060d25d2004-06-29 23:29:38 +00001966 SeenGlobalTypePlane = true;
Chris Lattner52e20b02003-03-19 20:54:26 +00001967 break;
1968
Misha Brukman8a96c532005-04-21 21:44:41 +00001969 case BytecodeFormat::ModuleGlobalInfoBlockID:
Reid Spencer46b002c2004-07-11 17:28:43 +00001970 if (SeenModuleGlobalInfo)
Reid Spencer24399722004-07-09 22:21:33 +00001971 error("Two ModuleGlobalInfo Blocks Encountered!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001972 ParseModuleGlobalInfo();
1973 SeenModuleGlobalInfo = true;
Chris Lattner52e20b02003-03-19 20:54:26 +00001974 break;
1975
Reid Spencerad89bd62004-07-25 18:07:36 +00001976 case BytecodeFormat::ConstantPoolBlockID:
Reid Spencer04cde2c2004-07-04 11:33:49 +00001977 ParseConstantPool(ModuleValues, ModuleTypes,false);
Chris Lattner00950542001-06-06 20:29:01 +00001978 break;
1979
Reid Spencerad89bd62004-07-25 18:07:36 +00001980 case BytecodeFormat::FunctionBlockID:
Reid Spencer060d25d2004-06-29 23:29:38 +00001981 ParseFunctionLazily();
Chris Lattner00950542001-06-06 20:29:01 +00001982 break;
Chris Lattner00950542001-06-06 20:29:01 +00001983
Reid Spencer78d033e2007-01-06 07:24:44 +00001984 case BytecodeFormat::ValueSymbolTableBlockID:
1985 ParseValueSymbolTable(0, &TheModule->getValueSymbolTable());
1986 break;
1987
1988 case BytecodeFormat::TypeSymbolTableBlockID:
1989 ParseTypeSymbolTable(&TheModule->getTypeSymbolTable());
Chris Lattner00950542001-06-06 20:29:01 +00001990 break;
Reid Spencer060d25d2004-06-29 23:29:38 +00001991
Chris Lattner00950542001-06-06 20:29:01 +00001992 default:
Reid Spencer060d25d2004-06-29 23:29:38 +00001993 At += Size;
1994 if (OldAt > At) {
Reid Spencer46b002c2004-07-11 17:28:43 +00001995 error("Unexpected Block of Type #" + utostr(Type) + " encountered!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001996 }
Chris Lattner00950542001-06-06 20:29:01 +00001997 break;
1998 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001999 BlockEnd = MyEnd;
Chris Lattner00950542001-06-06 20:29:01 +00002000 }
2001
Chris Lattner52e20b02003-03-19 20:54:26 +00002002 // After the module constant pool has been read, we can safely initialize
2003 // global variables...
2004 while (!GlobalInits.empty()) {
2005 GlobalVariable *GV = GlobalInits.back().first;
2006 unsigned Slot = GlobalInits.back().second;
2007 GlobalInits.pop_back();
2008
2009 // Look up the initializer value...
Chris Lattner29b789b2003-11-19 17:27:18 +00002010 // FIXME: Preserve this type ID!
Reid Spencer060d25d2004-06-29 23:29:38 +00002011
2012 const llvm::PointerType* GVType = GV->getType();
2013 unsigned TypeSlot = getTypeSlot(GVType->getElementType());
Chris Lattner93361992004-01-15 18:45:25 +00002014 if (Constant *CV = getConstantValue(TypeSlot, Slot)) {
Misha Brukman8a96c532005-04-21 21:44:41 +00002015 if (GV->hasInitializer())
Reid Spencer24399722004-07-09 22:21:33 +00002016 error("Global *already* has an initializer?!");
Reid Spencer04cde2c2004-07-04 11:33:49 +00002017 if (Handler) Handler->handleGlobalInitializer(GV,CV);
Chris Lattner93361992004-01-15 18:45:25 +00002018 GV->setInitializer(CV);
Chris Lattner52e20b02003-03-19 20:54:26 +00002019 } else
Reid Spencer24399722004-07-09 22:21:33 +00002020 error("Cannot find initializer value.");
Chris Lattner52e20b02003-03-19 20:54:26 +00002021 }
2022
Chris Lattneraba5ff52005-05-05 20:57:00 +00002023 if (!ConstantFwdRefs.empty())
2024 error("Use of undefined constants in a module");
2025
Reid Spencer060d25d2004-06-29 23:29:38 +00002026 /// Make sure we pulled them all out. If we didn't then there's a declaration
2027 /// but a missing body. That's not allowed.
Misha Brukman12c29d12003-09-22 23:38:23 +00002028 if (!FunctionSignatureList.empty())
Reid Spencer24399722004-07-09 22:21:33 +00002029 error("Function declared, but bytecode stream ended before definition");
Chris Lattner00950542001-06-06 20:29:01 +00002030}
2031
Reid Spencer04cde2c2004-07-04 11:33:49 +00002032/// This function completely parses a bytecode buffer given by the \p Buf
2033/// and \p Length parameters.
Anton Korobeynikov7d515442006-09-01 20:35:17 +00002034bool BytecodeReader::ParseBytecode(volatile BufPtr Buf, unsigned Length,
Reid Spencer233fe722006-08-22 16:09:19 +00002035 const std::string &ModuleID,
Chris Lattnerf2e292c2007-02-07 21:41:02 +00002036 BCDecompressor_t *Decompressor,
Reid Spencer233fe722006-08-22 16:09:19 +00002037 std::string* ErrMsg) {
Misha Brukmane0dd0d42003-09-23 16:15:29 +00002038
Reid Spencer233fe722006-08-22 16:09:19 +00002039 /// We handle errors by
2040 if (setjmp(context)) {
2041 // Cleanup after error
2042 if (Handler) Handler->handleError(ErrorMsg);
Reid Spencer060d25d2004-06-29 23:29:38 +00002043 freeState();
Chris Lattner2a7b6ba2003-03-06 17:15:19 +00002044 delete TheModule;
2045 TheModule = 0;
Chris Lattner3bdad692004-11-15 21:55:33 +00002046 if (decompressedBlock != 0 ) {
Reid Spencer61aaf2e2004-11-14 21:59:21 +00002047 ::free(decompressedBlock);
Chris Lattner3bdad692004-11-15 21:55:33 +00002048 decompressedBlock = 0;
2049 }
Reid Spencer233fe722006-08-22 16:09:19 +00002050 // Set caller's error message, if requested
2051 if (ErrMsg)
2052 *ErrMsg = ErrorMsg;
2053 // Indicate an error occurred
2054 return true;
Chris Lattner2a7b6ba2003-03-06 17:15:19 +00002055 }
Reid Spencer233fe722006-08-22 16:09:19 +00002056
2057 RevisionNum = 0;
2058 At = MemStart = BlockStart = Buf;
2059 MemEnd = BlockEnd = Buf + Length;
2060
2061 // Create the module
2062 TheModule = new Module(ModuleID);
2063
2064 if (Handler) Handler->handleStart(TheModule, Length);
2065
2066 // Read the four bytes of the signature.
2067 unsigned Sig = read_uint();
2068
2069 // If this is a compressed file
2070 if (Sig == ('l' | ('l' << 8) | ('v' << 16) | ('c' << 24))) {
Chris Lattnerf2e292c2007-02-07 21:41:02 +00002071 if (!Decompressor) {
2072 error("Compressed bytecode found, but not decompressor available");
2073 }
Reid Spencer233fe722006-08-22 16:09:19 +00002074
2075 // Invoke the decompression of the bytecode. Note that we have to skip the
2076 // file's magic number which is not part of the compressed block. Hence,
2077 // the Buf+4 and Length-4. The result goes into decompressedBlock, a data
2078 // member for retention until BytecodeReader is destructed.
Chris Lattner0d3382a2007-02-07 19:49:01 +00002079 unsigned decompressedLength =
2080 Decompressor((char*)Buf+4,Length-4,decompressedBlock, 0);
Reid Spencer233fe722006-08-22 16:09:19 +00002081
2082 // We must adjust the buffer pointers used by the bytecode reader to point
2083 // into the new decompressed block. After decompression, the
2084 // decompressedBlock will point to a contiguous memory area that has
2085 // the decompressed data.
2086 At = MemStart = BlockStart = Buf = (BufPtr) decompressedBlock;
2087 MemEnd = BlockEnd = Buf + decompressedLength;
2088
2089 // else if this isn't a regular (uncompressed) bytecode file, then its
2090 // and error, generate that now.
2091 } else if (Sig != ('l' | ('l' << 8) | ('v' << 16) | ('m' << 24))) {
2092 error("Invalid bytecode signature: " + utohexstr(Sig));
2093 }
2094
2095 // Tell the handler we're starting a module
2096 if (Handler) Handler->handleModuleBegin(ModuleID);
2097
2098 // Get the module block and size and verify. This is handled specially
2099 // because the module block/size is always written in long format. Other
2100 // blocks are written in short format so the read_block method is used.
2101 unsigned Type, Size;
2102 Type = read_uint();
2103 Size = read_uint();
2104 if (Type != BytecodeFormat::ModuleBlockID) {
2105 error("Expected Module Block! Type:" + utostr(Type) + ", Size:"
2106 + utostr(Size));
2107 }
2108
2109 // It looks like the darwin ranlib program is broken, and adds trailing
2110 // garbage to the end of some bytecode files. This hack allows the bc
2111 // reader to ignore trailing garbage on bytecode files.
2112 if (At + Size < MemEnd)
2113 MemEnd = BlockEnd = At+Size;
2114
2115 if (At + Size != MemEnd)
2116 error("Invalid Top Level Block Length! Type:" + utostr(Type)
2117 + ", Size:" + utostr(Size));
2118
2119 // Parse the module contents
2120 this->ParseModule();
2121
2122 // Check for missing functions
2123 if (hasFunctions())
2124 error("Function expected, but bytecode stream ended!");
2125
Reid Spencer233fe722006-08-22 16:09:19 +00002126 // Tell the handler we're done with the module
2127 if (Handler)
2128 Handler->handleModuleEnd(ModuleID);
2129
2130 // Tell the handler we're finished the parse
2131 if (Handler) Handler->handleFinish();
2132
2133 return false;
2134
Chris Lattner00950542001-06-06 20:29:01 +00002135}
Reid Spencer060d25d2004-06-29 23:29:38 +00002136
2137//===----------------------------------------------------------------------===//
2138//=== Default Implementations of Handler Methods
2139//===----------------------------------------------------------------------===//
2140
2141BytecodeHandler::~BytecodeHandler() {}