blob: 55e16062306721af869aef8e61a85879a1f1fab3 [file] [log] [blame]
Chris Lattnerd6b65252001-10-24 01:15:12 +00001//===- Reader.cpp - Code to read bytecode files ---------------------------===//
Misha Brukman8a96c532005-04-21 21:44:41 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
Misha Brukman8a96c532005-04-21 21:44:41 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner00950542001-06-06 20:29:01 +00009//
10// This library implements the functionality defined in llvm/Bytecode/Reader.h
11//
Misha Brukman8a96c532005-04-21 21:44:41 +000012// Note that this library should be as fast as possible, reentrant, and
Chris Lattner00950542001-06-06 20:29:01 +000013// threadsafe!!
14//
Chris Lattner00950542001-06-06 20:29:01 +000015// TODO: Allow passing in an option to ignore the symbol table
16//
Chris Lattnerd6b65252001-10-24 01:15:12 +000017//===----------------------------------------------------------------------===//
Chris Lattner00950542001-06-06 20:29:01 +000018
Reid Spencer060d25d2004-06-29 23:29:38 +000019#include "Reader.h"
Reid Spencer0b118202006-01-16 21:12:35 +000020#include "llvm/Assembly/AutoUpgrade.h"
Reid Spencer060d25d2004-06-29 23:29:38 +000021#include "llvm/Bytecode/BytecodeHandler.h"
22#include "llvm/BasicBlock.h"
Chris Lattnerdee199f2005-05-06 22:34:01 +000023#include "llvm/CallingConv.h"
Reid Spencer060d25d2004-06-29 23:29:38 +000024#include "llvm/Constants.h"
Reid Spencer04cde2c2004-07-04 11:33:49 +000025#include "llvm/Instructions.h"
26#include "llvm/SymbolTable.h"
Chris Lattner00950542001-06-06 20:29:01 +000027#include "llvm/Bytecode/Format.h"
Chris Lattnerdee199f2005-05-06 22:34:01 +000028#include "llvm/Config/alloca.h"
Reid Spencer060d25d2004-06-29 23:29:38 +000029#include "llvm/Support/GetElementPtrTypeIterator.h"
Reid Spencer17f52c52004-11-06 23:17:23 +000030#include "llvm/Support/Compressor.h"
Jim Laskeycb6682f2005-08-17 19:34:49 +000031#include "llvm/Support/MathExtras.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000032#include "llvm/ADT/StringExtras.h"
Reid Spencer060d25d2004-06-29 23:29:38 +000033#include <sstream>
Alkis Evlogimenos20aa4742004-09-03 18:19:51 +000034#include <algorithm>
Chris Lattner29b789b2003-11-19 17:27:18 +000035using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000036
Reid Spencer46b002c2004-07-11 17:28:43 +000037namespace {
Chris Lattnercad28bd2005-01-29 00:36:19 +000038 /// @brief A class for maintaining the slot number definition
39 /// as a placeholder for the actual definition for forward constants defs.
40 class ConstantPlaceHolder : public ConstantExpr {
41 ConstantPlaceHolder(); // DO NOT IMPLEMENT
42 void operator=(const ConstantPlaceHolder &); // DO NOT IMPLEMENT
43 public:
Chris Lattner61323322005-01-31 01:11:13 +000044 Use Op;
Misha Brukman8a96c532005-04-21 21:44:41 +000045 ConstantPlaceHolder(const Type *Ty)
Chris Lattner61323322005-01-31 01:11:13 +000046 : ConstantExpr(Ty, Instruction::UserOp1, &Op, 1),
47 Op(UndefValue::get(Type::IntTy), this) {
48 }
Chris Lattnercad28bd2005-01-29 00:36:19 +000049 };
Reid Spencer46b002c2004-07-11 17:28:43 +000050}
Reid Spencer060d25d2004-06-29 23:29:38 +000051
Reid Spencer24399722004-07-09 22:21:33 +000052// Provide some details on error
53inline void BytecodeReader::error(std::string err) {
54 err += " (Vers=" ;
55 err += itostr(RevisionNum) ;
56 err += ", Pos=" ;
57 err += itostr(At-MemStart);
58 err += ")";
59 throw err;
60}
61
Reid Spencer060d25d2004-06-29 23:29:38 +000062//===----------------------------------------------------------------------===//
63// Bytecode Reading Methods
64//===----------------------------------------------------------------------===//
65
Reid Spencer04cde2c2004-07-04 11:33:49 +000066/// Determine if the current block being read contains any more data.
Reid Spencer060d25d2004-06-29 23:29:38 +000067inline bool BytecodeReader::moreInBlock() {
68 return At < BlockEnd;
Chris Lattner00950542001-06-06 20:29:01 +000069}
70
Reid Spencer04cde2c2004-07-04 11:33:49 +000071/// Throw an error if we've read past the end of the current block
Reid Spencer060d25d2004-06-29 23:29:38 +000072inline void BytecodeReader::checkPastBlockEnd(const char * block_name) {
Reid Spencer46b002c2004-07-11 17:28:43 +000073 if (At > BlockEnd)
Chris Lattnera79e7cc2004-10-16 18:18:16 +000074 error(std::string("Attempt to read past the end of ") + block_name +
75 " block.");
Reid Spencer060d25d2004-06-29 23:29:38 +000076}
Chris Lattner36392bc2003-10-08 21:18:57 +000077
Reid Spencer04cde2c2004-07-04 11:33:49 +000078/// Align the buffer position to a 32 bit boundary
Reid Spencer060d25d2004-06-29 23:29:38 +000079inline void BytecodeReader::align32() {
Reid Spencer38d54be2004-08-17 07:45:14 +000080 if (hasAlignment) {
81 BufPtr Save = At;
82 At = (const unsigned char *)((unsigned long)(At+3) & (~3UL));
Misha Brukman8a96c532005-04-21 21:44:41 +000083 if (At > Save)
Reid Spencer38d54be2004-08-17 07:45:14 +000084 if (Handler) Handler->handleAlignment(At - Save);
Misha Brukman8a96c532005-04-21 21:44:41 +000085 if (At > BlockEnd)
Reid Spencer38d54be2004-08-17 07:45:14 +000086 error("Ran out of data while aligning!");
87 }
Reid Spencer060d25d2004-06-29 23:29:38 +000088}
89
Reid Spencer04cde2c2004-07-04 11:33:49 +000090/// Read a whole unsigned integer
Reid Spencer060d25d2004-06-29 23:29:38 +000091inline unsigned BytecodeReader::read_uint() {
Misha Brukman8a96c532005-04-21 21:44:41 +000092 if (At+4 > BlockEnd)
Reid Spencer24399722004-07-09 22:21:33 +000093 error("Ran out of data reading uint!");
Reid Spencer060d25d2004-06-29 23:29:38 +000094 At += 4;
95 return At[-4] | (At[-3] << 8) | (At[-2] << 16) | (At[-1] << 24);
96}
97
Reid Spencer04cde2c2004-07-04 11:33:49 +000098/// Read a variable-bit-rate encoded unsigned integer
Reid Spencer060d25d2004-06-29 23:29:38 +000099inline unsigned BytecodeReader::read_vbr_uint() {
100 unsigned Shift = 0;
101 unsigned Result = 0;
102 BufPtr Save = At;
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_uint!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000107 Result |= (unsigned)((*At++) & 0x7F) << Shift;
108 Shift += 7;
109 } while (At[-1] & 0x80);
Reid Spencer04cde2c2004-07-04 11:33:49 +0000110 if (Handler) Handler->handleVBR32(At-Save);
Reid Spencer060d25d2004-06-29 23:29:38 +0000111 return Result;
112}
113
Reid Spencer04cde2c2004-07-04 11:33:49 +0000114/// Read a variable-bit-rate encoded unsigned 64-bit integer.
Reid Spencer060d25d2004-06-29 23:29:38 +0000115inline uint64_t BytecodeReader::read_vbr_uint64() {
116 unsigned Shift = 0;
117 uint64_t Result = 0;
118 BufPtr Save = At;
Misha Brukman8a96c532005-04-21 21:44:41 +0000119
Reid Spencer060d25d2004-06-29 23:29:38 +0000120 do {
Misha Brukman8a96c532005-04-21 21:44:41 +0000121 if (At == BlockEnd)
Reid Spencer24399722004-07-09 22:21:33 +0000122 error("Ran out of data reading vbr_uint64!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000123 Result |= (uint64_t)((*At++) & 0x7F) << Shift;
124 Shift += 7;
125 } while (At[-1] & 0x80);
Reid Spencer04cde2c2004-07-04 11:33:49 +0000126 if (Handler) Handler->handleVBR64(At-Save);
Reid Spencer060d25d2004-06-29 23:29:38 +0000127 return Result;
128}
129
Reid Spencer04cde2c2004-07-04 11:33:49 +0000130/// Read a variable-bit-rate encoded signed 64-bit integer.
Reid Spencer060d25d2004-06-29 23:29:38 +0000131inline int64_t BytecodeReader::read_vbr_int64() {
132 uint64_t R = read_vbr_uint64();
133 if (R & 1) {
134 if (R != 1)
135 return -(int64_t)(R >> 1);
136 else // There is no such thing as -0 with integers. "-0" really means
137 // 0x8000000000000000.
138 return 1LL << 63;
139 } else
140 return (int64_t)(R >> 1);
141}
142
Reid Spencer04cde2c2004-07-04 11:33:49 +0000143/// Read a pascal-style string (length followed by text)
Reid Spencer060d25d2004-06-29 23:29:38 +0000144inline std::string BytecodeReader::read_str() {
145 unsigned Size = read_vbr_uint();
146 const unsigned char *OldAt = At;
147 At += Size;
148 if (At > BlockEnd) // Size invalid?
Reid Spencer24399722004-07-09 22:21:33 +0000149 error("Ran out of data reading a string!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000150 return std::string((char*)OldAt, Size);
151}
152
Reid Spencer04cde2c2004-07-04 11:33:49 +0000153/// Read an arbitrary block of data
Reid Spencer060d25d2004-06-29 23:29:38 +0000154inline void BytecodeReader::read_data(void *Ptr, void *End) {
155 unsigned char *Start = (unsigned char *)Ptr;
156 unsigned Amount = (unsigned char *)End - Start;
Misha Brukman8a96c532005-04-21 21:44:41 +0000157 if (At+Amount > BlockEnd)
Reid Spencer24399722004-07-09 22:21:33 +0000158 error("Ran out of data!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000159 std::copy(At, At+Amount, Start);
160 At += Amount;
161}
162
Reid Spencer46b002c2004-07-11 17:28:43 +0000163/// Read a float value in little-endian order
164inline void BytecodeReader::read_float(float& FloatVal) {
Reid Spencerada16182004-07-25 21:36:26 +0000165 /// FIXME: This isn't optimal, it has size problems on some platforms
166 /// where FP is not IEEE.
Jim Laskeycb6682f2005-08-17 19:34:49 +0000167 FloatVal = BitsToFloat(At[0] | (At[1] << 8) | (At[2] << 16) | (At[3] << 24));
Reid Spencerada16182004-07-25 21:36:26 +0000168 At+=sizeof(uint32_t);
Reid Spencer46b002c2004-07-11 17:28:43 +0000169}
170
171/// Read a double value in little-endian order
172inline void BytecodeReader::read_double(double& DoubleVal) {
Reid Spencerada16182004-07-25 21:36:26 +0000173 /// FIXME: This isn't optimal, it has size problems on some platforms
174 /// where FP is not IEEE.
Jim Laskeycb6682f2005-08-17 19:34:49 +0000175 DoubleVal = BitsToDouble((uint64_t(At[0]) << 0) | (uint64_t(At[1]) << 8) |
176 (uint64_t(At[2]) << 16) | (uint64_t(At[3]) << 24) |
177 (uint64_t(At[4]) << 32) | (uint64_t(At[5]) << 40) |
178 (uint64_t(At[6]) << 48) | (uint64_t(At[7]) << 56));
Reid Spencerada16182004-07-25 21:36:26 +0000179 At+=sizeof(uint64_t);
Reid Spencer46b002c2004-07-11 17:28:43 +0000180}
181
Reid Spencer04cde2c2004-07-04 11:33:49 +0000182/// Read a block header and obtain its type and size
Reid Spencer060d25d2004-06-29 23:29:38 +0000183inline void BytecodeReader::read_block(unsigned &Type, unsigned &Size) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000184 if ( hasLongBlockHeaders ) {
185 Type = read_uint();
186 Size = read_uint();
187 switch (Type) {
Misha Brukman8a96c532005-04-21 21:44:41 +0000188 case BytecodeFormat::Reserved_DoNotUse :
Reid Spencerad89bd62004-07-25 18:07:36 +0000189 error("Reserved_DoNotUse used as Module Type?");
Reid Spencer5b472d92004-08-21 20:49:23 +0000190 Type = BytecodeFormat::ModuleBlockID; break;
Misha Brukman8a96c532005-04-21 21:44:41 +0000191 case BytecodeFormat::Module:
Reid Spencerad89bd62004-07-25 18:07:36 +0000192 Type = BytecodeFormat::ModuleBlockID; break;
193 case BytecodeFormat::Function:
194 Type = BytecodeFormat::FunctionBlockID; break;
195 case BytecodeFormat::ConstantPool:
196 Type = BytecodeFormat::ConstantPoolBlockID; break;
197 case BytecodeFormat::SymbolTable:
198 Type = BytecodeFormat::SymbolTableBlockID; break;
199 case BytecodeFormat::ModuleGlobalInfo:
200 Type = BytecodeFormat::ModuleGlobalInfoBlockID; break;
201 case BytecodeFormat::GlobalTypePlane:
202 Type = BytecodeFormat::GlobalTypePlaneBlockID; break;
203 case BytecodeFormat::InstructionList:
204 Type = BytecodeFormat::InstructionListBlockID; break;
205 case BytecodeFormat::CompactionTable:
206 Type = BytecodeFormat::CompactionTableBlockID; break;
207 case BytecodeFormat::BasicBlock:
208 /// This block type isn't used after version 1.1. However, we have to
209 /// still allow the value in case this is an old bc format file.
210 /// We just let its value creep thru.
211 break;
212 default:
Reid Spencer5b472d92004-08-21 20:49:23 +0000213 error("Invalid block id found: " + utostr(Type));
Reid Spencerad89bd62004-07-25 18:07:36 +0000214 break;
215 }
216 } else {
217 Size = read_uint();
218 Type = Size & 0x1F; // mask low order five bits
219 Size >>= 5; // get rid of five low order bits, leaving high 27
220 }
Reid Spencer060d25d2004-06-29 23:29:38 +0000221 BlockStart = At;
Reid Spencer46b002c2004-07-11 17:28:43 +0000222 if (At + Size > BlockEnd)
Reid Spencer24399722004-07-09 22:21:33 +0000223 error("Attempt to size a block past end of memory");
Reid Spencer060d25d2004-06-29 23:29:38 +0000224 BlockEnd = At + Size;
Reid Spencer46b002c2004-07-11 17:28:43 +0000225 if (Handler) Handler->handleBlock(Type, BlockStart, Size);
Reid Spencer04cde2c2004-07-04 11:33:49 +0000226}
227
228
229/// In LLVM 1.2 and before, Types were derived from Value and so they were
230/// written as part of the type planes along with any other Value. In LLVM
231/// 1.3 this changed so that Type does not derive from Value. Consequently,
232/// the BytecodeReader's containers for Values can't contain Types because
233/// there's no inheritance relationship. This means that the "Type Type"
Misha Brukman8a96c532005-04-21 21:44:41 +0000234/// plane is defunct along with the Type::TypeTyID TypeID. In LLVM 1.3
235/// whenever a bytecode construct must have both types and values together,
Reid Spencer04cde2c2004-07-04 11:33:49 +0000236/// the types are always read/written first and then the Values. Furthermore
237/// since Type::TypeTyID no longer exists, its value (12) now corresponds to
238/// Type::LabelTyID. In order to overcome this we must "sanitize" all the
239/// type TypeIDs we encounter. For LLVM 1.3 bytecode files, there's no change.
240/// For LLVM 1.2 and before, this function will decrement the type id by
241/// one to account for the missing Type::TypeTyID enumerator if the value is
242/// larger than 12 (Type::LabelTyID). If the value is exactly 12, then this
243/// function returns true, otherwise false. This helps detect situations
244/// where the pre 1.3 bytecode is indicating that what follows is a type.
Misha Brukman8a96c532005-04-21 21:44:41 +0000245/// @returns true iff type id corresponds to pre 1.3 "type type"
Reid Spencer46b002c2004-07-11 17:28:43 +0000246inline bool BytecodeReader::sanitizeTypeId(unsigned &TypeId) {
247 if (hasTypeDerivedFromValue) { /// do nothing if 1.3 or later
248 if (TypeId == Type::LabelTyID) {
Reid Spencer04cde2c2004-07-04 11:33:49 +0000249 TypeId = Type::VoidTyID; // sanitize it
250 return true; // indicate we got TypeTyID in pre 1.3 bytecode
Reid Spencer46b002c2004-07-11 17:28:43 +0000251 } else if (TypeId > Type::LabelTyID)
Reid Spencer04cde2c2004-07-04 11:33:49 +0000252 --TypeId; // shift all planes down because type type plane is missing
253 }
254 return false;
255}
256
257/// Reads a vbr uint to read in a type id and does the necessary
258/// conversion on it by calling sanitizeTypeId.
259/// @returns true iff \p TypeId read corresponds to a pre 1.3 "type type"
260/// @see sanitizeTypeId
261inline bool BytecodeReader::read_typeid(unsigned &TypeId) {
262 TypeId = read_vbr_uint();
Reid Spencerad89bd62004-07-25 18:07:36 +0000263 if ( !has32BitTypes )
264 if ( TypeId == 0x00FFFFFF )
265 TypeId = read_vbr_uint();
Reid Spencer04cde2c2004-07-04 11:33:49 +0000266 return sanitizeTypeId(TypeId);
Reid Spencer060d25d2004-06-29 23:29:38 +0000267}
268
269//===----------------------------------------------------------------------===//
270// IR Lookup Methods
271//===----------------------------------------------------------------------===//
272
Reid Spencer04cde2c2004-07-04 11:33:49 +0000273/// Determine if a type id has an implicit null value
Reid Spencer46b002c2004-07-11 17:28:43 +0000274inline bool BytecodeReader::hasImplicitNull(unsigned TyID) {
Reid Spencer060d25d2004-06-29 23:29:38 +0000275 if (!hasExplicitPrimitiveZeros)
Reid Spencer04cde2c2004-07-04 11:33:49 +0000276 return TyID != Type::LabelTyID && TyID != Type::VoidTyID;
Reid Spencer060d25d2004-06-29 23:29:38 +0000277 return TyID >= Type::FirstDerivedTyID;
278}
279
Reid Spencer04cde2c2004-07-04 11:33:49 +0000280/// Obtain a type given a typeid and account for things like compaction tables,
281/// function level vs module level, and the offsetting for the primitive types.
Reid Spencer060d25d2004-06-29 23:29:38 +0000282const Type *BytecodeReader::getType(unsigned ID) {
Chris Lattner89e02532004-01-18 21:08:15 +0000283 if (ID < Type::FirstDerivedTyID)
Chris Lattnerf70c22b2004-06-17 18:19:28 +0000284 if (const Type *T = Type::getPrimitiveType((Type::TypeID)ID))
Chris Lattner927b1852003-10-09 20:22:47 +0000285 return T; // Asked for a primitive type...
Chris Lattner36392bc2003-10-08 21:18:57 +0000286
287 // Otherwise, derived types need offset...
Chris Lattner89e02532004-01-18 21:08:15 +0000288 ID -= Type::FirstDerivedTyID;
289
Reid Spencer060d25d2004-06-29 23:29:38 +0000290 if (!CompactionTypes.empty()) {
291 if (ID >= CompactionTypes.size())
Reid Spencer24399722004-07-09 22:21:33 +0000292 error("Type ID out of range for compaction table!");
Chris Lattner45b5dd22004-08-03 23:41:28 +0000293 return CompactionTypes[ID].first;
Chris Lattner89e02532004-01-18 21:08:15 +0000294 }
Chris Lattner36392bc2003-10-08 21:18:57 +0000295
296 // Is it a module-level type?
Reid Spencer46b002c2004-07-11 17:28:43 +0000297 if (ID < ModuleTypes.size())
298 return ModuleTypes[ID].get();
Chris Lattner36392bc2003-10-08 21:18:57 +0000299
Reid Spencer46b002c2004-07-11 17:28:43 +0000300 // Nope, is it a function-level type?
301 ID -= ModuleTypes.size();
302 if (ID < FunctionTypes.size())
303 return FunctionTypes[ID].get();
Chris Lattner36392bc2003-10-08 21:18:57 +0000304
Reid Spencer46b002c2004-07-11 17:28:43 +0000305 error("Illegal type reference!");
306 return Type::VoidTy;
Chris Lattner00950542001-06-06 20:29:01 +0000307}
308
Reid Spencer04cde2c2004-07-04 11:33:49 +0000309/// Get a sanitized type id. This just makes sure that the \p ID
310/// is both sanitized and not the "type type" of pre-1.3 bytecode.
311/// @see sanitizeTypeId
312inline const Type* BytecodeReader::getSanitizedType(unsigned& ID) {
Reid Spencer46b002c2004-07-11 17:28:43 +0000313 if (sanitizeTypeId(ID))
Reid Spencer24399722004-07-09 22:21:33 +0000314 error("Invalid type id encountered");
Reid Spencer04cde2c2004-07-04 11:33:49 +0000315 return getType(ID);
316}
317
318/// This method just saves some coding. It uses read_typeid to read
Reid Spencer24399722004-07-09 22:21:33 +0000319/// in a sanitized type id, errors that its not the type type, and
Reid Spencer04cde2c2004-07-04 11:33:49 +0000320/// then calls getType to return the type value.
321inline const Type* BytecodeReader::readSanitizedType() {
322 unsigned ID;
Reid Spencer46b002c2004-07-11 17:28:43 +0000323 if (read_typeid(ID))
324 error("Invalid type id encountered");
Reid Spencer04cde2c2004-07-04 11:33:49 +0000325 return getType(ID);
326}
327
328/// Get the slot number associated with a type accounting for primitive
329/// types, compaction tables, and function level vs module level.
Reid Spencer060d25d2004-06-29 23:29:38 +0000330unsigned BytecodeReader::getTypeSlot(const Type *Ty) {
331 if (Ty->isPrimitiveType())
332 return Ty->getTypeID();
333
334 // Scan the compaction table for the type if needed.
335 if (!CompactionTypes.empty()) {
Chris Lattner45b5dd22004-08-03 23:41:28 +0000336 for (unsigned i = 0, e = CompactionTypes.size(); i != e; ++i)
337 if (CompactionTypes[i].first == Ty)
Misha Brukman8a96c532005-04-21 21:44:41 +0000338 return Type::FirstDerivedTyID + i;
Reid Spencer060d25d2004-06-29 23:29:38 +0000339
Chris Lattner45b5dd22004-08-03 23:41:28 +0000340 error("Couldn't find type specified in compaction table!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000341 }
342
343 // Check the function level types first...
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000344 TypeListTy::iterator I = std::find(FunctionTypes.begin(),
345 FunctionTypes.end(), Ty);
Reid Spencer060d25d2004-06-29 23:29:38 +0000346
347 if (I != FunctionTypes.end())
Misha Brukman8a96c532005-04-21 21:44:41 +0000348 return Type::FirstDerivedTyID + ModuleTypes.size() +
Reid Spencer46b002c2004-07-11 17:28:43 +0000349 (&*I - &FunctionTypes[0]);
Reid Spencer060d25d2004-06-29 23:29:38 +0000350
Chris Lattnereebac5f2005-10-03 21:26:53 +0000351 // If we don't have our cache yet, build it now.
352 if (ModuleTypeIDCache.empty()) {
353 unsigned N = 0;
354 ModuleTypeIDCache.reserve(ModuleTypes.size());
355 for (TypeListTy::iterator I = ModuleTypes.begin(), E = ModuleTypes.end();
356 I != E; ++I, ++N)
357 ModuleTypeIDCache.push_back(std::make_pair(*I, N));
358
359 std::sort(ModuleTypeIDCache.begin(), ModuleTypeIDCache.end());
360 }
361
362 // Binary search the cache for the entry.
363 std::vector<std::pair<const Type*, unsigned> >::iterator IT =
364 std::lower_bound(ModuleTypeIDCache.begin(), ModuleTypeIDCache.end(),
365 std::make_pair(Ty, 0U));
366 if (IT == ModuleTypeIDCache.end() || IT->first != Ty)
Reid Spencer24399722004-07-09 22:21:33 +0000367 error("Didn't find type in ModuleTypes.");
Chris Lattnereebac5f2005-10-03 21:26:53 +0000368
369 return Type::FirstDerivedTyID + IT->second;
Chris Lattner80b97342004-01-17 23:25:43 +0000370}
371
Reid Spencer04cde2c2004-07-04 11:33:49 +0000372/// This is just like getType, but when a compaction table is in use, it is
373/// ignored. It also ignores function level types.
374/// @see getType
Reid Spencer060d25d2004-06-29 23:29:38 +0000375const Type *BytecodeReader::getGlobalTableType(unsigned Slot) {
376 if (Slot < Type::FirstDerivedTyID) {
377 const Type *Ty = Type::getPrimitiveType((Type::TypeID)Slot);
Reid Spencer46b002c2004-07-11 17:28:43 +0000378 if (!Ty)
Reid Spencer24399722004-07-09 22:21:33 +0000379 error("Not a primitive type ID?");
Reid Spencer060d25d2004-06-29 23:29:38 +0000380 return Ty;
381 }
382 Slot -= Type::FirstDerivedTyID;
383 if (Slot >= ModuleTypes.size())
Reid Spencer24399722004-07-09 22:21:33 +0000384 error("Illegal compaction table type reference!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000385 return ModuleTypes[Slot];
Chris Lattner52e20b02003-03-19 20:54:26 +0000386}
387
Reid Spencer04cde2c2004-07-04 11:33:49 +0000388/// This is just like getTypeSlot, but when a compaction table is in use, it
389/// is ignored. It also ignores function level types.
Reid Spencer060d25d2004-06-29 23:29:38 +0000390unsigned BytecodeReader::getGlobalTableTypeSlot(const Type *Ty) {
391 if (Ty->isPrimitiveType())
392 return Ty->getTypeID();
Chris Lattnereebac5f2005-10-03 21:26:53 +0000393
394 // If we don't have our cache yet, build it now.
395 if (ModuleTypeIDCache.empty()) {
396 unsigned N = 0;
397 ModuleTypeIDCache.reserve(ModuleTypes.size());
398 for (TypeListTy::iterator I = ModuleTypes.begin(), E = ModuleTypes.end();
399 I != E; ++I, ++N)
400 ModuleTypeIDCache.push_back(std::make_pair(*I, N));
401
402 std::sort(ModuleTypeIDCache.begin(), ModuleTypeIDCache.end());
403 }
404
405 // Binary search the cache for the entry.
406 std::vector<std::pair<const Type*, unsigned> >::iterator IT =
407 std::lower_bound(ModuleTypeIDCache.begin(), ModuleTypeIDCache.end(),
408 std::make_pair(Ty, 0U));
409 if (IT == ModuleTypeIDCache.end() || IT->first != Ty)
Reid Spencer24399722004-07-09 22:21:33 +0000410 error("Didn't find type in ModuleTypes.");
Chris Lattnereebac5f2005-10-03 21:26:53 +0000411
412 return Type::FirstDerivedTyID + IT->second;
Reid Spencer060d25d2004-06-29 23:29:38 +0000413}
414
Misha Brukman8a96c532005-04-21 21:44:41 +0000415/// Retrieve a value of a given type and slot number, possibly creating
416/// it if it doesn't already exist.
Reid Spencer060d25d2004-06-29 23:29:38 +0000417Value * BytecodeReader::getValue(unsigned type, unsigned oNum, bool Create) {
Chris Lattner4ee8ef22003-10-08 22:52:54 +0000418 assert(type != Type::LabelTyID && "getValue() cannot get blocks!");
Chris Lattner00950542001-06-06 20:29:01 +0000419 unsigned Num = oNum;
Chris Lattner00950542001-06-06 20:29:01 +0000420
Chris Lattner89e02532004-01-18 21:08:15 +0000421 // If there is a compaction table active, it defines the low-level numbers.
422 // If not, the module values define the low-level numbers.
Reid Spencer060d25d2004-06-29 23:29:38 +0000423 if (CompactionValues.size() > type && !CompactionValues[type].empty()) {
424 if (Num < CompactionValues[type].size())
425 return CompactionValues[type][Num];
426 Num -= CompactionValues[type].size();
Chris Lattner89e02532004-01-18 21:08:15 +0000427 } else {
Reid Spencer060d25d2004-06-29 23:29:38 +0000428 // By default, the global type id is the type id passed in
Chris Lattner52f86d62004-01-20 00:54:06 +0000429 unsigned GlobalTyID = type;
Reid Spencer060d25d2004-06-29 23:29:38 +0000430
Chris Lattner45b5dd22004-08-03 23:41:28 +0000431 // If the type plane was compactified, figure out the global type ID by
432 // adding the derived type ids and the distance.
433 if (!CompactionTypes.empty() && type >= Type::FirstDerivedTyID)
434 GlobalTyID = CompactionTypes[type-Type::FirstDerivedTyID].second;
Chris Lattner00950542001-06-06 20:29:01 +0000435
Reid Spencer060d25d2004-06-29 23:29:38 +0000436 if (hasImplicitNull(GlobalTyID)) {
Chris Lattneraba5ff52005-05-05 20:57:00 +0000437 const Type *Ty = getType(type);
438 if (!isa<OpaqueType>(Ty)) {
439 if (Num == 0)
440 return Constant::getNullValue(Ty);
441 --Num;
442 }
Chris Lattner89e02532004-01-18 21:08:15 +0000443 }
444
Chris Lattner52f86d62004-01-20 00:54:06 +0000445 if (GlobalTyID < ModuleValues.size() && ModuleValues[GlobalTyID]) {
446 if (Num < ModuleValues[GlobalTyID]->size())
Reid Spencer04cde2c2004-07-04 11:33:49 +0000447 return ModuleValues[GlobalTyID]->getOperand(Num);
Chris Lattner52f86d62004-01-20 00:54:06 +0000448 Num -= ModuleValues[GlobalTyID]->size();
Chris Lattner89e02532004-01-18 21:08:15 +0000449 }
Chris Lattner52e20b02003-03-19 20:54:26 +0000450 }
451
Misha Brukman8a96c532005-04-21 21:44:41 +0000452 if (FunctionValues.size() > type &&
453 FunctionValues[type] &&
Reid Spencer060d25d2004-06-29 23:29:38 +0000454 Num < FunctionValues[type]->size())
455 return FunctionValues[type]->getOperand(Num);
Chris Lattner00950542001-06-06 20:29:01 +0000456
Chris Lattner74734132002-08-17 22:01:27 +0000457 if (!Create) return 0; // Do not create a placeholder?
Chris Lattner00950542001-06-06 20:29:01 +0000458
Reid Spencer551ccae2004-09-01 22:55:40 +0000459 // Did we already create a place holder?
Chris Lattner8eb10ce2003-10-09 06:05:40 +0000460 std::pair<unsigned,unsigned> KeyValue(type, oNum);
Reid Spencer060d25d2004-06-29 23:29:38 +0000461 ForwardReferenceMap::iterator I = ForwardReferences.lower_bound(KeyValue);
Chris Lattner8eb10ce2003-10-09 06:05:40 +0000462 if (I != ForwardReferences.end() && I->first == KeyValue)
463 return I->second; // We have already created this placeholder
464
Reid Spencer551ccae2004-09-01 22:55:40 +0000465 // If the type exists (it should)
466 if (const Type* Ty = getType(type)) {
467 // Create the place holder
468 Value *Val = new Argument(Ty);
469 ForwardReferences.insert(I, std::make_pair(KeyValue, Val));
470 return Val;
471 }
472 throw "Can't create placeholder for value of type slot #" + utostr(type);
Chris Lattner00950542001-06-06 20:29:01 +0000473}
474
Misha Brukman8a96c532005-04-21 21:44:41 +0000475/// This is just like getValue, but when a compaction table is in use, it
476/// is ignored. Also, no forward references or other fancy features are
Reid Spencer04cde2c2004-07-04 11:33:49 +0000477/// supported.
Chris Lattner2c6c14d2004-08-04 00:19:23 +0000478Value* BytecodeReader::getGlobalTableValue(unsigned TyID, unsigned SlotNo) {
479 if (SlotNo == 0)
480 return Constant::getNullValue(getType(TyID));
481
482 if (!CompactionTypes.empty() && TyID >= Type::FirstDerivedTyID) {
483 TyID -= Type::FirstDerivedTyID;
484 if (TyID >= CompactionTypes.size())
485 error("Type ID out of range for compaction table!");
486 TyID = CompactionTypes[TyID].second;
Reid Spencer060d25d2004-06-29 23:29:38 +0000487 }
488
Chris Lattner2c6c14d2004-08-04 00:19:23 +0000489 --SlotNo;
490
Reid Spencer060d25d2004-06-29 23:29:38 +0000491 if (TyID >= ModuleValues.size() || ModuleValues[TyID] == 0 ||
492 SlotNo >= ModuleValues[TyID]->size()) {
Chris Lattner2c6c14d2004-08-04 00:19:23 +0000493 if (TyID >= ModuleValues.size() || ModuleValues[TyID] == 0)
494 error("Corrupt compaction table entry!"
Misha Brukman8a96c532005-04-21 21:44:41 +0000495 + utostr(TyID) + ", " + utostr(SlotNo) + ": "
Chris Lattner2c6c14d2004-08-04 00:19:23 +0000496 + utostr(ModuleValues.size()));
Misha Brukman8a96c532005-04-21 21:44:41 +0000497 else
Chris Lattner2c6c14d2004-08-04 00:19:23 +0000498 error("Corrupt compaction table entry!"
Misha Brukman8a96c532005-04-21 21:44:41 +0000499 + utostr(TyID) + ", " + utostr(SlotNo) + ": "
Chris Lattner2c6c14d2004-08-04 00:19:23 +0000500 + utostr(ModuleValues.size()) + ", "
Reid Spencer9a7e0c52004-08-04 22:56:46 +0000501 + utohexstr(reinterpret_cast<uint64_t>(((void*)ModuleValues[TyID])))
502 + ", "
Chris Lattner2c6c14d2004-08-04 00:19:23 +0000503 + utostr(ModuleValues[TyID]->size()));
Reid Spencer060d25d2004-06-29 23:29:38 +0000504 }
505 return ModuleValues[TyID]->getOperand(SlotNo);
506}
507
Reid Spencer04cde2c2004-07-04 11:33:49 +0000508/// Just like getValue, except that it returns a null pointer
509/// only on error. It always returns a constant (meaning that if the value is
510/// defined, but is not a constant, that is an error). If the specified
Misha Brukman8a96c532005-04-21 21:44:41 +0000511/// constant hasn't been parsed yet, a placeholder is defined and used.
Reid Spencer04cde2c2004-07-04 11:33:49 +0000512/// Later, after the real value is parsed, the placeholder is eliminated.
Reid Spencer060d25d2004-06-29 23:29:38 +0000513Constant* BytecodeReader::getConstantValue(unsigned TypeSlot, unsigned Slot) {
514 if (Value *V = getValue(TypeSlot, Slot, false))
515 if (Constant *C = dyn_cast<Constant>(V))
516 return C; // If we already have the value parsed, just return it
Reid Spencer060d25d2004-06-29 23:29:38 +0000517 else
Misha Brukman8a96c532005-04-21 21:44:41 +0000518 error("Value for slot " + utostr(Slot) +
Reid Spencera86037e2004-07-18 00:12:03 +0000519 " is expected to be a constant!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000520
Chris Lattner389bd042004-12-09 06:19:44 +0000521 std::pair<unsigned, unsigned> Key(TypeSlot, Slot);
Reid Spencer060d25d2004-06-29 23:29:38 +0000522 ConstantRefsType::iterator I = ConstantFwdRefs.lower_bound(Key);
523
524 if (I != ConstantFwdRefs.end() && I->first == Key) {
525 return I->second;
526 } else {
527 // Create a placeholder for the constant reference and
528 // keep track of the fact that we have a forward ref to recycle it
Chris Lattner389bd042004-12-09 06:19:44 +0000529 Constant *C = new ConstantPlaceHolder(getType(TypeSlot));
Misha Brukman8a96c532005-04-21 21:44:41 +0000530
Reid Spencer060d25d2004-06-29 23:29:38 +0000531 // Keep track of the fact that we have a forward ref to recycle it
532 ConstantFwdRefs.insert(I, std::make_pair(Key, C));
533 return C;
534 }
535}
536
537//===----------------------------------------------------------------------===//
538// IR Construction Methods
539//===----------------------------------------------------------------------===//
540
Reid Spencer04cde2c2004-07-04 11:33:49 +0000541/// As values are created, they are inserted into the appropriate place
542/// with this method. The ValueTable argument must be one of ModuleValues
543/// or FunctionValues data members of this class.
Misha Brukman8a96c532005-04-21 21:44:41 +0000544unsigned BytecodeReader::insertValue(Value *Val, unsigned type,
Reid Spencer46b002c2004-07-11 17:28:43 +0000545 ValueTable &ValueTab) {
Reid Spencer060d25d2004-06-29 23:29:38 +0000546 assert((!isa<Constant>(Val) || !cast<Constant>(Val)->isNullValue()) ||
Reid Spencer04cde2c2004-07-04 11:33:49 +0000547 !hasImplicitNull(type) &&
548 "Cannot read null values from bytecode!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000549
550 if (ValueTab.size() <= type)
551 ValueTab.resize(type+1);
552
553 if (!ValueTab[type]) ValueTab[type] = new ValueList();
554
555 ValueTab[type]->push_back(Val);
556
Chris Lattneraba5ff52005-05-05 20:57:00 +0000557 bool HasOffset = hasImplicitNull(type) && !isa<OpaqueType>(Val->getType());
Reid Spencer060d25d2004-06-29 23:29:38 +0000558 return ValueTab[type]->size()-1 + HasOffset;
559}
560
Reid Spencer04cde2c2004-07-04 11:33:49 +0000561/// Insert the arguments of a function as new values in the reader.
Reid Spencer46b002c2004-07-11 17:28:43 +0000562void BytecodeReader::insertArguments(Function* F) {
Reid Spencer060d25d2004-06-29 23:29:38 +0000563 const FunctionType *FT = F->getFunctionType();
Chris Lattnere4d5c442005-03-15 04:54:21 +0000564 Function::arg_iterator AI = F->arg_begin();
Reid Spencer060d25d2004-06-29 23:29:38 +0000565 for (FunctionType::param_iterator It = FT->param_begin();
566 It != FT->param_end(); ++It, ++AI)
567 insertValue(AI, getTypeSlot(AI->getType()), FunctionValues);
568}
569
570//===----------------------------------------------------------------------===//
571// Bytecode Parsing Methods
572//===----------------------------------------------------------------------===//
573
Reid Spencer04cde2c2004-07-04 11:33:49 +0000574/// This method parses a single instruction. The instruction is
575/// inserted at the end of the \p BB provided. The arguments of
Misha Brukman44666b12004-09-28 16:57:46 +0000576/// the instruction are provided in the \p Oprnds vector.
Reid Spencer060d25d2004-06-29 23:29:38 +0000577void BytecodeReader::ParseInstruction(std::vector<unsigned> &Oprnds,
Reid Spencer46b002c2004-07-11 17:28:43 +0000578 BasicBlock* BB) {
Reid Spencer060d25d2004-06-29 23:29:38 +0000579 BufPtr SaveAt = At;
580
581 // Clear instruction data
582 Oprnds.clear();
583 unsigned iType = 0;
584 unsigned Opcode = 0;
585 unsigned Op = read_uint();
586
587 // bits Instruction format: Common to all formats
588 // --------------------------
589 // 01-00: Opcode type, fixed to 1.
590 // 07-02: Opcode
591 Opcode = (Op >> 2) & 63;
592 Oprnds.resize((Op >> 0) & 03);
593
594 // Extract the operands
595 switch (Oprnds.size()) {
596 case 1:
597 // bits Instruction format:
598 // --------------------------
599 // 19-08: Resulting type plane
600 // 31-20: Operand #1 (if set to (2^12-1), then zero operands)
601 //
602 iType = (Op >> 8) & 4095;
603 Oprnds[0] = (Op >> 20) & 4095;
604 if (Oprnds[0] == 4095) // Handle special encoding for 0 operands...
605 Oprnds.resize(0);
606 break;
607 case 2:
608 // bits Instruction format:
609 // --------------------------
610 // 15-08: Resulting type plane
611 // 23-16: Operand #1
Misha Brukman8a96c532005-04-21 21:44:41 +0000612 // 31-24: Operand #2
Reid Spencer060d25d2004-06-29 23:29:38 +0000613 //
614 iType = (Op >> 8) & 255;
615 Oprnds[0] = (Op >> 16) & 255;
616 Oprnds[1] = (Op >> 24) & 255;
617 break;
618 case 3:
619 // bits Instruction format:
620 // --------------------------
621 // 13-08: Resulting type plane
622 // 19-14: Operand #1
623 // 25-20: Operand #2
624 // 31-26: Operand #3
625 //
626 iType = (Op >> 8) & 63;
627 Oprnds[0] = (Op >> 14) & 63;
628 Oprnds[1] = (Op >> 20) & 63;
629 Oprnds[2] = (Op >> 26) & 63;
630 break;
631 case 0:
632 At -= 4; // Hrm, try this again...
633 Opcode = read_vbr_uint();
634 Opcode >>= 2;
635 iType = read_vbr_uint();
636
637 unsigned NumOprnds = read_vbr_uint();
638 Oprnds.resize(NumOprnds);
639
640 if (NumOprnds == 0)
Reid Spencer24399722004-07-09 22:21:33 +0000641 error("Zero-argument instruction found; this is invalid.");
Reid Spencer060d25d2004-06-29 23:29:38 +0000642
643 for (unsigned i = 0; i != NumOprnds; ++i)
644 Oprnds[i] = read_vbr_uint();
645 align32();
646 break;
647 }
648
Reid Spencer04cde2c2004-07-04 11:33:49 +0000649 const Type *InstTy = getSanitizedType(iType);
Reid Spencer060d25d2004-06-29 23:29:38 +0000650
Reid Spencer46b002c2004-07-11 17:28:43 +0000651 // We have enough info to inform the handler now.
Reid Spencer04cde2c2004-07-04 11:33:49 +0000652 if (Handler) Handler->handleInstruction(Opcode, InstTy, Oprnds, At-SaveAt);
Reid Spencer060d25d2004-06-29 23:29:38 +0000653
654 // Declare the resulting instruction we'll build.
655 Instruction *Result = 0;
656
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000657 // If this is a bytecode format that did not include the unreachable
658 // instruction, bump up all opcodes numbers to make space.
659 if (hasNoUnreachableInst) {
660 if (Opcode >= Instruction::Unreachable &&
661 Opcode < 62) {
662 ++Opcode;
663 }
664 }
665
Reid Spencer060d25d2004-06-29 23:29:38 +0000666 // Handle binary operators
667 if (Opcode >= Instruction::BinaryOpsBegin &&
668 Opcode < Instruction::BinaryOpsEnd && Oprnds.size() == 2)
669 Result = BinaryOperator::create((Instruction::BinaryOps)Opcode,
670 getValue(iType, Oprnds[0]),
671 getValue(iType, Oprnds[1]));
672
673 switch (Opcode) {
Misha Brukman8a96c532005-04-21 21:44:41 +0000674 default:
675 if (Result == 0)
Reid Spencer24399722004-07-09 22:21:33 +0000676 error("Illegal instruction read!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000677 break;
678 case Instruction::VAArg:
Misha Brukman8a96c532005-04-21 21:44:41 +0000679 Result = new VAArgInst(getValue(iType, Oprnds[0]),
Reid Spencer46b002c2004-07-11 17:28:43 +0000680 getSanitizedType(Oprnds[1]));
Reid Spencer060d25d2004-06-29 23:29:38 +0000681 break;
Andrew Lenharth558bc882005-06-18 18:34:52 +0000682 case 32: { //VANext_old
683 const Type* ArgTy = getValue(iType, Oprnds[0])->getType();
Jeff Cohen66c5fd62005-10-23 04:37:20 +0000684 Function* NF = TheModule->getOrInsertFunction("llvm.va_copy", ArgTy, ArgTy,
685 (Type *)0);
Andrew Lenharth558bc882005-06-18 18:34:52 +0000686
687 //b = vanext a, t ->
688 //foo = alloca 1 of t
689 //bar = vacopy a
690 //store bar -> foo
691 //tmp = vaarg foo, t
692 //b = load foo
693 AllocaInst* foo = new AllocaInst(ArgTy, 0, "vanext.fix");
694 BB->getInstList().push_back(foo);
695 CallInst* bar = new CallInst(NF, getValue(iType, Oprnds[0]));
696 BB->getInstList().push_back(bar);
697 BB->getInstList().push_back(new StoreInst(bar, foo));
698 Instruction* tmp = new VAArgInst(foo, getSanitizedType(Oprnds[1]));
699 BB->getInstList().push_back(tmp);
700 Result = new LoadInst(foo);
Reid Spencer060d25d2004-06-29 23:29:38 +0000701 break;
Andrew Lenharth558bc882005-06-18 18:34:52 +0000702 }
703 case 33: { //VAArg_old
704 const Type* ArgTy = getValue(iType, Oprnds[0])->getType();
Jeff Cohen66c5fd62005-10-23 04:37:20 +0000705 Function* NF = TheModule->getOrInsertFunction("llvm.va_copy", ArgTy, ArgTy,
706 (Type *)0);
Andrew Lenharth558bc882005-06-18 18:34:52 +0000707
Jeff Cohen00b168892005-07-27 06:12:32 +0000708 //b = vaarg a, t ->
Andrew Lenharth558bc882005-06-18 18:34:52 +0000709 //foo = alloca 1 of t
Jeff Cohen00b168892005-07-27 06:12:32 +0000710 //bar = vacopy a
Andrew Lenharth558bc882005-06-18 18:34:52 +0000711 //store bar -> foo
712 //b = vaarg foo, t
713 AllocaInst* foo = new AllocaInst(ArgTy, 0, "vaarg.fix");
714 BB->getInstList().push_back(foo);
715 CallInst* bar = new CallInst(NF, getValue(iType, Oprnds[0]));
716 BB->getInstList().push_back(bar);
717 BB->getInstList().push_back(new StoreInst(bar, foo));
718 Result = new VAArgInst(foo, getSanitizedType(Oprnds[1]));
719 break;
720 }
Robert Bocchinofee31b32006-01-10 19:04:39 +0000721 case Instruction::ExtractElement: {
722 if (Oprnds.size() != 2)
723 throw std::string("Invalid extractelement instruction!");
724 Result = new ExtractElementInst(getValue(iType, Oprnds[0]),
725 getValue(Type::UIntTyID, Oprnds[1]));
726 break;
727 }
Robert Bocchinob1f240b2006-01-17 20:06:35 +0000728 case Instruction::InsertElement: {
729 const PackedType *PackedTy = dyn_cast<PackedType>(InstTy);
730 if (!PackedTy || Oprnds.size() != 3)
731 throw std::string("Invalid insertelement instruction!");
732 Result =
733 new InsertElementInst(getValue(iType, Oprnds[0]),
734 getValue(getTypeSlot(PackedTy->getElementType()),
735 Oprnds[1]),
736 getValue(Type::UIntTyID, Oprnds[2]));
737 break;
738 }
Reid Spencer060d25d2004-06-29 23:29:38 +0000739 case Instruction::Cast:
Misha Brukman8a96c532005-04-21 21:44:41 +0000740 Result = new CastInst(getValue(iType, Oprnds[0]),
Reid Spencer46b002c2004-07-11 17:28:43 +0000741 getSanitizedType(Oprnds[1]));
Reid Spencer060d25d2004-06-29 23:29:38 +0000742 break;
743 case Instruction::Select:
744 Result = new SelectInst(getValue(Type::BoolTyID, Oprnds[0]),
745 getValue(iType, Oprnds[1]),
746 getValue(iType, Oprnds[2]));
747 break;
748 case Instruction::PHI: {
749 if (Oprnds.size() == 0 || (Oprnds.size() & 1))
Reid Spencer24399722004-07-09 22:21:33 +0000750 error("Invalid phi node encountered!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000751
752 PHINode *PN = new PHINode(InstTy);
Chris Lattnercad28bd2005-01-29 00:36:19 +0000753 PN->reserveOperandSpace(Oprnds.size());
Reid Spencer060d25d2004-06-29 23:29:38 +0000754 for (unsigned i = 0, e = Oprnds.size(); i != e; i += 2)
755 PN->addIncoming(getValue(iType, Oprnds[i]), getBasicBlock(Oprnds[i+1]));
756 Result = PN;
757 break;
758 }
759
760 case Instruction::Shl:
761 case Instruction::Shr:
762 Result = new ShiftInst((Instruction::OtherOps)Opcode,
763 getValue(iType, Oprnds[0]),
764 getValue(Type::UByteTyID, Oprnds[1]));
765 break;
766 case Instruction::Ret:
767 if (Oprnds.size() == 0)
768 Result = new ReturnInst();
769 else if (Oprnds.size() == 1)
770 Result = new ReturnInst(getValue(iType, Oprnds[0]));
771 else
Reid Spencer24399722004-07-09 22:21:33 +0000772 error("Unrecognized instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000773 break;
774
775 case Instruction::Br:
776 if (Oprnds.size() == 1)
777 Result = new BranchInst(getBasicBlock(Oprnds[0]));
778 else if (Oprnds.size() == 3)
Misha Brukman8a96c532005-04-21 21:44:41 +0000779 Result = new BranchInst(getBasicBlock(Oprnds[0]),
Reid Spencer04cde2c2004-07-04 11:33:49 +0000780 getBasicBlock(Oprnds[1]), getValue(Type::BoolTyID , Oprnds[2]));
Reid Spencer060d25d2004-06-29 23:29:38 +0000781 else
Reid Spencer24399722004-07-09 22:21:33 +0000782 error("Invalid number of operands for a 'br' instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000783 break;
784 case Instruction::Switch: {
785 if (Oprnds.size() & 1)
Reid Spencer24399722004-07-09 22:21:33 +0000786 error("Switch statement with odd number of arguments!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000787
788 SwitchInst *I = new SwitchInst(getValue(iType, Oprnds[0]),
Chris Lattnercad28bd2005-01-29 00:36:19 +0000789 getBasicBlock(Oprnds[1]),
790 Oprnds.size()/2-1);
Reid Spencer060d25d2004-06-29 23:29:38 +0000791 for (unsigned i = 2, e = Oprnds.size(); i != e; i += 2)
Chris Lattner7e618232005-02-24 05:26:04 +0000792 I->addCase(cast<ConstantInt>(getValue(iType, Oprnds[i])),
Reid Spencer060d25d2004-06-29 23:29:38 +0000793 getBasicBlock(Oprnds[i+1]));
794 Result = I;
795 break;
796 }
797
Chris Lattnerdee199f2005-05-06 22:34:01 +0000798 case 58: // Call with extra operand for calling conv
799 case 59: // tail call, Fast CC
800 case 60: // normal call, Fast CC
801 case 61: // tail call, C Calling Conv
802 case Instruction::Call: { // Normal Call, C Calling Convention
Reid Spencer060d25d2004-06-29 23:29:38 +0000803 if (Oprnds.size() == 0)
Reid Spencer24399722004-07-09 22:21:33 +0000804 error("Invalid call instruction encountered!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000805
806 Value *F = getValue(iType, Oprnds[0]);
807
Chris Lattnerdee199f2005-05-06 22:34:01 +0000808 unsigned CallingConv = CallingConv::C;
809 bool isTailCall = false;
810
811 if (Opcode == 61 || Opcode == 59)
812 isTailCall = true;
813
Reid Spencer060d25d2004-06-29 23:29:38 +0000814 // Check to make sure we have a pointer to function type
815 const PointerType *PTy = dyn_cast<PointerType>(F->getType());
Reid Spencer24399722004-07-09 22:21:33 +0000816 if (PTy == 0) error("Call to non function pointer value!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000817 const FunctionType *FTy = dyn_cast<FunctionType>(PTy->getElementType());
Reid Spencer24399722004-07-09 22:21:33 +0000818 if (FTy == 0) error("Call to non function pointer value!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000819
820 std::vector<Value *> Params;
821 if (!FTy->isVarArg()) {
822 FunctionType::param_iterator It = FTy->param_begin();
823
Chris Lattnerdee199f2005-05-06 22:34:01 +0000824 if (Opcode == 58) {
825 isTailCall = Oprnds.back() & 1;
826 CallingConv = Oprnds.back() >> 1;
827 Oprnds.pop_back();
828 } else if (Opcode == 59 || Opcode == 60)
829 CallingConv = CallingConv::Fast;
830
Reid Spencer060d25d2004-06-29 23:29:38 +0000831 for (unsigned i = 1, e = Oprnds.size(); i != e; ++i) {
832 if (It == FTy->param_end())
Reid Spencer24399722004-07-09 22:21:33 +0000833 error("Invalid call instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000834 Params.push_back(getValue(getTypeSlot(*It++), Oprnds[i]));
835 }
836 if (It != FTy->param_end())
Reid Spencer24399722004-07-09 22:21:33 +0000837 error("Invalid call instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000838 } else {
839 Oprnds.erase(Oprnds.begin(), Oprnds.begin()+1);
840
841 unsigned FirstVariableOperand;
842 if (Oprnds.size() < FTy->getNumParams())
Reid Spencer24399722004-07-09 22:21:33 +0000843 error("Call instruction missing operands!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000844
845 // Read all of the fixed arguments
846 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
847 Params.push_back(getValue(getTypeSlot(FTy->getParamType(i)),Oprnds[i]));
Misha Brukman8a96c532005-04-21 21:44:41 +0000848
Reid Spencer060d25d2004-06-29 23:29:38 +0000849 FirstVariableOperand = FTy->getNumParams();
850
Misha Brukman8a96c532005-04-21 21:44:41 +0000851 if ((Oprnds.size()-FirstVariableOperand) & 1)
Chris Lattner4a242b32004-10-14 01:39:18 +0000852 error("Invalid call instruction!"); // Must be pairs of type/value
Misha Brukman8a96c532005-04-21 21:44:41 +0000853
854 for (unsigned i = FirstVariableOperand, e = Oprnds.size();
Reid Spencer04cde2c2004-07-04 11:33:49 +0000855 i != e; i += 2)
Reid Spencer060d25d2004-06-29 23:29:38 +0000856 Params.push_back(getValue(Oprnds[i], Oprnds[i+1]));
857 }
858
859 Result = new CallInst(F, Params);
Reid Spencere812fb22006-01-19 01:21:04 +0000860 if (CallInst* newCI = UpgradeIntrinsicCall(cast<CallInst>(Result))) {
861 Result->replaceAllUsesWith(newCI);
862 Result->eraseFromParent();
863 Result = newCI;
864 }
Chris Lattnerdee199f2005-05-06 22:34:01 +0000865 if (isTailCall) cast<CallInst>(Result)->setTailCall();
866 if (CallingConv) cast<CallInst>(Result)->setCallingConv(CallingConv);
Reid Spencer060d25d2004-06-29 23:29:38 +0000867 break;
868 }
Chris Lattnerdee199f2005-05-06 22:34:01 +0000869 case 56: // Invoke with encoded CC
870 case 57: // Invoke Fast CC
871 case Instruction::Invoke: { // Invoke C CC
Misha Brukman8a96c532005-04-21 21:44:41 +0000872 if (Oprnds.size() < 3)
Reid Spencer24399722004-07-09 22:21:33 +0000873 error("Invalid invoke instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000874 Value *F = getValue(iType, Oprnds[0]);
875
876 // Check to make sure we have a pointer to function type
877 const PointerType *PTy = dyn_cast<PointerType>(F->getType());
Misha Brukman8a96c532005-04-21 21:44:41 +0000878 if (PTy == 0)
Reid Spencer24399722004-07-09 22:21:33 +0000879 error("Invoke to non function pointer value!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000880 const FunctionType *FTy = dyn_cast<FunctionType>(PTy->getElementType());
Misha Brukman8a96c532005-04-21 21:44:41 +0000881 if (FTy == 0)
Reid Spencer24399722004-07-09 22:21:33 +0000882 error("Invoke to non function pointer value!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000883
884 std::vector<Value *> Params;
885 BasicBlock *Normal, *Except;
Chris Lattnerdee199f2005-05-06 22:34:01 +0000886 unsigned CallingConv = CallingConv::C;
887
888 if (Opcode == 57)
889 CallingConv = CallingConv::Fast;
890 else if (Opcode == 56) {
891 CallingConv = Oprnds.back();
892 Oprnds.pop_back();
893 }
Reid Spencer060d25d2004-06-29 23:29:38 +0000894
895 if (!FTy->isVarArg()) {
896 Normal = getBasicBlock(Oprnds[1]);
897 Except = getBasicBlock(Oprnds[2]);
898
899 FunctionType::param_iterator It = FTy->param_begin();
900 for (unsigned i = 3, e = Oprnds.size(); i != e; ++i) {
901 if (It == FTy->param_end())
Reid Spencer24399722004-07-09 22:21:33 +0000902 error("Invalid invoke instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000903 Params.push_back(getValue(getTypeSlot(*It++), Oprnds[i]));
904 }
905 if (It != FTy->param_end())
Reid Spencer24399722004-07-09 22:21:33 +0000906 error("Invalid invoke instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000907 } else {
908 Oprnds.erase(Oprnds.begin(), Oprnds.begin()+1);
909
910 Normal = getBasicBlock(Oprnds[0]);
911 Except = getBasicBlock(Oprnds[1]);
Misha Brukman8a96c532005-04-21 21:44:41 +0000912
Reid Spencer060d25d2004-06-29 23:29:38 +0000913 unsigned FirstVariableArgument = FTy->getNumParams()+2;
914 for (unsigned i = 2; i != FirstVariableArgument; ++i)
915 Params.push_back(getValue(getTypeSlot(FTy->getParamType(i-2)),
916 Oprnds[i]));
Misha Brukman8a96c532005-04-21 21:44:41 +0000917
Reid Spencer060d25d2004-06-29 23:29:38 +0000918 if (Oprnds.size()-FirstVariableArgument & 1) // Must be type/value pairs
Reid Spencer24399722004-07-09 22:21:33 +0000919 error("Invalid invoke instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000920
921 for (unsigned i = FirstVariableArgument; i < Oprnds.size(); i += 2)
922 Params.push_back(getValue(Oprnds[i], Oprnds[i+1]));
923 }
924
925 Result = new InvokeInst(F, Normal, Except, Params);
Chris Lattnerdee199f2005-05-06 22:34:01 +0000926 if (CallingConv) cast<InvokeInst>(Result)->setCallingConv(CallingConv);
Reid Spencer060d25d2004-06-29 23:29:38 +0000927 break;
928 }
Chris Lattner42ba6b42005-11-05 22:08:14 +0000929 case Instruction::Malloc: {
930 unsigned Align = 0;
931 if (Oprnds.size() == 2)
932 Align = (1 << Oprnds[1]) >> 1;
933 else if (Oprnds.size() > 2)
Reid Spencer24399722004-07-09 22:21:33 +0000934 error("Invalid malloc instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000935 if (!isa<PointerType>(InstTy))
Reid Spencer24399722004-07-09 22:21:33 +0000936 error("Invalid malloc instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000937
938 Result = new MallocInst(cast<PointerType>(InstTy)->getElementType(),
Chris Lattner42ba6b42005-11-05 22:08:14 +0000939 getValue(Type::UIntTyID, Oprnds[0]), Align);
Reid Spencer060d25d2004-06-29 23:29:38 +0000940 break;
Chris Lattner42ba6b42005-11-05 22:08:14 +0000941 }
Reid Spencer060d25d2004-06-29 23:29:38 +0000942
Chris Lattner42ba6b42005-11-05 22:08:14 +0000943 case Instruction::Alloca: {
944 unsigned Align = 0;
945 if (Oprnds.size() == 2)
946 Align = (1 << Oprnds[1]) >> 1;
947 else if (Oprnds.size() > 2)
Reid Spencer24399722004-07-09 22:21:33 +0000948 error("Invalid alloca instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000949 if (!isa<PointerType>(InstTy))
Reid Spencer24399722004-07-09 22:21:33 +0000950 error("Invalid alloca instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000951
952 Result = new AllocaInst(cast<PointerType>(InstTy)->getElementType(),
Chris Lattner42ba6b42005-11-05 22:08:14 +0000953 getValue(Type::UIntTyID, Oprnds[0]), Align);
Reid Spencer060d25d2004-06-29 23:29:38 +0000954 break;
Chris Lattner42ba6b42005-11-05 22:08:14 +0000955 }
Reid Spencer060d25d2004-06-29 23:29:38 +0000956 case Instruction::Free:
957 if (!isa<PointerType>(InstTy))
Reid Spencer24399722004-07-09 22:21:33 +0000958 error("Invalid free instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000959 Result = new FreeInst(getValue(iType, Oprnds[0]));
960 break;
961 case Instruction::GetElementPtr: {
962 if (Oprnds.size() == 0 || !isa<PointerType>(InstTy))
Reid Spencer24399722004-07-09 22:21:33 +0000963 error("Invalid getelementptr instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000964
965 std::vector<Value*> Idx;
966
967 const Type *NextTy = InstTy;
968 for (unsigned i = 1, e = Oprnds.size(); i != e; ++i) {
969 const CompositeType *TopTy = dyn_cast_or_null<CompositeType>(NextTy);
Misha Brukman8a96c532005-04-21 21:44:41 +0000970 if (!TopTy)
971 error("Invalid getelementptr instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000972
973 unsigned ValIdx = Oprnds[i];
974 unsigned IdxTy = 0;
975 if (!hasRestrictedGEPTypes) {
976 // Struct indices are always uints, sequential type indices can be any
977 // of the 32 or 64-bit integer types. The actual choice of type is
978 // encoded in the low two bits of the slot number.
979 if (isa<StructType>(TopTy))
980 IdxTy = Type::UIntTyID;
981 else {
982 switch (ValIdx & 3) {
983 default:
984 case 0: IdxTy = Type::UIntTyID; break;
985 case 1: IdxTy = Type::IntTyID; break;
986 case 2: IdxTy = Type::ULongTyID; break;
987 case 3: IdxTy = Type::LongTyID; break;
988 }
989 ValIdx >>= 2;
990 }
991 } else {
992 IdxTy = isa<StructType>(TopTy) ? Type::UByteTyID : Type::LongTyID;
993 }
994
995 Idx.push_back(getValue(IdxTy, ValIdx));
996
997 // Convert ubyte struct indices into uint struct indices.
998 if (isa<StructType>(TopTy) && hasRestrictedGEPTypes)
999 if (ConstantUInt *C = dyn_cast<ConstantUInt>(Idx.back()))
1000 Idx[Idx.size()-1] = ConstantExpr::getCast(C, Type::UIntTy);
1001
1002 NextTy = GetElementPtrInst::getIndexedType(InstTy, Idx, true);
1003 }
1004
1005 Result = new GetElementPtrInst(getValue(iType, Oprnds[0]), Idx);
1006 break;
1007 }
1008
1009 case 62: // volatile load
1010 case Instruction::Load:
1011 if (Oprnds.size() != 1 || !isa<PointerType>(InstTy))
Reid Spencer24399722004-07-09 22:21:33 +00001012 error("Invalid load instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001013 Result = new LoadInst(getValue(iType, Oprnds[0]), "", Opcode == 62);
1014 break;
1015
Misha Brukman8a96c532005-04-21 21:44:41 +00001016 case 63: // volatile store
Reid Spencer060d25d2004-06-29 23:29:38 +00001017 case Instruction::Store: {
1018 if (!isa<PointerType>(InstTy) || Oprnds.size() != 2)
Reid Spencer24399722004-07-09 22:21:33 +00001019 error("Invalid store instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001020
1021 Value *Ptr = getValue(iType, Oprnds[1]);
1022 const Type *ValTy = cast<PointerType>(Ptr->getType())->getElementType();
1023 Result = new StoreInst(getValue(getTypeSlot(ValTy), Oprnds[0]), Ptr,
1024 Opcode == 63);
1025 break;
1026 }
1027 case Instruction::Unwind:
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001028 if (Oprnds.size() != 0) error("Invalid unwind instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001029 Result = new UnwindInst();
1030 break;
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001031 case Instruction::Unreachable:
1032 if (Oprnds.size() != 0) error("Invalid unreachable instruction!");
1033 Result = new UnreachableInst();
1034 break;
Misha Brukman8a96c532005-04-21 21:44:41 +00001035 } // end switch(Opcode)
Reid Spencer060d25d2004-06-29 23:29:38 +00001036
1037 unsigned TypeSlot;
1038 if (Result->getType() == InstTy)
1039 TypeSlot = iType;
1040 else
1041 TypeSlot = getTypeSlot(Result->getType());
1042
1043 insertValue(Result, TypeSlot, FunctionValues);
1044 BB->getInstList().push_back(Result);
1045}
1046
Reid Spencer04cde2c2004-07-04 11:33:49 +00001047/// Get a particular numbered basic block, which might be a forward reference.
1048/// This works together with ParseBasicBlock to handle these forward references
Chris Lattner4a242b32004-10-14 01:39:18 +00001049/// in a clean manner. This function is used when constructing phi, br, switch,
1050/// and other instructions that reference basic blocks. Blocks are numbered
Reid Spencer04cde2c2004-07-04 11:33:49 +00001051/// sequentially as they appear in the function.
Reid Spencer060d25d2004-06-29 23:29:38 +00001052BasicBlock *BytecodeReader::getBasicBlock(unsigned ID) {
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001053 // Make sure there is room in the table...
1054 if (ParsedBasicBlocks.size() <= ID) ParsedBasicBlocks.resize(ID+1);
1055
1056 // First check to see if this is a backwards reference, i.e., ParseBasicBlock
1057 // has already created this block, or if the forward reference has already
1058 // been created.
1059 if (ParsedBasicBlocks[ID])
1060 return ParsedBasicBlocks[ID];
1061
1062 // Otherwise, the basic block has not yet been created. Do so and add it to
1063 // the ParsedBasicBlocks list.
1064 return ParsedBasicBlocks[ID] = new BasicBlock();
1065}
1066
Misha Brukman8a96c532005-04-21 21:44:41 +00001067/// In LLVM 1.0 bytecode files, we used to output one basicblock at a time.
Reid Spencer04cde2c2004-07-04 11:33:49 +00001068/// This method reads in one of the basicblock packets. This method is not used
1069/// for bytecode files after LLVM 1.0
1070/// @returns The basic block constructed.
Reid Spencer46b002c2004-07-11 17:28:43 +00001071BasicBlock *BytecodeReader::ParseBasicBlock(unsigned BlockNo) {
1072 if (Handler) Handler->handleBasicBlockBegin(BlockNo);
Reid Spencer060d25d2004-06-29 23:29:38 +00001073
1074 BasicBlock *BB = 0;
1075
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001076 if (ParsedBasicBlocks.size() == BlockNo)
1077 ParsedBasicBlocks.push_back(BB = new BasicBlock());
1078 else if (ParsedBasicBlocks[BlockNo] == 0)
1079 BB = ParsedBasicBlocks[BlockNo] = new BasicBlock();
1080 else
1081 BB = ParsedBasicBlocks[BlockNo];
Chris Lattner00950542001-06-06 20:29:01 +00001082
Reid Spencer060d25d2004-06-29 23:29:38 +00001083 std::vector<unsigned> Operands;
Reid Spencer46b002c2004-07-11 17:28:43 +00001084 while (moreInBlock())
Reid Spencer060d25d2004-06-29 23:29:38 +00001085 ParseInstruction(Operands, BB);
Chris Lattner00950542001-06-06 20:29:01 +00001086
Reid Spencer46b002c2004-07-11 17:28:43 +00001087 if (Handler) Handler->handleBasicBlockEnd(BlockNo);
Misha Brukman12c29d12003-09-22 23:38:23 +00001088 return BB;
Chris Lattner00950542001-06-06 20:29:01 +00001089}
1090
Reid Spencer04cde2c2004-07-04 11:33:49 +00001091/// Parse all of the BasicBlock's & Instruction's in the body of a function.
Misha Brukman8a96c532005-04-21 21:44:41 +00001092/// In post 1.0 bytecode files, we no longer emit basic block individually,
Reid Spencer04cde2c2004-07-04 11:33:49 +00001093/// in order to avoid per-basic-block overhead.
1094/// @returns Rhe number of basic blocks encountered.
Reid Spencer060d25d2004-06-29 23:29:38 +00001095unsigned BytecodeReader::ParseInstructionList(Function* F) {
Chris Lattner8d1dbd22003-12-01 07:05:31 +00001096 unsigned BlockNo = 0;
1097 std::vector<unsigned> Args;
1098
Reid Spencer46b002c2004-07-11 17:28:43 +00001099 while (moreInBlock()) {
1100 if (Handler) Handler->handleBasicBlockBegin(BlockNo);
Chris Lattner8d1dbd22003-12-01 07:05:31 +00001101 BasicBlock *BB;
1102 if (ParsedBasicBlocks.size() == BlockNo)
1103 ParsedBasicBlocks.push_back(BB = new BasicBlock());
1104 else if (ParsedBasicBlocks[BlockNo] == 0)
1105 BB = ParsedBasicBlocks[BlockNo] = new BasicBlock();
1106 else
1107 BB = ParsedBasicBlocks[BlockNo];
1108 ++BlockNo;
1109 F->getBasicBlockList().push_back(BB);
1110
1111 // Read instructions into this basic block until we get to a terminator
Reid Spencer46b002c2004-07-11 17:28:43 +00001112 while (moreInBlock() && !BB->getTerminator())
Reid Spencer060d25d2004-06-29 23:29:38 +00001113 ParseInstruction(Args, BB);
Chris Lattner8d1dbd22003-12-01 07:05:31 +00001114
1115 if (!BB->getTerminator())
Reid Spencer24399722004-07-09 22:21:33 +00001116 error("Non-terminated basic block found!");
Reid Spencer5c15fe52004-07-05 00:57:50 +00001117
Reid Spencer46b002c2004-07-11 17:28:43 +00001118 if (Handler) Handler->handleBasicBlockEnd(BlockNo-1);
Chris Lattner8d1dbd22003-12-01 07:05:31 +00001119 }
1120
1121 return BlockNo;
1122}
1123
Reid Spencer04cde2c2004-07-04 11:33:49 +00001124/// Parse a symbol table. This works for both module level and function
1125/// level symbol tables. For function level symbol tables, the CurrentFunction
1126/// parameter must be non-zero and the ST parameter must correspond to
1127/// CurrentFunction's symbol table. For Module level symbol tables, the
1128/// CurrentFunction argument must be zero.
Reid Spencer060d25d2004-06-29 23:29:38 +00001129void BytecodeReader::ParseSymbolTable(Function *CurrentFunction,
Reid Spencer04cde2c2004-07-04 11:33:49 +00001130 SymbolTable *ST) {
1131 if (Handler) Handler->handleSymbolTableBegin(CurrentFunction,ST);
Reid Spencer060d25d2004-06-29 23:29:38 +00001132
Chris Lattner39cacce2003-10-10 05:43:47 +00001133 // Allow efficient basic block lookup by number.
1134 std::vector<BasicBlock*> BBMap;
1135 if (CurrentFunction)
1136 for (Function::iterator I = CurrentFunction->begin(),
1137 E = CurrentFunction->end(); I != E; ++I)
1138 BBMap.push_back(I);
1139
Reid Spencer04cde2c2004-07-04 11:33:49 +00001140 /// In LLVM 1.3 we write types separately from values so
1141 /// The types are always first in the symbol table. This is
1142 /// because Type no longer derives from Value.
Reid Spencer46b002c2004-07-11 17:28:43 +00001143 if (!hasTypeDerivedFromValue) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001144 // Symtab block header: [num entries]
1145 unsigned NumEntries = read_vbr_uint();
Reid Spencer46b002c2004-07-11 17:28:43 +00001146 for (unsigned i = 0; i < NumEntries; ++i) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001147 // Symtab entry: [def slot #][name]
1148 unsigned slot = read_vbr_uint();
1149 std::string Name = read_str();
1150 const Type* T = getType(slot);
1151 ST->insert(Name, T);
1152 }
1153 }
1154
Reid Spencer46b002c2004-07-11 17:28:43 +00001155 while (moreInBlock()) {
Chris Lattner00950542001-06-06 20:29:01 +00001156 // Symtab block header: [num entries][type id number]
Reid Spencer060d25d2004-06-29 23:29:38 +00001157 unsigned NumEntries = read_vbr_uint();
Reid Spencer04cde2c2004-07-04 11:33:49 +00001158 unsigned Typ = 0;
1159 bool isTypeType = read_typeid(Typ);
Chris Lattner00950542001-06-06 20:29:01 +00001160 const Type *Ty = getType(Typ);
Chris Lattner1d670cc2001-09-07 16:37:43 +00001161
Chris Lattner7dc3a2e2003-10-13 14:57:53 +00001162 for (unsigned i = 0; i != NumEntries; ++i) {
Chris Lattner00950542001-06-06 20:29:01 +00001163 // Symtab entry: [def slot #][name]
Reid Spencer060d25d2004-06-29 23:29:38 +00001164 unsigned slot = read_vbr_uint();
1165 std::string Name = read_str();
Chris Lattner00950542001-06-06 20:29:01 +00001166
Reid Spencer04cde2c2004-07-04 11:33:49 +00001167 // if we're reading a pre 1.3 bytecode file and the type plane
1168 // is the "type type", handle it here
Reid Spencer46b002c2004-07-11 17:28:43 +00001169 if (isTypeType) {
1170 const Type* T = getType(slot);
1171 if (T == 0)
1172 error("Failed type look-up for name '" + Name + "'");
1173 ST->insert(Name, T);
1174 continue; // code below must be short circuited
Chris Lattner39cacce2003-10-10 05:43:47 +00001175 } else {
Reid Spencer46b002c2004-07-11 17:28:43 +00001176 Value *V = 0;
1177 if (Typ == Type::LabelTyID) {
1178 if (slot < BBMap.size())
1179 V = BBMap[slot];
1180 } else {
1181 V = getValue(Typ, slot, false); // Find mapping...
1182 }
1183 if (V == 0)
1184 error("Failed value look-up for name '" + Name + "'");
Chris Lattner7acff252005-03-05 19:05:20 +00001185 V->setName(Name);
Chris Lattner39cacce2003-10-10 05:43:47 +00001186 }
Chris Lattner00950542001-06-06 20:29:01 +00001187 }
1188 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001189 checkPastBlockEnd("Symbol Table");
Reid Spencer04cde2c2004-07-04 11:33:49 +00001190 if (Handler) Handler->handleSymbolTableEnd();
Chris Lattner00950542001-06-06 20:29:01 +00001191}
1192
Misha Brukman8a96c532005-04-21 21:44:41 +00001193/// Read in the types portion of a compaction table.
Reid Spencer46b002c2004-07-11 17:28:43 +00001194void BytecodeReader::ParseCompactionTypes(unsigned NumEntries) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001195 for (unsigned i = 0; i != NumEntries; ++i) {
1196 unsigned TypeSlot = 0;
Reid Spencer46b002c2004-07-11 17:28:43 +00001197 if (read_typeid(TypeSlot))
Reid Spencer24399722004-07-09 22:21:33 +00001198 error("Invalid type in compaction table: type type");
Reid Spencer04cde2c2004-07-04 11:33:49 +00001199 const Type *Typ = getGlobalTableType(TypeSlot);
Chris Lattner45b5dd22004-08-03 23:41:28 +00001200 CompactionTypes.push_back(std::make_pair(Typ, TypeSlot));
Reid Spencer46b002c2004-07-11 17:28:43 +00001201 if (Handler) Handler->handleCompactionTableType(i, TypeSlot, Typ);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001202 }
1203}
1204
1205/// Parse a compaction table.
Reid Spencer060d25d2004-06-29 23:29:38 +00001206void BytecodeReader::ParseCompactionTable() {
1207
Reid Spencer46b002c2004-07-11 17:28:43 +00001208 // Notify handler that we're beginning a compaction table.
Reid Spencer04cde2c2004-07-04 11:33:49 +00001209 if (Handler) Handler->handleCompactionTableBegin();
1210
Misha Brukman8a96c532005-04-21 21:44:41 +00001211 // In LLVM 1.3 Type no longer derives from Value. So,
Reid Spencer46b002c2004-07-11 17:28:43 +00001212 // we always write them first in the compaction table
1213 // because they can't occupy a "type plane" where the
1214 // Values reside.
1215 if (! hasTypeDerivedFromValue) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001216 unsigned NumEntries = read_vbr_uint();
Reid Spencer46b002c2004-07-11 17:28:43 +00001217 ParseCompactionTypes(NumEntries);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001218 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001219
Reid Spencer46b002c2004-07-11 17:28:43 +00001220 // Compaction tables live in separate blocks so we have to loop
1221 // until we've read the whole thing.
1222 while (moreInBlock()) {
1223 // Read the number of Value* entries in the compaction table
Reid Spencer060d25d2004-06-29 23:29:38 +00001224 unsigned NumEntries = read_vbr_uint();
Reid Spencer04cde2c2004-07-04 11:33:49 +00001225 unsigned Ty = 0;
1226 unsigned isTypeType = false;
Reid Spencer060d25d2004-06-29 23:29:38 +00001227
Reid Spencer46b002c2004-07-11 17:28:43 +00001228 // Decode the type from value read in. Most compaction table
1229 // planes will have one or two entries in them. If that's the
1230 // case then the length is encoded in the bottom two bits and
1231 // the higher bits encode the type. This saves another VBR value.
Reid Spencer060d25d2004-06-29 23:29:38 +00001232 if ((NumEntries & 3) == 3) {
Reid Spencer46b002c2004-07-11 17:28:43 +00001233 // In this case, both low-order bits are set (value 3). This
1234 // is a signal that the typeid follows.
Reid Spencer060d25d2004-06-29 23:29:38 +00001235 NumEntries >>= 2;
Reid Spencer04cde2c2004-07-04 11:33:49 +00001236 isTypeType = read_typeid(Ty);
Reid Spencer060d25d2004-06-29 23:29:38 +00001237 } else {
Reid Spencer46b002c2004-07-11 17:28:43 +00001238 // In this case, the low-order bits specify the number of entries
1239 // and the high order bits specify the type.
Reid Spencer060d25d2004-06-29 23:29:38 +00001240 Ty = NumEntries >> 2;
Reid Spencer04cde2c2004-07-04 11:33:49 +00001241 isTypeType = sanitizeTypeId(Ty);
Reid Spencer060d25d2004-06-29 23:29:38 +00001242 NumEntries &= 3;
1243 }
1244
Reid Spencer04cde2c2004-07-04 11:33:49 +00001245 // if we're reading a pre 1.3 bytecode file and the type plane
1246 // is the "type type", handle it here
Reid Spencer46b002c2004-07-11 17:28:43 +00001247 if (isTypeType) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001248 ParseCompactionTypes(NumEntries);
Reid Spencer060d25d2004-06-29 23:29:38 +00001249 } else {
Chris Lattner2c6c14d2004-08-04 00:19:23 +00001250 // Make sure we have enough room for the plane.
Reid Spencer04cde2c2004-07-04 11:33:49 +00001251 if (Ty >= CompactionValues.size())
Reid Spencer46b002c2004-07-11 17:28:43 +00001252 CompactionValues.resize(Ty+1);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001253
Chris Lattner2c6c14d2004-08-04 00:19:23 +00001254 // Make sure the plane is empty or we have some kind of error.
Reid Spencer04cde2c2004-07-04 11:33:49 +00001255 if (!CompactionValues[Ty].empty())
Reid Spencer46b002c2004-07-11 17:28:43 +00001256 error("Compaction table plane contains multiple entries!");
Reid Spencer04cde2c2004-07-04 11:33:49 +00001257
Chris Lattner2c6c14d2004-08-04 00:19:23 +00001258 // Notify handler about the plane.
Reid Spencer46b002c2004-07-11 17:28:43 +00001259 if (Handler) Handler->handleCompactionTablePlane(Ty, NumEntries);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001260
Chris Lattner2c6c14d2004-08-04 00:19:23 +00001261 // Push the implicit zero.
1262 CompactionValues[Ty].push_back(Constant::getNullValue(getType(Ty)));
Reid Spencer46b002c2004-07-11 17:28:43 +00001263
1264 // Read in each of the entries, put them in the compaction table
1265 // and notify the handler that we have a new compaction table value.
Reid Spencer060d25d2004-06-29 23:29:38 +00001266 for (unsigned i = 0; i != NumEntries; ++i) {
Reid Spencer46b002c2004-07-11 17:28:43 +00001267 unsigned ValSlot = read_vbr_uint();
Chris Lattner2c6c14d2004-08-04 00:19:23 +00001268 Value *V = getGlobalTableValue(Ty, ValSlot);
Reid Spencer46b002c2004-07-11 17:28:43 +00001269 CompactionValues[Ty].push_back(V);
Chris Lattner2c6c14d2004-08-04 00:19:23 +00001270 if (Handler) Handler->handleCompactionTableValue(i, Ty, ValSlot);
Reid Spencer060d25d2004-06-29 23:29:38 +00001271 }
1272 }
1273 }
Reid Spencer46b002c2004-07-11 17:28:43 +00001274 // Notify handler that the compaction table is done.
Reid Spencer04cde2c2004-07-04 11:33:49 +00001275 if (Handler) Handler->handleCompactionTableEnd();
Reid Spencer060d25d2004-06-29 23:29:38 +00001276}
Misha Brukman8a96c532005-04-21 21:44:41 +00001277
Reid Spencer46b002c2004-07-11 17:28:43 +00001278// Parse a single type. The typeid is read in first. If its a primitive type
1279// then nothing else needs to be read, we know how to instantiate it. If its
Misha Brukman8a96c532005-04-21 21:44:41 +00001280// a derived type, then additional data is read to fill out the type
Reid Spencer46b002c2004-07-11 17:28:43 +00001281// definition.
1282const Type *BytecodeReader::ParseType() {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001283 unsigned PrimType = 0;
Reid Spencer46b002c2004-07-11 17:28:43 +00001284 if (read_typeid(PrimType))
Reid Spencer24399722004-07-09 22:21:33 +00001285 error("Invalid type (type type) in type constants!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001286
1287 const Type *Result = 0;
1288 if ((Result = Type::getPrimitiveType((Type::TypeID)PrimType)))
1289 return Result;
Misha Brukman8a96c532005-04-21 21:44:41 +00001290
Reid Spencer060d25d2004-06-29 23:29:38 +00001291 switch (PrimType) {
1292 case Type::FunctionTyID: {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001293 const Type *RetType = readSanitizedType();
Reid Spencer060d25d2004-06-29 23:29:38 +00001294
1295 unsigned NumParams = read_vbr_uint();
1296
1297 std::vector<const Type*> Params;
Misha Brukman8a96c532005-04-21 21:44:41 +00001298 while (NumParams--)
Reid Spencer04cde2c2004-07-04 11:33:49 +00001299 Params.push_back(readSanitizedType());
Reid Spencer060d25d2004-06-29 23:29:38 +00001300
1301 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1302 if (isVarArg) Params.pop_back();
1303
1304 Result = FunctionType::get(RetType, Params, isVarArg);
1305 break;
1306 }
1307 case Type::ArrayTyID: {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001308 const Type *ElementType = readSanitizedType();
Reid Spencer060d25d2004-06-29 23:29:38 +00001309 unsigned NumElements = read_vbr_uint();
Reid Spencer060d25d2004-06-29 23:29:38 +00001310 Result = ArrayType::get(ElementType, NumElements);
1311 break;
1312 }
Brian Gaeke715c90b2004-08-20 06:00:58 +00001313 case Type::PackedTyID: {
1314 const Type *ElementType = readSanitizedType();
1315 unsigned NumElements = read_vbr_uint();
1316 Result = PackedType::get(ElementType, NumElements);
1317 break;
1318 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001319 case Type::StructTyID: {
1320 std::vector<const Type*> Elements;
Reid Spencer04cde2c2004-07-04 11:33:49 +00001321 unsigned Typ = 0;
Reid Spencer46b002c2004-07-11 17:28:43 +00001322 if (read_typeid(Typ))
Reid Spencer24399722004-07-09 22:21:33 +00001323 error("Invalid element type (type type) for structure!");
1324
Reid Spencer060d25d2004-06-29 23:29:38 +00001325 while (Typ) { // List is terminated by void/0 typeid
1326 Elements.push_back(getType(Typ));
Reid Spencer46b002c2004-07-11 17:28:43 +00001327 if (read_typeid(Typ))
1328 error("Invalid element type (type type) for structure!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001329 }
1330
1331 Result = StructType::get(Elements);
1332 break;
1333 }
1334 case Type::PointerTyID: {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001335 Result = PointerType::get(readSanitizedType());
Reid Spencer060d25d2004-06-29 23:29:38 +00001336 break;
1337 }
1338
1339 case Type::OpaqueTyID: {
1340 Result = OpaqueType::get();
1341 break;
1342 }
1343
1344 default:
Reid Spencer24399722004-07-09 22:21:33 +00001345 error("Don't know how to deserialize primitive type " + utostr(PrimType));
Reid Spencer060d25d2004-06-29 23:29:38 +00001346 break;
1347 }
Reid Spencer46b002c2004-07-11 17:28:43 +00001348 if (Handler) Handler->handleType(Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001349 return Result;
1350}
1351
Reid Spencer5b472d92004-08-21 20:49:23 +00001352// ParseTypes - We have to use this weird code to handle recursive
Reid Spencer060d25d2004-06-29 23:29:38 +00001353// types. We know that recursive types will only reference the current slab of
1354// values in the type plane, but they can forward reference types before they
1355// have been read. For example, Type #0 might be '{ Ty#1 }' and Type #1 might
1356// be 'Ty#0*'. When reading Type #0, type number one doesn't exist. To fix
1357// this ugly problem, we pessimistically insert an opaque type for each type we
1358// are about to read. This means that forward references will resolve to
1359// something and when we reread the type later, we can replace the opaque type
1360// with a new resolved concrete type.
1361//
Reid Spencer46b002c2004-07-11 17:28:43 +00001362void BytecodeReader::ParseTypes(TypeListTy &Tab, unsigned NumEntries){
Reid Spencer060d25d2004-06-29 23:29:38 +00001363 assert(Tab.size() == 0 && "should not have read type constants in before!");
1364
1365 // Insert a bunch of opaque types to be resolved later...
1366 Tab.reserve(NumEntries);
1367 for (unsigned i = 0; i != NumEntries; ++i)
1368 Tab.push_back(OpaqueType::get());
1369
Misha Brukman8a96c532005-04-21 21:44:41 +00001370 if (Handler)
Reid Spencer5b472d92004-08-21 20:49:23 +00001371 Handler->handleTypeList(NumEntries);
1372
Chris Lattnereebac5f2005-10-03 21:26:53 +00001373 // If we are about to resolve types, make sure the type cache is clear.
1374 if (NumEntries)
1375 ModuleTypeIDCache.clear();
1376
Reid Spencer060d25d2004-06-29 23:29:38 +00001377 // Loop through reading all of the types. Forward types will make use of the
1378 // opaque types just inserted.
1379 //
1380 for (unsigned i = 0; i != NumEntries; ++i) {
Reid Spencer46b002c2004-07-11 17:28:43 +00001381 const Type* NewTy = ParseType();
Reid Spencer04cde2c2004-07-04 11:33:49 +00001382 const Type* OldTy = Tab[i].get();
Misha Brukman8a96c532005-04-21 21:44:41 +00001383 if (NewTy == 0)
Reid Spencer24399722004-07-09 22:21:33 +00001384 error("Couldn't parse type!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001385
Misha Brukman8a96c532005-04-21 21:44:41 +00001386 // Don't directly push the new type on the Tab. Instead we want to replace
Reid Spencer060d25d2004-06-29 23:29:38 +00001387 // the opaque type we previously inserted with the new concrete value. This
1388 // approach helps with forward references to types. The refinement from the
1389 // abstract (opaque) type to the new type causes all uses of the abstract
1390 // type to use the concrete type (NewTy). This will also cause the opaque
1391 // type to be deleted.
1392 cast<DerivedType>(const_cast<Type*>(OldTy))->refineAbstractTypeTo(NewTy);
1393
1394 // This should have replaced the old opaque type with the new type in the
1395 // value table... or with a preexisting type that was already in the system.
1396 // Let's just make sure it did.
1397 assert(Tab[i] != OldTy && "refineAbstractType didn't work!");
1398 }
1399}
1400
Reid Spencer04cde2c2004-07-04 11:33:49 +00001401/// Parse a single constant value
Reid Spencer46b002c2004-07-11 17:28:43 +00001402Constant *BytecodeReader::ParseConstantValue(unsigned TypeID) {
Reid Spencer060d25d2004-06-29 23:29:38 +00001403 // We must check for a ConstantExpr before switching by type because
1404 // a ConstantExpr can be of any type, and has no explicit value.
Misha Brukman8a96c532005-04-21 21:44:41 +00001405 //
Reid Spencer060d25d2004-06-29 23:29:38 +00001406 // 0 if not expr; numArgs if is expr
1407 unsigned isExprNumArgs = read_vbr_uint();
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001408
Reid Spencer060d25d2004-06-29 23:29:38 +00001409 if (isExprNumArgs) {
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001410 // 'undef' is encoded with 'exprnumargs' == 1.
1411 if (!hasNoUndefValue)
1412 if (--isExprNumArgs == 0)
1413 return UndefValue::get(getType(TypeID));
Misha Brukman8a96c532005-04-21 21:44:41 +00001414
Reid Spencer060d25d2004-06-29 23:29:38 +00001415 // FIXME: Encoding of constant exprs could be much more compact!
1416 std::vector<Constant*> ArgVec;
1417 ArgVec.reserve(isExprNumArgs);
1418 unsigned Opcode = read_vbr_uint();
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001419
1420 // Bytecode files before LLVM 1.4 need have a missing terminator inst.
1421 if (hasNoUnreachableInst) Opcode++;
Misha Brukman8a96c532005-04-21 21:44:41 +00001422
Reid Spencer060d25d2004-06-29 23:29:38 +00001423 // Read the slot number and types of each of the arguments
1424 for (unsigned i = 0; i != isExprNumArgs; ++i) {
1425 unsigned ArgValSlot = read_vbr_uint();
Reid Spencer04cde2c2004-07-04 11:33:49 +00001426 unsigned ArgTypeSlot = 0;
Reid Spencer46b002c2004-07-11 17:28:43 +00001427 if (read_typeid(ArgTypeSlot))
1428 error("Invalid argument type (type type) for constant value");
Misha Brukman8a96c532005-04-21 21:44:41 +00001429
Reid Spencer060d25d2004-06-29 23:29:38 +00001430 // Get the arg value from its slot if it exists, otherwise a placeholder
1431 ArgVec.push_back(getConstantValue(ArgTypeSlot, ArgValSlot));
1432 }
Misha Brukman8a96c532005-04-21 21:44:41 +00001433
Reid Spencer060d25d2004-06-29 23:29:38 +00001434 // Construct a ConstantExpr of the appropriate kind
1435 if (isExprNumArgs == 1) { // All one-operand expressions
Reid Spencer46b002c2004-07-11 17:28:43 +00001436 if (Opcode != Instruction::Cast)
Chris Lattner02dce162004-12-04 05:28:27 +00001437 error("Only cast instruction has one argument for ConstantExpr");
Reid Spencer46b002c2004-07-11 17:28:43 +00001438
Reid Spencer060d25d2004-06-29 23:29:38 +00001439 Constant* Result = ConstantExpr::getCast(ArgVec[0], getType(TypeID));
Reid Spencer04cde2c2004-07-04 11:33:49 +00001440 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001441 return Result;
1442 } else if (Opcode == Instruction::GetElementPtr) { // GetElementPtr
1443 std::vector<Constant*> IdxList(ArgVec.begin()+1, ArgVec.end());
1444
1445 if (hasRestrictedGEPTypes) {
1446 const Type *BaseTy = ArgVec[0]->getType();
1447 generic_gep_type_iterator<std::vector<Constant*>::iterator>
1448 GTI = gep_type_begin(BaseTy, IdxList.begin(), IdxList.end()),
1449 E = gep_type_end(BaseTy, IdxList.begin(), IdxList.end());
1450 for (unsigned i = 0; GTI != E; ++GTI, ++i)
1451 if (isa<StructType>(*GTI)) {
1452 if (IdxList[i]->getType() != Type::UByteTy)
Reid Spencer24399722004-07-09 22:21:33 +00001453 error("Invalid index for getelementptr!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001454 IdxList[i] = ConstantExpr::getCast(IdxList[i], Type::UIntTy);
1455 }
1456 }
1457
1458 Constant* Result = ConstantExpr::getGetElementPtr(ArgVec[0], IdxList);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001459 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001460 return Result;
1461 } else if (Opcode == Instruction::Select) {
Reid Spencer46b002c2004-07-11 17:28:43 +00001462 if (ArgVec.size() != 3)
1463 error("Select instruction must have three arguments.");
Misha Brukman8a96c532005-04-21 21:44:41 +00001464 Constant* Result = ConstantExpr::getSelect(ArgVec[0], ArgVec[1],
Reid Spencer04cde2c2004-07-04 11:33:49 +00001465 ArgVec[2]);
1466 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001467 return Result;
Robert Bocchinofee31b32006-01-10 19:04:39 +00001468 } else if (Opcode == Instruction::ExtractElement) {
1469 if (ArgVec.size() != 2)
1470 error("ExtractElement instruction must have two arguments.");
1471 Constant* Result = ConstantExpr::getExtractElement(ArgVec[0], ArgVec[1]);
1472 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
1473 return Result;
Robert Bocchinob1f240b2006-01-17 20:06:35 +00001474 } else if (Opcode == Instruction::InsertElement) {
1475 if (ArgVec.size() != 3)
1476 error("InsertElement instruction must have three arguments.");
1477 Constant* Result =
1478 ConstantExpr::getInsertElement(ArgVec[0], ArgVec[1], ArgVec[2]);
1479 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
1480 return Result;
Reid Spencer060d25d2004-06-29 23:29:38 +00001481 } else { // All other 2-operand expressions
1482 Constant* Result = ConstantExpr::get(Opcode, ArgVec[0], ArgVec[1]);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001483 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001484 return Result;
1485 }
1486 }
Misha Brukman8a96c532005-04-21 21:44:41 +00001487
Reid Spencer060d25d2004-06-29 23:29:38 +00001488 // Ok, not an ConstantExpr. We now know how to read the given type...
1489 const Type *Ty = getType(TypeID);
1490 switch (Ty->getTypeID()) {
1491 case Type::BoolTyID: {
1492 unsigned Val = read_vbr_uint();
Misha Brukman8a96c532005-04-21 21:44:41 +00001493 if (Val != 0 && Val != 1)
Reid Spencer24399722004-07-09 22:21:33 +00001494 error("Invalid boolean value read.");
Reid Spencer060d25d2004-06-29 23:29:38 +00001495 Constant* Result = ConstantBool::get(Val == 1);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001496 if (Handler) Handler->handleConstantValue(Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001497 return Result;
1498 }
1499
1500 case Type::UByteTyID: // Unsigned integer types...
1501 case Type::UShortTyID:
1502 case Type::UIntTyID: {
1503 unsigned Val = read_vbr_uint();
Misha Brukman8a96c532005-04-21 21:44:41 +00001504 if (!ConstantUInt::isValueValidForType(Ty, Val))
Reid Spencer24399722004-07-09 22:21:33 +00001505 error("Invalid unsigned byte/short/int read.");
Reid Spencer060d25d2004-06-29 23:29:38 +00001506 Constant* Result = ConstantUInt::get(Ty, Val);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001507 if (Handler) Handler->handleConstantValue(Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001508 return Result;
1509 }
1510
1511 case Type::ULongTyID: {
1512 Constant* Result = ConstantUInt::get(Ty, read_vbr_uint64());
Reid Spencer04cde2c2004-07-04 11:33:49 +00001513 if (Handler) Handler->handleConstantValue(Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001514 return Result;
1515 }
1516
1517 case Type::SByteTyID: // Signed integer types...
1518 case Type::ShortTyID:
1519 case Type::IntTyID: {
1520 case Type::LongTyID:
1521 int64_t Val = read_vbr_int64();
Misha Brukman8a96c532005-04-21 21:44:41 +00001522 if (!ConstantSInt::isValueValidForType(Ty, Val))
Reid Spencer24399722004-07-09 22:21:33 +00001523 error("Invalid signed byte/short/int/long read.");
Reid Spencer060d25d2004-06-29 23:29:38 +00001524 Constant* Result = ConstantSInt::get(Ty, Val);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001525 if (Handler) Handler->handleConstantValue(Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001526 return Result;
1527 }
1528
1529 case Type::FloatTyID: {
Reid Spencer46b002c2004-07-11 17:28:43 +00001530 float Val;
1531 read_float(Val);
1532 Constant* Result = ConstantFP::get(Ty, Val);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001533 if (Handler) Handler->handleConstantValue(Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001534 return Result;
1535 }
1536
1537 case Type::DoubleTyID: {
1538 double Val;
Reid Spencer46b002c2004-07-11 17:28:43 +00001539 read_double(Val);
Reid Spencer060d25d2004-06-29 23:29:38 +00001540 Constant* Result = ConstantFP::get(Ty, Val);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001541 if (Handler) Handler->handleConstantValue(Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001542 return Result;
1543 }
1544
Reid Spencer060d25d2004-06-29 23:29:38 +00001545 case Type::ArrayTyID: {
1546 const ArrayType *AT = cast<ArrayType>(Ty);
1547 unsigned NumElements = AT->getNumElements();
1548 unsigned TypeSlot = getTypeSlot(AT->getElementType());
1549 std::vector<Constant*> Elements;
1550 Elements.reserve(NumElements);
1551 while (NumElements--) // Read all of the elements of the constant.
1552 Elements.push_back(getConstantValue(TypeSlot,
1553 read_vbr_uint()));
1554 Constant* Result = ConstantArray::get(AT, Elements);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001555 if (Handler) Handler->handleConstantArray(AT, Elements, TypeSlot, Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001556 return Result;
1557 }
1558
1559 case Type::StructTyID: {
1560 const StructType *ST = cast<StructType>(Ty);
1561
1562 std::vector<Constant *> Elements;
1563 Elements.reserve(ST->getNumElements());
1564 for (unsigned i = 0; i != ST->getNumElements(); ++i)
1565 Elements.push_back(getConstantValue(ST->getElementType(i),
1566 read_vbr_uint()));
1567
1568 Constant* Result = ConstantStruct::get(ST, Elements);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001569 if (Handler) Handler->handleConstantStruct(ST, Elements, Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001570 return Result;
Misha Brukman8a96c532005-04-21 21:44:41 +00001571 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001572
Brian Gaeke715c90b2004-08-20 06:00:58 +00001573 case Type::PackedTyID: {
1574 const PackedType *PT = cast<PackedType>(Ty);
1575 unsigned NumElements = PT->getNumElements();
1576 unsigned TypeSlot = getTypeSlot(PT->getElementType());
1577 std::vector<Constant*> Elements;
1578 Elements.reserve(NumElements);
1579 while (NumElements--) // Read all of the elements of the constant.
1580 Elements.push_back(getConstantValue(TypeSlot,
1581 read_vbr_uint()));
1582 Constant* Result = ConstantPacked::get(PT, Elements);
1583 if (Handler) Handler->handleConstantPacked(PT, Elements, TypeSlot, Result);
1584 return Result;
1585 }
1586
Chris Lattner638c3812004-11-19 16:24:05 +00001587 case Type::PointerTyID: { // ConstantPointerRef value (backwards compat).
Reid Spencer060d25d2004-06-29 23:29:38 +00001588 const PointerType *PT = cast<PointerType>(Ty);
1589 unsigned Slot = read_vbr_uint();
Misha Brukman8a96c532005-04-21 21:44:41 +00001590
Reid Spencer060d25d2004-06-29 23:29:38 +00001591 // Check to see if we have already read this global variable...
1592 Value *Val = getValue(TypeID, Slot, false);
Reid Spencer060d25d2004-06-29 23:29:38 +00001593 if (Val) {
Chris Lattnerbcb11cf2004-07-27 02:34:49 +00001594 GlobalValue *GV = dyn_cast<GlobalValue>(Val);
1595 if (!GV) error("GlobalValue not in ValueTable!");
1596 if (Handler) Handler->handleConstantPointer(PT, Slot, GV);
1597 return GV;
Reid Spencer060d25d2004-06-29 23:29:38 +00001598 } else {
Reid Spencer24399722004-07-09 22:21:33 +00001599 error("Forward references are not allowed here.");
Reid Spencer060d25d2004-06-29 23:29:38 +00001600 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001601 }
1602
1603 default:
Reid Spencer24399722004-07-09 22:21:33 +00001604 error("Don't know how to deserialize constant value of type '" +
Reid Spencer060d25d2004-06-29 23:29:38 +00001605 Ty->getDescription());
1606 break;
1607 }
Reid Spencer24399722004-07-09 22:21:33 +00001608 return 0;
Reid Spencer060d25d2004-06-29 23:29:38 +00001609}
1610
Misha Brukman8a96c532005-04-21 21:44:41 +00001611/// Resolve references for constants. This function resolves the forward
1612/// referenced constants in the ConstantFwdRefs map. It uses the
Reid Spencer04cde2c2004-07-04 11:33:49 +00001613/// replaceAllUsesWith method of Value class to substitute the placeholder
1614/// instance with the actual instance.
Chris Lattner389bd042004-12-09 06:19:44 +00001615void BytecodeReader::ResolveReferencesToConstant(Constant *NewV, unsigned Typ,
1616 unsigned Slot) {
Chris Lattner29b789b2003-11-19 17:27:18 +00001617 ConstantRefsType::iterator I =
Chris Lattner389bd042004-12-09 06:19:44 +00001618 ConstantFwdRefs.find(std::make_pair(Typ, Slot));
Chris Lattner29b789b2003-11-19 17:27:18 +00001619 if (I == ConstantFwdRefs.end()) return; // Never forward referenced?
Chris Lattner00950542001-06-06 20:29:01 +00001620
Chris Lattner29b789b2003-11-19 17:27:18 +00001621 Value *PH = I->second; // Get the placeholder...
1622 PH->replaceAllUsesWith(NewV);
1623 delete PH; // Delete the old placeholder
1624 ConstantFwdRefs.erase(I); // Remove the map entry for it
Vikram S. Advec1e4a812002-07-14 23:04:18 +00001625}
1626
Reid Spencer04cde2c2004-07-04 11:33:49 +00001627/// Parse the constant strings section.
Reid Spencer060d25d2004-06-29 23:29:38 +00001628void BytecodeReader::ParseStringConstants(unsigned NumEntries, ValueTable &Tab){
1629 for (; NumEntries; --NumEntries) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001630 unsigned Typ = 0;
Reid Spencer46b002c2004-07-11 17:28:43 +00001631 if (read_typeid(Typ))
Reid Spencer24399722004-07-09 22:21:33 +00001632 error("Invalid type (type type) for string constant");
Reid Spencer060d25d2004-06-29 23:29:38 +00001633 const Type *Ty = getType(Typ);
1634 if (!isa<ArrayType>(Ty))
Reid Spencer24399722004-07-09 22:21:33 +00001635 error("String constant data invalid!");
Misha Brukman8a96c532005-04-21 21:44:41 +00001636
Reid Spencer060d25d2004-06-29 23:29:38 +00001637 const ArrayType *ATy = cast<ArrayType>(Ty);
1638 if (ATy->getElementType() != Type::SByteTy &&
1639 ATy->getElementType() != Type::UByteTy)
Reid Spencer24399722004-07-09 22:21:33 +00001640 error("String constant data invalid!");
Misha Brukman8a96c532005-04-21 21:44:41 +00001641
Reid Spencer060d25d2004-06-29 23:29:38 +00001642 // Read character data. The type tells us how long the string is.
Misha Brukman8a96c532005-04-21 21:44:41 +00001643 char *Data = reinterpret_cast<char *>(alloca(ATy->getNumElements()));
Reid Spencer060d25d2004-06-29 23:29:38 +00001644 read_data(Data, Data+ATy->getNumElements());
Chris Lattner52e20b02003-03-19 20:54:26 +00001645
Reid Spencer060d25d2004-06-29 23:29:38 +00001646 std::vector<Constant*> Elements(ATy->getNumElements());
1647 if (ATy->getElementType() == Type::SByteTy)
1648 for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
1649 Elements[i] = ConstantSInt::get(Type::SByteTy, (signed char)Data[i]);
1650 else
1651 for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
1652 Elements[i] = ConstantUInt::get(Type::UByteTy, (unsigned char)Data[i]);
Misha Brukman12c29d12003-09-22 23:38:23 +00001653
Reid Spencer060d25d2004-06-29 23:29:38 +00001654 // Create the constant, inserting it as needed.
1655 Constant *C = ConstantArray::get(ATy, Elements);
1656 unsigned Slot = insertValue(C, Typ, Tab);
Chris Lattner389bd042004-12-09 06:19:44 +00001657 ResolveReferencesToConstant(C, Typ, Slot);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001658 if (Handler) Handler->handleConstantString(cast<ConstantArray>(C));
Reid Spencer060d25d2004-06-29 23:29:38 +00001659 }
Misha Brukman12c29d12003-09-22 23:38:23 +00001660}
1661
Reid Spencer04cde2c2004-07-04 11:33:49 +00001662/// Parse the constant pool.
Misha Brukman8a96c532005-04-21 21:44:41 +00001663void BytecodeReader::ParseConstantPool(ValueTable &Tab,
Reid Spencer04cde2c2004-07-04 11:33:49 +00001664 TypeListTy &TypeTab,
Reid Spencer46b002c2004-07-11 17:28:43 +00001665 bool isFunction) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001666 if (Handler) Handler->handleGlobalConstantsBegin();
1667
1668 /// In LLVM 1.3 Type does not derive from Value so the types
1669 /// do not occupy a plane. Consequently, we read the types
1670 /// first in the constant pool.
Reid Spencer46b002c2004-07-11 17:28:43 +00001671 if (isFunction && !hasTypeDerivedFromValue) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001672 unsigned NumEntries = read_vbr_uint();
Reid Spencer46b002c2004-07-11 17:28:43 +00001673 ParseTypes(TypeTab, NumEntries);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001674 }
1675
Reid Spencer46b002c2004-07-11 17:28:43 +00001676 while (moreInBlock()) {
Reid Spencer060d25d2004-06-29 23:29:38 +00001677 unsigned NumEntries = read_vbr_uint();
Reid Spencer04cde2c2004-07-04 11:33:49 +00001678 unsigned Typ = 0;
1679 bool isTypeType = read_typeid(Typ);
1680
1681 /// In LLVM 1.2 and before, Types were written to the
1682 /// bytecode file in the "Type Type" plane (#12).
1683 /// In 1.3 plane 12 is now the label plane. Handle this here.
Reid Spencer46b002c2004-07-11 17:28:43 +00001684 if (isTypeType) {
1685 ParseTypes(TypeTab, NumEntries);
Reid Spencer060d25d2004-06-29 23:29:38 +00001686 } else if (Typ == Type::VoidTyID) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001687 /// Use of Type::VoidTyID is a misnomer. It actually means
1688 /// that the following plane is constant strings
Reid Spencer060d25d2004-06-29 23:29:38 +00001689 assert(&Tab == &ModuleValues && "Cannot read strings in functions!");
1690 ParseStringConstants(NumEntries, Tab);
1691 } else {
1692 for (unsigned i = 0; i < NumEntries; ++i) {
1693 Constant *C = ParseConstantValue(Typ);
1694 assert(C && "ParseConstantValue returned NULL!");
1695 unsigned Slot = insertValue(C, Typ, Tab);
Chris Lattner29b789b2003-11-19 17:27:18 +00001696
Reid Spencer060d25d2004-06-29 23:29:38 +00001697 // If we are reading a function constant table, make sure that we adjust
1698 // the slot number to be the real global constant number.
1699 //
1700 if (&Tab != &ModuleValues && Typ < ModuleValues.size() &&
1701 ModuleValues[Typ])
1702 Slot += ModuleValues[Typ]->size();
Chris Lattner389bd042004-12-09 06:19:44 +00001703 ResolveReferencesToConstant(C, Typ, Slot);
Reid Spencer060d25d2004-06-29 23:29:38 +00001704 }
1705 }
1706 }
Chris Lattner02dce162004-12-04 05:28:27 +00001707
1708 // After we have finished parsing the constant pool, we had better not have
1709 // any dangling references left.
Reid Spencer3c391272004-12-04 22:19:53 +00001710 if (!ConstantFwdRefs.empty()) {
Reid Spencer3c391272004-12-04 22:19:53 +00001711 ConstantRefsType::const_iterator I = ConstantFwdRefs.begin();
Reid Spencer3c391272004-12-04 22:19:53 +00001712 Constant* missingConst = I->second;
Misha Brukman8a96c532005-04-21 21:44:41 +00001713 error(utostr(ConstantFwdRefs.size()) +
1714 " unresolved constant reference exist. First one is '" +
1715 missingConst->getName() + "' of type '" +
Chris Lattner389bd042004-12-09 06:19:44 +00001716 missingConst->getType()->getDescription() + "'.");
Reid Spencer3c391272004-12-04 22:19:53 +00001717 }
Chris Lattner02dce162004-12-04 05:28:27 +00001718
Reid Spencer060d25d2004-06-29 23:29:38 +00001719 checkPastBlockEnd("Constant Pool");
Reid Spencer04cde2c2004-07-04 11:33:49 +00001720 if (Handler) Handler->handleGlobalConstantsEnd();
Reid Spencer060d25d2004-06-29 23:29:38 +00001721}
Chris Lattner00950542001-06-06 20:29:01 +00001722
Reid Spencer04cde2c2004-07-04 11:33:49 +00001723/// Parse the contents of a function. Note that this function can be
1724/// called lazily by materializeFunction
1725/// @see materializeFunction
Reid Spencer46b002c2004-07-11 17:28:43 +00001726void BytecodeReader::ParseFunctionBody(Function* F) {
Reid Spencer060d25d2004-06-29 23:29:38 +00001727
1728 unsigned FuncSize = BlockEnd - At;
Chris Lattnere3869c82003-04-16 21:16:05 +00001729 GlobalValue::LinkageTypes Linkage = GlobalValue::ExternalLinkage;
1730
Reid Spencer060d25d2004-06-29 23:29:38 +00001731 unsigned LinkageType = read_vbr_uint();
Chris Lattnerc08912f2004-01-14 16:44:44 +00001732 switch (LinkageType) {
1733 case 0: Linkage = GlobalValue::ExternalLinkage; break;
1734 case 1: Linkage = GlobalValue::WeakLinkage; break;
1735 case 2: Linkage = GlobalValue::AppendingLinkage; break;
1736 case 3: Linkage = GlobalValue::InternalLinkage; break;
1737 case 4: Linkage = GlobalValue::LinkOnceLinkage; break;
Reid Spencer060d25d2004-06-29 23:29:38 +00001738 default:
Reid Spencer24399722004-07-09 22:21:33 +00001739 error("Invalid linkage type for Function.");
Reid Spencer060d25d2004-06-29 23:29:38 +00001740 Linkage = GlobalValue::InternalLinkage;
1741 break;
Chris Lattnere3869c82003-04-16 21:16:05 +00001742 }
Chris Lattnerd23b1d32001-11-26 18:56:10 +00001743
Reid Spencer46b002c2004-07-11 17:28:43 +00001744 F->setLinkage(Linkage);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001745 if (Handler) Handler->handleFunctionBegin(F,FuncSize);
Chris Lattner00950542001-06-06 20:29:01 +00001746
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001747 // Keep track of how many basic blocks we have read in...
1748 unsigned BlockNum = 0;
Chris Lattner89e02532004-01-18 21:08:15 +00001749 bool InsertedArguments = false;
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001750
Reid Spencer060d25d2004-06-29 23:29:38 +00001751 BufPtr MyEnd = BlockEnd;
Reid Spencer46b002c2004-07-11 17:28:43 +00001752 while (At < MyEnd) {
Chris Lattner00950542001-06-06 20:29:01 +00001753 unsigned Type, Size;
Reid Spencer060d25d2004-06-29 23:29:38 +00001754 BufPtr OldAt = At;
1755 read_block(Type, Size);
Chris Lattner00950542001-06-06 20:29:01 +00001756
1757 switch (Type) {
Reid Spencerad89bd62004-07-25 18:07:36 +00001758 case BytecodeFormat::ConstantPoolBlockID:
Chris Lattner89e02532004-01-18 21:08:15 +00001759 if (!InsertedArguments) {
1760 // Insert arguments into the value table before we parse the first basic
1761 // block in the function, but after we potentially read in the
1762 // compaction table.
Reid Spencer04cde2c2004-07-04 11:33:49 +00001763 insertArguments(F);
Chris Lattner89e02532004-01-18 21:08:15 +00001764 InsertedArguments = true;
1765 }
1766
Reid Spencer04cde2c2004-07-04 11:33:49 +00001767 ParseConstantPool(FunctionValues, FunctionTypes, true);
Chris Lattner00950542001-06-06 20:29:01 +00001768 break;
1769
Reid Spencerad89bd62004-07-25 18:07:36 +00001770 case BytecodeFormat::CompactionTableBlockID:
Reid Spencer060d25d2004-06-29 23:29:38 +00001771 ParseCompactionTable();
Chris Lattner89e02532004-01-18 21:08:15 +00001772 break;
1773
Chris Lattner00950542001-06-06 20:29:01 +00001774 case BytecodeFormat::BasicBlock: {
Chris Lattner89e02532004-01-18 21:08:15 +00001775 if (!InsertedArguments) {
1776 // Insert arguments into the value table before we parse the first basic
1777 // block in the function, but after we potentially read in the
1778 // compaction table.
Reid Spencer04cde2c2004-07-04 11:33:49 +00001779 insertArguments(F);
Chris Lattner89e02532004-01-18 21:08:15 +00001780 InsertedArguments = true;
1781 }
1782
Reid Spencer060d25d2004-06-29 23:29:38 +00001783 BasicBlock *BB = ParseBasicBlock(BlockNum++);
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001784 F->getBasicBlockList().push_back(BB);
Chris Lattner00950542001-06-06 20:29:01 +00001785 break;
1786 }
1787
Reid Spencerad89bd62004-07-25 18:07:36 +00001788 case BytecodeFormat::InstructionListBlockID: {
Chris Lattner89e02532004-01-18 21:08:15 +00001789 // Insert arguments into the value table before we parse the instruction
1790 // list for the function, but after we potentially read in the compaction
1791 // table.
1792 if (!InsertedArguments) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001793 insertArguments(F);
Chris Lattner89e02532004-01-18 21:08:15 +00001794 InsertedArguments = true;
1795 }
1796
Misha Brukman8a96c532005-04-21 21:44:41 +00001797 if (BlockNum)
Reid Spencer24399722004-07-09 22:21:33 +00001798 error("Already parsed basic blocks!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001799 BlockNum = ParseInstructionList(F);
Chris Lattner8d1dbd22003-12-01 07:05:31 +00001800 break;
1801 }
1802
Reid Spencerad89bd62004-07-25 18:07:36 +00001803 case BytecodeFormat::SymbolTableBlockID:
Reid Spencer060d25d2004-06-29 23:29:38 +00001804 ParseSymbolTable(F, &F->getSymbolTable());
Chris Lattner00950542001-06-06 20:29:01 +00001805 break;
1806
1807 default:
Reid Spencer060d25d2004-06-29 23:29:38 +00001808 At += Size;
Misha Brukman8a96c532005-04-21 21:44:41 +00001809 if (OldAt > At)
Reid Spencer24399722004-07-09 22:21:33 +00001810 error("Wrapped around reading bytecode.");
Chris Lattner00950542001-06-06 20:29:01 +00001811 break;
1812 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001813 BlockEnd = MyEnd;
Chris Lattner1d670cc2001-09-07 16:37:43 +00001814
Misha Brukman12c29d12003-09-22 23:38:23 +00001815 // Malformed bc file if read past end of block.
Reid Spencer060d25d2004-06-29 23:29:38 +00001816 align32();
Chris Lattner00950542001-06-06 20:29:01 +00001817 }
1818
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001819 // Make sure there were no references to non-existant basic blocks.
1820 if (BlockNum != ParsedBasicBlocks.size())
Reid Spencer24399722004-07-09 22:21:33 +00001821 error("Illegal basic block operand reference");
Reid Spencer060d25d2004-06-29 23:29:38 +00001822
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001823 ParsedBasicBlocks.clear();
1824
Chris Lattner97330cf2003-10-09 23:10:14 +00001825 // Resolve forward references. Replace any uses of a forward reference value
1826 // with the real value.
Chris Lattner8eb10ce2003-10-09 06:05:40 +00001827 while (!ForwardReferences.empty()) {
Chris Lattnerc4d69162004-12-09 04:51:50 +00001828 std::map<std::pair<unsigned,unsigned>, Value*>::iterator
1829 I = ForwardReferences.begin();
1830 Value *V = getValue(I->first.first, I->first.second, false);
Chris Lattner8eb10ce2003-10-09 06:05:40 +00001831 Value *PlaceHolder = I->second;
Chris Lattnerc4d69162004-12-09 04:51:50 +00001832 PlaceHolder->replaceAllUsesWith(V);
Chris Lattner8eb10ce2003-10-09 06:05:40 +00001833 ForwardReferences.erase(I);
Chris Lattner8eb10ce2003-10-09 06:05:40 +00001834 delete PlaceHolder;
Chris Lattner6e448022003-10-08 21:51:46 +00001835 }
Chris Lattner00950542001-06-06 20:29:01 +00001836
Misha Brukman12c29d12003-09-22 23:38:23 +00001837 // Clear out function-level types...
Reid Spencer060d25d2004-06-29 23:29:38 +00001838 FunctionTypes.clear();
1839 CompactionTypes.clear();
1840 CompactionValues.clear();
1841 freeTable(FunctionValues);
1842
Reid Spencer04cde2c2004-07-04 11:33:49 +00001843 if (Handler) Handler->handleFunctionEnd(F);
Chris Lattner00950542001-06-06 20:29:01 +00001844}
1845
Reid Spencer04cde2c2004-07-04 11:33:49 +00001846/// This function parses LLVM functions lazily. It obtains the type of the
1847/// function and records where the body of the function is in the bytecode
Misha Brukman8a96c532005-04-21 21:44:41 +00001848/// buffer. The caller can then use the ParseNextFunction and
Reid Spencer04cde2c2004-07-04 11:33:49 +00001849/// ParseAllFunctionBodies to get handler events for the functions.
Reid Spencer060d25d2004-06-29 23:29:38 +00001850void BytecodeReader::ParseFunctionLazily() {
1851 if (FunctionSignatureList.empty())
Reid Spencer24399722004-07-09 22:21:33 +00001852 error("FunctionSignatureList empty!");
Chris Lattner89e02532004-01-18 21:08:15 +00001853
Reid Spencer060d25d2004-06-29 23:29:38 +00001854 Function *Func = FunctionSignatureList.back();
1855 FunctionSignatureList.pop_back();
Chris Lattner24102432004-01-18 22:35:34 +00001856
Reid Spencer060d25d2004-06-29 23:29:38 +00001857 // Save the information for future reading of the function
1858 LazyFunctionLoadMap[Func] = LazyFunctionInfo(BlockStart, BlockEnd);
Chris Lattner89e02532004-01-18 21:08:15 +00001859
Misha Brukmana3e6ad62004-11-14 21:02:55 +00001860 // This function has a body but it's not loaded so it appears `External'.
1861 // Mark it as a `Ghost' instead to notify the users that it has a body.
1862 Func->setLinkage(GlobalValue::GhostLinkage);
1863
Reid Spencer060d25d2004-06-29 23:29:38 +00001864 // Pretend we've `parsed' this function
1865 At = BlockEnd;
1866}
Chris Lattner89e02532004-01-18 21:08:15 +00001867
Misha Brukman8a96c532005-04-21 21:44:41 +00001868/// The ParserFunction method lazily parses one function. Use this method to
1869/// casue the parser to parse a specific function in the module. Note that
1870/// this will remove the function from what is to be included by
Reid Spencer04cde2c2004-07-04 11:33:49 +00001871/// ParseAllFunctionBodies.
1872/// @see ParseAllFunctionBodies
1873/// @see ParseBytecode
Reid Spencer060d25d2004-06-29 23:29:38 +00001874void BytecodeReader::ParseFunction(Function* Func) {
1875 // Find {start, end} pointers and slot in the map. If not there, we're done.
1876 LazyFunctionMap::iterator Fi = LazyFunctionLoadMap.find(Func);
Chris Lattner89e02532004-01-18 21:08:15 +00001877
Reid Spencer060d25d2004-06-29 23:29:38 +00001878 // Make sure we found it
Reid Spencer46b002c2004-07-11 17:28:43 +00001879 if (Fi == LazyFunctionLoadMap.end()) {
Reid Spencer24399722004-07-09 22:21:33 +00001880 error("Unrecognized function of type " + Func->getType()->getDescription());
Reid Spencer060d25d2004-06-29 23:29:38 +00001881 return;
Chris Lattner89e02532004-01-18 21:08:15 +00001882 }
1883
Reid Spencer060d25d2004-06-29 23:29:38 +00001884 BlockStart = At = Fi->second.Buf;
1885 BlockEnd = Fi->second.EndBuf;
Reid Spencer24399722004-07-09 22:21:33 +00001886 assert(Fi->first == Func && "Found wrong function?");
Reid Spencer060d25d2004-06-29 23:29:38 +00001887
1888 LazyFunctionLoadMap.erase(Fi);
1889
Reid Spencer46b002c2004-07-11 17:28:43 +00001890 this->ParseFunctionBody(Func);
Chris Lattner89e02532004-01-18 21:08:15 +00001891}
1892
Reid Spencer04cde2c2004-07-04 11:33:49 +00001893/// The ParseAllFunctionBodies method parses through all the previously
1894/// unparsed functions in the bytecode file. If you want to completely parse
1895/// a bytecode file, this method should be called after Parsebytecode because
1896/// Parsebytecode only records the locations in the bytecode file of where
1897/// the function definitions are located. This function uses that information
1898/// to materialize the functions.
1899/// @see ParseBytecode
Reid Spencer060d25d2004-06-29 23:29:38 +00001900void BytecodeReader::ParseAllFunctionBodies() {
1901 LazyFunctionMap::iterator Fi = LazyFunctionLoadMap.begin();
1902 LazyFunctionMap::iterator Fe = LazyFunctionLoadMap.end();
Chris Lattner89e02532004-01-18 21:08:15 +00001903
Reid Spencer46b002c2004-07-11 17:28:43 +00001904 while (Fi != Fe) {
Reid Spencer060d25d2004-06-29 23:29:38 +00001905 Function* Func = Fi->first;
1906 BlockStart = At = Fi->second.Buf;
1907 BlockEnd = Fi->second.EndBuf;
Chris Lattnerb52f1c22005-02-13 17:48:18 +00001908 ParseFunctionBody(Func);
Reid Spencer060d25d2004-06-29 23:29:38 +00001909 ++Fi;
1910 }
Chris Lattnerb52f1c22005-02-13 17:48:18 +00001911 LazyFunctionLoadMap.clear();
Reid Spencer060d25d2004-06-29 23:29:38 +00001912}
Chris Lattner89e02532004-01-18 21:08:15 +00001913
Reid Spencer04cde2c2004-07-04 11:33:49 +00001914/// Parse the global type list
Reid Spencer060d25d2004-06-29 23:29:38 +00001915void BytecodeReader::ParseGlobalTypes() {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001916 // Read the number of types
1917 unsigned NumEntries = read_vbr_uint();
Reid Spencer011bed52004-07-09 21:13:53 +00001918
1919 // Ignore the type plane identifier for types if the bc file is pre 1.3
1920 if (hasTypeDerivedFromValue)
1921 read_vbr_uint();
1922
Reid Spencer46b002c2004-07-11 17:28:43 +00001923 ParseTypes(ModuleTypes, NumEntries);
Reid Spencer060d25d2004-06-29 23:29:38 +00001924}
1925
Reid Spencer04cde2c2004-07-04 11:33:49 +00001926/// Parse the Global info (types, global vars, constants)
Reid Spencer060d25d2004-06-29 23:29:38 +00001927void BytecodeReader::ParseModuleGlobalInfo() {
1928
Reid Spencer04cde2c2004-07-04 11:33:49 +00001929 if (Handler) Handler->handleModuleGlobalsBegin();
Chris Lattner00950542001-06-06 20:29:01 +00001930
Chris Lattner404cddf2005-11-12 01:33:40 +00001931 // SectionID - If a global has an explicit section specified, this map
1932 // remembers the ID until we can translate it into a string.
1933 std::map<GlobalValue*, unsigned> SectionID;
1934
Chris Lattner70cc3392001-09-10 07:58:01 +00001935 // Read global variables...
Reid Spencer060d25d2004-06-29 23:29:38 +00001936 unsigned VarType = read_vbr_uint();
Chris Lattner70cc3392001-09-10 07:58:01 +00001937 while (VarType != Type::VoidTyID) { // List is terminated by Void
Chris Lattner9dd87702004-04-03 23:43:42 +00001938 // VarType Fields: bit0 = isConstant, bit1 = hasInitializer, bit2,3,4 =
1939 // Linkage, bit4+ = slot#
1940 unsigned SlotNo = VarType >> 5;
Reid Spencer46b002c2004-07-11 17:28:43 +00001941 if (sanitizeTypeId(SlotNo))
Reid Spencer24399722004-07-09 22:21:33 +00001942 error("Invalid type (type type) for global var!");
Chris Lattner9dd87702004-04-03 23:43:42 +00001943 unsigned LinkageID = (VarType >> 2) & 7;
Reid Spencer060d25d2004-06-29 23:29:38 +00001944 bool isConstant = VarType & 1;
Chris Lattnerce5e04e2005-11-06 08:23:17 +00001945 bool hasInitializer = (VarType & 2) != 0;
Chris Lattner8eb52dd2005-11-06 07:11:04 +00001946 unsigned Alignment = 0;
Chris Lattner404cddf2005-11-12 01:33:40 +00001947 unsigned GlobalSectionID = 0;
Chris Lattner8eb52dd2005-11-06 07:11:04 +00001948
1949 // An extension word is present when linkage = 3 (internal) and hasinit = 0.
1950 if (LinkageID == 3 && !hasInitializer) {
1951 unsigned ExtWord = read_vbr_uint();
1952 // The extension word has this format: bit 0 = has initializer, bit 1-3 =
1953 // linkage, bit 4-8 = alignment (log2), bits 10+ = future use.
1954 hasInitializer = ExtWord & 1;
1955 LinkageID = (ExtWord >> 1) & 7;
1956 Alignment = (1 << ((ExtWord >> 4) & 31)) >> 1;
Chris Lattner404cddf2005-11-12 01:33:40 +00001957
1958 if (ExtWord & (1 << 9)) // Has a section ID.
1959 GlobalSectionID = read_vbr_uint();
Chris Lattner8eb52dd2005-11-06 07:11:04 +00001960 }
Chris Lattnere3869c82003-04-16 21:16:05 +00001961
Chris Lattnerce5e04e2005-11-06 08:23:17 +00001962 GlobalValue::LinkageTypes Linkage;
Chris Lattnerc08912f2004-01-14 16:44:44 +00001963 switch (LinkageID) {
Chris Lattnerc08912f2004-01-14 16:44:44 +00001964 case 0: Linkage = GlobalValue::ExternalLinkage; break;
1965 case 1: Linkage = GlobalValue::WeakLinkage; break;
1966 case 2: Linkage = GlobalValue::AppendingLinkage; break;
1967 case 3: Linkage = GlobalValue::InternalLinkage; break;
1968 case 4: Linkage = GlobalValue::LinkOnceLinkage; break;
Misha Brukman8a96c532005-04-21 21:44:41 +00001969 default:
Reid Spencer24399722004-07-09 22:21:33 +00001970 error("Unknown linkage type: " + utostr(LinkageID));
Reid Spencer060d25d2004-06-29 23:29:38 +00001971 Linkage = GlobalValue::InternalLinkage;
1972 break;
Chris Lattnere3869c82003-04-16 21:16:05 +00001973 }
1974
1975 const Type *Ty = getType(SlotNo);
Chris Lattnere73bd452005-11-06 07:43:39 +00001976 if (!Ty)
Reid Spencer24399722004-07-09 22:21:33 +00001977 error("Global has no type! SlotNo=" + utostr(SlotNo));
Reid Spencer060d25d2004-06-29 23:29:38 +00001978
Chris Lattnere73bd452005-11-06 07:43:39 +00001979 if (!isa<PointerType>(Ty))
Reid Spencer24399722004-07-09 22:21:33 +00001980 error("Global not a pointer type! Ty= " + Ty->getDescription());
Chris Lattner70cc3392001-09-10 07:58:01 +00001981
Chris Lattner52e20b02003-03-19 20:54:26 +00001982 const Type *ElTy = cast<PointerType>(Ty)->getElementType();
Chris Lattnerd70684f2001-09-18 04:01:05 +00001983
Chris Lattner70cc3392001-09-10 07:58:01 +00001984 // Create the global variable...
Reid Spencer060d25d2004-06-29 23:29:38 +00001985 GlobalVariable *GV = new GlobalVariable(ElTy, isConstant, Linkage,
Chris Lattner52e20b02003-03-19 20:54:26 +00001986 0, "", TheModule);
Chris Lattner8eb52dd2005-11-06 07:11:04 +00001987 GV->setAlignment(Alignment);
Chris Lattner29b789b2003-11-19 17:27:18 +00001988 insertValue(GV, SlotNo, ModuleValues);
Chris Lattner05950c32001-10-13 06:47:01 +00001989
Chris Lattner404cddf2005-11-12 01:33:40 +00001990 if (GlobalSectionID != 0)
1991 SectionID[GV] = GlobalSectionID;
1992
Reid Spencer060d25d2004-06-29 23:29:38 +00001993 unsigned initSlot = 0;
Misha Brukman8a96c532005-04-21 21:44:41 +00001994 if (hasInitializer) {
Reid Spencer060d25d2004-06-29 23:29:38 +00001995 initSlot = read_vbr_uint();
1996 GlobalInits.push_back(std::make_pair(GV, initSlot));
1997 }
1998
1999 // Notify handler about the global value.
Chris Lattner4a242b32004-10-14 01:39:18 +00002000 if (Handler)
2001 Handler->handleGlobalVariable(ElTy, isConstant, Linkage, SlotNo,initSlot);
Reid Spencer060d25d2004-06-29 23:29:38 +00002002
2003 // Get next item
2004 VarType = read_vbr_uint();
Chris Lattner70cc3392001-09-10 07:58:01 +00002005 }
2006
Chris Lattner52e20b02003-03-19 20:54:26 +00002007 // Read the function objects for all of the functions that are coming
Chris Lattnera79e7cc2004-10-16 18:18:16 +00002008 unsigned FnSignature = read_vbr_uint();
Reid Spencer24399722004-07-09 22:21:33 +00002009
Chris Lattnera79e7cc2004-10-16 18:18:16 +00002010 if (hasNoFlagsForFunctions)
2011 FnSignature = (FnSignature << 5) + 1;
2012
2013 // List is terminated by VoidTy.
Chris Lattnere73bd452005-11-06 07:43:39 +00002014 while (((FnSignature & (~0U >> 1)) >> 5) != Type::VoidTyID) {
2015 const Type *Ty = getType((FnSignature & (~0U >> 1)) >> 5);
Chris Lattner927b1852003-10-09 20:22:47 +00002016 if (!isa<PointerType>(Ty) ||
Reid Spencer060d25d2004-06-29 23:29:38 +00002017 !isa<FunctionType>(cast<PointerType>(Ty)->getElementType())) {
Misha Brukman8a96c532005-04-21 21:44:41 +00002018 error("Function not a pointer to function type! Ty = " +
Reid Spencer46b002c2004-07-11 17:28:43 +00002019 Ty->getDescription());
Reid Spencer060d25d2004-06-29 23:29:38 +00002020 }
Chris Lattner8cdc6b72002-10-23 00:51:54 +00002021
Chris Lattner2a7b6ba2003-03-06 17:15:19 +00002022 // We create functions by passing the underlying FunctionType to create...
Misha Brukman8a96c532005-04-21 21:44:41 +00002023 const FunctionType* FTy =
Reid Spencer060d25d2004-06-29 23:29:38 +00002024 cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
Chris Lattner00950542001-06-06 20:29:01 +00002025
Chris Lattner18549c22004-11-15 21:43:03 +00002026 // Insert the place holder.
Chris Lattner404cddf2005-11-12 01:33:40 +00002027 Function *Func = new Function(FTy, GlobalValue::ExternalLinkage,
Reid Spencer04cde2c2004-07-04 11:33:49 +00002028 "", TheModule);
Reid Spencer0b118202006-01-16 21:12:35 +00002029 UpgradeIntrinsicFunction(Func);
Chris Lattnere73bd452005-11-06 07:43:39 +00002030 insertValue(Func, (FnSignature & (~0U >> 1)) >> 5, ModuleValues);
Chris Lattnera79e7cc2004-10-16 18:18:16 +00002031
2032 // Flags are not used yet.
Chris Lattner97fbc502004-11-15 22:38:52 +00002033 unsigned Flags = FnSignature & 31;
Chris Lattner00950542001-06-06 20:29:01 +00002034
Chris Lattner97fbc502004-11-15 22:38:52 +00002035 // Save this for later so we know type of lazily instantiated functions.
2036 // Note that known-external functions do not have FunctionInfo blocks, so we
2037 // do not add them to the FunctionSignatureList.
2038 if ((Flags & (1 << 4)) == 0)
2039 FunctionSignatureList.push_back(Func);
Chris Lattner52e20b02003-03-19 20:54:26 +00002040
Chris Lattnere73bd452005-11-06 07:43:39 +00002041 // Get the calling convention from the low bits.
2042 unsigned CC = Flags & 15;
2043 unsigned Alignment = 0;
2044 if (FnSignature & (1 << 31)) { // Has extension word?
2045 unsigned ExtWord = read_vbr_uint();
2046 Alignment = (1 << (ExtWord & 31)) >> 1;
2047 CC |= ((ExtWord >> 5) & 15) << 4;
Chris Lattner404cddf2005-11-12 01:33:40 +00002048
2049 if (ExtWord & (1 << 10)) // Has a section ID.
2050 SectionID[Func] = read_vbr_uint();
Chris Lattnere73bd452005-11-06 07:43:39 +00002051 }
2052
Chris Lattner54b369e2005-11-06 07:46:13 +00002053 Func->setCallingConv(CC-1);
Chris Lattnere73bd452005-11-06 07:43:39 +00002054 Func->setAlignment(Alignment);
Chris Lattner479ffeb2005-05-06 20:42:57 +00002055
Reid Spencer04cde2c2004-07-04 11:33:49 +00002056 if (Handler) Handler->handleFunctionDeclaration(Func);
Reid Spencer060d25d2004-06-29 23:29:38 +00002057
Chris Lattnera79e7cc2004-10-16 18:18:16 +00002058 // Get the next function signature.
2059 FnSignature = read_vbr_uint();
2060 if (hasNoFlagsForFunctions)
2061 FnSignature = (FnSignature << 5) + 1;
Chris Lattner00950542001-06-06 20:29:01 +00002062 }
2063
Misha Brukman8a96c532005-04-21 21:44:41 +00002064 // Now that the function signature list is set up, reverse it so that we can
Chris Lattner74734132002-08-17 22:01:27 +00002065 // remove elements efficiently from the back of the vector.
2066 std::reverse(FunctionSignatureList.begin(), FunctionSignatureList.end());
Chris Lattner00950542001-06-06 20:29:01 +00002067
Chris Lattner404cddf2005-11-12 01:33:40 +00002068 /// SectionNames - This contains the list of section names encoded in the
2069 /// moduleinfoblock. Functions and globals with an explicit section index
2070 /// into this to get their section name.
2071 std::vector<std::string> SectionNames;
2072
2073 if (hasInconsistentModuleGlobalInfo) {
2074 align32();
2075 } else if (!hasNoDependentLibraries) {
2076 // If this bytecode format has dependent library information in it, read in
2077 // the number of dependent library items that follow.
Reid Spencerad89bd62004-07-25 18:07:36 +00002078 unsigned num_dep_libs = read_vbr_uint();
2079 std::string dep_lib;
Chris Lattner404cddf2005-11-12 01:33:40 +00002080 while (num_dep_libs--) {
Reid Spencerad89bd62004-07-25 18:07:36 +00002081 dep_lib = read_str();
Reid Spencerada16182004-07-25 21:36:26 +00002082 TheModule->addLibrary(dep_lib);
Reid Spencer5b472d92004-08-21 20:49:23 +00002083 if (Handler)
2084 Handler->handleDependentLibrary(dep_lib);
Reid Spencerad89bd62004-07-25 18:07:36 +00002085 }
2086
Chris Lattner404cddf2005-11-12 01:33:40 +00002087 // Read target triple and place into the module.
Reid Spencerad89bd62004-07-25 18:07:36 +00002088 std::string triple = read_str();
2089 TheModule->setTargetTriple(triple);
Reid Spencer5b472d92004-08-21 20:49:23 +00002090 if (Handler)
2091 Handler->handleTargetTriple(triple);
Chris Lattner404cddf2005-11-12 01:33:40 +00002092
Chris Lattner39979ea2005-11-12 18:31:54 +00002093 if (At != BlockEnd && !hasAlignment) {
Chris Lattner404cddf2005-11-12 01:33:40 +00002094 // If the file has section info in it, read the section names now.
2095 unsigned NumSections = read_vbr_uint();
2096 while (NumSections--)
2097 SectionNames.push_back(read_str());
2098 }
Reid Spencerad89bd62004-07-25 18:07:36 +00002099 }
2100
Chris Lattner404cddf2005-11-12 01:33:40 +00002101 // If any globals are in specified sections, assign them now.
2102 for (std::map<GlobalValue*, unsigned>::iterator I = SectionID.begin(), E =
2103 SectionID.end(); I != E; ++I)
2104 if (I->second) {
2105 if (I->second > SectionID.size())
2106 error("SectionID out of range for global!");
2107 I->first->setSection(SectionNames[I->second-1]);
2108 }
Reid Spencerad89bd62004-07-25 18:07:36 +00002109
Chris Lattner00950542001-06-06 20:29:01 +00002110 // This is for future proofing... in the future extra fields may be added that
2111 // we don't understand, so we transparently ignore them.
2112 //
Reid Spencer060d25d2004-06-29 23:29:38 +00002113 At = BlockEnd;
2114
Reid Spencer04cde2c2004-07-04 11:33:49 +00002115 if (Handler) Handler->handleModuleGlobalsEnd();
Chris Lattner00950542001-06-06 20:29:01 +00002116}
2117
Reid Spencer04cde2c2004-07-04 11:33:49 +00002118/// Parse the version information and decode it by setting flags on the
2119/// Reader that enable backward compatibility of the reader.
Reid Spencer060d25d2004-06-29 23:29:38 +00002120void BytecodeReader::ParseVersionInfo() {
2121 unsigned Version = read_vbr_uint();
Chris Lattner036b8aa2003-03-06 17:55:45 +00002122
2123 // Unpack version number: low four bits are for flags, top bits = version
Chris Lattnerd445c6b2003-08-24 13:47:36 +00002124 Module::Endianness Endianness;
2125 Module::PointerSize PointerSize;
2126 Endianness = (Version & 1) ? Module::BigEndian : Module::LittleEndian;
2127 PointerSize = (Version & 2) ? Module::Pointer64 : Module::Pointer32;
2128
2129 bool hasNoEndianness = Version & 4;
2130 bool hasNoPointerSize = Version & 8;
Misha Brukman8a96c532005-04-21 21:44:41 +00002131
Chris Lattnerd445c6b2003-08-24 13:47:36 +00002132 RevisionNum = Version >> 4;
Chris Lattnere3869c82003-04-16 21:16:05 +00002133
2134 // Default values for the current bytecode version
Chris Lattner44d0eeb2004-01-15 17:55:01 +00002135 hasInconsistentModuleGlobalInfo = false;
Chris Lattner80b97342004-01-17 23:25:43 +00002136 hasExplicitPrimitiveZeros = false;
Chris Lattner5fa428f2004-04-05 01:27:26 +00002137 hasRestrictedGEPTypes = false;
Reid Spencer04cde2c2004-07-04 11:33:49 +00002138 hasTypeDerivedFromValue = false;
Reid Spencerad89bd62004-07-25 18:07:36 +00002139 hasLongBlockHeaders = false;
Reid Spencerad89bd62004-07-25 18:07:36 +00002140 has32BitTypes = false;
2141 hasNoDependentLibraries = false;
Reid Spencer38d54be2004-08-17 07:45:14 +00002142 hasAlignment = false;
Chris Lattnera79e7cc2004-10-16 18:18:16 +00002143 hasNoUndefValue = false;
2144 hasNoFlagsForFunctions = false;
2145 hasNoUnreachableInst = false;
Chris Lattner036b8aa2003-03-06 17:55:45 +00002146
2147 switch (RevisionNum) {
Reid Spencer5b472d92004-08-21 20:49:23 +00002148 case 0: // LLVM 1.0, 1.1 (Released)
Chris Lattner9e893e82004-01-14 23:35:21 +00002149 // Base LLVM 1.0 bytecode format.
Chris Lattner44d0eeb2004-01-15 17:55:01 +00002150 hasInconsistentModuleGlobalInfo = true;
Chris Lattner80b97342004-01-17 23:25:43 +00002151 hasExplicitPrimitiveZeros = true;
Reid Spencer04cde2c2004-07-04 11:33:49 +00002152
Chris Lattner80b97342004-01-17 23:25:43 +00002153 // FALL THROUGH
Reid Spencer5b472d92004-08-21 20:49:23 +00002154
2155 case 1: // LLVM 1.2 (Released)
Chris Lattner9e893e82004-01-14 23:35:21 +00002156 // LLVM 1.2 added explicit support for emitting strings efficiently.
Chris Lattner44d0eeb2004-01-15 17:55:01 +00002157
2158 // Also, it fixed the problem where the size of the ModuleGlobalInfo block
2159 // included the size for the alignment at the end, where the rest of the
2160 // blocks did not.
Chris Lattner5fa428f2004-04-05 01:27:26 +00002161
2162 // LLVM 1.2 and before required that GEP indices be ubyte constants for
2163 // structures and longs for sequential types.
2164 hasRestrictedGEPTypes = true;
2165
Reid Spencer04cde2c2004-07-04 11:33:49 +00002166 // LLVM 1.2 and before had the Type class derive from Value class. This
2167 // changed in release 1.3 and consequently LLVM 1.3 bytecode files are
Misha Brukman8a96c532005-04-21 21:44:41 +00002168 // written differently because Types can no longer be part of the
Reid Spencer04cde2c2004-07-04 11:33:49 +00002169 // type planes for Values.
2170 hasTypeDerivedFromValue = true;
2171
Chris Lattner5fa428f2004-04-05 01:27:26 +00002172 // FALL THROUGH
Misha Brukman8a96c532005-04-21 21:44:41 +00002173
Reid Spencer5b472d92004-08-21 20:49:23 +00002174 case 2: // 1.2.5 (Not Released)
Reid Spencerad89bd62004-07-25 18:07:36 +00002175
Reid Spencer5b472d92004-08-21 20:49:23 +00002176 // LLVM 1.2 and earlier had two-word block headers. This is a bit wasteful,
Chris Lattner4a242b32004-10-14 01:39:18 +00002177 // especially for small files where the 8 bytes per block is a large
2178 // fraction of the total block size. In LLVM 1.3, the block type and length
2179 // are compressed into a single 32-bit unsigned integer. 27 bits for length,
2180 // 5 bits for block type.
Reid Spencerad89bd62004-07-25 18:07:36 +00002181 hasLongBlockHeaders = true;
2182
Reid Spencer5b472d92004-08-21 20:49:23 +00002183 // LLVM 1.2 and earlier wrote type slot numbers as vbr_uint32. In LLVM 1.3
Chris Lattner4a242b32004-10-14 01:39:18 +00002184 // this has been reduced to vbr_uint24. It shouldn't make much difference
2185 // since we haven't run into a module with > 24 million types, but for
2186 // safety the 24-bit restriction has been enforced in 1.3 to free some bits
2187 // in various places and to ensure consistency.
Reid Spencerad89bd62004-07-25 18:07:36 +00002188 has32BitTypes = true;
2189
Misha Brukman8a96c532005-04-21 21:44:41 +00002190 // LLVM 1.2 and earlier did not provide a target triple nor a list of
Reid Spencer5b472d92004-08-21 20:49:23 +00002191 // libraries on which the bytecode is dependent. LLVM 1.3 provides these
2192 // features, for use in future versions of LLVM.
Reid Spencerad89bd62004-07-25 18:07:36 +00002193 hasNoDependentLibraries = true;
2194
2195 // FALL THROUGH
Reid Spencer5b472d92004-08-21 20:49:23 +00002196
2197 case 3: // LLVM 1.3 (Released)
2198 // LLVM 1.3 and earlier caused alignment bytes to be written on some block
Misha Brukman8a96c532005-04-21 21:44:41 +00002199 // boundaries and at the end of some strings. In extreme cases (e.g. lots
Reid Spencer5b472d92004-08-21 20:49:23 +00002200 // of GEP references to a constant array), this can increase the file size
2201 // by 30% or more. In version 1.4 alignment is done away with completely.
Reid Spencer38d54be2004-08-17 07:45:14 +00002202 hasAlignment = true;
2203
2204 // FALL THROUGH
Misha Brukman8a96c532005-04-21 21:44:41 +00002205
Reid Spencer5b472d92004-08-21 20:49:23 +00002206 case 4: // 1.3.1 (Not Released)
Chris Lattnera79e7cc2004-10-16 18:18:16 +00002207 // In version 4, we did not support the 'undef' constant.
2208 hasNoUndefValue = true;
2209
2210 // In version 4 and above, we did not include space for flags for functions
2211 // in the module info block.
2212 hasNoFlagsForFunctions = true;
2213
2214 // In version 4 and above, we did not include the 'unreachable' instruction
2215 // in the opcode numbering in the bytecode file.
2216 hasNoUnreachableInst = true;
Chris Lattner2e7ec122004-10-16 18:56:02 +00002217 break;
Chris Lattnera79e7cc2004-10-16 18:18:16 +00002218
2219 // FALL THROUGH
2220
Chris Lattnerdee199f2005-05-06 22:34:01 +00002221 case 5: // 1.4 (Released)
Chris Lattnera79e7cc2004-10-16 18:18:16 +00002222 break;
2223
Chris Lattner036b8aa2003-03-06 17:55:45 +00002224 default:
Reid Spencer24399722004-07-09 22:21:33 +00002225 error("Unknown bytecode version number: " + itostr(RevisionNum));
Chris Lattner036b8aa2003-03-06 17:55:45 +00002226 }
2227
Chris Lattnerd445c6b2003-08-24 13:47:36 +00002228 if (hasNoEndianness) Endianness = Module::AnyEndianness;
2229 if (hasNoPointerSize) PointerSize = Module::AnyPointerSize;
Chris Lattner76e38962003-04-22 18:15:10 +00002230
Brian Gaekefe2102b2004-07-14 20:33:13 +00002231 TheModule->setEndianness(Endianness);
2232 TheModule->setPointerSize(PointerSize);
2233
Reid Spencer46b002c2004-07-11 17:28:43 +00002234 if (Handler) Handler->handleVersionInfo(RevisionNum, Endianness, PointerSize);
Chris Lattner036b8aa2003-03-06 17:55:45 +00002235}
2236
Reid Spencer04cde2c2004-07-04 11:33:49 +00002237/// Parse a whole module.
Reid Spencer060d25d2004-06-29 23:29:38 +00002238void BytecodeReader::ParseModule() {
Chris Lattner00950542001-06-06 20:29:01 +00002239 unsigned Type, Size;
Chris Lattner00950542001-06-06 20:29:01 +00002240
Reid Spencer060d25d2004-06-29 23:29:38 +00002241 FunctionSignatureList.clear(); // Just in case...
Chris Lattner00950542001-06-06 20:29:01 +00002242
2243 // Read into instance variables...
Reid Spencer060d25d2004-06-29 23:29:38 +00002244 ParseVersionInfo();
Reid Spencerad89bd62004-07-25 18:07:36 +00002245 align32();
Chris Lattner00950542001-06-06 20:29:01 +00002246
Reid Spencer060d25d2004-06-29 23:29:38 +00002247 bool SeenModuleGlobalInfo = false;
2248 bool SeenGlobalTypePlane = false;
2249 BufPtr MyEnd = BlockEnd;
2250 while (At < MyEnd) {
2251 BufPtr OldAt = At;
2252 read_block(Type, Size);
2253
Chris Lattner00950542001-06-06 20:29:01 +00002254 switch (Type) {
Reid Spencer060d25d2004-06-29 23:29:38 +00002255
Reid Spencerad89bd62004-07-25 18:07:36 +00002256 case BytecodeFormat::GlobalTypePlaneBlockID:
Reid Spencer46b002c2004-07-11 17:28:43 +00002257 if (SeenGlobalTypePlane)
Reid Spencer24399722004-07-09 22:21:33 +00002258 error("Two GlobalTypePlane Blocks Encountered!");
Reid Spencer060d25d2004-06-29 23:29:38 +00002259
Reid Spencer5b472d92004-08-21 20:49:23 +00002260 if (Size > 0)
2261 ParseGlobalTypes();
Reid Spencer060d25d2004-06-29 23:29:38 +00002262 SeenGlobalTypePlane = true;
Chris Lattner52e20b02003-03-19 20:54:26 +00002263 break;
2264
Misha Brukman8a96c532005-04-21 21:44:41 +00002265 case BytecodeFormat::ModuleGlobalInfoBlockID:
Reid Spencer46b002c2004-07-11 17:28:43 +00002266 if (SeenModuleGlobalInfo)
Reid Spencer24399722004-07-09 22:21:33 +00002267 error("Two ModuleGlobalInfo Blocks Encountered!");
Reid Spencer060d25d2004-06-29 23:29:38 +00002268 ParseModuleGlobalInfo();
2269 SeenModuleGlobalInfo = true;
Chris Lattner52e20b02003-03-19 20:54:26 +00002270 break;
2271
Reid Spencerad89bd62004-07-25 18:07:36 +00002272 case BytecodeFormat::ConstantPoolBlockID:
Reid Spencer04cde2c2004-07-04 11:33:49 +00002273 ParseConstantPool(ModuleValues, ModuleTypes,false);
Chris Lattner00950542001-06-06 20:29:01 +00002274 break;
2275
Reid Spencerad89bd62004-07-25 18:07:36 +00002276 case BytecodeFormat::FunctionBlockID:
Reid Spencer060d25d2004-06-29 23:29:38 +00002277 ParseFunctionLazily();
Chris Lattner00950542001-06-06 20:29:01 +00002278 break;
Chris Lattner00950542001-06-06 20:29:01 +00002279
Reid Spencerad89bd62004-07-25 18:07:36 +00002280 case BytecodeFormat::SymbolTableBlockID:
Reid Spencer060d25d2004-06-29 23:29:38 +00002281 ParseSymbolTable(0, &TheModule->getSymbolTable());
Chris Lattner00950542001-06-06 20:29:01 +00002282 break;
Reid Spencer060d25d2004-06-29 23:29:38 +00002283
Chris Lattner00950542001-06-06 20:29:01 +00002284 default:
Reid Spencer060d25d2004-06-29 23:29:38 +00002285 At += Size;
2286 if (OldAt > At) {
Reid Spencer46b002c2004-07-11 17:28:43 +00002287 error("Unexpected Block of Type #" + utostr(Type) + " encountered!");
Reid Spencer060d25d2004-06-29 23:29:38 +00002288 }
Chris Lattner00950542001-06-06 20:29:01 +00002289 break;
2290 }
Reid Spencer060d25d2004-06-29 23:29:38 +00002291 BlockEnd = MyEnd;
2292 align32();
Chris Lattner00950542001-06-06 20:29:01 +00002293 }
2294
Chris Lattner52e20b02003-03-19 20:54:26 +00002295 // After the module constant pool has been read, we can safely initialize
2296 // global variables...
2297 while (!GlobalInits.empty()) {
2298 GlobalVariable *GV = GlobalInits.back().first;
2299 unsigned Slot = GlobalInits.back().second;
2300 GlobalInits.pop_back();
2301
2302 // Look up the initializer value...
Chris Lattner29b789b2003-11-19 17:27:18 +00002303 // FIXME: Preserve this type ID!
Reid Spencer060d25d2004-06-29 23:29:38 +00002304
2305 const llvm::PointerType* GVType = GV->getType();
2306 unsigned TypeSlot = getTypeSlot(GVType->getElementType());
Chris Lattner93361992004-01-15 18:45:25 +00002307 if (Constant *CV = getConstantValue(TypeSlot, Slot)) {
Misha Brukman8a96c532005-04-21 21:44:41 +00002308 if (GV->hasInitializer())
Reid Spencer24399722004-07-09 22:21:33 +00002309 error("Global *already* has an initializer?!");
Reid Spencer04cde2c2004-07-04 11:33:49 +00002310 if (Handler) Handler->handleGlobalInitializer(GV,CV);
Chris Lattner93361992004-01-15 18:45:25 +00002311 GV->setInitializer(CV);
Chris Lattner52e20b02003-03-19 20:54:26 +00002312 } else
Reid Spencer24399722004-07-09 22:21:33 +00002313 error("Cannot find initializer value.");
Chris Lattner52e20b02003-03-19 20:54:26 +00002314 }
2315
Chris Lattneraba5ff52005-05-05 20:57:00 +00002316 if (!ConstantFwdRefs.empty())
2317 error("Use of undefined constants in a module");
2318
Reid Spencer060d25d2004-06-29 23:29:38 +00002319 /// Make sure we pulled them all out. If we didn't then there's a declaration
2320 /// but a missing body. That's not allowed.
Misha Brukman12c29d12003-09-22 23:38:23 +00002321 if (!FunctionSignatureList.empty())
Reid Spencer24399722004-07-09 22:21:33 +00002322 error("Function declared, but bytecode stream ended before definition");
Chris Lattner00950542001-06-06 20:29:01 +00002323}
2324
Reid Spencer04cde2c2004-07-04 11:33:49 +00002325/// This function completely parses a bytecode buffer given by the \p Buf
2326/// and \p Length parameters.
Misha Brukman8a96c532005-04-21 21:44:41 +00002327void BytecodeReader::ParseBytecode(BufPtr Buf, unsigned Length,
Reid Spencer5b472d92004-08-21 20:49:23 +00002328 const std::string &ModuleID) {
Misha Brukmane0dd0d42003-09-23 16:15:29 +00002329
Reid Spencer060d25d2004-06-29 23:29:38 +00002330 try {
Chris Lattner3af4b4f2004-11-30 16:58:18 +00002331 RevisionNum = 0;
Reid Spencer060d25d2004-06-29 23:29:38 +00002332 At = MemStart = BlockStart = Buf;
2333 MemEnd = BlockEnd = Buf + Length;
Misha Brukmane0dd0d42003-09-23 16:15:29 +00002334
Reid Spencer060d25d2004-06-29 23:29:38 +00002335 // Create the module
2336 TheModule = new Module(ModuleID);
Chris Lattner00950542001-06-06 20:29:01 +00002337
Reid Spencer04cde2c2004-07-04 11:33:49 +00002338 if (Handler) Handler->handleStart(TheModule, Length);
Reid Spencer060d25d2004-06-29 23:29:38 +00002339
Reid Spencerf0c977c2004-11-07 18:20:55 +00002340 // Read the four bytes of the signature.
2341 unsigned Sig = read_uint();
Reid Spencer17f52c52004-11-06 23:17:23 +00002342
Reid Spencerf0c977c2004-11-07 18:20:55 +00002343 // If this is a compressed file
2344 if (Sig == ('l' | ('l' << 8) | ('v' << 16) | ('c' << 24))) {
Reid Spencer17f52c52004-11-06 23:17:23 +00002345
Reid Spencerf0c977c2004-11-07 18:20:55 +00002346 // Invoke the decompression of the bytecode. Note that we have to skip the
2347 // file's magic number which is not part of the compressed block. Hence,
Reid Spencer61aaf2e2004-11-14 21:59:21 +00002348 // the Buf+4 and Length-4. The result goes into decompressedBlock, a data
2349 // member for retention until BytecodeReader is destructed.
2350 unsigned decompressedLength = Compressor::decompressToNewBuffer(
2351 (char*)Buf+4,Length-4,decompressedBlock);
Reid Spencerf0c977c2004-11-07 18:20:55 +00002352
2353 // We must adjust the buffer pointers used by the bytecode reader to point
Reid Spencer61aaf2e2004-11-14 21:59:21 +00002354 // into the new decompressed block. After decompression, the
2355 // decompressedBlock will point to a contiguous memory area that has
Reid Spencerf0c977c2004-11-07 18:20:55 +00002356 // the decompressed data.
Reid Spencer61aaf2e2004-11-14 21:59:21 +00002357 At = MemStart = BlockStart = Buf = (BufPtr) decompressedBlock;
Reid Spencerf0c977c2004-11-07 18:20:55 +00002358 MemEnd = BlockEnd = Buf + decompressedLength;
Reid Spencer17f52c52004-11-06 23:17:23 +00002359
Reid Spencerf0c977c2004-11-07 18:20:55 +00002360 // else if this isn't a regular (uncompressed) bytecode file, then its
2361 // and error, generate that now.
2362 } else if (Sig != ('l' | ('l' << 8) | ('v' << 16) | ('m' << 24))) {
2363 error("Invalid bytecode signature: " + utohexstr(Sig));
Reid Spencer060d25d2004-06-29 23:29:38 +00002364 }
2365
Reid Spencer060d25d2004-06-29 23:29:38 +00002366 // Tell the handler we're starting a module
Reid Spencer04cde2c2004-07-04 11:33:49 +00002367 if (Handler) Handler->handleModuleBegin(ModuleID);
Reid Spencer060d25d2004-06-29 23:29:38 +00002368
Reid Spencerad89bd62004-07-25 18:07:36 +00002369 // Get the module block and size and verify. This is handled specially
2370 // because the module block/size is always written in long format. Other
2371 // blocks are written in short format so the read_block method is used.
Reid Spencer060d25d2004-06-29 23:29:38 +00002372 unsigned Type, Size;
Reid Spencerad89bd62004-07-25 18:07:36 +00002373 Type = read_uint();
2374 Size = read_uint();
2375 if (Type != BytecodeFormat::ModuleBlockID) {
Misha Brukman8a96c532005-04-21 21:44:41 +00002376 error("Expected Module Block! Type:" + utostr(Type) + ", Size:"
Reid Spencer46b002c2004-07-11 17:28:43 +00002377 + utostr(Size));
Reid Spencer060d25d2004-06-29 23:29:38 +00002378 }
Chris Lattner56bc8942004-09-27 16:59:06 +00002379
2380 // It looks like the darwin ranlib program is broken, and adds trailing
2381 // garbage to the end of some bytecode files. This hack allows the bc
2382 // reader to ignore trailing garbage on bytecode files.
2383 if (At + Size < MemEnd)
2384 MemEnd = BlockEnd = At+Size;
2385
2386 if (At + Size != MemEnd)
Reid Spencer24399722004-07-09 22:21:33 +00002387 error("Invalid Top Level Block Length! Type:" + utostr(Type)
Reid Spencer46b002c2004-07-11 17:28:43 +00002388 + ", Size:" + utostr(Size));
Reid Spencer060d25d2004-06-29 23:29:38 +00002389
2390 // Parse the module contents
2391 this->ParseModule();
2392
Reid Spencer060d25d2004-06-29 23:29:38 +00002393 // Check for missing functions
Reid Spencer46b002c2004-07-11 17:28:43 +00002394 if (hasFunctions())
Reid Spencer24399722004-07-09 22:21:33 +00002395 error("Function expected, but bytecode stream ended!");
Reid Spencer060d25d2004-06-29 23:29:38 +00002396
Reid Spencer5c15fe52004-07-05 00:57:50 +00002397 // Tell the handler we're done with the module
Misha Brukman8a96c532005-04-21 21:44:41 +00002398 if (Handler)
Reid Spencer5c15fe52004-07-05 00:57:50 +00002399 Handler->handleModuleEnd(ModuleID);
2400
2401 // Tell the handler we're finished the parse
Reid Spencer04cde2c2004-07-04 11:33:49 +00002402 if (Handler) Handler->handleFinish();
Reid Spencer060d25d2004-06-29 23:29:38 +00002403
Reid Spencer46b002c2004-07-11 17:28:43 +00002404 } catch (std::string& errstr) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00002405 if (Handler) Handler->handleError(errstr);
Reid Spencer060d25d2004-06-29 23:29:38 +00002406 freeState();
Chris Lattner2a7b6ba2003-03-06 17:15:19 +00002407 delete TheModule;
2408 TheModule = 0;
Chris Lattner3bdad692004-11-15 21:55:33 +00002409 if (decompressedBlock != 0 ) {
Reid Spencer61aaf2e2004-11-14 21:59:21 +00002410 ::free(decompressedBlock);
Chris Lattner3bdad692004-11-15 21:55:33 +00002411 decompressedBlock = 0;
2412 }
Chris Lattnerb0b7c0d2003-09-26 14:44:52 +00002413 throw;
Reid Spencer060d25d2004-06-29 23:29:38 +00002414 } catch (...) {
2415 std::string msg("Unknown Exception Occurred");
Reid Spencer04cde2c2004-07-04 11:33:49 +00002416 if (Handler) Handler->handleError(msg);
Reid Spencer060d25d2004-06-29 23:29:38 +00002417 freeState();
2418 delete TheModule;
2419 TheModule = 0;
Chris Lattner3bdad692004-11-15 21:55:33 +00002420 if (decompressedBlock != 0) {
Reid Spencer61aaf2e2004-11-14 21:59:21 +00002421 ::free(decompressedBlock);
Chris Lattner3bdad692004-11-15 21:55:33 +00002422 decompressedBlock = 0;
2423 }
Reid Spencer060d25d2004-06-29 23:29:38 +00002424 throw msg;
Chris Lattner2a7b6ba2003-03-06 17:15:19 +00002425 }
Chris Lattner00950542001-06-06 20:29:01 +00002426}
Reid Spencer060d25d2004-06-29 23:29:38 +00002427
2428//===----------------------------------------------------------------------===//
2429//=== Default Implementations of Handler Methods
2430//===----------------------------------------------------------------------===//
2431
2432BytecodeHandler::~BytecodeHandler() {}
Reid Spencer060d25d2004-06-29 23:29:38 +00002433