blob: 43150365e5bead8ab7601a6aced2e01864080c23 [file] [log] [blame]
Chris Lattnerd6b65252001-10-24 01:15:12 +00001//===- Reader.cpp - Code to read bytecode files ---------------------------===//
Misha Brukman8a96c532005-04-21 21:44:41 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
Misha Brukman8a96c532005-04-21 21:44:41 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner00950542001-06-06 20:29:01 +00009//
10// This library implements the functionality defined in llvm/Bytecode/Reader.h
11//
Misha Brukman8a96c532005-04-21 21:44:41 +000012// Note that this library should be as fast as possible, reentrant, and
Chris Lattner00950542001-06-06 20:29:01 +000013// threadsafe!!
14//
Chris Lattner00950542001-06-06 20:29:01 +000015// TODO: Allow passing in an option to ignore the symbol table
16//
Chris Lattnerd6b65252001-10-24 01:15:12 +000017//===----------------------------------------------------------------------===//
Chris Lattner00950542001-06-06 20:29:01 +000018
Reid Spencer060d25d2004-06-29 23:29:38 +000019#include "Reader.h"
Reid Spencer0b118202006-01-16 21:12:35 +000020#include "llvm/Assembly/AutoUpgrade.h"
Reid Spencer060d25d2004-06-29 23:29:38 +000021#include "llvm/Bytecode/BytecodeHandler.h"
22#include "llvm/BasicBlock.h"
Chris Lattnerdee199f2005-05-06 22:34:01 +000023#include "llvm/CallingConv.h"
Reid Spencer060d25d2004-06-29 23:29:38 +000024#include "llvm/Constants.h"
Chris Lattner3bc5a602006-01-25 23:08:15 +000025#include "llvm/InlineAsm.h"
Reid Spencer04cde2c2004-07-04 11:33:49 +000026#include "llvm/Instructions.h"
27#include "llvm/SymbolTable.h"
Chris Lattner00950542001-06-06 20:29:01 +000028#include "llvm/Bytecode/Format.h"
Chris Lattnerdee199f2005-05-06 22:34:01 +000029#include "llvm/Config/alloca.h"
Reid Spencer060d25d2004-06-29 23:29:38 +000030#include "llvm/Support/GetElementPtrTypeIterator.h"
Reid Spencer17f52c52004-11-06 23:17:23 +000031#include "llvm/Support/Compressor.h"
Jim Laskeycb6682f2005-08-17 19:34:49 +000032#include "llvm/Support/MathExtras.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000033#include "llvm/ADT/StringExtras.h"
Reid Spencer060d25d2004-06-29 23:29:38 +000034#include <sstream>
Alkis Evlogimenos20aa4742004-09-03 18:19:51 +000035#include <algorithm>
Chris Lattner29b789b2003-11-19 17:27:18 +000036using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000037
Reid Spencer46b002c2004-07-11 17:28:43 +000038namespace {
Chris Lattnercad28bd2005-01-29 00:36:19 +000039 /// @brief A class for maintaining the slot number definition
40 /// as a placeholder for the actual definition for forward constants defs.
41 class ConstantPlaceHolder : public ConstantExpr {
42 ConstantPlaceHolder(); // DO NOT IMPLEMENT
43 void operator=(const ConstantPlaceHolder &); // DO NOT IMPLEMENT
44 public:
Chris Lattner61323322005-01-31 01:11:13 +000045 Use Op;
Misha Brukman8a96c532005-04-21 21:44:41 +000046 ConstantPlaceHolder(const Type *Ty)
Chris Lattner61323322005-01-31 01:11:13 +000047 : ConstantExpr(Ty, Instruction::UserOp1, &Op, 1),
48 Op(UndefValue::get(Type::IntTy), this) {
49 }
Chris Lattnercad28bd2005-01-29 00:36:19 +000050 };
Reid Spencer46b002c2004-07-11 17:28:43 +000051}
Reid Spencer060d25d2004-06-29 23:29:38 +000052
Reid Spencer24399722004-07-09 22:21:33 +000053// Provide some details on error
Reid Spencer233fe722006-08-22 16:09:19 +000054inline void BytecodeReader::error(const std::string& err) {
55 ErrorMsg = err + " (Vers=" + itostr(RevisionNum) + ", Pos="
56 + itostr(At-MemStart) + ")";
57 longjmp(context,1);
Reid Spencer24399722004-07-09 22:21:33 +000058}
59
Reid Spencer060d25d2004-06-29 23:29:38 +000060//===----------------------------------------------------------------------===//
61// Bytecode Reading Methods
62//===----------------------------------------------------------------------===//
63
Reid Spencer04cde2c2004-07-04 11:33:49 +000064/// Determine if the current block being read contains any more data.
Reid Spencer060d25d2004-06-29 23:29:38 +000065inline bool BytecodeReader::moreInBlock() {
66 return At < BlockEnd;
Chris Lattner00950542001-06-06 20:29:01 +000067}
68
Reid Spencer04cde2c2004-07-04 11:33:49 +000069/// Throw an error if we've read past the end of the current block
Reid Spencer060d25d2004-06-29 23:29:38 +000070inline void BytecodeReader::checkPastBlockEnd(const char * block_name) {
Reid Spencer46b002c2004-07-11 17:28:43 +000071 if (At > BlockEnd)
Chris Lattnera79e7cc2004-10-16 18:18:16 +000072 error(std::string("Attempt to read past the end of ") + block_name +
73 " block.");
Reid Spencer060d25d2004-06-29 23:29:38 +000074}
Chris Lattner36392bc2003-10-08 21:18:57 +000075
Reid Spencer04cde2c2004-07-04 11:33:49 +000076/// Align the buffer position to a 32 bit boundary
Reid Spencer060d25d2004-06-29 23:29:38 +000077inline void BytecodeReader::align32() {
Reid Spencer38d54be2004-08-17 07:45:14 +000078 if (hasAlignment) {
79 BufPtr Save = At;
Jeff Cohen05ebc8d2006-01-25 17:18:50 +000080 At = (const unsigned char *)((intptr_t)(At+3) & (~3UL));
Misha Brukman8a96c532005-04-21 21:44:41 +000081 if (At > Save)
Reid Spencer38d54be2004-08-17 07:45:14 +000082 if (Handler) Handler->handleAlignment(At - Save);
Misha Brukman8a96c532005-04-21 21:44:41 +000083 if (At > BlockEnd)
Reid Spencer38d54be2004-08-17 07:45:14 +000084 error("Ran out of data while aligning!");
85 }
Reid Spencer060d25d2004-06-29 23:29:38 +000086}
87
Reid Spencer04cde2c2004-07-04 11:33:49 +000088/// Read a whole unsigned integer
Reid Spencer060d25d2004-06-29 23:29:38 +000089inline unsigned BytecodeReader::read_uint() {
Misha Brukman8a96c532005-04-21 21:44:41 +000090 if (At+4 > BlockEnd)
Reid Spencer24399722004-07-09 22:21:33 +000091 error("Ran out of data reading uint!");
Reid Spencer060d25d2004-06-29 23:29:38 +000092 At += 4;
93 return At[-4] | (At[-3] << 8) | (At[-2] << 16) | (At[-1] << 24);
94}
95
Reid Spencer04cde2c2004-07-04 11:33:49 +000096/// Read a variable-bit-rate encoded unsigned integer
Reid Spencer060d25d2004-06-29 23:29:38 +000097inline unsigned BytecodeReader::read_vbr_uint() {
98 unsigned Shift = 0;
99 unsigned Result = 0;
100 BufPtr Save = At;
Misha Brukman8a96c532005-04-21 21:44:41 +0000101
Reid Spencer060d25d2004-06-29 23:29:38 +0000102 do {
Misha Brukman8a96c532005-04-21 21:44:41 +0000103 if (At == BlockEnd)
Reid Spencer24399722004-07-09 22:21:33 +0000104 error("Ran out of data reading vbr_uint!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000105 Result |= (unsigned)((*At++) & 0x7F) << Shift;
106 Shift += 7;
107 } while (At[-1] & 0x80);
Reid Spencer04cde2c2004-07-04 11:33:49 +0000108 if (Handler) Handler->handleVBR32(At-Save);
Reid Spencer060d25d2004-06-29 23:29:38 +0000109 return Result;
110}
111
Reid Spencer04cde2c2004-07-04 11:33:49 +0000112/// Read a variable-bit-rate encoded unsigned 64-bit integer.
Reid Spencer060d25d2004-06-29 23:29:38 +0000113inline uint64_t BytecodeReader::read_vbr_uint64() {
114 unsigned Shift = 0;
115 uint64_t Result = 0;
116 BufPtr Save = At;
Misha Brukman8a96c532005-04-21 21:44:41 +0000117
Reid Spencer060d25d2004-06-29 23:29:38 +0000118 do {
Misha Brukman8a96c532005-04-21 21:44:41 +0000119 if (At == BlockEnd)
Reid Spencer24399722004-07-09 22:21:33 +0000120 error("Ran out of data reading vbr_uint64!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000121 Result |= (uint64_t)((*At++) & 0x7F) << Shift;
122 Shift += 7;
123 } while (At[-1] & 0x80);
Reid Spencer04cde2c2004-07-04 11:33:49 +0000124 if (Handler) Handler->handleVBR64(At-Save);
Reid Spencer060d25d2004-06-29 23:29:38 +0000125 return Result;
126}
127
Reid Spencer04cde2c2004-07-04 11:33:49 +0000128/// Read a variable-bit-rate encoded signed 64-bit integer.
Reid Spencer060d25d2004-06-29 23:29:38 +0000129inline int64_t BytecodeReader::read_vbr_int64() {
130 uint64_t R = read_vbr_uint64();
131 if (R & 1) {
132 if (R != 1)
133 return -(int64_t)(R >> 1);
134 else // There is no such thing as -0 with integers. "-0" really means
135 // 0x8000000000000000.
136 return 1LL << 63;
137 } else
138 return (int64_t)(R >> 1);
139}
140
Reid Spencer04cde2c2004-07-04 11:33:49 +0000141/// Read a pascal-style string (length followed by text)
Reid Spencer060d25d2004-06-29 23:29:38 +0000142inline std::string BytecodeReader::read_str() {
143 unsigned Size = read_vbr_uint();
144 const unsigned char *OldAt = At;
145 At += Size;
146 if (At > BlockEnd) // Size invalid?
Reid Spencer24399722004-07-09 22:21:33 +0000147 error("Ran out of data reading a string!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000148 return std::string((char*)OldAt, Size);
149}
150
Reid Spencer04cde2c2004-07-04 11:33:49 +0000151/// Read an arbitrary block of data
Reid Spencer060d25d2004-06-29 23:29:38 +0000152inline void BytecodeReader::read_data(void *Ptr, void *End) {
153 unsigned char *Start = (unsigned char *)Ptr;
154 unsigned Amount = (unsigned char *)End - Start;
Misha Brukman8a96c532005-04-21 21:44:41 +0000155 if (At+Amount > BlockEnd)
Reid Spencer24399722004-07-09 22:21:33 +0000156 error("Ran out of data!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000157 std::copy(At, At+Amount, Start);
158 At += Amount;
159}
160
Reid Spencer46b002c2004-07-11 17:28:43 +0000161/// Read a float value in little-endian order
162inline void BytecodeReader::read_float(float& FloatVal) {
Reid Spencerada16182004-07-25 21:36:26 +0000163 /// FIXME: This isn't optimal, it has size problems on some platforms
164 /// where FP is not IEEE.
Jim Laskeycb6682f2005-08-17 19:34:49 +0000165 FloatVal = BitsToFloat(At[0] | (At[1] << 8) | (At[2] << 16) | (At[3] << 24));
Reid Spencerada16182004-07-25 21:36:26 +0000166 At+=sizeof(uint32_t);
Reid Spencer46b002c2004-07-11 17:28:43 +0000167}
168
169/// Read a double value in little-endian order
170inline void BytecodeReader::read_double(double& DoubleVal) {
Reid Spencerada16182004-07-25 21:36:26 +0000171 /// FIXME: This isn't optimal, it has size problems on some platforms
172 /// where FP is not IEEE.
Jim Laskeycb6682f2005-08-17 19:34:49 +0000173 DoubleVal = BitsToDouble((uint64_t(At[0]) << 0) | (uint64_t(At[1]) << 8) |
174 (uint64_t(At[2]) << 16) | (uint64_t(At[3]) << 24) |
175 (uint64_t(At[4]) << 32) | (uint64_t(At[5]) << 40) |
176 (uint64_t(At[6]) << 48) | (uint64_t(At[7]) << 56));
Reid Spencerada16182004-07-25 21:36:26 +0000177 At+=sizeof(uint64_t);
Reid Spencer46b002c2004-07-11 17:28:43 +0000178}
179
Reid Spencer04cde2c2004-07-04 11:33:49 +0000180/// Read a block header and obtain its type and size
Reid Spencer060d25d2004-06-29 23:29:38 +0000181inline void BytecodeReader::read_block(unsigned &Type, unsigned &Size) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000182 if ( hasLongBlockHeaders ) {
183 Type = read_uint();
184 Size = read_uint();
185 switch (Type) {
Misha Brukman8a96c532005-04-21 21:44:41 +0000186 case BytecodeFormat::Reserved_DoNotUse :
Reid Spencerad89bd62004-07-25 18:07:36 +0000187 error("Reserved_DoNotUse used as Module Type?");
Reid Spencer5b472d92004-08-21 20:49:23 +0000188 Type = BytecodeFormat::ModuleBlockID; break;
Misha Brukman8a96c532005-04-21 21:44:41 +0000189 case BytecodeFormat::Module:
Reid Spencerad89bd62004-07-25 18:07:36 +0000190 Type = BytecodeFormat::ModuleBlockID; break;
191 case BytecodeFormat::Function:
192 Type = BytecodeFormat::FunctionBlockID; break;
193 case BytecodeFormat::ConstantPool:
194 Type = BytecodeFormat::ConstantPoolBlockID; break;
195 case BytecodeFormat::SymbolTable:
196 Type = BytecodeFormat::SymbolTableBlockID; break;
197 case BytecodeFormat::ModuleGlobalInfo:
198 Type = BytecodeFormat::ModuleGlobalInfoBlockID; break;
199 case BytecodeFormat::GlobalTypePlane:
200 Type = BytecodeFormat::GlobalTypePlaneBlockID; break;
201 case BytecodeFormat::InstructionList:
202 Type = BytecodeFormat::InstructionListBlockID; break;
203 case BytecodeFormat::CompactionTable:
204 Type = BytecodeFormat::CompactionTableBlockID; break;
205 case BytecodeFormat::BasicBlock:
206 /// This block type isn't used after version 1.1. However, we have to
207 /// still allow the value in case this is an old bc format file.
208 /// We just let its value creep thru.
209 break;
210 default:
Reid Spencer5b472d92004-08-21 20:49:23 +0000211 error("Invalid block id found: " + utostr(Type));
Reid Spencerad89bd62004-07-25 18:07:36 +0000212 break;
213 }
214 } else {
215 Size = read_uint();
216 Type = Size & 0x1F; // mask low order five bits
217 Size >>= 5; // get rid of five low order bits, leaving high 27
218 }
Reid Spencer060d25d2004-06-29 23:29:38 +0000219 BlockStart = At;
Reid Spencer46b002c2004-07-11 17:28:43 +0000220 if (At + Size > BlockEnd)
Reid Spencer24399722004-07-09 22:21:33 +0000221 error("Attempt to size a block past end of memory");
Reid Spencer060d25d2004-06-29 23:29:38 +0000222 BlockEnd = At + Size;
Reid Spencer46b002c2004-07-11 17:28:43 +0000223 if (Handler) Handler->handleBlock(Type, BlockStart, Size);
Reid Spencer04cde2c2004-07-04 11:33:49 +0000224}
225
226
227/// In LLVM 1.2 and before, Types were derived from Value and so they were
228/// written as part of the type planes along with any other Value. In LLVM
229/// 1.3 this changed so that Type does not derive from Value. Consequently,
230/// the BytecodeReader's containers for Values can't contain Types because
231/// there's no inheritance relationship. This means that the "Type Type"
Misha Brukman8a96c532005-04-21 21:44:41 +0000232/// plane is defunct along with the Type::TypeTyID TypeID. In LLVM 1.3
233/// whenever a bytecode construct must have both types and values together,
Reid Spencer04cde2c2004-07-04 11:33:49 +0000234/// the types are always read/written first and then the Values. Furthermore
235/// since Type::TypeTyID no longer exists, its value (12) now corresponds to
236/// Type::LabelTyID. In order to overcome this we must "sanitize" all the
237/// type TypeIDs we encounter. For LLVM 1.3 bytecode files, there's no change.
238/// For LLVM 1.2 and before, this function will decrement the type id by
239/// one to account for the missing Type::TypeTyID enumerator if the value is
240/// larger than 12 (Type::LabelTyID). If the value is exactly 12, then this
241/// function returns true, otherwise false. This helps detect situations
242/// where the pre 1.3 bytecode is indicating that what follows is a type.
Misha Brukman8a96c532005-04-21 21:44:41 +0000243/// @returns true iff type id corresponds to pre 1.3 "type type"
Reid Spencer46b002c2004-07-11 17:28:43 +0000244inline bool BytecodeReader::sanitizeTypeId(unsigned &TypeId) {
245 if (hasTypeDerivedFromValue) { /// do nothing if 1.3 or later
246 if (TypeId == Type::LabelTyID) {
Reid Spencer04cde2c2004-07-04 11:33:49 +0000247 TypeId = Type::VoidTyID; // sanitize it
248 return true; // indicate we got TypeTyID in pre 1.3 bytecode
Reid Spencer46b002c2004-07-11 17:28:43 +0000249 } else if (TypeId > Type::LabelTyID)
Reid Spencer04cde2c2004-07-04 11:33:49 +0000250 --TypeId; // shift all planes down because type type plane is missing
251 }
252 return false;
253}
254
255/// Reads a vbr uint to read in a type id and does the necessary
256/// conversion on it by calling sanitizeTypeId.
257/// @returns true iff \p TypeId read corresponds to a pre 1.3 "type type"
258/// @see sanitizeTypeId
259inline bool BytecodeReader::read_typeid(unsigned &TypeId) {
260 TypeId = read_vbr_uint();
Reid Spencerad89bd62004-07-25 18:07:36 +0000261 if ( !has32BitTypes )
262 if ( TypeId == 0x00FFFFFF )
263 TypeId = read_vbr_uint();
Reid Spencer04cde2c2004-07-04 11:33:49 +0000264 return sanitizeTypeId(TypeId);
Reid Spencer060d25d2004-06-29 23:29:38 +0000265}
266
267//===----------------------------------------------------------------------===//
268// IR Lookup Methods
269//===----------------------------------------------------------------------===//
270
Reid Spencer04cde2c2004-07-04 11:33:49 +0000271/// Determine if a type id has an implicit null value
Reid Spencer46b002c2004-07-11 17:28:43 +0000272inline bool BytecodeReader::hasImplicitNull(unsigned TyID) {
Reid Spencer060d25d2004-06-29 23:29:38 +0000273 if (!hasExplicitPrimitiveZeros)
Reid Spencer04cde2c2004-07-04 11:33:49 +0000274 return TyID != Type::LabelTyID && TyID != Type::VoidTyID;
Reid Spencer060d25d2004-06-29 23:29:38 +0000275 return TyID >= Type::FirstDerivedTyID;
276}
277
Reid Spencer04cde2c2004-07-04 11:33:49 +0000278/// Obtain a type given a typeid and account for things like compaction tables,
279/// function level vs module level, and the offsetting for the primitive types.
Reid Spencer060d25d2004-06-29 23:29:38 +0000280const Type *BytecodeReader::getType(unsigned ID) {
Chris Lattner89e02532004-01-18 21:08:15 +0000281 if (ID < Type::FirstDerivedTyID)
Chris Lattnerf70c22b2004-06-17 18:19:28 +0000282 if (const Type *T = Type::getPrimitiveType((Type::TypeID)ID))
Chris Lattner927b1852003-10-09 20:22:47 +0000283 return T; // Asked for a primitive type...
Chris Lattner36392bc2003-10-08 21:18:57 +0000284
285 // Otherwise, derived types need offset...
Chris Lattner89e02532004-01-18 21:08:15 +0000286 ID -= Type::FirstDerivedTyID;
287
Reid Spencer060d25d2004-06-29 23:29:38 +0000288 if (!CompactionTypes.empty()) {
289 if (ID >= CompactionTypes.size())
Reid Spencer24399722004-07-09 22:21:33 +0000290 error("Type ID out of range for compaction table!");
Chris Lattner45b5dd22004-08-03 23:41:28 +0000291 return CompactionTypes[ID].first;
Chris Lattner89e02532004-01-18 21:08:15 +0000292 }
Chris Lattner36392bc2003-10-08 21:18:57 +0000293
294 // Is it a module-level type?
Reid Spencer46b002c2004-07-11 17:28:43 +0000295 if (ID < ModuleTypes.size())
296 return ModuleTypes[ID].get();
Chris Lattner36392bc2003-10-08 21:18:57 +0000297
Reid Spencer46b002c2004-07-11 17:28:43 +0000298 // Nope, is it a function-level type?
299 ID -= ModuleTypes.size();
300 if (ID < FunctionTypes.size())
301 return FunctionTypes[ID].get();
Chris Lattner36392bc2003-10-08 21:18:57 +0000302
Reid Spencer46b002c2004-07-11 17:28:43 +0000303 error("Illegal type reference!");
304 return Type::VoidTy;
Chris Lattner00950542001-06-06 20:29:01 +0000305}
306
Reid Spencer04cde2c2004-07-04 11:33:49 +0000307/// Get a sanitized type id. This just makes sure that the \p ID
308/// is both sanitized and not the "type type" of pre-1.3 bytecode.
309/// @see sanitizeTypeId
310inline const Type* BytecodeReader::getSanitizedType(unsigned& ID) {
Reid Spencer46b002c2004-07-11 17:28:43 +0000311 if (sanitizeTypeId(ID))
Reid Spencer24399722004-07-09 22:21:33 +0000312 error("Invalid type id encountered");
Reid Spencer04cde2c2004-07-04 11:33:49 +0000313 return getType(ID);
314}
315
316/// This method just saves some coding. It uses read_typeid to read
Reid Spencer24399722004-07-09 22:21:33 +0000317/// in a sanitized type id, errors that its not the type type, and
Reid Spencer04cde2c2004-07-04 11:33:49 +0000318/// then calls getType to return the type value.
319inline const Type* BytecodeReader::readSanitizedType() {
320 unsigned ID;
Reid Spencer46b002c2004-07-11 17:28:43 +0000321 if (read_typeid(ID))
322 error("Invalid type id encountered");
Reid Spencer04cde2c2004-07-04 11:33:49 +0000323 return getType(ID);
324}
325
326/// Get the slot number associated with a type accounting for primitive
327/// types, compaction tables, and function level vs module level.
Reid Spencer060d25d2004-06-29 23:29:38 +0000328unsigned BytecodeReader::getTypeSlot(const Type *Ty) {
329 if (Ty->isPrimitiveType())
330 return Ty->getTypeID();
331
332 // Scan the compaction table for the type if needed.
333 if (!CompactionTypes.empty()) {
Chris Lattner45b5dd22004-08-03 23:41:28 +0000334 for (unsigned i = 0, e = CompactionTypes.size(); i != e; ++i)
335 if (CompactionTypes[i].first == Ty)
Misha Brukman8a96c532005-04-21 21:44:41 +0000336 return Type::FirstDerivedTyID + i;
Reid Spencer060d25d2004-06-29 23:29:38 +0000337
Chris Lattner45b5dd22004-08-03 23:41:28 +0000338 error("Couldn't find type specified in compaction table!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000339 }
340
341 // Check the function level types first...
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000342 TypeListTy::iterator I = std::find(FunctionTypes.begin(),
343 FunctionTypes.end(), Ty);
Reid Spencer060d25d2004-06-29 23:29:38 +0000344
345 if (I != FunctionTypes.end())
Misha Brukman8a96c532005-04-21 21:44:41 +0000346 return Type::FirstDerivedTyID + ModuleTypes.size() +
Reid Spencer46b002c2004-07-11 17:28:43 +0000347 (&*I - &FunctionTypes[0]);
Reid Spencer060d25d2004-06-29 23:29:38 +0000348
Chris Lattnereebac5f2005-10-03 21:26:53 +0000349 // If we don't have our cache yet, build it now.
350 if (ModuleTypeIDCache.empty()) {
351 unsigned N = 0;
352 ModuleTypeIDCache.reserve(ModuleTypes.size());
353 for (TypeListTy::iterator I = ModuleTypes.begin(), E = ModuleTypes.end();
354 I != E; ++I, ++N)
355 ModuleTypeIDCache.push_back(std::make_pair(*I, N));
356
357 std::sort(ModuleTypeIDCache.begin(), ModuleTypeIDCache.end());
358 }
359
360 // Binary search the cache for the entry.
361 std::vector<std::pair<const Type*, unsigned> >::iterator IT =
362 std::lower_bound(ModuleTypeIDCache.begin(), ModuleTypeIDCache.end(),
363 std::make_pair(Ty, 0U));
364 if (IT == ModuleTypeIDCache.end() || IT->first != Ty)
Reid Spencer24399722004-07-09 22:21:33 +0000365 error("Didn't find type in ModuleTypes.");
Chris Lattnereebac5f2005-10-03 21:26:53 +0000366
367 return Type::FirstDerivedTyID + IT->second;
Chris Lattner80b97342004-01-17 23:25:43 +0000368}
369
Reid Spencer04cde2c2004-07-04 11:33:49 +0000370/// This is just like getType, but when a compaction table is in use, it is
371/// ignored. It also ignores function level types.
372/// @see getType
Reid Spencer060d25d2004-06-29 23:29:38 +0000373const Type *BytecodeReader::getGlobalTableType(unsigned Slot) {
374 if (Slot < Type::FirstDerivedTyID) {
375 const Type *Ty = Type::getPrimitiveType((Type::TypeID)Slot);
Reid Spencer46b002c2004-07-11 17:28:43 +0000376 if (!Ty)
Reid Spencer24399722004-07-09 22:21:33 +0000377 error("Not a primitive type ID?");
Reid Spencer060d25d2004-06-29 23:29:38 +0000378 return Ty;
379 }
380 Slot -= Type::FirstDerivedTyID;
381 if (Slot >= ModuleTypes.size())
Reid Spencer24399722004-07-09 22:21:33 +0000382 error("Illegal compaction table type reference!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000383 return ModuleTypes[Slot];
Chris Lattner52e20b02003-03-19 20:54:26 +0000384}
385
Reid Spencer04cde2c2004-07-04 11:33:49 +0000386/// This is just like getTypeSlot, but when a compaction table is in use, it
387/// is ignored. It also ignores function level types.
Reid Spencer060d25d2004-06-29 23:29:38 +0000388unsigned BytecodeReader::getGlobalTableTypeSlot(const Type *Ty) {
389 if (Ty->isPrimitiveType())
390 return Ty->getTypeID();
Chris Lattnereebac5f2005-10-03 21:26:53 +0000391
392 // If we don't have our cache yet, build it now.
393 if (ModuleTypeIDCache.empty()) {
394 unsigned N = 0;
395 ModuleTypeIDCache.reserve(ModuleTypes.size());
396 for (TypeListTy::iterator I = ModuleTypes.begin(), E = ModuleTypes.end();
397 I != E; ++I, ++N)
398 ModuleTypeIDCache.push_back(std::make_pair(*I, N));
399
400 std::sort(ModuleTypeIDCache.begin(), ModuleTypeIDCache.end());
401 }
402
403 // Binary search the cache for the entry.
404 std::vector<std::pair<const Type*, unsigned> >::iterator IT =
405 std::lower_bound(ModuleTypeIDCache.begin(), ModuleTypeIDCache.end(),
406 std::make_pair(Ty, 0U));
407 if (IT == ModuleTypeIDCache.end() || IT->first != Ty)
Reid Spencer24399722004-07-09 22:21:33 +0000408 error("Didn't find type in ModuleTypes.");
Chris Lattnereebac5f2005-10-03 21:26:53 +0000409
410 return Type::FirstDerivedTyID + IT->second;
Reid Spencer060d25d2004-06-29 23:29:38 +0000411}
412
Misha Brukman8a96c532005-04-21 21:44:41 +0000413/// Retrieve a value of a given type and slot number, possibly creating
414/// it if it doesn't already exist.
Reid Spencer060d25d2004-06-29 23:29:38 +0000415Value * BytecodeReader::getValue(unsigned type, unsigned oNum, bool Create) {
Chris Lattner4ee8ef22003-10-08 22:52:54 +0000416 assert(type != Type::LabelTyID && "getValue() cannot get blocks!");
Chris Lattner00950542001-06-06 20:29:01 +0000417 unsigned Num = oNum;
Chris Lattner00950542001-06-06 20:29:01 +0000418
Chris Lattner89e02532004-01-18 21:08:15 +0000419 // If there is a compaction table active, it defines the low-level numbers.
420 // If not, the module values define the low-level numbers.
Reid Spencer060d25d2004-06-29 23:29:38 +0000421 if (CompactionValues.size() > type && !CompactionValues[type].empty()) {
422 if (Num < CompactionValues[type].size())
423 return CompactionValues[type][Num];
424 Num -= CompactionValues[type].size();
Chris Lattner89e02532004-01-18 21:08:15 +0000425 } else {
Reid Spencer060d25d2004-06-29 23:29:38 +0000426 // By default, the global type id is the type id passed in
Chris Lattner52f86d62004-01-20 00:54:06 +0000427 unsigned GlobalTyID = type;
Reid Spencer060d25d2004-06-29 23:29:38 +0000428
Chris Lattner45b5dd22004-08-03 23:41:28 +0000429 // If the type plane was compactified, figure out the global type ID by
430 // adding the derived type ids and the distance.
431 if (!CompactionTypes.empty() && type >= Type::FirstDerivedTyID)
432 GlobalTyID = CompactionTypes[type-Type::FirstDerivedTyID].second;
Chris Lattner00950542001-06-06 20:29:01 +0000433
Reid Spencer060d25d2004-06-29 23:29:38 +0000434 if (hasImplicitNull(GlobalTyID)) {
Chris Lattneraba5ff52005-05-05 20:57:00 +0000435 const Type *Ty = getType(type);
436 if (!isa<OpaqueType>(Ty)) {
437 if (Num == 0)
438 return Constant::getNullValue(Ty);
439 --Num;
440 }
Chris Lattner89e02532004-01-18 21:08:15 +0000441 }
442
Chris Lattner52f86d62004-01-20 00:54:06 +0000443 if (GlobalTyID < ModuleValues.size() && ModuleValues[GlobalTyID]) {
444 if (Num < ModuleValues[GlobalTyID]->size())
Reid Spencer04cde2c2004-07-04 11:33:49 +0000445 return ModuleValues[GlobalTyID]->getOperand(Num);
Chris Lattner52f86d62004-01-20 00:54:06 +0000446 Num -= ModuleValues[GlobalTyID]->size();
Chris Lattner89e02532004-01-18 21:08:15 +0000447 }
Chris Lattner52e20b02003-03-19 20:54:26 +0000448 }
449
Misha Brukman8a96c532005-04-21 21:44:41 +0000450 if (FunctionValues.size() > type &&
451 FunctionValues[type] &&
Reid Spencer060d25d2004-06-29 23:29:38 +0000452 Num < FunctionValues[type]->size())
453 return FunctionValues[type]->getOperand(Num);
Chris Lattner00950542001-06-06 20:29:01 +0000454
Chris Lattner74734132002-08-17 22:01:27 +0000455 if (!Create) return 0; // Do not create a placeholder?
Chris Lattner00950542001-06-06 20:29:01 +0000456
Reid Spencer551ccae2004-09-01 22:55:40 +0000457 // Did we already create a place holder?
Chris Lattner8eb10ce2003-10-09 06:05:40 +0000458 std::pair<unsigned,unsigned> KeyValue(type, oNum);
Reid Spencer060d25d2004-06-29 23:29:38 +0000459 ForwardReferenceMap::iterator I = ForwardReferences.lower_bound(KeyValue);
Chris Lattner8eb10ce2003-10-09 06:05:40 +0000460 if (I != ForwardReferences.end() && I->first == KeyValue)
461 return I->second; // We have already created this placeholder
462
Reid Spencer551ccae2004-09-01 22:55:40 +0000463 // If the type exists (it should)
464 if (const Type* Ty = getType(type)) {
465 // Create the place holder
466 Value *Val = new Argument(Ty);
467 ForwardReferences.insert(I, std::make_pair(KeyValue, Val));
468 return Val;
469 }
Reid Spencer233fe722006-08-22 16:09:19 +0000470 error("Can't create placeholder for value of type slot #" + utostr(type));
471 return 0; // just silence warning, error calls longjmp
Chris Lattner00950542001-06-06 20:29:01 +0000472}
473
Misha Brukman8a96c532005-04-21 21:44:41 +0000474/// This is just like getValue, but when a compaction table is in use, it
475/// is ignored. Also, no forward references or other fancy features are
Reid Spencer04cde2c2004-07-04 11:33:49 +0000476/// supported.
Chris Lattner2c6c14d2004-08-04 00:19:23 +0000477Value* BytecodeReader::getGlobalTableValue(unsigned TyID, unsigned SlotNo) {
478 if (SlotNo == 0)
479 return Constant::getNullValue(getType(TyID));
480
481 if (!CompactionTypes.empty() && TyID >= Type::FirstDerivedTyID) {
482 TyID -= Type::FirstDerivedTyID;
483 if (TyID >= CompactionTypes.size())
484 error("Type ID out of range for compaction table!");
485 TyID = CompactionTypes[TyID].second;
Reid Spencer060d25d2004-06-29 23:29:38 +0000486 }
487
Chris Lattner2c6c14d2004-08-04 00:19:23 +0000488 --SlotNo;
489
Reid Spencer060d25d2004-06-29 23:29:38 +0000490 if (TyID >= ModuleValues.size() || ModuleValues[TyID] == 0 ||
491 SlotNo >= ModuleValues[TyID]->size()) {
Chris Lattner2c6c14d2004-08-04 00:19:23 +0000492 if (TyID >= ModuleValues.size() || ModuleValues[TyID] == 0)
493 error("Corrupt compaction table entry!"
Misha Brukman8a96c532005-04-21 21:44:41 +0000494 + utostr(TyID) + ", " + utostr(SlotNo) + ": "
Chris Lattner2c6c14d2004-08-04 00:19:23 +0000495 + utostr(ModuleValues.size()));
Misha Brukman8a96c532005-04-21 21:44:41 +0000496 else
Chris Lattner2c6c14d2004-08-04 00:19:23 +0000497 error("Corrupt compaction table entry!"
Misha Brukman8a96c532005-04-21 21:44:41 +0000498 + utostr(TyID) + ", " + utostr(SlotNo) + ": "
Chris Lattner2c6c14d2004-08-04 00:19:23 +0000499 + utostr(ModuleValues.size()) + ", "
Reid Spencer9a7e0c52004-08-04 22:56:46 +0000500 + utohexstr(reinterpret_cast<uint64_t>(((void*)ModuleValues[TyID])))
501 + ", "
Chris Lattner2c6c14d2004-08-04 00:19:23 +0000502 + utostr(ModuleValues[TyID]->size()));
Reid Spencer060d25d2004-06-29 23:29:38 +0000503 }
504 return ModuleValues[TyID]->getOperand(SlotNo);
505}
506
Reid Spencer04cde2c2004-07-04 11:33:49 +0000507/// Just like getValue, except that it returns a null pointer
508/// only on error. It always returns a constant (meaning that if the value is
509/// defined, but is not a constant, that is an error). If the specified
Misha Brukman8a96c532005-04-21 21:44:41 +0000510/// constant hasn't been parsed yet, a placeholder is defined and used.
Reid Spencer04cde2c2004-07-04 11:33:49 +0000511/// Later, after the real value is parsed, the placeholder is eliminated.
Reid Spencer060d25d2004-06-29 23:29:38 +0000512Constant* BytecodeReader::getConstantValue(unsigned TypeSlot, unsigned Slot) {
513 if (Value *V = getValue(TypeSlot, Slot, false))
514 if (Constant *C = dyn_cast<Constant>(V))
515 return C; // If we already have the value parsed, just return it
Reid Spencer060d25d2004-06-29 23:29:38 +0000516 else
Misha Brukman8a96c532005-04-21 21:44:41 +0000517 error("Value for slot " + utostr(Slot) +
Reid Spencera86037e2004-07-18 00:12:03 +0000518 " is expected to be a constant!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000519
Chris Lattner389bd042004-12-09 06:19:44 +0000520 std::pair<unsigned, unsigned> Key(TypeSlot, Slot);
Reid Spencer060d25d2004-06-29 23:29:38 +0000521 ConstantRefsType::iterator I = ConstantFwdRefs.lower_bound(Key);
522
523 if (I != ConstantFwdRefs.end() && I->first == Key) {
524 return I->second;
525 } else {
526 // Create a placeholder for the constant reference and
527 // keep track of the fact that we have a forward ref to recycle it
Chris Lattner389bd042004-12-09 06:19:44 +0000528 Constant *C = new ConstantPlaceHolder(getType(TypeSlot));
Misha Brukman8a96c532005-04-21 21:44:41 +0000529
Reid Spencer060d25d2004-06-29 23:29:38 +0000530 // Keep track of the fact that we have a forward ref to recycle it
531 ConstantFwdRefs.insert(I, std::make_pair(Key, C));
532 return C;
533 }
534}
535
536//===----------------------------------------------------------------------===//
537// IR Construction Methods
538//===----------------------------------------------------------------------===//
539
Reid Spencer04cde2c2004-07-04 11:33:49 +0000540/// As values are created, they are inserted into the appropriate place
541/// with this method. The ValueTable argument must be one of ModuleValues
542/// or FunctionValues data members of this class.
Misha Brukman8a96c532005-04-21 21:44:41 +0000543unsigned BytecodeReader::insertValue(Value *Val, unsigned type,
Reid Spencer46b002c2004-07-11 17:28:43 +0000544 ValueTable &ValueTab) {
Reid Spencer060d25d2004-06-29 23:29:38 +0000545 if (ValueTab.size() <= type)
546 ValueTab.resize(type+1);
547
548 if (!ValueTab[type]) ValueTab[type] = new ValueList();
549
550 ValueTab[type]->push_back(Val);
551
Chris Lattneraba5ff52005-05-05 20:57:00 +0000552 bool HasOffset = hasImplicitNull(type) && !isa<OpaqueType>(Val->getType());
Reid Spencer060d25d2004-06-29 23:29:38 +0000553 return ValueTab[type]->size()-1 + HasOffset;
554}
555
Reid Spencer04cde2c2004-07-04 11:33:49 +0000556/// Insert the arguments of a function as new values in the reader.
Reid Spencer46b002c2004-07-11 17:28:43 +0000557void BytecodeReader::insertArguments(Function* F) {
Reid Spencer060d25d2004-06-29 23:29:38 +0000558 const FunctionType *FT = F->getFunctionType();
Chris Lattnere4d5c442005-03-15 04:54:21 +0000559 Function::arg_iterator AI = F->arg_begin();
Reid Spencer060d25d2004-06-29 23:29:38 +0000560 for (FunctionType::param_iterator It = FT->param_begin();
561 It != FT->param_end(); ++It, ++AI)
562 insertValue(AI, getTypeSlot(AI->getType()), FunctionValues);
563}
564
Reid Spencer1628cec2006-10-26 06:15:43 +0000565// Convert previous opcode values into the current value and/or construct
566// the instruction. This function handles all *abnormal* cases for instruction
567// generation based on obsolete opcode values. The normal cases are handled
568// in ParseInstruction below. Generally this function just produces a new
569// Opcode value (first argument). In a few cases (VAArg, VANext) the upgrade
570// path requies that the instruction (sequence) be generated differently from
571// the normal case in order to preserve the original semantics. In these
572// cases the result of the function will be a non-zero Instruction pointer. In
573// all other cases, zero will be returned indicating that the *normal*
574// instruction generation should be used, but with the new Opcode value.
575//
576Instruction*
Reid Spencer6996feb2006-11-08 21:27:54 +0000577BytecodeReader::upgradeInstrOpcodes(
Reid Spencer1628cec2006-10-26 06:15:43 +0000578 unsigned &Opcode, ///< The old opcode, possibly updated by this function
579 std::vector<unsigned> &Oprnds, ///< The operands to the instruction
580 unsigned &iType, ///< The type code from the bytecode file
581 const Type* InstTy, ///< The type of the instruction
582 BasicBlock* BB ///< The basic block to insert into, if we need to
583) {
584
585 // First, short circuit this if no conversion is required. When signless
Reid Spencer6996feb2006-11-08 21:27:54 +0000586 // instructions were implemented the entire opcode sequence was revised in
587 // two stages: first Div/Rem became signed, then Shr/Cast/Setcc became
588 // signed. If all of these instructions are signed then we don't have to
589 // upgrade the opcode.
590 if (!hasSignlessDivRem && !hasSignlessShrCastSetcc)
Reid Spencer1628cec2006-10-26 06:15:43 +0000591 return 0; // The opcode is fine the way it is.
592
Reid Spencer6996feb2006-11-08 21:27:54 +0000593 // If this is a bytecode format that did not include the unreachable
594 // instruction, bump up the opcode number to adjust it.
595 if (hasNoUnreachableInst)
596 if (Opcode >= 6 && Opcode < 62)
597 ++Opcode;
598
599 // If this is bytecode version 6, that only had signed Rem and Div
600 // instructions, then we must compensate for those two instructions only.
601 // So that the switch statement below works, we're trying to turn this into
602 // a version 5 opcode. To do that we must adjust the opcode to 10 (Div) if its
603 // any of the UDiv, SDiv or FDiv instructions; or, adjust the opcode to
604 // 11 (Rem) if its any of the URem, SRem, or FRem instructions; or, simply
605 // decrement the instruction code if its beyond FRem.
606 if (!hasSignlessDivRem) {
607 // If its one of the signed Div/Rem opcodes, its fine the way it is
608 if (Opcode >= 10 && Opcode <= 12) // UDiv through FDiv
609 Opcode = 10; // Div
610 else if (Opcode >=13 && Opcode <= 15) // URem through FRem
611 Opcode = 11; // Rem
612 else if (Opcode >= 16 && Opcode <= 35) // And through Shr
613 // Adjust for new instruction codes
614 Opcode -= 4;
615 else if (Opcode >= 36 && Opcode <= 42) // Everything after Select
616 // In vers 6 bytecode we eliminated the placeholders for the obsolete
617 // VAARG and VANEXT instructions. Consequently those two slots were
618 // filled starting with Select (36) which was 34. So now we only need
619 // to subtract two. This circumvents hitting opcodes 32 and 33
620 Opcode -= 2;
621 else { // Opcode < 10 or > 42
622 // No upgrade necessary.
623 return 0;
624 }
625 }
626
Reid Spencer1628cec2006-10-26 06:15:43 +0000627 // Declare the resulting instruction we might build. In general we just
628 // change the Opcode argument but in a few cases we need to generate the
629 // Instruction here because the upgrade case is significantly different from
630 // the normal case.
631 Instruction *Result = 0;
632
Reid Spencer1628cec2006-10-26 06:15:43 +0000633 // We're dealing with an upgrade situation. For each of the opcode values,
634 // perform the necessary conversion.
635 switch (Opcode) {
636 default: // Error
637 // This switch statement provides cases for all known opcodes prior to
638 // version 6 bytecode format. We know we're in an upgrade situation so
639 // if there isn't a match in this switch, then something is horribly
640 // wrong.
641 error("Unknown obsolete opcode encountered.");
642 break;
643 case 1: // Ret
644 Opcode = Instruction::Ret;
645 break;
646 case 2: // Br
647 Opcode = Instruction::Br;
648 break;
649 case 3: // Switch
650 Opcode = Instruction::Switch;
651 break;
652 case 4: // Invoke
653 Opcode = Instruction::Invoke;
654 break;
655 case 5: // Unwind
656 Opcode = Instruction::Unwind;
657 break;
658 case 6: // Unreachable
659 Opcode = Instruction::Unreachable;
660 break;
661 case 7: // Add
662 Opcode = Instruction::Add;
663 break;
664 case 8: // Sub
665 Opcode = Instruction::Sub;
666 break;
667 case 9: // Mul
668 Opcode = Instruction::Mul;
669 break;
670 case 10: // Div
671 // The type of the instruction is based on the operands. We need to select
672 // fdiv, udiv or sdiv based on that type. The iType values are hardcoded
673 // to the values used in bytecode version 5 (and prior) because it is
674 // likely these codes will change in future versions of LLVM.
675 if (iType == 10 || iType == 11 )
676 Opcode = Instruction::FDiv;
677 else if (iType >= 2 && iType <= 9 && iType % 2 != 0)
678 Opcode = Instruction::SDiv;
679 else
680 Opcode = Instruction::UDiv;
681 break;
682
683 case 11: // Rem
Reid Spencer0a783f72006-11-02 01:53:59 +0000684 // As with "Div", make the signed/unsigned or floating point Rem
685 // instruction choice based on the type of the operands.
686 if (iType == 10 || iType == 11)
687 Opcode = Instruction::FRem;
688 else if (iType >= 2 && iType <= 9 && iType % 2 != 0)
689 Opcode = Instruction::SRem;
690 else
691 Opcode = Instruction::URem;
Reid Spencer1628cec2006-10-26 06:15:43 +0000692 break;
693 case 12: // And
694 Opcode = Instruction::And;
695 break;
696 case 13: // Or
697 Opcode = Instruction::Or;
698 break;
699 case 14: // Xor
700 Opcode = Instruction::Xor;
701 break;
702 case 15: // SetEQ
703 Opcode = Instruction::SetEQ;
704 break;
705 case 16: // SetNE
706 Opcode = Instruction::SetNE;
707 break;
708 case 17: // SetLE
709 Opcode = Instruction::SetLE;
710 break;
711 case 18: // SetGE
712 Opcode = Instruction::SetGE;
713 break;
714 case 19: // SetLT
715 Opcode = Instruction::SetLT;
716 break;
717 case 20: // SetGT
718 Opcode = Instruction::SetGT;
719 break;
720 case 21: // Malloc
721 Opcode = Instruction::Malloc;
722 break;
723 case 22: // Free
724 Opcode = Instruction::Free;
725 break;
726 case 23: // Alloca
727 Opcode = Instruction::Alloca;
728 break;
729 case 24: // Load
730 Opcode = Instruction::Load;
731 break;
732 case 25: // Store
733 Opcode = Instruction::Store;
734 break;
735 case 26: // GetElementPtr
736 Opcode = Instruction::GetElementPtr;
737 break;
738 case 27: // PHI
739 Opcode = Instruction::PHI;
740 break;
741 case 28: // Cast
742 Opcode = Instruction::Cast;
743 break;
744 case 29: // Call
745 Opcode = Instruction::Call;
746 break;
747 case 30: // Shl
748 Opcode = Instruction::Shl;
749 break;
750 case 31: // Shr
Reid Spencer3822ff52006-11-08 06:47:33 +0000751 // The type of the instruction is based on the operands. We need to
752 // select ashr or lshr based on that type. The iType values are hardcoded
753 // to the values used in bytecode version 5 (and prior) because it is
754 // likely these codes will change in future versions of LLVM. This if
755 // statement says "if (integer type and signed)"
756 if (iType >= 2 && iType <= 9 && iType % 2 != 0)
757 Opcode = Instruction::AShr;
758 else
759 Opcode = Instruction::LShr;
Reid Spencer1628cec2006-10-26 06:15:43 +0000760 break;
761 case 32: { //VANext_old ( <= llvm 1.5 )
762 const Type* ArgTy = getValue(iType, Oprnds[0])->getType();
763 Function* NF = TheModule->getOrInsertFunction(
764 "llvm.va_copy", ArgTy, ArgTy, (Type *)0);
765
766 // In llvm 1.6 the VANext instruction was dropped because it was only
767 // necessary to have a VAArg instruction. The code below transforms an
768 // old vanext instruction into the equivalent code given only the
769 // availability of the new vaarg instruction. Essentially, the transform
770 // is as follows:
771 // b = vanext a, t ->
772 // foo = alloca 1 of t
773 // bar = vacopy a
774 // store bar -> foo
775 // tmp = vaarg foo, t
776 // b = load foo
777 AllocaInst* foo = new AllocaInst(ArgTy, 0, "vanext.fix");
778 BB->getInstList().push_back(foo);
779 CallInst* bar = new CallInst(NF, getValue(iType, Oprnds[0]));
780 BB->getInstList().push_back(bar);
781 BB->getInstList().push_back(new StoreInst(bar, foo));
782 Instruction* tmp = new VAArgInst(foo, getSanitizedType(Oprnds[1]));
783 BB->getInstList().push_back(tmp);
784 Result = new LoadInst(foo);
785 break;
786 }
787 case 33: { //VAArg_old
788 const Type* ArgTy = getValue(iType, Oprnds[0])->getType();
789 Function* NF = TheModule->getOrInsertFunction(
790 "llvm.va_copy", ArgTy, ArgTy, (Type *)0);
791
792 // In llvm 1.6 the VAArg's instruction semantics were changed. The code
793 // below transforms an old vaarg instruction into the equivalent code
794 // given only the availability of the new vaarg instruction. Essentially,
795 // the transform is as follows:
796 // b = vaarg a, t ->
797 // foo = alloca 1 of t
798 // bar = vacopy a
799 // store bar -> foo
800 // b = vaarg foo, t
801 AllocaInst* foo = new AllocaInst(ArgTy, 0, "vaarg.fix");
802 BB->getInstList().push_back(foo);
803 CallInst* bar = new CallInst(NF, getValue(iType, Oprnds[0]));
804 BB->getInstList().push_back(bar);
805 BB->getInstList().push_back(new StoreInst(bar, foo));
806 Result = new VAArgInst(foo, getSanitizedType(Oprnds[1]));
807 break;
808 }
809 case 34: // Select
810 Opcode = Instruction::Select;
811 break;
812 case 35: // UserOp1
813 Opcode = Instruction::UserOp1;
814 break;
815 case 36: // UserOp2
816 Opcode = Instruction::UserOp2;
817 break;
818 case 37: // VAArg
819 Opcode = Instruction::VAArg;
820 break;
821 case 38: // ExtractElement
822 Opcode = Instruction::ExtractElement;
823 break;
824 case 39: // InsertElement
825 Opcode = Instruction::InsertElement;
826 break;
827 case 40: // ShuffleVector
828 Opcode = Instruction::ShuffleVector;
829 break;
830 case 56: // Invoke with encoded CC
831 case 57: // Invoke Fast CC
832 case 58: // Call with extra operand for calling conv
833 case 59: // tail call, Fast CC
834 case 60: // normal call, Fast CC
835 case 61: // tail call, C Calling Conv
836 case 62: // volatile load
837 case 63: // volatile store
838 // In all these cases, we pass the opcode through. The new version uses
839 // the same code (for now, this might change in 2.0). These are listed
840 // here to document the opcodes in use in vers 5 bytecode and to make it
841 // easier to migrate these opcodes in the future.
842 break;
843 }
844 return Result;
845}
846
Reid Spencer060d25d2004-06-29 23:29:38 +0000847//===----------------------------------------------------------------------===//
848// Bytecode Parsing Methods
849//===----------------------------------------------------------------------===//
850
Reid Spencer04cde2c2004-07-04 11:33:49 +0000851/// This method parses a single instruction. The instruction is
852/// inserted at the end of the \p BB provided. The arguments of
Misha Brukman44666b12004-09-28 16:57:46 +0000853/// the instruction are provided in the \p Oprnds vector.
Reid Spencer060d25d2004-06-29 23:29:38 +0000854void BytecodeReader::ParseInstruction(std::vector<unsigned> &Oprnds,
Reid Spencer46b002c2004-07-11 17:28:43 +0000855 BasicBlock* BB) {
Reid Spencer060d25d2004-06-29 23:29:38 +0000856 BufPtr SaveAt = At;
857
858 // Clear instruction data
859 Oprnds.clear();
860 unsigned iType = 0;
861 unsigned Opcode = 0;
862 unsigned Op = read_uint();
863
864 // bits Instruction format: Common to all formats
865 // --------------------------
866 // 01-00: Opcode type, fixed to 1.
867 // 07-02: Opcode
868 Opcode = (Op >> 2) & 63;
869 Oprnds.resize((Op >> 0) & 03);
870
871 // Extract the operands
872 switch (Oprnds.size()) {
873 case 1:
874 // bits Instruction format:
875 // --------------------------
876 // 19-08: Resulting type plane
877 // 31-20: Operand #1 (if set to (2^12-1), then zero operands)
878 //
879 iType = (Op >> 8) & 4095;
880 Oprnds[0] = (Op >> 20) & 4095;
881 if (Oprnds[0] == 4095) // Handle special encoding for 0 operands...
882 Oprnds.resize(0);
883 break;
884 case 2:
885 // bits Instruction format:
886 // --------------------------
887 // 15-08: Resulting type plane
888 // 23-16: Operand #1
Misha Brukman8a96c532005-04-21 21:44:41 +0000889 // 31-24: Operand #2
Reid Spencer060d25d2004-06-29 23:29:38 +0000890 //
891 iType = (Op >> 8) & 255;
892 Oprnds[0] = (Op >> 16) & 255;
893 Oprnds[1] = (Op >> 24) & 255;
894 break;
895 case 3:
896 // bits Instruction format:
897 // --------------------------
898 // 13-08: Resulting type plane
899 // 19-14: Operand #1
900 // 25-20: Operand #2
901 // 31-26: Operand #3
902 //
903 iType = (Op >> 8) & 63;
904 Oprnds[0] = (Op >> 14) & 63;
905 Oprnds[1] = (Op >> 20) & 63;
906 Oprnds[2] = (Op >> 26) & 63;
907 break;
908 case 0:
909 At -= 4; // Hrm, try this again...
910 Opcode = read_vbr_uint();
911 Opcode >>= 2;
912 iType = read_vbr_uint();
913
914 unsigned NumOprnds = read_vbr_uint();
915 Oprnds.resize(NumOprnds);
916
917 if (NumOprnds == 0)
Reid Spencer24399722004-07-09 22:21:33 +0000918 error("Zero-argument instruction found; this is invalid.");
Reid Spencer060d25d2004-06-29 23:29:38 +0000919
920 for (unsigned i = 0; i != NumOprnds; ++i)
921 Oprnds[i] = read_vbr_uint();
922 align32();
923 break;
924 }
925
Reid Spencer04cde2c2004-07-04 11:33:49 +0000926 const Type *InstTy = getSanitizedType(iType);
Reid Spencer060d25d2004-06-29 23:29:38 +0000927
Reid Spencer1628cec2006-10-26 06:15:43 +0000928 // Make the necessary adjustments for dealing with backwards compatibility
929 // of opcodes.
930 Instruction* Result =
Reid Spencer6996feb2006-11-08 21:27:54 +0000931 upgradeInstrOpcodes(Opcode, Oprnds, iType, InstTy, BB);
Reid Spencer1628cec2006-10-26 06:15:43 +0000932
Reid Spencer46b002c2004-07-11 17:28:43 +0000933 // We have enough info to inform the handler now.
Reid Spencer1628cec2006-10-26 06:15:43 +0000934 if (Handler)
935 Handler->handleInstruction(Opcode, InstTy, Oprnds, At-SaveAt);
Reid Spencer060d25d2004-06-29 23:29:38 +0000936
Reid Spencer1628cec2006-10-26 06:15:43 +0000937 // If the backwards compatibility code didn't produce an instruction then
938 // we do the *normal* thing ..
939 if (!Result) {
940 // First, handle the easy binary operators case
941 if (Opcode >= Instruction::BinaryOpsBegin &&
942 Opcode < Instruction::BinaryOpsEnd && Oprnds.size() == 2)
943 Result = BinaryOperator::create(Instruction::BinaryOps(Opcode),
944 getValue(iType, Oprnds[0]),
945 getValue(iType, Oprnds[1]));
Reid Spencer060d25d2004-06-29 23:29:38 +0000946
Reid Spencer1628cec2006-10-26 06:15:43 +0000947 // Indicate that we don't think this is a call instruction (yet).
948 // Process based on the Opcode read
949 switch (Opcode) {
950 default: // There was an error, this shouldn't happen.
951 if (Result == 0)
952 error("Illegal instruction read!");
953 break;
954 case Instruction::VAArg:
955 if (Oprnds.size() != 2)
956 error("Invalid VAArg instruction!");
957 Result = new VAArgInst(getValue(iType, Oprnds[0]),
958 getSanitizedType(Oprnds[1]));
959 break;
960 case Instruction::ExtractElement: {
961 if (Oprnds.size() != 2)
962 error("Invalid extractelement instruction!");
963 Value *V1 = getValue(iType, Oprnds[0]);
964 Value *V2 = getValue(Type::UIntTyID, Oprnds[1]);
Chris Lattner59fecec2006-04-08 04:09:19 +0000965
Reid Spencer1628cec2006-10-26 06:15:43 +0000966 if (!ExtractElementInst::isValidOperands(V1, V2))
967 error("Invalid extractelement instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000968
Reid Spencer1628cec2006-10-26 06:15:43 +0000969 Result = new ExtractElementInst(V1, V2);
970 break;
Chris Lattnera65371e2006-05-26 18:42:34 +0000971 }
Reid Spencer1628cec2006-10-26 06:15:43 +0000972 case Instruction::InsertElement: {
973 const PackedType *PackedTy = dyn_cast<PackedType>(InstTy);
974 if (!PackedTy || Oprnds.size() != 3)
975 error("Invalid insertelement instruction!");
976
977 Value *V1 = getValue(iType, Oprnds[0]);
978 Value *V2 = getValue(getTypeSlot(PackedTy->getElementType()),Oprnds[1]);
979 Value *V3 = getValue(Type::UIntTyID, Oprnds[2]);
980
981 if (!InsertElementInst::isValidOperands(V1, V2, V3))
982 error("Invalid insertelement instruction!");
983 Result = new InsertElementInst(V1, V2, V3);
984 break;
985 }
986 case Instruction::ShuffleVector: {
987 const PackedType *PackedTy = dyn_cast<PackedType>(InstTy);
988 if (!PackedTy || Oprnds.size() != 3)
989 error("Invalid shufflevector instruction!");
990 Value *V1 = getValue(iType, Oprnds[0]);
991 Value *V2 = getValue(iType, Oprnds[1]);
992 const PackedType *EltTy =
993 PackedType::get(Type::UIntTy, PackedTy->getNumElements());
994 Value *V3 = getValue(getTypeSlot(EltTy), Oprnds[2]);
995 if (!ShuffleVectorInst::isValidOperands(V1, V2, V3))
996 error("Invalid shufflevector instruction!");
997 Result = new ShuffleVectorInst(V1, V2, V3);
998 break;
999 }
1000 case Instruction::Cast:
1001 if (Oprnds.size() != 2)
1002 error("Invalid Cast instruction!");
1003 Result = new CastInst(getValue(iType, Oprnds[0]),
1004 getSanitizedType(Oprnds[1]));
1005 break;
1006 case Instruction::Select:
1007 if (Oprnds.size() != 3)
1008 error("Invalid Select instruction!");
1009 Result = new SelectInst(getValue(Type::BoolTyID, Oprnds[0]),
1010 getValue(iType, Oprnds[1]),
1011 getValue(iType, Oprnds[2]));
1012 break;
1013 case Instruction::PHI: {
1014 if (Oprnds.size() == 0 || (Oprnds.size() & 1))
1015 error("Invalid phi node encountered!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001016
Reid Spencer1628cec2006-10-26 06:15:43 +00001017 PHINode *PN = new PHINode(InstTy);
1018 PN->reserveOperandSpace(Oprnds.size());
1019 for (unsigned i = 0, e = Oprnds.size(); i != e; i += 2)
1020 PN->addIncoming(
1021 getValue(iType, Oprnds[i]), getBasicBlock(Oprnds[i+1]));
1022 Result = PN;
1023 break;
1024 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001025
Reid Spencer1628cec2006-10-26 06:15:43 +00001026 case Instruction::Shl:
Reid Spencer3822ff52006-11-08 06:47:33 +00001027 case Instruction::LShr:
1028 case Instruction::AShr:
Reid Spencer1628cec2006-10-26 06:15:43 +00001029 Result = new ShiftInst(Instruction::OtherOps(Opcode),
1030 getValue(iType, Oprnds[0]),
1031 getValue(Type::UByteTyID, Oprnds[1]));
1032 break;
1033 case Instruction::Ret:
1034 if (Oprnds.size() == 0)
1035 Result = new ReturnInst();
1036 else if (Oprnds.size() == 1)
1037 Result = new ReturnInst(getValue(iType, Oprnds[0]));
1038 else
1039 error("Unrecognized instruction!");
1040 break;
1041
1042 case Instruction::Br:
1043 if (Oprnds.size() == 1)
1044 Result = new BranchInst(getBasicBlock(Oprnds[0]));
1045 else if (Oprnds.size() == 3)
1046 Result = new BranchInst(getBasicBlock(Oprnds[0]),
1047 getBasicBlock(Oprnds[1]), getValue(Type::BoolTyID , Oprnds[2]));
1048 else
1049 error("Invalid number of operands for a 'br' instruction!");
1050 break;
1051 case Instruction::Switch: {
1052 if (Oprnds.size() & 1)
1053 error("Switch statement with odd number of arguments!");
1054
1055 SwitchInst *I = new SwitchInst(getValue(iType, Oprnds[0]),
1056 getBasicBlock(Oprnds[1]),
1057 Oprnds.size()/2-1);
1058 for (unsigned i = 2, e = Oprnds.size(); i != e; i += 2)
1059 I->addCase(cast<ConstantInt>(getValue(iType, Oprnds[i])),
1060 getBasicBlock(Oprnds[i+1]));
1061 Result = I;
1062 break;
1063 }
1064 case 58: // Call with extra operand for calling conv
1065 case 59: // tail call, Fast CC
1066 case 60: // normal call, Fast CC
1067 case 61: // tail call, C Calling Conv
1068 case Instruction::Call: { // Normal Call, C Calling Convention
1069 if (Oprnds.size() == 0)
1070 error("Invalid call instruction encountered!");
1071
1072 Value *F = getValue(iType, Oprnds[0]);
1073
1074 unsigned CallingConv = CallingConv::C;
1075 bool isTailCall = false;
1076
1077 if (Opcode == 61 || Opcode == 59)
1078 isTailCall = true;
1079
1080 if (Opcode == 58) {
1081 isTailCall = Oprnds.back() & 1;
1082 CallingConv = Oprnds.back() >> 1;
1083 Oprnds.pop_back();
1084 } else if (Opcode == 59 || Opcode == 60) {
1085 CallingConv = CallingConv::Fast;
1086 }
1087
1088 // Check to make sure we have a pointer to function type
1089 const PointerType *PTy = dyn_cast<PointerType>(F->getType());
1090 if (PTy == 0) error("Call to non function pointer value!");
1091 const FunctionType *FTy = dyn_cast<FunctionType>(PTy->getElementType());
1092 if (FTy == 0) error("Call to non function pointer value!");
1093
1094 std::vector<Value *> Params;
1095 if (!FTy->isVarArg()) {
1096 FunctionType::param_iterator It = FTy->param_begin();
1097
1098 for (unsigned i = 1, e = Oprnds.size(); i != e; ++i) {
1099 if (It == FTy->param_end())
1100 error("Invalid call instruction!");
1101 Params.push_back(getValue(getTypeSlot(*It++), Oprnds[i]));
1102 }
1103 if (It != FTy->param_end())
Reid Spencer24399722004-07-09 22:21:33 +00001104 error("Invalid call instruction!");
Reid Spencer1628cec2006-10-26 06:15:43 +00001105 } else {
1106 Oprnds.erase(Oprnds.begin(), Oprnds.begin()+1);
1107
1108 unsigned FirstVariableOperand;
1109 if (Oprnds.size() < FTy->getNumParams())
1110 error("Call instruction missing operands!");
1111
1112 // Read all of the fixed arguments
1113 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
1114 Params.push_back(
1115 getValue(getTypeSlot(FTy->getParamType(i)),Oprnds[i]));
1116
1117 FirstVariableOperand = FTy->getNumParams();
1118
1119 if ((Oprnds.size()-FirstVariableOperand) & 1)
1120 error("Invalid call instruction!"); // Must be pairs of type/value
1121
1122 for (unsigned i = FirstVariableOperand, e = Oprnds.size();
1123 i != e; i += 2)
1124 Params.push_back(getValue(Oprnds[i], Oprnds[i+1]));
Reid Spencer060d25d2004-06-29 23:29:38 +00001125 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001126
Reid Spencer1628cec2006-10-26 06:15:43 +00001127 Result = new CallInst(F, Params);
1128 if (isTailCall) cast<CallInst>(Result)->setTailCall();
1129 if (CallingConv) cast<CallInst>(Result)->setCallingConv(CallingConv);
1130 break;
Reid Spencer060d25d2004-06-29 23:29:38 +00001131 }
Reid Spencer1628cec2006-10-26 06:15:43 +00001132 case 56: // Invoke with encoded CC
1133 case 57: // Invoke Fast CC
1134 case Instruction::Invoke: { // Invoke C CC
1135 if (Oprnds.size() < 3)
1136 error("Invalid invoke instruction!");
1137 Value *F = getValue(iType, Oprnds[0]);
Reid Spencer060d25d2004-06-29 23:29:38 +00001138
Reid Spencer1628cec2006-10-26 06:15:43 +00001139 // Check to make sure we have a pointer to function type
1140 const PointerType *PTy = dyn_cast<PointerType>(F->getType());
1141 if (PTy == 0)
1142 error("Invoke to non function pointer value!");
1143 const FunctionType *FTy = dyn_cast<FunctionType>(PTy->getElementType());
1144 if (FTy == 0)
1145 error("Invoke to non function pointer value!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001146
Reid Spencer1628cec2006-10-26 06:15:43 +00001147 std::vector<Value *> Params;
1148 BasicBlock *Normal, *Except;
1149 unsigned CallingConv = CallingConv::C;
Reid Spencer060d25d2004-06-29 23:29:38 +00001150
Reid Spencer1628cec2006-10-26 06:15:43 +00001151 if (Opcode == 57)
1152 CallingConv = CallingConv::Fast;
1153 else if (Opcode == 56) {
1154 CallingConv = Oprnds.back();
1155 Oprnds.pop_back();
1156 }
Chris Lattnerdee199f2005-05-06 22:34:01 +00001157
Reid Spencer1628cec2006-10-26 06:15:43 +00001158 if (!FTy->isVarArg()) {
1159 Normal = getBasicBlock(Oprnds[1]);
1160 Except = getBasicBlock(Oprnds[2]);
Reid Spencer060d25d2004-06-29 23:29:38 +00001161
Reid Spencer1628cec2006-10-26 06:15:43 +00001162 FunctionType::param_iterator It = FTy->param_begin();
1163 for (unsigned i = 3, e = Oprnds.size(); i != e; ++i) {
1164 if (It == FTy->param_end())
1165 error("Invalid invoke instruction!");
1166 Params.push_back(getValue(getTypeSlot(*It++), Oprnds[i]));
1167 }
1168 if (It != FTy->param_end())
Reid Spencer24399722004-07-09 22:21:33 +00001169 error("Invalid invoke instruction!");
Reid Spencer1628cec2006-10-26 06:15:43 +00001170 } else {
1171 Oprnds.erase(Oprnds.begin(), Oprnds.begin()+1);
1172
1173 Normal = getBasicBlock(Oprnds[0]);
1174 Except = getBasicBlock(Oprnds[1]);
1175
1176 unsigned FirstVariableArgument = FTy->getNumParams()+2;
1177 for (unsigned i = 2; i != FirstVariableArgument; ++i)
1178 Params.push_back(getValue(getTypeSlot(FTy->getParamType(i-2)),
1179 Oprnds[i]));
1180
1181 // Must be type/value pairs. If not, error out.
1182 if (Oprnds.size()-FirstVariableArgument & 1)
1183 error("Invalid invoke instruction!");
1184
1185 for (unsigned i = FirstVariableArgument; i < Oprnds.size(); i += 2)
1186 Params.push_back(getValue(Oprnds[i], Oprnds[i+1]));
Reid Spencer060d25d2004-06-29 23:29:38 +00001187 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001188
Reid Spencer1628cec2006-10-26 06:15:43 +00001189 Result = new InvokeInst(F, Normal, Except, Params);
1190 if (CallingConv) cast<InvokeInst>(Result)->setCallingConv(CallingConv);
1191 break;
Reid Spencer060d25d2004-06-29 23:29:38 +00001192 }
Reid Spencer1628cec2006-10-26 06:15:43 +00001193 case Instruction::Malloc: {
1194 unsigned Align = 0;
1195 if (Oprnds.size() == 2)
1196 Align = (1 << Oprnds[1]) >> 1;
1197 else if (Oprnds.size() > 2)
1198 error("Invalid malloc instruction!");
1199 if (!isa<PointerType>(InstTy))
1200 error("Invalid malloc instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001201
Reid Spencer1628cec2006-10-26 06:15:43 +00001202 Result = new MallocInst(cast<PointerType>(InstTy)->getElementType(),
1203 getValue(Type::UIntTyID, Oprnds[0]), Align);
1204 break;
1205 }
1206 case Instruction::Alloca: {
1207 unsigned Align = 0;
1208 if (Oprnds.size() == 2)
1209 Align = (1 << Oprnds[1]) >> 1;
1210 else if (Oprnds.size() > 2)
1211 error("Invalid alloca instruction!");
1212 if (!isa<PointerType>(InstTy))
1213 error("Invalid alloca instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001214
Reid Spencer1628cec2006-10-26 06:15:43 +00001215 Result = new AllocaInst(cast<PointerType>(InstTy)->getElementType(),
1216 getValue(Type::UIntTyID, Oprnds[0]), Align);
1217 break;
1218 }
1219 case Instruction::Free:
1220 if (!isa<PointerType>(InstTy))
1221 error("Invalid free instruction!");
1222 Result = new FreeInst(getValue(iType, Oprnds[0]));
1223 break;
1224 case Instruction::GetElementPtr: {
1225 if (Oprnds.size() == 0 || !isa<PointerType>(InstTy))
Misha Brukman8a96c532005-04-21 21:44:41 +00001226 error("Invalid getelementptr instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001227
Reid Spencer1628cec2006-10-26 06:15:43 +00001228 std::vector<Value*> Idx;
1229
1230 const Type *NextTy = InstTy;
1231 for (unsigned i = 1, e = Oprnds.size(); i != e; ++i) {
1232 const CompositeType *TopTy = dyn_cast_or_null<CompositeType>(NextTy);
1233 if (!TopTy)
1234 error("Invalid getelementptr instruction!");
1235
1236 unsigned ValIdx = Oprnds[i];
1237 unsigned IdxTy = 0;
1238 if (!hasRestrictedGEPTypes) {
1239 // Struct indices are always uints, sequential type indices can be
1240 // any of the 32 or 64-bit integer types. The actual choice of
1241 // type is encoded in the low two bits of the slot number.
1242 if (isa<StructType>(TopTy))
1243 IdxTy = Type::UIntTyID;
1244 else {
1245 switch (ValIdx & 3) {
1246 default:
1247 case 0: IdxTy = Type::UIntTyID; break;
1248 case 1: IdxTy = Type::IntTyID; break;
1249 case 2: IdxTy = Type::ULongTyID; break;
1250 case 3: IdxTy = Type::LongTyID; break;
1251 }
1252 ValIdx >>= 2;
Reid Spencer060d25d2004-06-29 23:29:38 +00001253 }
Reid Spencer1628cec2006-10-26 06:15:43 +00001254 } else {
1255 IdxTy = isa<StructType>(TopTy) ? Type::UByteTyID : Type::LongTyID;
Reid Spencer060d25d2004-06-29 23:29:38 +00001256 }
Reid Spencer1628cec2006-10-26 06:15:43 +00001257
1258 Idx.push_back(getValue(IdxTy, ValIdx));
1259
1260 // Convert ubyte struct indices into uint struct indices.
1261 if (isa<StructType>(TopTy) && hasRestrictedGEPTypes)
1262 if (ConstantInt *C = dyn_cast<ConstantInt>(Idx.back()))
1263 if (C->getType() == Type::UByteTy)
1264 Idx[Idx.size()-1] = ConstantExpr::getCast(C, Type::UIntTy);
1265
1266 NextTy = GetElementPtrInst::getIndexedType(InstTy, Idx, true);
Reid Spencer060d25d2004-06-29 23:29:38 +00001267 }
1268
Reid Spencer1628cec2006-10-26 06:15:43 +00001269 Result = new GetElementPtrInst(getValue(iType, Oprnds[0]), Idx);
1270 break;
Reid Spencer060d25d2004-06-29 23:29:38 +00001271 }
Reid Spencer1628cec2006-10-26 06:15:43 +00001272 case 62: // volatile load
1273 case Instruction::Load:
1274 if (Oprnds.size() != 1 || !isa<PointerType>(InstTy))
1275 error("Invalid load instruction!");
1276 Result = new LoadInst(getValue(iType, Oprnds[0]), "", Opcode == 62);
1277 break;
1278 case 63: // volatile store
1279 case Instruction::Store: {
1280 if (!isa<PointerType>(InstTy) || Oprnds.size() != 2)
1281 error("Invalid store instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001282
Reid Spencer1628cec2006-10-26 06:15:43 +00001283 Value *Ptr = getValue(iType, Oprnds[1]);
1284 const Type *ValTy = cast<PointerType>(Ptr->getType())->getElementType();
1285 Result = new StoreInst(getValue(getTypeSlot(ValTy), Oprnds[0]), Ptr,
1286 Opcode == 63);
1287 break;
1288 }
1289 case Instruction::Unwind:
1290 if (Oprnds.size() != 0) error("Invalid unwind instruction!");
1291 Result = new UnwindInst();
1292 break;
1293 case Instruction::Unreachable:
1294 if (Oprnds.size() != 0) error("Invalid unreachable instruction!");
1295 Result = new UnreachableInst();
1296 break;
1297 } // end switch(Opcode)
1298 } // end if *normal*
Reid Spencer060d25d2004-06-29 23:29:38 +00001299
Reid Spencere1e96c02006-01-19 07:02:16 +00001300 BB->getInstList().push_back(Result);
1301
Reid Spencer060d25d2004-06-29 23:29:38 +00001302 unsigned TypeSlot;
1303 if (Result->getType() == InstTy)
1304 TypeSlot = iType;
1305 else
1306 TypeSlot = getTypeSlot(Result->getType());
1307
1308 insertValue(Result, TypeSlot, FunctionValues);
Reid Spencer060d25d2004-06-29 23:29:38 +00001309}
1310
Reid Spencer04cde2c2004-07-04 11:33:49 +00001311/// Get a particular numbered basic block, which might be a forward reference.
1312/// This works together with ParseBasicBlock to handle these forward references
Chris Lattner4a242b32004-10-14 01:39:18 +00001313/// in a clean manner. This function is used when constructing phi, br, switch,
1314/// and other instructions that reference basic blocks. Blocks are numbered
Reid Spencer04cde2c2004-07-04 11:33:49 +00001315/// sequentially as they appear in the function.
Reid Spencer060d25d2004-06-29 23:29:38 +00001316BasicBlock *BytecodeReader::getBasicBlock(unsigned ID) {
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001317 // Make sure there is room in the table...
1318 if (ParsedBasicBlocks.size() <= ID) ParsedBasicBlocks.resize(ID+1);
1319
1320 // First check to see if this is a backwards reference, i.e., ParseBasicBlock
1321 // has already created this block, or if the forward reference has already
1322 // been created.
1323 if (ParsedBasicBlocks[ID])
1324 return ParsedBasicBlocks[ID];
1325
1326 // Otherwise, the basic block has not yet been created. Do so and add it to
1327 // the ParsedBasicBlocks list.
1328 return ParsedBasicBlocks[ID] = new BasicBlock();
1329}
1330
Misha Brukman8a96c532005-04-21 21:44:41 +00001331/// In LLVM 1.0 bytecode files, we used to output one basicblock at a time.
Reid Spencer04cde2c2004-07-04 11:33:49 +00001332/// This method reads in one of the basicblock packets. This method is not used
1333/// for bytecode files after LLVM 1.0
1334/// @returns The basic block constructed.
Reid Spencer46b002c2004-07-11 17:28:43 +00001335BasicBlock *BytecodeReader::ParseBasicBlock(unsigned BlockNo) {
1336 if (Handler) Handler->handleBasicBlockBegin(BlockNo);
Reid Spencer060d25d2004-06-29 23:29:38 +00001337
1338 BasicBlock *BB = 0;
1339
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001340 if (ParsedBasicBlocks.size() == BlockNo)
1341 ParsedBasicBlocks.push_back(BB = new BasicBlock());
1342 else if (ParsedBasicBlocks[BlockNo] == 0)
1343 BB = ParsedBasicBlocks[BlockNo] = new BasicBlock();
1344 else
1345 BB = ParsedBasicBlocks[BlockNo];
Chris Lattner00950542001-06-06 20:29:01 +00001346
Reid Spencer060d25d2004-06-29 23:29:38 +00001347 std::vector<unsigned> Operands;
Reid Spencer46b002c2004-07-11 17:28:43 +00001348 while (moreInBlock())
Reid Spencer060d25d2004-06-29 23:29:38 +00001349 ParseInstruction(Operands, BB);
Chris Lattner00950542001-06-06 20:29:01 +00001350
Reid Spencer46b002c2004-07-11 17:28:43 +00001351 if (Handler) Handler->handleBasicBlockEnd(BlockNo);
Misha Brukman12c29d12003-09-22 23:38:23 +00001352 return BB;
Chris Lattner00950542001-06-06 20:29:01 +00001353}
1354
Reid Spencer04cde2c2004-07-04 11:33:49 +00001355/// Parse all of the BasicBlock's & Instruction's in the body of a function.
Misha Brukman8a96c532005-04-21 21:44:41 +00001356/// In post 1.0 bytecode files, we no longer emit basic block individually,
Reid Spencer04cde2c2004-07-04 11:33:49 +00001357/// in order to avoid per-basic-block overhead.
1358/// @returns Rhe number of basic blocks encountered.
Reid Spencer060d25d2004-06-29 23:29:38 +00001359unsigned BytecodeReader::ParseInstructionList(Function* F) {
Chris Lattner8d1dbd22003-12-01 07:05:31 +00001360 unsigned BlockNo = 0;
1361 std::vector<unsigned> Args;
1362
Reid Spencer46b002c2004-07-11 17:28:43 +00001363 while (moreInBlock()) {
1364 if (Handler) Handler->handleBasicBlockBegin(BlockNo);
Chris Lattner8d1dbd22003-12-01 07:05:31 +00001365 BasicBlock *BB;
1366 if (ParsedBasicBlocks.size() == BlockNo)
1367 ParsedBasicBlocks.push_back(BB = new BasicBlock());
1368 else if (ParsedBasicBlocks[BlockNo] == 0)
1369 BB = ParsedBasicBlocks[BlockNo] = new BasicBlock();
1370 else
1371 BB = ParsedBasicBlocks[BlockNo];
1372 ++BlockNo;
1373 F->getBasicBlockList().push_back(BB);
1374
1375 // Read instructions into this basic block until we get to a terminator
Reid Spencer46b002c2004-07-11 17:28:43 +00001376 while (moreInBlock() && !BB->getTerminator())
Reid Spencer060d25d2004-06-29 23:29:38 +00001377 ParseInstruction(Args, BB);
Chris Lattner8d1dbd22003-12-01 07:05:31 +00001378
1379 if (!BB->getTerminator())
Reid Spencer24399722004-07-09 22:21:33 +00001380 error("Non-terminated basic block found!");
Reid Spencer5c15fe52004-07-05 00:57:50 +00001381
Reid Spencer46b002c2004-07-11 17:28:43 +00001382 if (Handler) Handler->handleBasicBlockEnd(BlockNo-1);
Chris Lattner8d1dbd22003-12-01 07:05:31 +00001383 }
1384
1385 return BlockNo;
1386}
1387
Reid Spencer04cde2c2004-07-04 11:33:49 +00001388/// Parse a symbol table. This works for both module level and function
1389/// level symbol tables. For function level symbol tables, the CurrentFunction
1390/// parameter must be non-zero and the ST parameter must correspond to
1391/// CurrentFunction's symbol table. For Module level symbol tables, the
1392/// CurrentFunction argument must be zero.
Reid Spencer060d25d2004-06-29 23:29:38 +00001393void BytecodeReader::ParseSymbolTable(Function *CurrentFunction,
Reid Spencer04cde2c2004-07-04 11:33:49 +00001394 SymbolTable *ST) {
1395 if (Handler) Handler->handleSymbolTableBegin(CurrentFunction,ST);
Reid Spencer060d25d2004-06-29 23:29:38 +00001396
Chris Lattner39cacce2003-10-10 05:43:47 +00001397 // Allow efficient basic block lookup by number.
1398 std::vector<BasicBlock*> BBMap;
1399 if (CurrentFunction)
1400 for (Function::iterator I = CurrentFunction->begin(),
1401 E = CurrentFunction->end(); I != E; ++I)
1402 BBMap.push_back(I);
1403
Reid Spencer04cde2c2004-07-04 11:33:49 +00001404 /// In LLVM 1.3 we write types separately from values so
1405 /// The types are always first in the symbol table. This is
1406 /// because Type no longer derives from Value.
Reid Spencer46b002c2004-07-11 17:28:43 +00001407 if (!hasTypeDerivedFromValue) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001408 // Symtab block header: [num entries]
1409 unsigned NumEntries = read_vbr_uint();
Reid Spencer46b002c2004-07-11 17:28:43 +00001410 for (unsigned i = 0; i < NumEntries; ++i) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001411 // Symtab entry: [def slot #][name]
1412 unsigned slot = read_vbr_uint();
1413 std::string Name = read_str();
1414 const Type* T = getType(slot);
1415 ST->insert(Name, T);
1416 }
1417 }
1418
Reid Spencer46b002c2004-07-11 17:28:43 +00001419 while (moreInBlock()) {
Chris Lattner00950542001-06-06 20:29:01 +00001420 // Symtab block header: [num entries][type id number]
Reid Spencer060d25d2004-06-29 23:29:38 +00001421 unsigned NumEntries = read_vbr_uint();
Reid Spencer04cde2c2004-07-04 11:33:49 +00001422 unsigned Typ = 0;
1423 bool isTypeType = read_typeid(Typ);
Chris Lattner1d670cc2001-09-07 16:37:43 +00001424
Chris Lattner7dc3a2e2003-10-13 14:57:53 +00001425 for (unsigned i = 0; i != NumEntries; ++i) {
Chris Lattner00950542001-06-06 20:29:01 +00001426 // Symtab entry: [def slot #][name]
Reid Spencer060d25d2004-06-29 23:29:38 +00001427 unsigned slot = read_vbr_uint();
1428 std::string Name = read_str();
Chris Lattner00950542001-06-06 20:29:01 +00001429
Reid Spencer04cde2c2004-07-04 11:33:49 +00001430 // if we're reading a pre 1.3 bytecode file and the type plane
1431 // is the "type type", handle it here
Reid Spencer46b002c2004-07-11 17:28:43 +00001432 if (isTypeType) {
1433 const Type* T = getType(slot);
1434 if (T == 0)
1435 error("Failed type look-up for name '" + Name + "'");
1436 ST->insert(Name, T);
1437 continue; // code below must be short circuited
Chris Lattner39cacce2003-10-10 05:43:47 +00001438 } else {
Reid Spencer46b002c2004-07-11 17:28:43 +00001439 Value *V = 0;
1440 if (Typ == Type::LabelTyID) {
1441 if (slot < BBMap.size())
1442 V = BBMap[slot];
1443 } else {
1444 V = getValue(Typ, slot, false); // Find mapping...
1445 }
1446 if (V == 0)
1447 error("Failed value look-up for name '" + Name + "'");
Chris Lattner7acff252005-03-05 19:05:20 +00001448 V->setName(Name);
Chris Lattner39cacce2003-10-10 05:43:47 +00001449 }
Chris Lattner00950542001-06-06 20:29:01 +00001450 }
1451 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001452 checkPastBlockEnd("Symbol Table");
Reid Spencer04cde2c2004-07-04 11:33:49 +00001453 if (Handler) Handler->handleSymbolTableEnd();
Chris Lattner00950542001-06-06 20:29:01 +00001454}
1455
Misha Brukman8a96c532005-04-21 21:44:41 +00001456/// Read in the types portion of a compaction table.
Reid Spencer46b002c2004-07-11 17:28:43 +00001457void BytecodeReader::ParseCompactionTypes(unsigned NumEntries) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001458 for (unsigned i = 0; i != NumEntries; ++i) {
1459 unsigned TypeSlot = 0;
Reid Spencer46b002c2004-07-11 17:28:43 +00001460 if (read_typeid(TypeSlot))
Reid Spencer24399722004-07-09 22:21:33 +00001461 error("Invalid type in compaction table: type type");
Reid Spencer04cde2c2004-07-04 11:33:49 +00001462 const Type *Typ = getGlobalTableType(TypeSlot);
Chris Lattner45b5dd22004-08-03 23:41:28 +00001463 CompactionTypes.push_back(std::make_pair(Typ, TypeSlot));
Reid Spencer46b002c2004-07-11 17:28:43 +00001464 if (Handler) Handler->handleCompactionTableType(i, TypeSlot, Typ);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001465 }
1466}
1467
1468/// Parse a compaction table.
Reid Spencer060d25d2004-06-29 23:29:38 +00001469void BytecodeReader::ParseCompactionTable() {
1470
Reid Spencer46b002c2004-07-11 17:28:43 +00001471 // Notify handler that we're beginning a compaction table.
Reid Spencer04cde2c2004-07-04 11:33:49 +00001472 if (Handler) Handler->handleCompactionTableBegin();
1473
Misha Brukman8a96c532005-04-21 21:44:41 +00001474 // In LLVM 1.3 Type no longer derives from Value. So,
Reid Spencer46b002c2004-07-11 17:28:43 +00001475 // we always write them first in the compaction table
1476 // because they can't occupy a "type plane" where the
1477 // Values reside.
1478 if (! hasTypeDerivedFromValue) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001479 unsigned NumEntries = read_vbr_uint();
Reid Spencer46b002c2004-07-11 17:28:43 +00001480 ParseCompactionTypes(NumEntries);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001481 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001482
Reid Spencer46b002c2004-07-11 17:28:43 +00001483 // Compaction tables live in separate blocks so we have to loop
1484 // until we've read the whole thing.
1485 while (moreInBlock()) {
1486 // Read the number of Value* entries in the compaction table
Reid Spencer060d25d2004-06-29 23:29:38 +00001487 unsigned NumEntries = read_vbr_uint();
Reid Spencer04cde2c2004-07-04 11:33:49 +00001488 unsigned Ty = 0;
1489 unsigned isTypeType = false;
Reid Spencer060d25d2004-06-29 23:29:38 +00001490
Reid Spencer46b002c2004-07-11 17:28:43 +00001491 // Decode the type from value read in. Most compaction table
1492 // planes will have one or two entries in them. If that's the
1493 // case then the length is encoded in the bottom two bits and
1494 // the higher bits encode the type. This saves another VBR value.
Reid Spencer060d25d2004-06-29 23:29:38 +00001495 if ((NumEntries & 3) == 3) {
Reid Spencer46b002c2004-07-11 17:28:43 +00001496 // In this case, both low-order bits are set (value 3). This
1497 // is a signal that the typeid follows.
Reid Spencer060d25d2004-06-29 23:29:38 +00001498 NumEntries >>= 2;
Reid Spencer04cde2c2004-07-04 11:33:49 +00001499 isTypeType = read_typeid(Ty);
Reid Spencer060d25d2004-06-29 23:29:38 +00001500 } else {
Reid Spencer46b002c2004-07-11 17:28:43 +00001501 // In this case, the low-order bits specify the number of entries
1502 // and the high order bits specify the type.
Reid Spencer060d25d2004-06-29 23:29:38 +00001503 Ty = NumEntries >> 2;
Reid Spencer04cde2c2004-07-04 11:33:49 +00001504 isTypeType = sanitizeTypeId(Ty);
Reid Spencer060d25d2004-06-29 23:29:38 +00001505 NumEntries &= 3;
1506 }
1507
Reid Spencer04cde2c2004-07-04 11:33:49 +00001508 // if we're reading a pre 1.3 bytecode file and the type plane
1509 // is the "type type", handle it here
Reid Spencer46b002c2004-07-11 17:28:43 +00001510 if (isTypeType) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001511 ParseCompactionTypes(NumEntries);
Reid Spencer060d25d2004-06-29 23:29:38 +00001512 } else {
Chris Lattner2c6c14d2004-08-04 00:19:23 +00001513 // Make sure we have enough room for the plane.
Reid Spencer04cde2c2004-07-04 11:33:49 +00001514 if (Ty >= CompactionValues.size())
Reid Spencer46b002c2004-07-11 17:28:43 +00001515 CompactionValues.resize(Ty+1);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001516
Chris Lattner2c6c14d2004-08-04 00:19:23 +00001517 // Make sure the plane is empty or we have some kind of error.
Reid Spencer04cde2c2004-07-04 11:33:49 +00001518 if (!CompactionValues[Ty].empty())
Reid Spencer46b002c2004-07-11 17:28:43 +00001519 error("Compaction table plane contains multiple entries!");
Reid Spencer04cde2c2004-07-04 11:33:49 +00001520
Chris Lattner2c6c14d2004-08-04 00:19:23 +00001521 // Notify handler about the plane.
Reid Spencer46b002c2004-07-11 17:28:43 +00001522 if (Handler) Handler->handleCompactionTablePlane(Ty, NumEntries);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001523
Chris Lattner2c6c14d2004-08-04 00:19:23 +00001524 // Push the implicit zero.
1525 CompactionValues[Ty].push_back(Constant::getNullValue(getType(Ty)));
Reid Spencer46b002c2004-07-11 17:28:43 +00001526
1527 // Read in each of the entries, put them in the compaction table
1528 // and notify the handler that we have a new compaction table value.
Reid Spencer060d25d2004-06-29 23:29:38 +00001529 for (unsigned i = 0; i != NumEntries; ++i) {
Reid Spencer46b002c2004-07-11 17:28:43 +00001530 unsigned ValSlot = read_vbr_uint();
Chris Lattner2c6c14d2004-08-04 00:19:23 +00001531 Value *V = getGlobalTableValue(Ty, ValSlot);
Reid Spencer46b002c2004-07-11 17:28:43 +00001532 CompactionValues[Ty].push_back(V);
Chris Lattner2c6c14d2004-08-04 00:19:23 +00001533 if (Handler) Handler->handleCompactionTableValue(i, Ty, ValSlot);
Reid Spencer060d25d2004-06-29 23:29:38 +00001534 }
1535 }
1536 }
Reid Spencer46b002c2004-07-11 17:28:43 +00001537 // Notify handler that the compaction table is done.
Reid Spencer04cde2c2004-07-04 11:33:49 +00001538 if (Handler) Handler->handleCompactionTableEnd();
Reid Spencer060d25d2004-06-29 23:29:38 +00001539}
Misha Brukman8a96c532005-04-21 21:44:41 +00001540
Reid Spencer46b002c2004-07-11 17:28:43 +00001541// Parse a single type. The typeid is read in first. If its a primitive type
1542// then nothing else needs to be read, we know how to instantiate it. If its
Misha Brukman8a96c532005-04-21 21:44:41 +00001543// a derived type, then additional data is read to fill out the type
Reid Spencer46b002c2004-07-11 17:28:43 +00001544// definition.
1545const Type *BytecodeReader::ParseType() {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001546 unsigned PrimType = 0;
Reid Spencer46b002c2004-07-11 17:28:43 +00001547 if (read_typeid(PrimType))
Reid Spencer24399722004-07-09 22:21:33 +00001548 error("Invalid type (type type) in type constants!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001549
1550 const Type *Result = 0;
1551 if ((Result = Type::getPrimitiveType((Type::TypeID)PrimType)))
1552 return Result;
Misha Brukman8a96c532005-04-21 21:44:41 +00001553
Reid Spencer060d25d2004-06-29 23:29:38 +00001554 switch (PrimType) {
1555 case Type::FunctionTyID: {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001556 const Type *RetType = readSanitizedType();
Reid Spencer060d25d2004-06-29 23:29:38 +00001557
1558 unsigned NumParams = read_vbr_uint();
1559
1560 std::vector<const Type*> Params;
Misha Brukman8a96c532005-04-21 21:44:41 +00001561 while (NumParams--)
Reid Spencer04cde2c2004-07-04 11:33:49 +00001562 Params.push_back(readSanitizedType());
Reid Spencer060d25d2004-06-29 23:29:38 +00001563
1564 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1565 if (isVarArg) Params.pop_back();
1566
1567 Result = FunctionType::get(RetType, Params, isVarArg);
1568 break;
1569 }
1570 case Type::ArrayTyID: {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001571 const Type *ElementType = readSanitizedType();
Reid Spencer060d25d2004-06-29 23:29:38 +00001572 unsigned NumElements = read_vbr_uint();
Reid Spencer060d25d2004-06-29 23:29:38 +00001573 Result = ArrayType::get(ElementType, NumElements);
1574 break;
1575 }
Brian Gaeke715c90b2004-08-20 06:00:58 +00001576 case Type::PackedTyID: {
1577 const Type *ElementType = readSanitizedType();
1578 unsigned NumElements = read_vbr_uint();
1579 Result = PackedType::get(ElementType, NumElements);
1580 break;
1581 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001582 case Type::StructTyID: {
1583 std::vector<const Type*> Elements;
Reid Spencer04cde2c2004-07-04 11:33:49 +00001584 unsigned Typ = 0;
Reid Spencer46b002c2004-07-11 17:28:43 +00001585 if (read_typeid(Typ))
Reid Spencer24399722004-07-09 22:21:33 +00001586 error("Invalid element type (type type) for structure!");
1587
Reid Spencer060d25d2004-06-29 23:29:38 +00001588 while (Typ) { // List is terminated by void/0 typeid
1589 Elements.push_back(getType(Typ));
Reid Spencer46b002c2004-07-11 17:28:43 +00001590 if (read_typeid(Typ))
1591 error("Invalid element type (type type) for structure!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001592 }
1593
1594 Result = StructType::get(Elements);
1595 break;
1596 }
1597 case Type::PointerTyID: {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001598 Result = PointerType::get(readSanitizedType());
Reid Spencer060d25d2004-06-29 23:29:38 +00001599 break;
1600 }
1601
1602 case Type::OpaqueTyID: {
1603 Result = OpaqueType::get();
1604 break;
1605 }
1606
1607 default:
Reid Spencer24399722004-07-09 22:21:33 +00001608 error("Don't know how to deserialize primitive type " + utostr(PrimType));
Reid Spencer060d25d2004-06-29 23:29:38 +00001609 break;
1610 }
Reid Spencer46b002c2004-07-11 17:28:43 +00001611 if (Handler) Handler->handleType(Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001612 return Result;
1613}
1614
Reid Spencer5b472d92004-08-21 20:49:23 +00001615// ParseTypes - We have to use this weird code to handle recursive
Reid Spencer060d25d2004-06-29 23:29:38 +00001616// types. We know that recursive types will only reference the current slab of
1617// values in the type plane, but they can forward reference types before they
1618// have been read. For example, Type #0 might be '{ Ty#1 }' and Type #1 might
1619// be 'Ty#0*'. When reading Type #0, type number one doesn't exist. To fix
1620// this ugly problem, we pessimistically insert an opaque type for each type we
1621// are about to read. This means that forward references will resolve to
1622// something and when we reread the type later, we can replace the opaque type
1623// with a new resolved concrete type.
1624//
Reid Spencer46b002c2004-07-11 17:28:43 +00001625void BytecodeReader::ParseTypes(TypeListTy &Tab, unsigned NumEntries){
Reid Spencer060d25d2004-06-29 23:29:38 +00001626 assert(Tab.size() == 0 && "should not have read type constants in before!");
1627
1628 // Insert a bunch of opaque types to be resolved later...
1629 Tab.reserve(NumEntries);
1630 for (unsigned i = 0; i != NumEntries; ++i)
1631 Tab.push_back(OpaqueType::get());
1632
Misha Brukman8a96c532005-04-21 21:44:41 +00001633 if (Handler)
Reid Spencer5b472d92004-08-21 20:49:23 +00001634 Handler->handleTypeList(NumEntries);
1635
Chris Lattnereebac5f2005-10-03 21:26:53 +00001636 // If we are about to resolve types, make sure the type cache is clear.
1637 if (NumEntries)
1638 ModuleTypeIDCache.clear();
1639
Reid Spencer060d25d2004-06-29 23:29:38 +00001640 // Loop through reading all of the types. Forward types will make use of the
1641 // opaque types just inserted.
1642 //
1643 for (unsigned i = 0; i != NumEntries; ++i) {
Reid Spencer46b002c2004-07-11 17:28:43 +00001644 const Type* NewTy = ParseType();
Reid Spencer04cde2c2004-07-04 11:33:49 +00001645 const Type* OldTy = Tab[i].get();
Misha Brukman8a96c532005-04-21 21:44:41 +00001646 if (NewTy == 0)
Reid Spencer24399722004-07-09 22:21:33 +00001647 error("Couldn't parse type!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001648
Misha Brukman8a96c532005-04-21 21:44:41 +00001649 // Don't directly push the new type on the Tab. Instead we want to replace
Reid Spencer060d25d2004-06-29 23:29:38 +00001650 // the opaque type we previously inserted with the new concrete value. This
1651 // approach helps with forward references to types. The refinement from the
1652 // abstract (opaque) type to the new type causes all uses of the abstract
1653 // type to use the concrete type (NewTy). This will also cause the opaque
1654 // type to be deleted.
1655 cast<DerivedType>(const_cast<Type*>(OldTy))->refineAbstractTypeTo(NewTy);
1656
1657 // This should have replaced the old opaque type with the new type in the
1658 // value table... or with a preexisting type that was already in the system.
1659 // Let's just make sure it did.
1660 assert(Tab[i] != OldTy && "refineAbstractType didn't work!");
1661 }
1662}
1663
Reid Spencer1628cec2006-10-26 06:15:43 +00001664// Upgrade obsolete constant expression opcodes (ver. 5 and prior) to the new
1665// values used after ver 6. bytecode format. The operands are provided to the
1666// function so that decisions based on the operand type can be made when
1667// auto-upgrading obsolete opcodes to the new ones.
Reid Spencer6996feb2006-11-08 21:27:54 +00001668// NOTE: This code needs to be kept synchronized with upgradeInstrOpcodes.
Reid Spencer1628cec2006-10-26 06:15:43 +00001669// We can't use that function because of that functions argument requirements.
1670// This function only deals with the subset of opcodes that are applicable to
Reid Spencer6996feb2006-11-08 21:27:54 +00001671// constant expressions and is therefore simpler than upgradeInstrOpcodes.
1672inline unsigned BytecodeReader::upgradeCEOpcodes(
Reid Spencer1628cec2006-10-26 06:15:43 +00001673 unsigned Opcode, const std::vector<Constant*> &ArgVec
1674) {
Reid Spencer6996feb2006-11-08 21:27:54 +00001675 // Determine if no upgrade necessary
1676 if (!hasSignlessDivRem && !hasSignlessShrCastSetcc)
1677 return Opcode;
1678
1679#if 0
1680 // If this is a bytecode format that did not include the unreachable
1681 // instruction, bump up the opcode number to adjust it.
1682 if (hasNoUnreachableInst)
1683 if (Opcode >= 6 && Opcode < 62)
1684 ++Opcode;
1685#endif
1686
1687 // If this is bytecode version 6, that only had signed Rem and Div
1688 // instructions, then we must compensate for those two instructions only.
1689 // So that the switch statement below works, we're trying to turn this into
1690 // a version 5 opcode. To do that we must adjust the opcode to 10 (Div) if its
1691 // any of the UDiv, SDiv or FDiv instructions; or, adjust the opcode to
1692 // 11 (Rem) if its any of the URem, SRem, or FRem instructions; or, simply
1693 // decrement the instruction code if its beyond FRem.
1694 if (!hasSignlessDivRem) {
1695 // If its one of the signed Div/Rem opcodes, its fine the way it is
1696 if (Opcode >= 10 && Opcode <= 12) // UDiv through FDiv
1697 Opcode = 10; // Div
1698 else if (Opcode >=13 && Opcode <= 15) // URem through FRem
1699 Opcode = 11; // Rem
1700 else if (Opcode > 15) // Everything above FRem
1701 // Adjust for new instruction codes
1702 Opcode -= 4;
1703 }
1704
Reid Spencer1628cec2006-10-26 06:15:43 +00001705 switch (Opcode) {
1706 default: // Pass Through
1707 // If we don't match any of the cases here then the opcode is fine the
1708 // way it is.
1709 break;
1710 case 7: // Add
1711 Opcode = Instruction::Add;
1712 break;
1713 case 8: // Sub
1714 Opcode = Instruction::Sub;
1715 break;
1716 case 9: // Mul
1717 Opcode = Instruction::Mul;
1718 break;
1719 case 10: // Div
1720 // The type of the instruction is based on the operands. We need to select
1721 // either udiv or sdiv based on that type. This expression selects the
1722 // cases where the type is floating point or signed in which case we
1723 // generated an sdiv instruction.
1724 if (ArgVec[0]->getType()->isFloatingPoint())
1725 Opcode = Instruction::FDiv;
1726 else if (ArgVec[0]->getType()->isSigned())
1727 Opcode = Instruction::SDiv;
1728 else
1729 Opcode = Instruction::UDiv;
1730 break;
Reid Spencer1628cec2006-10-26 06:15:43 +00001731 case 11: // Rem
Reid Spencer0a783f72006-11-02 01:53:59 +00001732 // As with "Div", make the signed/unsigned or floating point Rem
1733 // instruction choice based on the type of the operands.
Reid Spencer1628cec2006-10-26 06:15:43 +00001734 if (ArgVec[0]->getType()->isFloatingPoint())
Reid Spencer0a783f72006-11-02 01:53:59 +00001735 Opcode = Instruction::FRem;
Reid Spencer1628cec2006-10-26 06:15:43 +00001736 else if (ArgVec[0]->getType()->isSigned())
Reid Spencer0a783f72006-11-02 01:53:59 +00001737 Opcode = Instruction::SRem;
Reid Spencer1628cec2006-10-26 06:15:43 +00001738 else
Reid Spencer0a783f72006-11-02 01:53:59 +00001739 Opcode = Instruction::URem;
Reid Spencer1628cec2006-10-26 06:15:43 +00001740 break;
Reid Spencer1628cec2006-10-26 06:15:43 +00001741 case 12: // And
1742 Opcode = Instruction::And;
1743 break;
1744 case 13: // Or
1745 Opcode = Instruction::Or;
1746 break;
1747 case 14: // Xor
1748 Opcode = Instruction::Xor;
1749 break;
1750 case 15: // SetEQ
1751 Opcode = Instruction::SetEQ;
1752 break;
1753 case 16: // SetNE
1754 Opcode = Instruction::SetNE;
1755 break;
1756 case 17: // SetLE
1757 Opcode = Instruction::SetLE;
1758 break;
1759 case 18: // SetGE
1760 Opcode = Instruction::SetGE;
1761 break;
1762 case 19: // SetLT
1763 Opcode = Instruction::SetLT;
1764 break;
1765 case 20: // SetGT
1766 Opcode = Instruction::SetGT;
1767 break;
1768 case 26: // GetElementPtr
1769 Opcode = Instruction::GetElementPtr;
1770 break;
1771 case 28: // Cast
1772 Opcode = Instruction::Cast;
1773 break;
1774 case 30: // Shl
1775 Opcode = Instruction::Shl;
1776 break;
1777 case 31: // Shr
Reid Spencer3822ff52006-11-08 06:47:33 +00001778 if (ArgVec[0]->getType()->isSigned())
1779 Opcode = Instruction::AShr;
1780 else
1781 Opcode = Instruction::LShr;
Reid Spencer1628cec2006-10-26 06:15:43 +00001782 break;
1783 case 34: // Select
1784 Opcode = Instruction::Select;
1785 break;
1786 case 38: // ExtractElement
1787 Opcode = Instruction::ExtractElement;
1788 break;
1789 case 39: // InsertElement
1790 Opcode = Instruction::InsertElement;
1791 break;
1792 case 40: // ShuffleVector
1793 Opcode = Instruction::ShuffleVector;
1794 break;
1795 }
1796 return Opcode;
1797}
1798
Reid Spencer04cde2c2004-07-04 11:33:49 +00001799/// Parse a single constant value
Chris Lattner3bc5a602006-01-25 23:08:15 +00001800Value *BytecodeReader::ParseConstantPoolValue(unsigned TypeID) {
Reid Spencer060d25d2004-06-29 23:29:38 +00001801 // We must check for a ConstantExpr before switching by type because
1802 // a ConstantExpr can be of any type, and has no explicit value.
Misha Brukman8a96c532005-04-21 21:44:41 +00001803 //
Reid Spencer060d25d2004-06-29 23:29:38 +00001804 // 0 if not expr; numArgs if is expr
1805 unsigned isExprNumArgs = read_vbr_uint();
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001806
Reid Spencer060d25d2004-06-29 23:29:38 +00001807 if (isExprNumArgs) {
Chris Lattner3bc5a602006-01-25 23:08:15 +00001808 if (!hasNoUndefValue) {
1809 // 'undef' is encoded with 'exprnumargs' == 1.
1810 if (isExprNumArgs == 1)
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001811 return UndefValue::get(getType(TypeID));
Misha Brukman8a96c532005-04-21 21:44:41 +00001812
Chris Lattner3bc5a602006-01-25 23:08:15 +00001813 // Inline asm is encoded with exprnumargs == ~0U.
1814 if (isExprNumArgs == ~0U) {
1815 std::string AsmStr = read_str();
1816 std::string ConstraintStr = read_str();
1817 unsigned Flags = read_vbr_uint();
1818
1819 const PointerType *PTy = dyn_cast<PointerType>(getType(TypeID));
1820 const FunctionType *FTy =
1821 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
1822
1823 if (!FTy || !InlineAsm::Verify(FTy, ConstraintStr))
1824 error("Invalid constraints for inline asm");
1825 if (Flags & ~1U)
1826 error("Invalid flags for inline asm");
1827 bool HasSideEffects = Flags & 1;
1828 return InlineAsm::get(FTy, AsmStr, ConstraintStr, HasSideEffects);
1829 }
1830
1831 --isExprNumArgs;
1832 }
1833
Reid Spencer060d25d2004-06-29 23:29:38 +00001834 // FIXME: Encoding of constant exprs could be much more compact!
1835 std::vector<Constant*> ArgVec;
1836 ArgVec.reserve(isExprNumArgs);
1837 unsigned Opcode = read_vbr_uint();
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001838
1839 // Bytecode files before LLVM 1.4 need have a missing terminator inst.
1840 if (hasNoUnreachableInst) Opcode++;
Misha Brukman8a96c532005-04-21 21:44:41 +00001841
Reid Spencer060d25d2004-06-29 23:29:38 +00001842 // Read the slot number and types of each of the arguments
1843 for (unsigned i = 0; i != isExprNumArgs; ++i) {
1844 unsigned ArgValSlot = read_vbr_uint();
Reid Spencer04cde2c2004-07-04 11:33:49 +00001845 unsigned ArgTypeSlot = 0;
Reid Spencer46b002c2004-07-11 17:28:43 +00001846 if (read_typeid(ArgTypeSlot))
1847 error("Invalid argument type (type type) for constant value");
Misha Brukman8a96c532005-04-21 21:44:41 +00001848
Reid Spencer060d25d2004-06-29 23:29:38 +00001849 // Get the arg value from its slot if it exists, otherwise a placeholder
1850 ArgVec.push_back(getConstantValue(ArgTypeSlot, ArgValSlot));
1851 }
Misha Brukman8a96c532005-04-21 21:44:41 +00001852
Reid Spencer1628cec2006-10-26 06:15:43 +00001853 // Handle backwards compatibility for the opcode numbers
Reid Spencer6996feb2006-11-08 21:27:54 +00001854 Opcode = upgradeCEOpcodes(Opcode, ArgVec);
Reid Spencer1628cec2006-10-26 06:15:43 +00001855
Reid Spencer060d25d2004-06-29 23:29:38 +00001856 // Construct a ConstantExpr of the appropriate kind
1857 if (isExprNumArgs == 1) { // All one-operand expressions
Reid Spencer46b002c2004-07-11 17:28:43 +00001858 if (Opcode != Instruction::Cast)
Chris Lattner02dce162004-12-04 05:28:27 +00001859 error("Only cast instruction has one argument for ConstantExpr");
Reid Spencer46b002c2004-07-11 17:28:43 +00001860
Reid Spencer060d25d2004-06-29 23:29:38 +00001861 Constant* Result = ConstantExpr::getCast(ArgVec[0], getType(TypeID));
Reid Spencer04cde2c2004-07-04 11:33:49 +00001862 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001863 return Result;
1864 } else if (Opcode == Instruction::GetElementPtr) { // GetElementPtr
1865 std::vector<Constant*> IdxList(ArgVec.begin()+1, ArgVec.end());
1866
1867 if (hasRestrictedGEPTypes) {
1868 const Type *BaseTy = ArgVec[0]->getType();
1869 generic_gep_type_iterator<std::vector<Constant*>::iterator>
1870 GTI = gep_type_begin(BaseTy, IdxList.begin(), IdxList.end()),
1871 E = gep_type_end(BaseTy, IdxList.begin(), IdxList.end());
1872 for (unsigned i = 0; GTI != E; ++GTI, ++i)
1873 if (isa<StructType>(*GTI)) {
1874 if (IdxList[i]->getType() != Type::UByteTy)
Reid Spencer24399722004-07-09 22:21:33 +00001875 error("Invalid index for getelementptr!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001876 IdxList[i] = ConstantExpr::getCast(IdxList[i], Type::UIntTy);
1877 }
1878 }
1879
1880 Constant* Result = ConstantExpr::getGetElementPtr(ArgVec[0], IdxList);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001881 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001882 return Result;
1883 } else if (Opcode == Instruction::Select) {
Reid Spencer46b002c2004-07-11 17:28:43 +00001884 if (ArgVec.size() != 3)
1885 error("Select instruction must have three arguments.");
Misha Brukman8a96c532005-04-21 21:44:41 +00001886 Constant* Result = ConstantExpr::getSelect(ArgVec[0], ArgVec[1],
Reid Spencer04cde2c2004-07-04 11:33:49 +00001887 ArgVec[2]);
1888 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001889 return Result;
Robert Bocchinofee31b32006-01-10 19:04:39 +00001890 } else if (Opcode == Instruction::ExtractElement) {
Chris Lattner59fecec2006-04-08 04:09:19 +00001891 if (ArgVec.size() != 2 ||
1892 !ExtractElementInst::isValidOperands(ArgVec[0], ArgVec[1]))
1893 error("Invalid extractelement constand expr arguments");
Robert Bocchinofee31b32006-01-10 19:04:39 +00001894 Constant* Result = ConstantExpr::getExtractElement(ArgVec[0], ArgVec[1]);
1895 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
1896 return Result;
Robert Bocchinob1f240b2006-01-17 20:06:35 +00001897 } else if (Opcode == Instruction::InsertElement) {
Chris Lattner59fecec2006-04-08 04:09:19 +00001898 if (ArgVec.size() != 3 ||
1899 !InsertElementInst::isValidOperands(ArgVec[0], ArgVec[1], ArgVec[2]))
1900 error("Invalid insertelement constand expr arguments");
1901
1902 Constant *Result =
Robert Bocchinob1f240b2006-01-17 20:06:35 +00001903 ConstantExpr::getInsertElement(ArgVec[0], ArgVec[1], ArgVec[2]);
1904 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
1905 return Result;
Chris Lattner30b44b62006-04-08 01:17:59 +00001906 } else if (Opcode == Instruction::ShuffleVector) {
1907 if (ArgVec.size() != 3 ||
1908 !ShuffleVectorInst::isValidOperands(ArgVec[0], ArgVec[1], ArgVec[2]))
Chris Lattner59fecec2006-04-08 04:09:19 +00001909 error("Invalid shufflevector constant expr arguments.");
Chris Lattner30b44b62006-04-08 01:17:59 +00001910 Constant *Result =
1911 ConstantExpr::getShuffleVector(ArgVec[0], ArgVec[1], ArgVec[2]);
1912 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
1913 return Result;
Reid Spencer060d25d2004-06-29 23:29:38 +00001914 } else { // All other 2-operand expressions
1915 Constant* Result = ConstantExpr::get(Opcode, ArgVec[0], ArgVec[1]);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001916 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001917 return Result;
1918 }
1919 }
Misha Brukman8a96c532005-04-21 21:44:41 +00001920
Reid Spencer060d25d2004-06-29 23:29:38 +00001921 // Ok, not an ConstantExpr. We now know how to read the given type...
1922 const Type *Ty = getType(TypeID);
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001923 Constant *Result = 0;
Reid Spencer060d25d2004-06-29 23:29:38 +00001924 switch (Ty->getTypeID()) {
1925 case Type::BoolTyID: {
1926 unsigned Val = read_vbr_uint();
Misha Brukman8a96c532005-04-21 21:44:41 +00001927 if (Val != 0 && Val != 1)
Reid Spencer24399722004-07-09 22:21:33 +00001928 error("Invalid boolean value read.");
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001929 Result = ConstantBool::get(Val == 1);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001930 if (Handler) Handler->handleConstantValue(Result);
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001931 break;
Reid Spencer060d25d2004-06-29 23:29:38 +00001932 }
1933
1934 case Type::UByteTyID: // Unsigned integer types...
1935 case Type::UShortTyID:
1936 case Type::UIntTyID: {
1937 unsigned Val = read_vbr_uint();
Reid Spencerb83eb642006-10-20 07:07:24 +00001938 if (!ConstantInt::isValueValidForType(Ty, uint64_t(Val)))
Reid Spencer24399722004-07-09 22:21:33 +00001939 error("Invalid unsigned byte/short/int read.");
Reid Spencerb83eb642006-10-20 07:07:24 +00001940 Result = ConstantInt::get(Ty, Val);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001941 if (Handler) Handler->handleConstantValue(Result);
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001942 break;
Reid Spencer060d25d2004-06-29 23:29:38 +00001943 }
1944
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001945 case Type::ULongTyID:
Reid Spencerb83eb642006-10-20 07:07:24 +00001946 Result = ConstantInt::get(Ty, read_vbr_uint64());
Reid Spencer04cde2c2004-07-04 11:33:49 +00001947 if (Handler) Handler->handleConstantValue(Result);
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001948 break;
1949
Reid Spencer060d25d2004-06-29 23:29:38 +00001950 case Type::SByteTyID: // Signed integer types...
1951 case Type::ShortTyID:
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001952 case Type::IntTyID:
1953 case Type::LongTyID: {
Reid Spencer060d25d2004-06-29 23:29:38 +00001954 int64_t Val = read_vbr_int64();
Reid Spencerb83eb642006-10-20 07:07:24 +00001955 if (!ConstantInt::isValueValidForType(Ty, Val))
Reid Spencer24399722004-07-09 22:21:33 +00001956 error("Invalid signed byte/short/int/long read.");
Reid Spencerb83eb642006-10-20 07:07:24 +00001957 Result = ConstantInt::get(Ty, Val);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001958 if (Handler) Handler->handleConstantValue(Result);
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001959 break;
Reid Spencer060d25d2004-06-29 23:29:38 +00001960 }
1961
1962 case Type::FloatTyID: {
Reid Spencer46b002c2004-07-11 17:28:43 +00001963 float Val;
1964 read_float(Val);
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001965 Result = ConstantFP::get(Ty, Val);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001966 if (Handler) Handler->handleConstantValue(Result);
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001967 break;
Reid Spencer060d25d2004-06-29 23:29:38 +00001968 }
1969
1970 case Type::DoubleTyID: {
1971 double Val;
Reid Spencer46b002c2004-07-11 17:28:43 +00001972 read_double(Val);
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001973 Result = ConstantFP::get(Ty, Val);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001974 if (Handler) Handler->handleConstantValue(Result);
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001975 break;
Reid Spencer060d25d2004-06-29 23:29:38 +00001976 }
1977
Reid Spencer060d25d2004-06-29 23:29:38 +00001978 case Type::ArrayTyID: {
1979 const ArrayType *AT = cast<ArrayType>(Ty);
1980 unsigned NumElements = AT->getNumElements();
1981 unsigned TypeSlot = getTypeSlot(AT->getElementType());
1982 std::vector<Constant*> Elements;
1983 Elements.reserve(NumElements);
1984 while (NumElements--) // Read all of the elements of the constant.
1985 Elements.push_back(getConstantValue(TypeSlot,
1986 read_vbr_uint()));
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001987 Result = ConstantArray::get(AT, Elements);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001988 if (Handler) Handler->handleConstantArray(AT, Elements, TypeSlot, Result);
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00001989 break;
Reid Spencer060d25d2004-06-29 23:29:38 +00001990 }
1991
1992 case Type::StructTyID: {
1993 const StructType *ST = cast<StructType>(Ty);
1994
1995 std::vector<Constant *> Elements;
1996 Elements.reserve(ST->getNumElements());
1997 for (unsigned i = 0; i != ST->getNumElements(); ++i)
1998 Elements.push_back(getConstantValue(ST->getElementType(i),
1999 read_vbr_uint()));
2000
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00002001 Result = ConstantStruct::get(ST, Elements);
Reid Spencer04cde2c2004-07-04 11:33:49 +00002002 if (Handler) Handler->handleConstantStruct(ST, Elements, Result);
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00002003 break;
Misha Brukman8a96c532005-04-21 21:44:41 +00002004 }
Reid Spencer060d25d2004-06-29 23:29:38 +00002005
Brian Gaeke715c90b2004-08-20 06:00:58 +00002006 case Type::PackedTyID: {
2007 const PackedType *PT = cast<PackedType>(Ty);
2008 unsigned NumElements = PT->getNumElements();
2009 unsigned TypeSlot = getTypeSlot(PT->getElementType());
2010 std::vector<Constant*> Elements;
2011 Elements.reserve(NumElements);
2012 while (NumElements--) // Read all of the elements of the constant.
2013 Elements.push_back(getConstantValue(TypeSlot,
2014 read_vbr_uint()));
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00002015 Result = ConstantPacked::get(PT, Elements);
Brian Gaeke715c90b2004-08-20 06:00:58 +00002016 if (Handler) Handler->handleConstantPacked(PT, Elements, TypeSlot, Result);
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00002017 break;
Brian Gaeke715c90b2004-08-20 06:00:58 +00002018 }
2019
Chris Lattner638c3812004-11-19 16:24:05 +00002020 case Type::PointerTyID: { // ConstantPointerRef value (backwards compat).
Reid Spencer060d25d2004-06-29 23:29:38 +00002021 const PointerType *PT = cast<PointerType>(Ty);
2022 unsigned Slot = read_vbr_uint();
Misha Brukman8a96c532005-04-21 21:44:41 +00002023
Reid Spencer060d25d2004-06-29 23:29:38 +00002024 // Check to see if we have already read this global variable...
2025 Value *Val = getValue(TypeID, Slot, false);
Reid Spencer060d25d2004-06-29 23:29:38 +00002026 if (Val) {
Chris Lattnerbcb11cf2004-07-27 02:34:49 +00002027 GlobalValue *GV = dyn_cast<GlobalValue>(Val);
2028 if (!GV) error("GlobalValue not in ValueTable!");
2029 if (Handler) Handler->handleConstantPointer(PT, Slot, GV);
2030 return GV;
Reid Spencer060d25d2004-06-29 23:29:38 +00002031 } else {
Reid Spencer24399722004-07-09 22:21:33 +00002032 error("Forward references are not allowed here.");
Reid Spencer060d25d2004-06-29 23:29:38 +00002033 }
Reid Spencer060d25d2004-06-29 23:29:38 +00002034 }
2035
2036 default:
Reid Spencer24399722004-07-09 22:21:33 +00002037 error("Don't know how to deserialize constant value of type '" +
Reid Spencer060d25d2004-06-29 23:29:38 +00002038 Ty->getDescription());
2039 break;
2040 }
Chris Lattnerd2cfb7a2006-04-07 05:00:02 +00002041
2042 // Check that we didn't read a null constant if they are implicit for this
2043 // type plane. Do not do this check for constantexprs, as they may be folded
2044 // to a null value in a way that isn't predicted when a .bc file is initially
2045 // produced.
2046 assert((!isa<Constant>(Result) || !cast<Constant>(Result)->isNullValue()) ||
2047 !hasImplicitNull(TypeID) &&
2048 "Cannot read null values from bytecode!");
2049 return Result;
Reid Spencer060d25d2004-06-29 23:29:38 +00002050}
2051
Misha Brukman8a96c532005-04-21 21:44:41 +00002052/// Resolve references for constants. This function resolves the forward
2053/// referenced constants in the ConstantFwdRefs map. It uses the
Reid Spencer04cde2c2004-07-04 11:33:49 +00002054/// replaceAllUsesWith method of Value class to substitute the placeholder
2055/// instance with the actual instance.
Chris Lattner389bd042004-12-09 06:19:44 +00002056void BytecodeReader::ResolveReferencesToConstant(Constant *NewV, unsigned Typ,
2057 unsigned Slot) {
Chris Lattner29b789b2003-11-19 17:27:18 +00002058 ConstantRefsType::iterator I =
Chris Lattner389bd042004-12-09 06:19:44 +00002059 ConstantFwdRefs.find(std::make_pair(Typ, Slot));
Chris Lattner29b789b2003-11-19 17:27:18 +00002060 if (I == ConstantFwdRefs.end()) return; // Never forward referenced?
Chris Lattner00950542001-06-06 20:29:01 +00002061
Chris Lattner29b789b2003-11-19 17:27:18 +00002062 Value *PH = I->second; // Get the placeholder...
2063 PH->replaceAllUsesWith(NewV);
2064 delete PH; // Delete the old placeholder
2065 ConstantFwdRefs.erase(I); // Remove the map entry for it
Vikram S. Advec1e4a812002-07-14 23:04:18 +00002066}
2067
Reid Spencer04cde2c2004-07-04 11:33:49 +00002068/// Parse the constant strings section.
Reid Spencer060d25d2004-06-29 23:29:38 +00002069void BytecodeReader::ParseStringConstants(unsigned NumEntries, ValueTable &Tab){
2070 for (; NumEntries; --NumEntries) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00002071 unsigned Typ = 0;
Reid Spencer46b002c2004-07-11 17:28:43 +00002072 if (read_typeid(Typ))
Reid Spencer24399722004-07-09 22:21:33 +00002073 error("Invalid type (type type) for string constant");
Reid Spencer060d25d2004-06-29 23:29:38 +00002074 const Type *Ty = getType(Typ);
2075 if (!isa<ArrayType>(Ty))
Reid Spencer24399722004-07-09 22:21:33 +00002076 error("String constant data invalid!");
Misha Brukman8a96c532005-04-21 21:44:41 +00002077
Reid Spencer060d25d2004-06-29 23:29:38 +00002078 const ArrayType *ATy = cast<ArrayType>(Ty);
2079 if (ATy->getElementType() != Type::SByteTy &&
2080 ATy->getElementType() != Type::UByteTy)
Reid Spencer24399722004-07-09 22:21:33 +00002081 error("String constant data invalid!");
Misha Brukman8a96c532005-04-21 21:44:41 +00002082
Reid Spencer060d25d2004-06-29 23:29:38 +00002083 // Read character data. The type tells us how long the string is.
Misha Brukman8a96c532005-04-21 21:44:41 +00002084 char *Data = reinterpret_cast<char *>(alloca(ATy->getNumElements()));
Reid Spencer060d25d2004-06-29 23:29:38 +00002085 read_data(Data, Data+ATy->getNumElements());
Chris Lattner52e20b02003-03-19 20:54:26 +00002086
Reid Spencer060d25d2004-06-29 23:29:38 +00002087 std::vector<Constant*> Elements(ATy->getNumElements());
Reid Spencerb83eb642006-10-20 07:07:24 +00002088 const Type* ElemType = ATy->getElementType();
2089 for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
2090 Elements[i] = ConstantInt::get(ElemType, (unsigned char)Data[i]);
Misha Brukman12c29d12003-09-22 23:38:23 +00002091
Reid Spencer060d25d2004-06-29 23:29:38 +00002092 // Create the constant, inserting it as needed.
2093 Constant *C = ConstantArray::get(ATy, Elements);
2094 unsigned Slot = insertValue(C, Typ, Tab);
Chris Lattner389bd042004-12-09 06:19:44 +00002095 ResolveReferencesToConstant(C, Typ, Slot);
Reid Spencer04cde2c2004-07-04 11:33:49 +00002096 if (Handler) Handler->handleConstantString(cast<ConstantArray>(C));
Reid Spencer060d25d2004-06-29 23:29:38 +00002097 }
Misha Brukman12c29d12003-09-22 23:38:23 +00002098}
2099
Reid Spencer04cde2c2004-07-04 11:33:49 +00002100/// Parse the constant pool.
Misha Brukman8a96c532005-04-21 21:44:41 +00002101void BytecodeReader::ParseConstantPool(ValueTable &Tab,
Reid Spencer04cde2c2004-07-04 11:33:49 +00002102 TypeListTy &TypeTab,
Reid Spencer46b002c2004-07-11 17:28:43 +00002103 bool isFunction) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00002104 if (Handler) Handler->handleGlobalConstantsBegin();
2105
2106 /// In LLVM 1.3 Type does not derive from Value so the types
2107 /// do not occupy a plane. Consequently, we read the types
2108 /// first in the constant pool.
Reid Spencer46b002c2004-07-11 17:28:43 +00002109 if (isFunction && !hasTypeDerivedFromValue) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00002110 unsigned NumEntries = read_vbr_uint();
Reid Spencer46b002c2004-07-11 17:28:43 +00002111 ParseTypes(TypeTab, NumEntries);
Reid Spencer04cde2c2004-07-04 11:33:49 +00002112 }
2113
Reid Spencer46b002c2004-07-11 17:28:43 +00002114 while (moreInBlock()) {
Reid Spencer060d25d2004-06-29 23:29:38 +00002115 unsigned NumEntries = read_vbr_uint();
Reid Spencer04cde2c2004-07-04 11:33:49 +00002116 unsigned Typ = 0;
2117 bool isTypeType = read_typeid(Typ);
2118
2119 /// In LLVM 1.2 and before, Types were written to the
2120 /// bytecode file in the "Type Type" plane (#12).
2121 /// In 1.3 plane 12 is now the label plane. Handle this here.
Reid Spencer46b002c2004-07-11 17:28:43 +00002122 if (isTypeType) {
2123 ParseTypes(TypeTab, NumEntries);
Reid Spencer060d25d2004-06-29 23:29:38 +00002124 } else if (Typ == Type::VoidTyID) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00002125 /// Use of Type::VoidTyID is a misnomer. It actually means
2126 /// that the following plane is constant strings
Reid Spencer060d25d2004-06-29 23:29:38 +00002127 assert(&Tab == &ModuleValues && "Cannot read strings in functions!");
2128 ParseStringConstants(NumEntries, Tab);
2129 } else {
2130 for (unsigned i = 0; i < NumEntries; ++i) {
Chris Lattner3bc5a602006-01-25 23:08:15 +00002131 Value *V = ParseConstantPoolValue(Typ);
2132 assert(V && "ParseConstantPoolValue returned NULL!");
2133 unsigned Slot = insertValue(V, Typ, Tab);
Chris Lattner29b789b2003-11-19 17:27:18 +00002134
Reid Spencer060d25d2004-06-29 23:29:38 +00002135 // If we are reading a function constant table, make sure that we adjust
2136 // the slot number to be the real global constant number.
2137 //
2138 if (&Tab != &ModuleValues && Typ < ModuleValues.size() &&
2139 ModuleValues[Typ])
2140 Slot += ModuleValues[Typ]->size();
Chris Lattner3bc5a602006-01-25 23:08:15 +00002141 if (Constant *C = dyn_cast<Constant>(V))
2142 ResolveReferencesToConstant(C, Typ, Slot);
Reid Spencer060d25d2004-06-29 23:29:38 +00002143 }
2144 }
2145 }
Chris Lattner02dce162004-12-04 05:28:27 +00002146
2147 // After we have finished parsing the constant pool, we had better not have
2148 // any dangling references left.
Reid Spencer3c391272004-12-04 22:19:53 +00002149 if (!ConstantFwdRefs.empty()) {
Reid Spencer3c391272004-12-04 22:19:53 +00002150 ConstantRefsType::const_iterator I = ConstantFwdRefs.begin();
Reid Spencer3c391272004-12-04 22:19:53 +00002151 Constant* missingConst = I->second;
Misha Brukman8a96c532005-04-21 21:44:41 +00002152 error(utostr(ConstantFwdRefs.size()) +
2153 " unresolved constant reference exist. First one is '" +
2154 missingConst->getName() + "' of type '" +
Chris Lattner389bd042004-12-09 06:19:44 +00002155 missingConst->getType()->getDescription() + "'.");
Reid Spencer3c391272004-12-04 22:19:53 +00002156 }
Chris Lattner02dce162004-12-04 05:28:27 +00002157
Reid Spencer060d25d2004-06-29 23:29:38 +00002158 checkPastBlockEnd("Constant Pool");
Reid Spencer04cde2c2004-07-04 11:33:49 +00002159 if (Handler) Handler->handleGlobalConstantsEnd();
Reid Spencer060d25d2004-06-29 23:29:38 +00002160}
Chris Lattner00950542001-06-06 20:29:01 +00002161
Reid Spencer04cde2c2004-07-04 11:33:49 +00002162/// Parse the contents of a function. Note that this function can be
2163/// called lazily by materializeFunction
2164/// @see materializeFunction
Reid Spencer46b002c2004-07-11 17:28:43 +00002165void BytecodeReader::ParseFunctionBody(Function* F) {
Reid Spencer060d25d2004-06-29 23:29:38 +00002166
2167 unsigned FuncSize = BlockEnd - At;
Chris Lattnere3869c82003-04-16 21:16:05 +00002168 GlobalValue::LinkageTypes Linkage = GlobalValue::ExternalLinkage;
2169
Reid Spencer060d25d2004-06-29 23:29:38 +00002170 unsigned LinkageType = read_vbr_uint();
Chris Lattnerc08912f2004-01-14 16:44:44 +00002171 switch (LinkageType) {
2172 case 0: Linkage = GlobalValue::ExternalLinkage; break;
2173 case 1: Linkage = GlobalValue::WeakLinkage; break;
2174 case 2: Linkage = GlobalValue::AppendingLinkage; break;
2175 case 3: Linkage = GlobalValue::InternalLinkage; break;
2176 case 4: Linkage = GlobalValue::LinkOnceLinkage; break;
Anton Korobeynikovb74ed072006-09-14 18:23:27 +00002177 case 5: Linkage = GlobalValue::DLLImportLinkage; break;
2178 case 6: Linkage = GlobalValue::DLLExportLinkage; break;
2179 case 7: Linkage = GlobalValue::ExternalWeakLinkage; break;
Reid Spencer060d25d2004-06-29 23:29:38 +00002180 default:
Reid Spencer24399722004-07-09 22:21:33 +00002181 error("Invalid linkage type for Function.");
Reid Spencer060d25d2004-06-29 23:29:38 +00002182 Linkage = GlobalValue::InternalLinkage;
2183 break;
Chris Lattnere3869c82003-04-16 21:16:05 +00002184 }
Chris Lattnerd23b1d32001-11-26 18:56:10 +00002185
Reid Spencer46b002c2004-07-11 17:28:43 +00002186 F->setLinkage(Linkage);
Reid Spencer04cde2c2004-07-04 11:33:49 +00002187 if (Handler) Handler->handleFunctionBegin(F,FuncSize);
Chris Lattner00950542001-06-06 20:29:01 +00002188
Chris Lattner4ee8ef22003-10-08 22:52:54 +00002189 // Keep track of how many basic blocks we have read in...
2190 unsigned BlockNum = 0;
Chris Lattner89e02532004-01-18 21:08:15 +00002191 bool InsertedArguments = false;
Chris Lattner4ee8ef22003-10-08 22:52:54 +00002192
Reid Spencer060d25d2004-06-29 23:29:38 +00002193 BufPtr MyEnd = BlockEnd;
Reid Spencer46b002c2004-07-11 17:28:43 +00002194 while (At < MyEnd) {
Chris Lattner00950542001-06-06 20:29:01 +00002195 unsigned Type, Size;
Reid Spencer060d25d2004-06-29 23:29:38 +00002196 BufPtr OldAt = At;
2197 read_block(Type, Size);
Chris Lattner00950542001-06-06 20:29:01 +00002198
2199 switch (Type) {
Reid Spencerad89bd62004-07-25 18:07:36 +00002200 case BytecodeFormat::ConstantPoolBlockID:
Chris Lattner89e02532004-01-18 21:08:15 +00002201 if (!InsertedArguments) {
2202 // Insert arguments into the value table before we parse the first basic
2203 // block in the function, but after we potentially read in the
2204 // compaction table.
Reid Spencer04cde2c2004-07-04 11:33:49 +00002205 insertArguments(F);
Chris Lattner89e02532004-01-18 21:08:15 +00002206 InsertedArguments = true;
2207 }
2208
Reid Spencer04cde2c2004-07-04 11:33:49 +00002209 ParseConstantPool(FunctionValues, FunctionTypes, true);
Chris Lattner00950542001-06-06 20:29:01 +00002210 break;
2211
Reid Spencerad89bd62004-07-25 18:07:36 +00002212 case BytecodeFormat::CompactionTableBlockID:
Reid Spencer060d25d2004-06-29 23:29:38 +00002213 ParseCompactionTable();
Chris Lattner89e02532004-01-18 21:08:15 +00002214 break;
2215
Chris Lattner00950542001-06-06 20:29:01 +00002216 case BytecodeFormat::BasicBlock: {
Chris Lattner89e02532004-01-18 21:08:15 +00002217 if (!InsertedArguments) {
2218 // Insert arguments into the value table before we parse the first basic
2219 // block in the function, but after we potentially read in the
2220 // compaction table.
Reid Spencer04cde2c2004-07-04 11:33:49 +00002221 insertArguments(F);
Chris Lattner89e02532004-01-18 21:08:15 +00002222 InsertedArguments = true;
2223 }
2224
Reid Spencer060d25d2004-06-29 23:29:38 +00002225 BasicBlock *BB = ParseBasicBlock(BlockNum++);
Chris Lattner4ee8ef22003-10-08 22:52:54 +00002226 F->getBasicBlockList().push_back(BB);
Chris Lattner00950542001-06-06 20:29:01 +00002227 break;
2228 }
2229
Reid Spencerad89bd62004-07-25 18:07:36 +00002230 case BytecodeFormat::InstructionListBlockID: {
Chris Lattner89e02532004-01-18 21:08:15 +00002231 // Insert arguments into the value table before we parse the instruction
2232 // list for the function, but after we potentially read in the compaction
2233 // table.
2234 if (!InsertedArguments) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00002235 insertArguments(F);
Chris Lattner89e02532004-01-18 21:08:15 +00002236 InsertedArguments = true;
2237 }
2238
Misha Brukman8a96c532005-04-21 21:44:41 +00002239 if (BlockNum)
Reid Spencer24399722004-07-09 22:21:33 +00002240 error("Already parsed basic blocks!");
Reid Spencer060d25d2004-06-29 23:29:38 +00002241 BlockNum = ParseInstructionList(F);
Chris Lattner8d1dbd22003-12-01 07:05:31 +00002242 break;
2243 }
2244
Reid Spencerad89bd62004-07-25 18:07:36 +00002245 case BytecodeFormat::SymbolTableBlockID:
Reid Spencer060d25d2004-06-29 23:29:38 +00002246 ParseSymbolTable(F, &F->getSymbolTable());
Chris Lattner00950542001-06-06 20:29:01 +00002247 break;
2248
2249 default:
Reid Spencer060d25d2004-06-29 23:29:38 +00002250 At += Size;
Misha Brukman8a96c532005-04-21 21:44:41 +00002251 if (OldAt > At)
Reid Spencer24399722004-07-09 22:21:33 +00002252 error("Wrapped around reading bytecode.");
Chris Lattner00950542001-06-06 20:29:01 +00002253 break;
2254 }
Reid Spencer060d25d2004-06-29 23:29:38 +00002255 BlockEnd = MyEnd;
Chris Lattner1d670cc2001-09-07 16:37:43 +00002256
Misha Brukman12c29d12003-09-22 23:38:23 +00002257 // Malformed bc file if read past end of block.
Reid Spencer060d25d2004-06-29 23:29:38 +00002258 align32();
Chris Lattner00950542001-06-06 20:29:01 +00002259 }
2260
Chris Lattner4ee8ef22003-10-08 22:52:54 +00002261 // Make sure there were no references to non-existant basic blocks.
2262 if (BlockNum != ParsedBasicBlocks.size())
Reid Spencer24399722004-07-09 22:21:33 +00002263 error("Illegal basic block operand reference");
Reid Spencer060d25d2004-06-29 23:29:38 +00002264
Chris Lattner4ee8ef22003-10-08 22:52:54 +00002265 ParsedBasicBlocks.clear();
2266
Chris Lattner97330cf2003-10-09 23:10:14 +00002267 // Resolve forward references. Replace any uses of a forward reference value
2268 // with the real value.
Chris Lattner8eb10ce2003-10-09 06:05:40 +00002269 while (!ForwardReferences.empty()) {
Chris Lattnerc4d69162004-12-09 04:51:50 +00002270 std::map<std::pair<unsigned,unsigned>, Value*>::iterator
2271 I = ForwardReferences.begin();
2272 Value *V = getValue(I->first.first, I->first.second, false);
Chris Lattner8eb10ce2003-10-09 06:05:40 +00002273 Value *PlaceHolder = I->second;
Chris Lattnerc4d69162004-12-09 04:51:50 +00002274 PlaceHolder->replaceAllUsesWith(V);
Chris Lattner8eb10ce2003-10-09 06:05:40 +00002275 ForwardReferences.erase(I);
Chris Lattner8eb10ce2003-10-09 06:05:40 +00002276 delete PlaceHolder;
Chris Lattner6e448022003-10-08 21:51:46 +00002277 }
Chris Lattner00950542001-06-06 20:29:01 +00002278
Reid Spencere2a5fb02006-01-27 11:49:27 +00002279 // If upgraded intrinsic functions were detected during reading of the
2280 // module information, then we need to look for instructions that need to
2281 // be upgraded. This can't be done while the instructions are read in because
2282 // additional instructions inserted mess up the slot numbering.
2283 if (!upgradedFunctions.empty()) {
2284 for (Function::iterator BI = F->begin(), BE = F->end(); BI != BE; ++BI)
2285 for (BasicBlock::iterator II = BI->begin(), IE = BI->end();
Jim Laskeyf4321a32006-03-13 13:07:37 +00002286 II != IE;)
2287 if (CallInst* CI = dyn_cast<CallInst>(II++)) {
Reid Spencere2a5fb02006-01-27 11:49:27 +00002288 std::map<Function*,Function*>::iterator FI =
2289 upgradedFunctions.find(CI->getCalledFunction());
Chris Lattnerbad08002006-03-02 23:59:12 +00002290 if (FI != upgradedFunctions.end())
2291 UpgradeIntrinsicCall(CI, FI->second);
Reid Spencere2a5fb02006-01-27 11:49:27 +00002292 }
2293 }
2294
Misha Brukman12c29d12003-09-22 23:38:23 +00002295 // Clear out function-level types...
Reid Spencer060d25d2004-06-29 23:29:38 +00002296 FunctionTypes.clear();
2297 CompactionTypes.clear();
2298 CompactionValues.clear();
2299 freeTable(FunctionValues);
2300
Reid Spencer04cde2c2004-07-04 11:33:49 +00002301 if (Handler) Handler->handleFunctionEnd(F);
Chris Lattner00950542001-06-06 20:29:01 +00002302}
2303
Reid Spencer04cde2c2004-07-04 11:33:49 +00002304/// This function parses LLVM functions lazily. It obtains the type of the
2305/// function and records where the body of the function is in the bytecode
Misha Brukman8a96c532005-04-21 21:44:41 +00002306/// buffer. The caller can then use the ParseNextFunction and
Reid Spencer04cde2c2004-07-04 11:33:49 +00002307/// ParseAllFunctionBodies to get handler events for the functions.
Reid Spencer060d25d2004-06-29 23:29:38 +00002308void BytecodeReader::ParseFunctionLazily() {
2309 if (FunctionSignatureList.empty())
Reid Spencer24399722004-07-09 22:21:33 +00002310 error("FunctionSignatureList empty!");
Chris Lattner89e02532004-01-18 21:08:15 +00002311
Reid Spencer060d25d2004-06-29 23:29:38 +00002312 Function *Func = FunctionSignatureList.back();
2313 FunctionSignatureList.pop_back();
Chris Lattner24102432004-01-18 22:35:34 +00002314
Reid Spencer060d25d2004-06-29 23:29:38 +00002315 // Save the information for future reading of the function
2316 LazyFunctionLoadMap[Func] = LazyFunctionInfo(BlockStart, BlockEnd);
Chris Lattner89e02532004-01-18 21:08:15 +00002317
Misha Brukmana3e6ad62004-11-14 21:02:55 +00002318 // This function has a body but it's not loaded so it appears `External'.
2319 // Mark it as a `Ghost' instead to notify the users that it has a body.
2320 Func->setLinkage(GlobalValue::GhostLinkage);
2321
Reid Spencer060d25d2004-06-29 23:29:38 +00002322 // Pretend we've `parsed' this function
2323 At = BlockEnd;
2324}
Chris Lattner89e02532004-01-18 21:08:15 +00002325
Misha Brukman8a96c532005-04-21 21:44:41 +00002326/// The ParserFunction method lazily parses one function. Use this method to
2327/// casue the parser to parse a specific function in the module. Note that
2328/// this will remove the function from what is to be included by
Reid Spencer04cde2c2004-07-04 11:33:49 +00002329/// ParseAllFunctionBodies.
2330/// @see ParseAllFunctionBodies
2331/// @see ParseBytecode
Reid Spencer99655e12006-08-25 19:54:53 +00002332bool BytecodeReader::ParseFunction(Function* Func, std::string* ErrMsg) {
2333
2334 if (setjmp(context))
2335 return true;
2336
Reid Spencer060d25d2004-06-29 23:29:38 +00002337 // Find {start, end} pointers and slot in the map. If not there, we're done.
2338 LazyFunctionMap::iterator Fi = LazyFunctionLoadMap.find(Func);
Chris Lattner89e02532004-01-18 21:08:15 +00002339
Reid Spencer060d25d2004-06-29 23:29:38 +00002340 // Make sure we found it
Reid Spencer46b002c2004-07-11 17:28:43 +00002341 if (Fi == LazyFunctionLoadMap.end()) {
Reid Spencer24399722004-07-09 22:21:33 +00002342 error("Unrecognized function of type " + Func->getType()->getDescription());
Reid Spencer99655e12006-08-25 19:54:53 +00002343 return true;
Chris Lattner89e02532004-01-18 21:08:15 +00002344 }
2345
Reid Spencer060d25d2004-06-29 23:29:38 +00002346 BlockStart = At = Fi->second.Buf;
2347 BlockEnd = Fi->second.EndBuf;
Reid Spencer24399722004-07-09 22:21:33 +00002348 assert(Fi->first == Func && "Found wrong function?");
Reid Spencer060d25d2004-06-29 23:29:38 +00002349
2350 LazyFunctionLoadMap.erase(Fi);
2351
Reid Spencer46b002c2004-07-11 17:28:43 +00002352 this->ParseFunctionBody(Func);
Reid Spencer99655e12006-08-25 19:54:53 +00002353 return false;
Chris Lattner89e02532004-01-18 21:08:15 +00002354}
2355
Reid Spencer04cde2c2004-07-04 11:33:49 +00002356/// The ParseAllFunctionBodies method parses through all the previously
2357/// unparsed functions in the bytecode file. If you want to completely parse
2358/// a bytecode file, this method should be called after Parsebytecode because
2359/// Parsebytecode only records the locations in the bytecode file of where
2360/// the function definitions are located. This function uses that information
2361/// to materialize the functions.
2362/// @see ParseBytecode
Reid Spencer99655e12006-08-25 19:54:53 +00002363bool BytecodeReader::ParseAllFunctionBodies(std::string* ErrMsg) {
2364 if (setjmp(context))
2365 return true;
2366
Reid Spencer060d25d2004-06-29 23:29:38 +00002367 LazyFunctionMap::iterator Fi = LazyFunctionLoadMap.begin();
2368 LazyFunctionMap::iterator Fe = LazyFunctionLoadMap.end();
Chris Lattner89e02532004-01-18 21:08:15 +00002369
Reid Spencer46b002c2004-07-11 17:28:43 +00002370 while (Fi != Fe) {
Reid Spencer060d25d2004-06-29 23:29:38 +00002371 Function* Func = Fi->first;
2372 BlockStart = At = Fi->second.Buf;
2373 BlockEnd = Fi->second.EndBuf;
Chris Lattnerb52f1c22005-02-13 17:48:18 +00002374 ParseFunctionBody(Func);
Reid Spencer060d25d2004-06-29 23:29:38 +00002375 ++Fi;
2376 }
Chris Lattnerb52f1c22005-02-13 17:48:18 +00002377 LazyFunctionLoadMap.clear();
Reid Spencer99655e12006-08-25 19:54:53 +00002378 return false;
Reid Spencer060d25d2004-06-29 23:29:38 +00002379}
Chris Lattner89e02532004-01-18 21:08:15 +00002380
Reid Spencer04cde2c2004-07-04 11:33:49 +00002381/// Parse the global type list
Reid Spencer060d25d2004-06-29 23:29:38 +00002382void BytecodeReader::ParseGlobalTypes() {
Reid Spencer04cde2c2004-07-04 11:33:49 +00002383 // Read the number of types
2384 unsigned NumEntries = read_vbr_uint();
Reid Spencer011bed52004-07-09 21:13:53 +00002385
2386 // Ignore the type plane identifier for types if the bc file is pre 1.3
2387 if (hasTypeDerivedFromValue)
2388 read_vbr_uint();
2389
Reid Spencer46b002c2004-07-11 17:28:43 +00002390 ParseTypes(ModuleTypes, NumEntries);
Reid Spencer060d25d2004-06-29 23:29:38 +00002391}
2392
Reid Spencer04cde2c2004-07-04 11:33:49 +00002393/// Parse the Global info (types, global vars, constants)
Reid Spencer060d25d2004-06-29 23:29:38 +00002394void BytecodeReader::ParseModuleGlobalInfo() {
2395
Reid Spencer04cde2c2004-07-04 11:33:49 +00002396 if (Handler) Handler->handleModuleGlobalsBegin();
Chris Lattner00950542001-06-06 20:29:01 +00002397
Chris Lattner404cddf2005-11-12 01:33:40 +00002398 // SectionID - If a global has an explicit section specified, this map
2399 // remembers the ID until we can translate it into a string.
2400 std::map<GlobalValue*, unsigned> SectionID;
2401
Chris Lattner70cc3392001-09-10 07:58:01 +00002402 // Read global variables...
Reid Spencer060d25d2004-06-29 23:29:38 +00002403 unsigned VarType = read_vbr_uint();
Chris Lattner70cc3392001-09-10 07:58:01 +00002404 while (VarType != Type::VoidTyID) { // List is terminated by Void
Chris Lattner9dd87702004-04-03 23:43:42 +00002405 // VarType Fields: bit0 = isConstant, bit1 = hasInitializer, bit2,3,4 =
2406 // Linkage, bit4+ = slot#
2407 unsigned SlotNo = VarType >> 5;
Reid Spencer46b002c2004-07-11 17:28:43 +00002408 if (sanitizeTypeId(SlotNo))
Reid Spencer24399722004-07-09 22:21:33 +00002409 error("Invalid type (type type) for global var!");
Chris Lattner9dd87702004-04-03 23:43:42 +00002410 unsigned LinkageID = (VarType >> 2) & 7;
Reid Spencer060d25d2004-06-29 23:29:38 +00002411 bool isConstant = VarType & 1;
Chris Lattnerce5e04e2005-11-06 08:23:17 +00002412 bool hasInitializer = (VarType & 2) != 0;
Chris Lattner8eb52dd2005-11-06 07:11:04 +00002413 unsigned Alignment = 0;
Chris Lattner404cddf2005-11-12 01:33:40 +00002414 unsigned GlobalSectionID = 0;
Chris Lattner8eb52dd2005-11-06 07:11:04 +00002415
2416 // An extension word is present when linkage = 3 (internal) and hasinit = 0.
2417 if (LinkageID == 3 && !hasInitializer) {
2418 unsigned ExtWord = read_vbr_uint();
2419 // The extension word has this format: bit 0 = has initializer, bit 1-3 =
2420 // linkage, bit 4-8 = alignment (log2), bits 10+ = future use.
2421 hasInitializer = ExtWord & 1;
2422 LinkageID = (ExtWord >> 1) & 7;
2423 Alignment = (1 << ((ExtWord >> 4) & 31)) >> 1;
Chris Lattner404cddf2005-11-12 01:33:40 +00002424
2425 if (ExtWord & (1 << 9)) // Has a section ID.
2426 GlobalSectionID = read_vbr_uint();
Chris Lattner8eb52dd2005-11-06 07:11:04 +00002427 }
Chris Lattnere3869c82003-04-16 21:16:05 +00002428
Chris Lattnerce5e04e2005-11-06 08:23:17 +00002429 GlobalValue::LinkageTypes Linkage;
Chris Lattnerc08912f2004-01-14 16:44:44 +00002430 switch (LinkageID) {
Chris Lattnerc08912f2004-01-14 16:44:44 +00002431 case 0: Linkage = GlobalValue::ExternalLinkage; break;
2432 case 1: Linkage = GlobalValue::WeakLinkage; break;
2433 case 2: Linkage = GlobalValue::AppendingLinkage; break;
2434 case 3: Linkage = GlobalValue::InternalLinkage; break;
2435 case 4: Linkage = GlobalValue::LinkOnceLinkage; break;
Anton Korobeynikovb74ed072006-09-14 18:23:27 +00002436 case 5: Linkage = GlobalValue::DLLImportLinkage; break;
2437 case 6: Linkage = GlobalValue::DLLExportLinkage; break;
2438 case 7: Linkage = GlobalValue::ExternalWeakLinkage; break;
Misha Brukman8a96c532005-04-21 21:44:41 +00002439 default:
Reid Spencer24399722004-07-09 22:21:33 +00002440 error("Unknown linkage type: " + utostr(LinkageID));
Reid Spencer060d25d2004-06-29 23:29:38 +00002441 Linkage = GlobalValue::InternalLinkage;
2442 break;
Chris Lattnere3869c82003-04-16 21:16:05 +00002443 }
2444
2445 const Type *Ty = getType(SlotNo);
Chris Lattnere73bd452005-11-06 07:43:39 +00002446 if (!Ty)
Reid Spencer24399722004-07-09 22:21:33 +00002447 error("Global has no type! SlotNo=" + utostr(SlotNo));
Reid Spencer060d25d2004-06-29 23:29:38 +00002448
Chris Lattnere73bd452005-11-06 07:43:39 +00002449 if (!isa<PointerType>(Ty))
Reid Spencer24399722004-07-09 22:21:33 +00002450 error("Global not a pointer type! Ty= " + Ty->getDescription());
Chris Lattner70cc3392001-09-10 07:58:01 +00002451
Chris Lattner52e20b02003-03-19 20:54:26 +00002452 const Type *ElTy = cast<PointerType>(Ty)->getElementType();
Chris Lattnerd70684f2001-09-18 04:01:05 +00002453
Chris Lattner70cc3392001-09-10 07:58:01 +00002454 // Create the global variable...
Reid Spencer060d25d2004-06-29 23:29:38 +00002455 GlobalVariable *GV = new GlobalVariable(ElTy, isConstant, Linkage,
Chris Lattner52e20b02003-03-19 20:54:26 +00002456 0, "", TheModule);
Chris Lattner8eb52dd2005-11-06 07:11:04 +00002457 GV->setAlignment(Alignment);
Chris Lattner29b789b2003-11-19 17:27:18 +00002458 insertValue(GV, SlotNo, ModuleValues);
Chris Lattner05950c32001-10-13 06:47:01 +00002459
Chris Lattner404cddf2005-11-12 01:33:40 +00002460 if (GlobalSectionID != 0)
2461 SectionID[GV] = GlobalSectionID;
2462
Reid Spencer060d25d2004-06-29 23:29:38 +00002463 unsigned initSlot = 0;
Misha Brukman8a96c532005-04-21 21:44:41 +00002464 if (hasInitializer) {
Reid Spencer060d25d2004-06-29 23:29:38 +00002465 initSlot = read_vbr_uint();
2466 GlobalInits.push_back(std::make_pair(GV, initSlot));
2467 }
2468
2469 // Notify handler about the global value.
Chris Lattner4a242b32004-10-14 01:39:18 +00002470 if (Handler)
2471 Handler->handleGlobalVariable(ElTy, isConstant, Linkage, SlotNo,initSlot);
Reid Spencer060d25d2004-06-29 23:29:38 +00002472
2473 // Get next item
2474 VarType = read_vbr_uint();
Chris Lattner70cc3392001-09-10 07:58:01 +00002475 }
2476
Chris Lattner52e20b02003-03-19 20:54:26 +00002477 // Read the function objects for all of the functions that are coming
Chris Lattnera79e7cc2004-10-16 18:18:16 +00002478 unsigned FnSignature = read_vbr_uint();
Reid Spencer24399722004-07-09 22:21:33 +00002479
Chris Lattnera79e7cc2004-10-16 18:18:16 +00002480 if (hasNoFlagsForFunctions)
2481 FnSignature = (FnSignature << 5) + 1;
2482
2483 // List is terminated by VoidTy.
Chris Lattnere73bd452005-11-06 07:43:39 +00002484 while (((FnSignature & (~0U >> 1)) >> 5) != Type::VoidTyID) {
2485 const Type *Ty = getType((FnSignature & (~0U >> 1)) >> 5);
Chris Lattner927b1852003-10-09 20:22:47 +00002486 if (!isa<PointerType>(Ty) ||
Reid Spencer060d25d2004-06-29 23:29:38 +00002487 !isa<FunctionType>(cast<PointerType>(Ty)->getElementType())) {
Misha Brukman8a96c532005-04-21 21:44:41 +00002488 error("Function not a pointer to function type! Ty = " +
Reid Spencer46b002c2004-07-11 17:28:43 +00002489 Ty->getDescription());
Reid Spencer060d25d2004-06-29 23:29:38 +00002490 }
Chris Lattner8cdc6b72002-10-23 00:51:54 +00002491
Chris Lattner2a7b6ba2003-03-06 17:15:19 +00002492 // We create functions by passing the underlying FunctionType to create...
Misha Brukman8a96c532005-04-21 21:44:41 +00002493 const FunctionType* FTy =
Reid Spencer060d25d2004-06-29 23:29:38 +00002494 cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
Chris Lattner00950542001-06-06 20:29:01 +00002495
Chris Lattner18549c22004-11-15 21:43:03 +00002496 // Insert the place holder.
Chris Lattner404cddf2005-11-12 01:33:40 +00002497 Function *Func = new Function(FTy, GlobalValue::ExternalLinkage,
Reid Spencer04cde2c2004-07-04 11:33:49 +00002498 "", TheModule);
Reid Spencere1e96c02006-01-19 07:02:16 +00002499
Chris Lattnere73bd452005-11-06 07:43:39 +00002500 insertValue(Func, (FnSignature & (~0U >> 1)) >> 5, ModuleValues);
Chris Lattnera79e7cc2004-10-16 18:18:16 +00002501
2502 // Flags are not used yet.
Chris Lattner97fbc502004-11-15 22:38:52 +00002503 unsigned Flags = FnSignature & 31;
Chris Lattner00950542001-06-06 20:29:01 +00002504
Chris Lattner97fbc502004-11-15 22:38:52 +00002505 // Save this for later so we know type of lazily instantiated functions.
2506 // Note that known-external functions do not have FunctionInfo blocks, so we
2507 // do not add them to the FunctionSignatureList.
2508 if ((Flags & (1 << 4)) == 0)
2509 FunctionSignatureList.push_back(Func);
Chris Lattner52e20b02003-03-19 20:54:26 +00002510
Chris Lattnere73bd452005-11-06 07:43:39 +00002511 // Get the calling convention from the low bits.
2512 unsigned CC = Flags & 15;
2513 unsigned Alignment = 0;
2514 if (FnSignature & (1 << 31)) { // Has extension word?
2515 unsigned ExtWord = read_vbr_uint();
2516 Alignment = (1 << (ExtWord & 31)) >> 1;
2517 CC |= ((ExtWord >> 5) & 15) << 4;
Chris Lattner404cddf2005-11-12 01:33:40 +00002518
2519 if (ExtWord & (1 << 10)) // Has a section ID.
2520 SectionID[Func] = read_vbr_uint();
Anton Korobeynikovb74ed072006-09-14 18:23:27 +00002521
2522 // Parse external declaration linkage
2523 switch ((ExtWord >> 11) & 3) {
2524 case 0: break;
2525 case 1: Func->setLinkage(Function::DLLImportLinkage); break;
2526 case 2: Func->setLinkage(Function::ExternalWeakLinkage); break;
2527 default: assert(0 && "Unsupported external linkage");
2528 }
Chris Lattnere73bd452005-11-06 07:43:39 +00002529 }
2530
Chris Lattner54b369e2005-11-06 07:46:13 +00002531 Func->setCallingConv(CC-1);
Chris Lattnere73bd452005-11-06 07:43:39 +00002532 Func->setAlignment(Alignment);
Chris Lattner479ffeb2005-05-06 20:42:57 +00002533
Reid Spencer04cde2c2004-07-04 11:33:49 +00002534 if (Handler) Handler->handleFunctionDeclaration(Func);
Reid Spencer060d25d2004-06-29 23:29:38 +00002535
Chris Lattnera79e7cc2004-10-16 18:18:16 +00002536 // Get the next function signature.
2537 FnSignature = read_vbr_uint();
2538 if (hasNoFlagsForFunctions)
2539 FnSignature = (FnSignature << 5) + 1;
Chris Lattner00950542001-06-06 20:29:01 +00002540 }
2541
Misha Brukman8a96c532005-04-21 21:44:41 +00002542 // Now that the function signature list is set up, reverse it so that we can
Chris Lattner74734132002-08-17 22:01:27 +00002543 // remove elements efficiently from the back of the vector.
2544 std::reverse(FunctionSignatureList.begin(), FunctionSignatureList.end());
Chris Lattner00950542001-06-06 20:29:01 +00002545
Chris Lattner404cddf2005-11-12 01:33:40 +00002546 /// SectionNames - This contains the list of section names encoded in the
2547 /// moduleinfoblock. Functions and globals with an explicit section index
2548 /// into this to get their section name.
2549 std::vector<std::string> SectionNames;
2550
2551 if (hasInconsistentModuleGlobalInfo) {
2552 align32();
2553 } else if (!hasNoDependentLibraries) {
2554 // If this bytecode format has dependent library information in it, read in
2555 // the number of dependent library items that follow.
Reid Spencerad89bd62004-07-25 18:07:36 +00002556 unsigned num_dep_libs = read_vbr_uint();
2557 std::string dep_lib;
Chris Lattner404cddf2005-11-12 01:33:40 +00002558 while (num_dep_libs--) {
Reid Spencerad89bd62004-07-25 18:07:36 +00002559 dep_lib = read_str();
Reid Spencerada16182004-07-25 21:36:26 +00002560 TheModule->addLibrary(dep_lib);
Reid Spencer5b472d92004-08-21 20:49:23 +00002561 if (Handler)
2562 Handler->handleDependentLibrary(dep_lib);
Reid Spencerad89bd62004-07-25 18:07:36 +00002563 }
2564
Chris Lattner404cddf2005-11-12 01:33:40 +00002565 // Read target triple and place into the module.
Reid Spencerad89bd62004-07-25 18:07:36 +00002566 std::string triple = read_str();
2567 TheModule->setTargetTriple(triple);
Reid Spencer5b472d92004-08-21 20:49:23 +00002568 if (Handler)
2569 Handler->handleTargetTriple(triple);
Chris Lattner404cddf2005-11-12 01:33:40 +00002570
Chris Lattner7e6db762006-01-23 23:43:17 +00002571 if (!hasAlignment && At != BlockEnd) {
Chris Lattner404cddf2005-11-12 01:33:40 +00002572 // If the file has section info in it, read the section names now.
2573 unsigned NumSections = read_vbr_uint();
2574 while (NumSections--)
2575 SectionNames.push_back(read_str());
2576 }
Chris Lattner7e6db762006-01-23 23:43:17 +00002577
2578 // If the file has module-level inline asm, read it now.
2579 if (!hasAlignment && At != BlockEnd)
Chris Lattner66316012006-01-24 04:14:29 +00002580 TheModule->setModuleInlineAsm(read_str());
Reid Spencerad89bd62004-07-25 18:07:36 +00002581 }
2582
Chris Lattner404cddf2005-11-12 01:33:40 +00002583 // If any globals are in specified sections, assign them now.
2584 for (std::map<GlobalValue*, unsigned>::iterator I = SectionID.begin(), E =
2585 SectionID.end(); I != E; ++I)
2586 if (I->second) {
2587 if (I->second > SectionID.size())
2588 error("SectionID out of range for global!");
2589 I->first->setSection(SectionNames[I->second-1]);
2590 }
Reid Spencerad89bd62004-07-25 18:07:36 +00002591
Chris Lattner00950542001-06-06 20:29:01 +00002592 // This is for future proofing... in the future extra fields may be added that
2593 // we don't understand, so we transparently ignore them.
2594 //
Reid Spencer060d25d2004-06-29 23:29:38 +00002595 At = BlockEnd;
2596
Reid Spencer04cde2c2004-07-04 11:33:49 +00002597 if (Handler) Handler->handleModuleGlobalsEnd();
Chris Lattner00950542001-06-06 20:29:01 +00002598}
2599
Reid Spencer04cde2c2004-07-04 11:33:49 +00002600/// Parse the version information and decode it by setting flags on the
2601/// Reader that enable backward compatibility of the reader.
Reid Spencer060d25d2004-06-29 23:29:38 +00002602void BytecodeReader::ParseVersionInfo() {
2603 unsigned Version = read_vbr_uint();
Chris Lattner036b8aa2003-03-06 17:55:45 +00002604
2605 // Unpack version number: low four bits are for flags, top bits = version
Chris Lattnerd445c6b2003-08-24 13:47:36 +00002606 Module::Endianness Endianness;
2607 Module::PointerSize PointerSize;
2608 Endianness = (Version & 1) ? Module::BigEndian : Module::LittleEndian;
2609 PointerSize = (Version & 2) ? Module::Pointer64 : Module::Pointer32;
2610
2611 bool hasNoEndianness = Version & 4;
2612 bool hasNoPointerSize = Version & 8;
Misha Brukman8a96c532005-04-21 21:44:41 +00002613
Chris Lattnerd445c6b2003-08-24 13:47:36 +00002614 RevisionNum = Version >> 4;
Chris Lattnere3869c82003-04-16 21:16:05 +00002615
2616 // Default values for the current bytecode version
Chris Lattner44d0eeb2004-01-15 17:55:01 +00002617 hasInconsistentModuleGlobalInfo = false;
Chris Lattner80b97342004-01-17 23:25:43 +00002618 hasExplicitPrimitiveZeros = false;
Chris Lattner5fa428f2004-04-05 01:27:26 +00002619 hasRestrictedGEPTypes = false;
Reid Spencer04cde2c2004-07-04 11:33:49 +00002620 hasTypeDerivedFromValue = false;
Reid Spencerad89bd62004-07-25 18:07:36 +00002621 hasLongBlockHeaders = false;
Reid Spencerad89bd62004-07-25 18:07:36 +00002622 has32BitTypes = false;
2623 hasNoDependentLibraries = false;
Reid Spencer38d54be2004-08-17 07:45:14 +00002624 hasAlignment = false;
Chris Lattnera79e7cc2004-10-16 18:18:16 +00002625 hasNoUndefValue = false;
2626 hasNoFlagsForFunctions = false;
2627 hasNoUnreachableInst = false;
Reid Spencer6996feb2006-11-08 21:27:54 +00002628 hasSignlessDivRem = false;
2629 hasSignlessShrCastSetcc = false;
Chris Lattner036b8aa2003-03-06 17:55:45 +00002630
Reid Spencer1628cec2006-10-26 06:15:43 +00002631 // Determine which backwards compatibility flags to set based on the
2632 // bytecode file's version number
Chris Lattner036b8aa2003-03-06 17:55:45 +00002633 switch (RevisionNum) {
Reid Spencer5b472d92004-08-21 20:49:23 +00002634 case 0: // LLVM 1.0, 1.1 (Released)
Chris Lattner9e893e82004-01-14 23:35:21 +00002635 // Base LLVM 1.0 bytecode format.
Chris Lattner44d0eeb2004-01-15 17:55:01 +00002636 hasInconsistentModuleGlobalInfo = true;
Chris Lattner80b97342004-01-17 23:25:43 +00002637 hasExplicitPrimitiveZeros = true;
Reid Spencer04cde2c2004-07-04 11:33:49 +00002638
Chris Lattner80b97342004-01-17 23:25:43 +00002639 // FALL THROUGH
Reid Spencer5b472d92004-08-21 20:49:23 +00002640
2641 case 1: // LLVM 1.2 (Released)
Chris Lattner9e893e82004-01-14 23:35:21 +00002642 // LLVM 1.2 added explicit support for emitting strings efficiently.
Chris Lattner44d0eeb2004-01-15 17:55:01 +00002643
2644 // Also, it fixed the problem where the size of the ModuleGlobalInfo block
2645 // included the size for the alignment at the end, where the rest of the
2646 // blocks did not.
Chris Lattner5fa428f2004-04-05 01:27:26 +00002647
2648 // LLVM 1.2 and before required that GEP indices be ubyte constants for
2649 // structures and longs for sequential types.
2650 hasRestrictedGEPTypes = true;
2651
Reid Spencer04cde2c2004-07-04 11:33:49 +00002652 // LLVM 1.2 and before had the Type class derive from Value class. This
2653 // changed in release 1.3 and consequently LLVM 1.3 bytecode files are
Misha Brukman8a96c532005-04-21 21:44:41 +00002654 // written differently because Types can no longer be part of the
Reid Spencer04cde2c2004-07-04 11:33:49 +00002655 // type planes for Values.
2656 hasTypeDerivedFromValue = true;
2657
Chris Lattner5fa428f2004-04-05 01:27:26 +00002658 // FALL THROUGH
Misha Brukman8a96c532005-04-21 21:44:41 +00002659
Reid Spencer5b472d92004-08-21 20:49:23 +00002660 case 2: // 1.2.5 (Not Released)
Reid Spencerad89bd62004-07-25 18:07:36 +00002661
Reid Spencer5b472d92004-08-21 20:49:23 +00002662 // LLVM 1.2 and earlier had two-word block headers. This is a bit wasteful,
Chris Lattner4a242b32004-10-14 01:39:18 +00002663 // especially for small files where the 8 bytes per block is a large
2664 // fraction of the total block size. In LLVM 1.3, the block type and length
2665 // are compressed into a single 32-bit unsigned integer. 27 bits for length,
2666 // 5 bits for block type.
Reid Spencerad89bd62004-07-25 18:07:36 +00002667 hasLongBlockHeaders = true;
2668
Reid Spencer5b472d92004-08-21 20:49:23 +00002669 // LLVM 1.2 and earlier wrote type slot numbers as vbr_uint32. In LLVM 1.3
Chris Lattner4a242b32004-10-14 01:39:18 +00002670 // this has been reduced to vbr_uint24. It shouldn't make much difference
2671 // since we haven't run into a module with > 24 million types, but for
2672 // safety the 24-bit restriction has been enforced in 1.3 to free some bits
2673 // in various places and to ensure consistency.
Reid Spencerad89bd62004-07-25 18:07:36 +00002674 has32BitTypes = true;
2675
Misha Brukman8a96c532005-04-21 21:44:41 +00002676 // LLVM 1.2 and earlier did not provide a target triple nor a list of
Reid Spencer5b472d92004-08-21 20:49:23 +00002677 // libraries on which the bytecode is dependent. LLVM 1.3 provides these
2678 // features, for use in future versions of LLVM.
Reid Spencerad89bd62004-07-25 18:07:36 +00002679 hasNoDependentLibraries = true;
2680
2681 // FALL THROUGH
Reid Spencer5b472d92004-08-21 20:49:23 +00002682
2683 case 3: // LLVM 1.3 (Released)
2684 // LLVM 1.3 and earlier caused alignment bytes to be written on some block
Misha Brukman8a96c532005-04-21 21:44:41 +00002685 // boundaries and at the end of some strings. In extreme cases (e.g. lots
Reid Spencer5b472d92004-08-21 20:49:23 +00002686 // of GEP references to a constant array), this can increase the file size
2687 // by 30% or more. In version 1.4 alignment is done away with completely.
Reid Spencer38d54be2004-08-17 07:45:14 +00002688 hasAlignment = true;
2689
2690 // FALL THROUGH
Misha Brukman8a96c532005-04-21 21:44:41 +00002691
Reid Spencer5b472d92004-08-21 20:49:23 +00002692 case 4: // 1.3.1 (Not Released)
Chris Lattnera79e7cc2004-10-16 18:18:16 +00002693 // In version 4, we did not support the 'undef' constant.
2694 hasNoUndefValue = true;
2695
2696 // In version 4 and above, we did not include space for flags for functions
2697 // in the module info block.
2698 hasNoFlagsForFunctions = true;
2699
2700 // In version 4 and above, we did not include the 'unreachable' instruction
2701 // in the opcode numbering in the bytecode file.
2702 hasNoUnreachableInst = true;
2703
2704 // FALL THROUGH
2705
Chris Lattnerdee199f2005-05-06 22:34:01 +00002706 case 5: // 1.4 (Released)
Reid Spencer6996feb2006-11-08 21:27:54 +00002707 // In version 6, the Div and Rem instructions were converted to their
2708 // signed and floating point counterparts: UDiv, SDiv, FDiv, URem, SRem,
2709 // and FRem. Versions prior to 6 need to indicate that they have the
2710 // signless Div and Rem instructions.
2711 hasSignlessDivRem = true;
2712
2713 // FALL THROUGH
2714
2715 case 6: // Signless Rem & Div Implementation (1.9 release)
Reid Spencer1628cec2006-10-26 06:15:43 +00002716 // In version 5 and prior, instructions were signless while integer types
2717 // were signed. In version 6, instructions became signed and types became
2718 // signless. For example in version 5 we have the DIV instruction but in
2719 // version 6 we have FDIV, SDIV and UDIV to replace it. This caused a
2720 // renumbering of the instruction codes in version 6 that must be dealt with
2721 // when reading old bytecode files.
Reid Spencer6996feb2006-11-08 21:27:54 +00002722 hasSignlessShrCastSetcc = true;
Reid Spencer1628cec2006-10-26 06:15:43 +00002723
2724 // FALL THROUGH
Reid Spencer6996feb2006-11-08 21:27:54 +00002725
2726 case 7:
Chris Lattnera79e7cc2004-10-16 18:18:16 +00002727 break;
2728
Chris Lattner036b8aa2003-03-06 17:55:45 +00002729 default:
Reid Spencer24399722004-07-09 22:21:33 +00002730 error("Unknown bytecode version number: " + itostr(RevisionNum));
Chris Lattner036b8aa2003-03-06 17:55:45 +00002731 }
2732
Chris Lattnerd445c6b2003-08-24 13:47:36 +00002733 if (hasNoEndianness) Endianness = Module::AnyEndianness;
2734 if (hasNoPointerSize) PointerSize = Module::AnyPointerSize;
Chris Lattner76e38962003-04-22 18:15:10 +00002735
Brian Gaekefe2102b2004-07-14 20:33:13 +00002736 TheModule->setEndianness(Endianness);
2737 TheModule->setPointerSize(PointerSize);
2738
Reid Spencer46b002c2004-07-11 17:28:43 +00002739 if (Handler) Handler->handleVersionInfo(RevisionNum, Endianness, PointerSize);
Chris Lattner036b8aa2003-03-06 17:55:45 +00002740}
2741
Reid Spencer04cde2c2004-07-04 11:33:49 +00002742/// Parse a whole module.
Reid Spencer060d25d2004-06-29 23:29:38 +00002743void BytecodeReader::ParseModule() {
Chris Lattner00950542001-06-06 20:29:01 +00002744 unsigned Type, Size;
Chris Lattner00950542001-06-06 20:29:01 +00002745
Reid Spencer060d25d2004-06-29 23:29:38 +00002746 FunctionSignatureList.clear(); // Just in case...
Chris Lattner00950542001-06-06 20:29:01 +00002747
2748 // Read into instance variables...
Reid Spencer060d25d2004-06-29 23:29:38 +00002749 ParseVersionInfo();
Reid Spencerad89bd62004-07-25 18:07:36 +00002750 align32();
Chris Lattner00950542001-06-06 20:29:01 +00002751
Reid Spencer060d25d2004-06-29 23:29:38 +00002752 bool SeenModuleGlobalInfo = false;
2753 bool SeenGlobalTypePlane = false;
2754 BufPtr MyEnd = BlockEnd;
2755 while (At < MyEnd) {
2756 BufPtr OldAt = At;
2757 read_block(Type, Size);
2758
Chris Lattner00950542001-06-06 20:29:01 +00002759 switch (Type) {
Reid Spencer060d25d2004-06-29 23:29:38 +00002760
Reid Spencerad89bd62004-07-25 18:07:36 +00002761 case BytecodeFormat::GlobalTypePlaneBlockID:
Reid Spencer46b002c2004-07-11 17:28:43 +00002762 if (SeenGlobalTypePlane)
Reid Spencer24399722004-07-09 22:21:33 +00002763 error("Two GlobalTypePlane Blocks Encountered!");
Reid Spencer060d25d2004-06-29 23:29:38 +00002764
Reid Spencer5b472d92004-08-21 20:49:23 +00002765 if (Size > 0)
2766 ParseGlobalTypes();
Reid Spencer060d25d2004-06-29 23:29:38 +00002767 SeenGlobalTypePlane = true;
Chris Lattner52e20b02003-03-19 20:54:26 +00002768 break;
2769
Misha Brukman8a96c532005-04-21 21:44:41 +00002770 case BytecodeFormat::ModuleGlobalInfoBlockID:
Reid Spencer46b002c2004-07-11 17:28:43 +00002771 if (SeenModuleGlobalInfo)
Reid Spencer24399722004-07-09 22:21:33 +00002772 error("Two ModuleGlobalInfo Blocks Encountered!");
Reid Spencer060d25d2004-06-29 23:29:38 +00002773 ParseModuleGlobalInfo();
2774 SeenModuleGlobalInfo = true;
Chris Lattner52e20b02003-03-19 20:54:26 +00002775 break;
2776
Reid Spencerad89bd62004-07-25 18:07:36 +00002777 case BytecodeFormat::ConstantPoolBlockID:
Reid Spencer04cde2c2004-07-04 11:33:49 +00002778 ParseConstantPool(ModuleValues, ModuleTypes,false);
Chris Lattner00950542001-06-06 20:29:01 +00002779 break;
2780
Reid Spencerad89bd62004-07-25 18:07:36 +00002781 case BytecodeFormat::FunctionBlockID:
Reid Spencer060d25d2004-06-29 23:29:38 +00002782 ParseFunctionLazily();
Chris Lattner00950542001-06-06 20:29:01 +00002783 break;
Chris Lattner00950542001-06-06 20:29:01 +00002784
Reid Spencerad89bd62004-07-25 18:07:36 +00002785 case BytecodeFormat::SymbolTableBlockID:
Reid Spencer060d25d2004-06-29 23:29:38 +00002786 ParseSymbolTable(0, &TheModule->getSymbolTable());
Chris Lattner00950542001-06-06 20:29:01 +00002787 break;
Reid Spencer060d25d2004-06-29 23:29:38 +00002788
Chris Lattner00950542001-06-06 20:29:01 +00002789 default:
Reid Spencer060d25d2004-06-29 23:29:38 +00002790 At += Size;
2791 if (OldAt > At) {
Reid Spencer46b002c2004-07-11 17:28:43 +00002792 error("Unexpected Block of Type #" + utostr(Type) + " encountered!");
Reid Spencer060d25d2004-06-29 23:29:38 +00002793 }
Chris Lattner00950542001-06-06 20:29:01 +00002794 break;
2795 }
Reid Spencer060d25d2004-06-29 23:29:38 +00002796 BlockEnd = MyEnd;
2797 align32();
Chris Lattner00950542001-06-06 20:29:01 +00002798 }
2799
Chris Lattner52e20b02003-03-19 20:54:26 +00002800 // After the module constant pool has been read, we can safely initialize
2801 // global variables...
2802 while (!GlobalInits.empty()) {
2803 GlobalVariable *GV = GlobalInits.back().first;
2804 unsigned Slot = GlobalInits.back().second;
2805 GlobalInits.pop_back();
2806
2807 // Look up the initializer value...
Chris Lattner29b789b2003-11-19 17:27:18 +00002808 // FIXME: Preserve this type ID!
Reid Spencer060d25d2004-06-29 23:29:38 +00002809
2810 const llvm::PointerType* GVType = GV->getType();
2811 unsigned TypeSlot = getTypeSlot(GVType->getElementType());
Chris Lattner93361992004-01-15 18:45:25 +00002812 if (Constant *CV = getConstantValue(TypeSlot, Slot)) {
Misha Brukman8a96c532005-04-21 21:44:41 +00002813 if (GV->hasInitializer())
Reid Spencer24399722004-07-09 22:21:33 +00002814 error("Global *already* has an initializer?!");
Reid Spencer04cde2c2004-07-04 11:33:49 +00002815 if (Handler) Handler->handleGlobalInitializer(GV,CV);
Chris Lattner93361992004-01-15 18:45:25 +00002816 GV->setInitializer(CV);
Chris Lattner52e20b02003-03-19 20:54:26 +00002817 } else
Reid Spencer24399722004-07-09 22:21:33 +00002818 error("Cannot find initializer value.");
Chris Lattner52e20b02003-03-19 20:54:26 +00002819 }
2820
Chris Lattneraba5ff52005-05-05 20:57:00 +00002821 if (!ConstantFwdRefs.empty())
2822 error("Use of undefined constants in a module");
2823
Reid Spencer060d25d2004-06-29 23:29:38 +00002824 /// Make sure we pulled them all out. If we didn't then there's a declaration
2825 /// but a missing body. That's not allowed.
Misha Brukman12c29d12003-09-22 23:38:23 +00002826 if (!FunctionSignatureList.empty())
Reid Spencer24399722004-07-09 22:21:33 +00002827 error("Function declared, but bytecode stream ended before definition");
Chris Lattner00950542001-06-06 20:29:01 +00002828}
2829
Reid Spencer04cde2c2004-07-04 11:33:49 +00002830/// This function completely parses a bytecode buffer given by the \p Buf
2831/// and \p Length parameters.
Anton Korobeynikov7d515442006-09-01 20:35:17 +00002832bool BytecodeReader::ParseBytecode(volatile BufPtr Buf, unsigned Length,
Reid Spencer233fe722006-08-22 16:09:19 +00002833 const std::string &ModuleID,
2834 std::string* ErrMsg) {
Misha Brukmane0dd0d42003-09-23 16:15:29 +00002835
Reid Spencer233fe722006-08-22 16:09:19 +00002836 /// We handle errors by
2837 if (setjmp(context)) {
2838 // Cleanup after error
2839 if (Handler) Handler->handleError(ErrorMsg);
Reid Spencer060d25d2004-06-29 23:29:38 +00002840 freeState();
Chris Lattner2a7b6ba2003-03-06 17:15:19 +00002841 delete TheModule;
2842 TheModule = 0;
Chris Lattner3bdad692004-11-15 21:55:33 +00002843 if (decompressedBlock != 0 ) {
Reid Spencer61aaf2e2004-11-14 21:59:21 +00002844 ::free(decompressedBlock);
Chris Lattner3bdad692004-11-15 21:55:33 +00002845 decompressedBlock = 0;
2846 }
Reid Spencer233fe722006-08-22 16:09:19 +00002847 // Set caller's error message, if requested
2848 if (ErrMsg)
2849 *ErrMsg = ErrorMsg;
2850 // Indicate an error occurred
2851 return true;
Chris Lattner2a7b6ba2003-03-06 17:15:19 +00002852 }
Reid Spencer233fe722006-08-22 16:09:19 +00002853
2854 RevisionNum = 0;
2855 At = MemStart = BlockStart = Buf;
2856 MemEnd = BlockEnd = Buf + Length;
2857
2858 // Create the module
2859 TheModule = new Module(ModuleID);
2860
2861 if (Handler) Handler->handleStart(TheModule, Length);
2862
2863 // Read the four bytes of the signature.
2864 unsigned Sig = read_uint();
2865
2866 // If this is a compressed file
2867 if (Sig == ('l' | ('l' << 8) | ('v' << 16) | ('c' << 24))) {
2868
2869 // Invoke the decompression of the bytecode. Note that we have to skip the
2870 // file's magic number which is not part of the compressed block. Hence,
2871 // the Buf+4 and Length-4. The result goes into decompressedBlock, a data
2872 // member for retention until BytecodeReader is destructed.
2873 unsigned decompressedLength = Compressor::decompressToNewBuffer(
2874 (char*)Buf+4,Length-4,decompressedBlock);
2875
2876 // We must adjust the buffer pointers used by the bytecode reader to point
2877 // into the new decompressed block. After decompression, the
2878 // decompressedBlock will point to a contiguous memory area that has
2879 // the decompressed data.
2880 At = MemStart = BlockStart = Buf = (BufPtr) decompressedBlock;
2881 MemEnd = BlockEnd = Buf + decompressedLength;
2882
2883 // else if this isn't a regular (uncompressed) bytecode file, then its
2884 // and error, generate that now.
2885 } else if (Sig != ('l' | ('l' << 8) | ('v' << 16) | ('m' << 24))) {
2886 error("Invalid bytecode signature: " + utohexstr(Sig));
2887 }
2888
2889 // Tell the handler we're starting a module
2890 if (Handler) Handler->handleModuleBegin(ModuleID);
2891
2892 // Get the module block and size and verify. This is handled specially
2893 // because the module block/size is always written in long format. Other
2894 // blocks are written in short format so the read_block method is used.
2895 unsigned Type, Size;
2896 Type = read_uint();
2897 Size = read_uint();
2898 if (Type != BytecodeFormat::ModuleBlockID) {
2899 error("Expected Module Block! Type:" + utostr(Type) + ", Size:"
2900 + utostr(Size));
2901 }
2902
2903 // It looks like the darwin ranlib program is broken, and adds trailing
2904 // garbage to the end of some bytecode files. This hack allows the bc
2905 // reader to ignore trailing garbage on bytecode files.
2906 if (At + Size < MemEnd)
2907 MemEnd = BlockEnd = At+Size;
2908
2909 if (At + Size != MemEnd)
2910 error("Invalid Top Level Block Length! Type:" + utostr(Type)
2911 + ", Size:" + utostr(Size));
2912
2913 // Parse the module contents
2914 this->ParseModule();
2915
2916 // Check for missing functions
2917 if (hasFunctions())
2918 error("Function expected, but bytecode stream ended!");
2919
2920 // Look for intrinsic functions to upgrade, upgrade them, and save the
2921 // mapping from old function to new for use later when instructions are
2922 // converted.
2923 for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
2924 FI != FE; ++FI)
2925 if (Function* newF = UpgradeIntrinsicFunction(FI)) {
2926 upgradedFunctions.insert(std::make_pair(FI, newF));
2927 FI->setName("");
2928 }
2929
2930 // Tell the handler we're done with the module
2931 if (Handler)
2932 Handler->handleModuleEnd(ModuleID);
2933
2934 // Tell the handler we're finished the parse
2935 if (Handler) Handler->handleFinish();
2936
2937 return false;
2938
Chris Lattner00950542001-06-06 20:29:01 +00002939}
Reid Spencer060d25d2004-06-29 23:29:38 +00002940
2941//===----------------------------------------------------------------------===//
2942//=== Default Implementations of Handler Methods
2943//===----------------------------------------------------------------------===//
2944
2945BytecodeHandler::~BytecodeHandler() {}
Reid Spencer060d25d2004-06-29 23:29:38 +00002946