blob: ba9c6ca97f61a8abfea797238f3e14efcd445697 [file] [log] [blame]
Chris Lattnerd6b65252001-10-24 01:15:12 +00001//===- Reader.cpp - Code to read bytecode files ---------------------------===//
Misha Brukman8a96c532005-04-21 21:44:41 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
Misha Brukman8a96c532005-04-21 21:44:41 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner00950542001-06-06 20:29:01 +00009//
10// This library implements the functionality defined in llvm/Bytecode/Reader.h
11//
Misha Brukman8a96c532005-04-21 21:44:41 +000012// Note that this library should be as fast as possible, reentrant, and
Chris Lattner00950542001-06-06 20:29:01 +000013// threadsafe!!
14//
Chris Lattner00950542001-06-06 20:29:01 +000015// TODO: Allow passing in an option to ignore the symbol table
16//
Chris Lattnerd6b65252001-10-24 01:15:12 +000017//===----------------------------------------------------------------------===//
Chris Lattner00950542001-06-06 20:29:01 +000018
Reid Spencer060d25d2004-06-29 23:29:38 +000019#include "Reader.h"
20#include "llvm/Bytecode/BytecodeHandler.h"
21#include "llvm/BasicBlock.h"
Chris Lattnerdee199f2005-05-06 22:34:01 +000022#include "llvm/CallingConv.h"
Reid Spencer060d25d2004-06-29 23:29:38 +000023#include "llvm/Constants.h"
Reid Spencer04cde2c2004-07-04 11:33:49 +000024#include "llvm/Instructions.h"
25#include "llvm/SymbolTable.h"
Chris Lattner00950542001-06-06 20:29:01 +000026#include "llvm/Bytecode/Format.h"
Chris Lattnerdee199f2005-05-06 22:34:01 +000027#include "llvm/Config/alloca.h"
Reid Spencer060d25d2004-06-29 23:29:38 +000028#include "llvm/Support/GetElementPtrTypeIterator.h"
Reid Spencer17f52c52004-11-06 23:17:23 +000029#include "llvm/Support/Compressor.h"
Jim Laskeycb6682f2005-08-17 19:34:49 +000030#include "llvm/Support/MathExtras.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000031#include "llvm/ADT/StringExtras.h"
Reid Spencer060d25d2004-06-29 23:29:38 +000032#include <sstream>
Alkis Evlogimenos20aa4742004-09-03 18:19:51 +000033#include <algorithm>
Chris Lattner29b789b2003-11-19 17:27:18 +000034using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000035
Reid Spencer46b002c2004-07-11 17:28:43 +000036namespace {
Chris Lattnercad28bd2005-01-29 00:36:19 +000037 /// @brief A class for maintaining the slot number definition
38 /// as a placeholder for the actual definition for forward constants defs.
39 class ConstantPlaceHolder : public ConstantExpr {
40 ConstantPlaceHolder(); // DO NOT IMPLEMENT
41 void operator=(const ConstantPlaceHolder &); // DO NOT IMPLEMENT
42 public:
Chris Lattner61323322005-01-31 01:11:13 +000043 Use Op;
Misha Brukman8a96c532005-04-21 21:44:41 +000044 ConstantPlaceHolder(const Type *Ty)
Chris Lattner61323322005-01-31 01:11:13 +000045 : ConstantExpr(Ty, Instruction::UserOp1, &Op, 1),
46 Op(UndefValue::get(Type::IntTy), this) {
47 }
Chris Lattnercad28bd2005-01-29 00:36:19 +000048 };
Reid Spencer46b002c2004-07-11 17:28:43 +000049}
Reid Spencer060d25d2004-06-29 23:29:38 +000050
Reid Spencer24399722004-07-09 22:21:33 +000051// Provide some details on error
52inline void BytecodeReader::error(std::string err) {
53 err += " (Vers=" ;
54 err += itostr(RevisionNum) ;
55 err += ", Pos=" ;
56 err += itostr(At-MemStart);
57 err += ")";
58 throw err;
59}
60
Reid Spencer060d25d2004-06-29 23:29:38 +000061//===----------------------------------------------------------------------===//
62// Bytecode Reading Methods
63//===----------------------------------------------------------------------===//
64
Reid Spencer04cde2c2004-07-04 11:33:49 +000065/// Determine if the current block being read contains any more data.
Reid Spencer060d25d2004-06-29 23:29:38 +000066inline bool BytecodeReader::moreInBlock() {
67 return At < BlockEnd;
Chris Lattner00950542001-06-06 20:29:01 +000068}
69
Reid Spencer04cde2c2004-07-04 11:33:49 +000070/// Throw an error if we've read past the end of the current block
Reid Spencer060d25d2004-06-29 23:29:38 +000071inline void BytecodeReader::checkPastBlockEnd(const char * block_name) {
Reid Spencer46b002c2004-07-11 17:28:43 +000072 if (At > BlockEnd)
Chris Lattnera79e7cc2004-10-16 18:18:16 +000073 error(std::string("Attempt to read past the end of ") + block_name +
74 " block.");
Reid Spencer060d25d2004-06-29 23:29:38 +000075}
Chris Lattner36392bc2003-10-08 21:18:57 +000076
Reid Spencer04cde2c2004-07-04 11:33:49 +000077/// Align the buffer position to a 32 bit boundary
Reid Spencer060d25d2004-06-29 23:29:38 +000078inline void BytecodeReader::align32() {
Reid Spencer38d54be2004-08-17 07:45:14 +000079 if (hasAlignment) {
80 BufPtr Save = At;
81 At = (const unsigned char *)((unsigned long)(At+3) & (~3UL));
Misha Brukman8a96c532005-04-21 21:44:41 +000082 if (At > Save)
Reid Spencer38d54be2004-08-17 07:45:14 +000083 if (Handler) Handler->handleAlignment(At - Save);
Misha Brukman8a96c532005-04-21 21:44:41 +000084 if (At > BlockEnd)
Reid Spencer38d54be2004-08-17 07:45:14 +000085 error("Ran out of data while aligning!");
86 }
Reid Spencer060d25d2004-06-29 23:29:38 +000087}
88
Reid Spencer04cde2c2004-07-04 11:33:49 +000089/// Read a whole unsigned integer
Reid Spencer060d25d2004-06-29 23:29:38 +000090inline unsigned BytecodeReader::read_uint() {
Misha Brukman8a96c532005-04-21 21:44:41 +000091 if (At+4 > BlockEnd)
Reid Spencer24399722004-07-09 22:21:33 +000092 error("Ran out of data reading uint!");
Reid Spencer060d25d2004-06-29 23:29:38 +000093 At += 4;
94 return At[-4] | (At[-3] << 8) | (At[-2] << 16) | (At[-1] << 24);
95}
96
Reid Spencer04cde2c2004-07-04 11:33:49 +000097/// Read a variable-bit-rate encoded unsigned integer
Reid Spencer060d25d2004-06-29 23:29:38 +000098inline unsigned BytecodeReader::read_vbr_uint() {
99 unsigned Shift = 0;
100 unsigned Result = 0;
101 BufPtr Save = At;
Misha Brukman8a96c532005-04-21 21:44:41 +0000102
Reid Spencer060d25d2004-06-29 23:29:38 +0000103 do {
Misha Brukman8a96c532005-04-21 21:44:41 +0000104 if (At == BlockEnd)
Reid Spencer24399722004-07-09 22:21:33 +0000105 error("Ran out of data reading vbr_uint!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000106 Result |= (unsigned)((*At++) & 0x7F) << Shift;
107 Shift += 7;
108 } while (At[-1] & 0x80);
Reid Spencer04cde2c2004-07-04 11:33:49 +0000109 if (Handler) Handler->handleVBR32(At-Save);
Reid Spencer060d25d2004-06-29 23:29:38 +0000110 return Result;
111}
112
Reid Spencer04cde2c2004-07-04 11:33:49 +0000113/// Read a variable-bit-rate encoded unsigned 64-bit integer.
Reid Spencer060d25d2004-06-29 23:29:38 +0000114inline uint64_t BytecodeReader::read_vbr_uint64() {
115 unsigned Shift = 0;
116 uint64_t Result = 0;
117 BufPtr Save = At;
Misha Brukman8a96c532005-04-21 21:44:41 +0000118
Reid Spencer060d25d2004-06-29 23:29:38 +0000119 do {
Misha Brukman8a96c532005-04-21 21:44:41 +0000120 if (At == BlockEnd)
Reid Spencer24399722004-07-09 22:21:33 +0000121 error("Ran out of data reading vbr_uint64!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000122 Result |= (uint64_t)((*At++) & 0x7F) << Shift;
123 Shift += 7;
124 } while (At[-1] & 0x80);
Reid Spencer04cde2c2004-07-04 11:33:49 +0000125 if (Handler) Handler->handleVBR64(At-Save);
Reid Spencer060d25d2004-06-29 23:29:38 +0000126 return Result;
127}
128
Reid Spencer04cde2c2004-07-04 11:33:49 +0000129/// Read a variable-bit-rate encoded signed 64-bit integer.
Reid Spencer060d25d2004-06-29 23:29:38 +0000130inline int64_t BytecodeReader::read_vbr_int64() {
131 uint64_t R = read_vbr_uint64();
132 if (R & 1) {
133 if (R != 1)
134 return -(int64_t)(R >> 1);
135 else // There is no such thing as -0 with integers. "-0" really means
136 // 0x8000000000000000.
137 return 1LL << 63;
138 } else
139 return (int64_t)(R >> 1);
140}
141
Reid Spencer04cde2c2004-07-04 11:33:49 +0000142/// Read a pascal-style string (length followed by text)
Reid Spencer060d25d2004-06-29 23:29:38 +0000143inline std::string BytecodeReader::read_str() {
144 unsigned Size = read_vbr_uint();
145 const unsigned char *OldAt = At;
146 At += Size;
147 if (At > BlockEnd) // Size invalid?
Reid Spencer24399722004-07-09 22:21:33 +0000148 error("Ran out of data reading a string!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000149 return std::string((char*)OldAt, Size);
150}
151
Reid Spencer04cde2c2004-07-04 11:33:49 +0000152/// Read an arbitrary block of data
Reid Spencer060d25d2004-06-29 23:29:38 +0000153inline void BytecodeReader::read_data(void *Ptr, void *End) {
154 unsigned char *Start = (unsigned char *)Ptr;
155 unsigned Amount = (unsigned char *)End - Start;
Misha Brukman8a96c532005-04-21 21:44:41 +0000156 if (At+Amount > BlockEnd)
Reid Spencer24399722004-07-09 22:21:33 +0000157 error("Ran out of data!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000158 std::copy(At, At+Amount, Start);
159 At += Amount;
160}
161
Reid Spencer46b002c2004-07-11 17:28:43 +0000162/// Read a float value in little-endian order
163inline void BytecodeReader::read_float(float& FloatVal) {
Reid Spencerada16182004-07-25 21:36:26 +0000164 /// FIXME: This isn't optimal, it has size problems on some platforms
165 /// where FP is not IEEE.
Jim Laskeycb6682f2005-08-17 19:34:49 +0000166 FloatVal = BitsToFloat(At[0] | (At[1] << 8) | (At[2] << 16) | (At[3] << 24));
Reid Spencerada16182004-07-25 21:36:26 +0000167 At+=sizeof(uint32_t);
Reid Spencer46b002c2004-07-11 17:28:43 +0000168}
169
170/// Read a double value in little-endian order
171inline void BytecodeReader::read_double(double& DoubleVal) {
Reid Spencerada16182004-07-25 21:36:26 +0000172 /// FIXME: This isn't optimal, it has size problems on some platforms
173 /// where FP is not IEEE.
Jim Laskeycb6682f2005-08-17 19:34:49 +0000174 DoubleVal = BitsToDouble((uint64_t(At[0]) << 0) | (uint64_t(At[1]) << 8) |
175 (uint64_t(At[2]) << 16) | (uint64_t(At[3]) << 24) |
176 (uint64_t(At[4]) << 32) | (uint64_t(At[5]) << 40) |
177 (uint64_t(At[6]) << 48) | (uint64_t(At[7]) << 56));
Reid Spencerada16182004-07-25 21:36:26 +0000178 At+=sizeof(uint64_t);
Reid Spencer46b002c2004-07-11 17:28:43 +0000179}
180
Reid Spencer04cde2c2004-07-04 11:33:49 +0000181/// Read a block header and obtain its type and size
Reid Spencer060d25d2004-06-29 23:29:38 +0000182inline void BytecodeReader::read_block(unsigned &Type, unsigned &Size) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000183 if ( hasLongBlockHeaders ) {
184 Type = read_uint();
185 Size = read_uint();
186 switch (Type) {
Misha Brukman8a96c532005-04-21 21:44:41 +0000187 case BytecodeFormat::Reserved_DoNotUse :
Reid Spencerad89bd62004-07-25 18:07:36 +0000188 error("Reserved_DoNotUse used as Module Type?");
Reid Spencer5b472d92004-08-21 20:49:23 +0000189 Type = BytecodeFormat::ModuleBlockID; break;
Misha Brukman8a96c532005-04-21 21:44:41 +0000190 case BytecodeFormat::Module:
Reid Spencerad89bd62004-07-25 18:07:36 +0000191 Type = BytecodeFormat::ModuleBlockID; break;
192 case BytecodeFormat::Function:
193 Type = BytecodeFormat::FunctionBlockID; break;
194 case BytecodeFormat::ConstantPool:
195 Type = BytecodeFormat::ConstantPoolBlockID; break;
196 case BytecodeFormat::SymbolTable:
197 Type = BytecodeFormat::SymbolTableBlockID; break;
198 case BytecodeFormat::ModuleGlobalInfo:
199 Type = BytecodeFormat::ModuleGlobalInfoBlockID; break;
200 case BytecodeFormat::GlobalTypePlane:
201 Type = BytecodeFormat::GlobalTypePlaneBlockID; break;
202 case BytecodeFormat::InstructionList:
203 Type = BytecodeFormat::InstructionListBlockID; break;
204 case BytecodeFormat::CompactionTable:
205 Type = BytecodeFormat::CompactionTableBlockID; break;
206 case BytecodeFormat::BasicBlock:
207 /// This block type isn't used after version 1.1. However, we have to
208 /// still allow the value in case this is an old bc format file.
209 /// We just let its value creep thru.
210 break;
211 default:
Reid Spencer5b472d92004-08-21 20:49:23 +0000212 error("Invalid block id found: " + utostr(Type));
Reid Spencerad89bd62004-07-25 18:07:36 +0000213 break;
214 }
215 } else {
216 Size = read_uint();
217 Type = Size & 0x1F; // mask low order five bits
218 Size >>= 5; // get rid of five low order bits, leaving high 27
219 }
Reid Spencer060d25d2004-06-29 23:29:38 +0000220 BlockStart = At;
Reid Spencer46b002c2004-07-11 17:28:43 +0000221 if (At + Size > BlockEnd)
Reid Spencer24399722004-07-09 22:21:33 +0000222 error("Attempt to size a block past end of memory");
Reid Spencer060d25d2004-06-29 23:29:38 +0000223 BlockEnd = At + Size;
Reid Spencer46b002c2004-07-11 17:28:43 +0000224 if (Handler) Handler->handleBlock(Type, BlockStart, Size);
Reid Spencer04cde2c2004-07-04 11:33:49 +0000225}
226
227
228/// In LLVM 1.2 and before, Types were derived from Value and so they were
229/// written as part of the type planes along with any other Value. In LLVM
230/// 1.3 this changed so that Type does not derive from Value. Consequently,
231/// the BytecodeReader's containers for Values can't contain Types because
232/// there's no inheritance relationship. This means that the "Type Type"
Misha Brukman8a96c532005-04-21 21:44:41 +0000233/// plane is defunct along with the Type::TypeTyID TypeID. In LLVM 1.3
234/// whenever a bytecode construct must have both types and values together,
Reid Spencer04cde2c2004-07-04 11:33:49 +0000235/// the types are always read/written first and then the Values. Furthermore
236/// since Type::TypeTyID no longer exists, its value (12) now corresponds to
237/// Type::LabelTyID. In order to overcome this we must "sanitize" all the
238/// type TypeIDs we encounter. For LLVM 1.3 bytecode files, there's no change.
239/// For LLVM 1.2 and before, this function will decrement the type id by
240/// one to account for the missing Type::TypeTyID enumerator if the value is
241/// larger than 12 (Type::LabelTyID). If the value is exactly 12, then this
242/// function returns true, otherwise false. This helps detect situations
243/// where the pre 1.3 bytecode is indicating that what follows is a type.
Misha Brukman8a96c532005-04-21 21:44:41 +0000244/// @returns true iff type id corresponds to pre 1.3 "type type"
Reid Spencer46b002c2004-07-11 17:28:43 +0000245inline bool BytecodeReader::sanitizeTypeId(unsigned &TypeId) {
246 if (hasTypeDerivedFromValue) { /// do nothing if 1.3 or later
247 if (TypeId == Type::LabelTyID) {
Reid Spencer04cde2c2004-07-04 11:33:49 +0000248 TypeId = Type::VoidTyID; // sanitize it
249 return true; // indicate we got TypeTyID in pre 1.3 bytecode
Reid Spencer46b002c2004-07-11 17:28:43 +0000250 } else if (TypeId > Type::LabelTyID)
Reid Spencer04cde2c2004-07-04 11:33:49 +0000251 --TypeId; // shift all planes down because type type plane is missing
252 }
253 return false;
254}
255
256/// Reads a vbr uint to read in a type id and does the necessary
257/// conversion on it by calling sanitizeTypeId.
258/// @returns true iff \p TypeId read corresponds to a pre 1.3 "type type"
259/// @see sanitizeTypeId
260inline bool BytecodeReader::read_typeid(unsigned &TypeId) {
261 TypeId = read_vbr_uint();
Reid Spencerad89bd62004-07-25 18:07:36 +0000262 if ( !has32BitTypes )
263 if ( TypeId == 0x00FFFFFF )
264 TypeId = read_vbr_uint();
Reid Spencer04cde2c2004-07-04 11:33:49 +0000265 return sanitizeTypeId(TypeId);
Reid Spencer060d25d2004-06-29 23:29:38 +0000266}
267
268//===----------------------------------------------------------------------===//
269// IR Lookup Methods
270//===----------------------------------------------------------------------===//
271
Reid Spencer04cde2c2004-07-04 11:33:49 +0000272/// Determine if a type id has an implicit null value
Reid Spencer46b002c2004-07-11 17:28:43 +0000273inline bool BytecodeReader::hasImplicitNull(unsigned TyID) {
Reid Spencer060d25d2004-06-29 23:29:38 +0000274 if (!hasExplicitPrimitiveZeros)
Reid Spencer04cde2c2004-07-04 11:33:49 +0000275 return TyID != Type::LabelTyID && TyID != Type::VoidTyID;
Reid Spencer060d25d2004-06-29 23:29:38 +0000276 return TyID >= Type::FirstDerivedTyID;
277}
278
Reid Spencer04cde2c2004-07-04 11:33:49 +0000279/// Obtain a type given a typeid and account for things like compaction tables,
280/// function level vs module level, and the offsetting for the primitive types.
Reid Spencer060d25d2004-06-29 23:29:38 +0000281const Type *BytecodeReader::getType(unsigned ID) {
Chris Lattner89e02532004-01-18 21:08:15 +0000282 if (ID < Type::FirstDerivedTyID)
Chris Lattnerf70c22b2004-06-17 18:19:28 +0000283 if (const Type *T = Type::getPrimitiveType((Type::TypeID)ID))
Chris Lattner927b1852003-10-09 20:22:47 +0000284 return T; // Asked for a primitive type...
Chris Lattner36392bc2003-10-08 21:18:57 +0000285
286 // Otherwise, derived types need offset...
Chris Lattner89e02532004-01-18 21:08:15 +0000287 ID -= Type::FirstDerivedTyID;
288
Reid Spencer060d25d2004-06-29 23:29:38 +0000289 if (!CompactionTypes.empty()) {
290 if (ID >= CompactionTypes.size())
Reid Spencer24399722004-07-09 22:21:33 +0000291 error("Type ID out of range for compaction table!");
Chris Lattner45b5dd22004-08-03 23:41:28 +0000292 return CompactionTypes[ID].first;
Chris Lattner89e02532004-01-18 21:08:15 +0000293 }
Chris Lattner36392bc2003-10-08 21:18:57 +0000294
295 // Is it a module-level type?
Reid Spencer46b002c2004-07-11 17:28:43 +0000296 if (ID < ModuleTypes.size())
297 return ModuleTypes[ID].get();
Chris Lattner36392bc2003-10-08 21:18:57 +0000298
Reid Spencer46b002c2004-07-11 17:28:43 +0000299 // Nope, is it a function-level type?
300 ID -= ModuleTypes.size();
301 if (ID < FunctionTypes.size())
302 return FunctionTypes[ID].get();
Chris Lattner36392bc2003-10-08 21:18:57 +0000303
Reid Spencer46b002c2004-07-11 17:28:43 +0000304 error("Illegal type reference!");
305 return Type::VoidTy;
Chris Lattner00950542001-06-06 20:29:01 +0000306}
307
Reid Spencer04cde2c2004-07-04 11:33:49 +0000308/// Get a sanitized type id. This just makes sure that the \p ID
309/// is both sanitized and not the "type type" of pre-1.3 bytecode.
310/// @see sanitizeTypeId
311inline const Type* BytecodeReader::getSanitizedType(unsigned& ID) {
Reid Spencer46b002c2004-07-11 17:28:43 +0000312 if (sanitizeTypeId(ID))
Reid Spencer24399722004-07-09 22:21:33 +0000313 error("Invalid type id encountered");
Reid Spencer04cde2c2004-07-04 11:33:49 +0000314 return getType(ID);
315}
316
317/// This method just saves some coding. It uses read_typeid to read
Reid Spencer24399722004-07-09 22:21:33 +0000318/// in a sanitized type id, errors that its not the type type, and
Reid Spencer04cde2c2004-07-04 11:33:49 +0000319/// then calls getType to return the type value.
320inline const Type* BytecodeReader::readSanitizedType() {
321 unsigned ID;
Reid Spencer46b002c2004-07-11 17:28:43 +0000322 if (read_typeid(ID))
323 error("Invalid type id encountered");
Reid Spencer04cde2c2004-07-04 11:33:49 +0000324 return getType(ID);
325}
326
327/// Get the slot number associated with a type accounting for primitive
328/// types, compaction tables, and function level vs module level.
Reid Spencer060d25d2004-06-29 23:29:38 +0000329unsigned BytecodeReader::getTypeSlot(const Type *Ty) {
330 if (Ty->isPrimitiveType())
331 return Ty->getTypeID();
332
333 // Scan the compaction table for the type if needed.
334 if (!CompactionTypes.empty()) {
Chris Lattner45b5dd22004-08-03 23:41:28 +0000335 for (unsigned i = 0, e = CompactionTypes.size(); i != e; ++i)
336 if (CompactionTypes[i].first == Ty)
Misha Brukman8a96c532005-04-21 21:44:41 +0000337 return Type::FirstDerivedTyID + i;
Reid Spencer060d25d2004-06-29 23:29:38 +0000338
Chris Lattner45b5dd22004-08-03 23:41:28 +0000339 error("Couldn't find type specified in compaction table!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000340 }
341
342 // Check the function level types first...
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000343 TypeListTy::iterator I = std::find(FunctionTypes.begin(),
344 FunctionTypes.end(), Ty);
Reid Spencer060d25d2004-06-29 23:29:38 +0000345
346 if (I != FunctionTypes.end())
Misha Brukman8a96c532005-04-21 21:44:41 +0000347 return Type::FirstDerivedTyID + ModuleTypes.size() +
Reid Spencer46b002c2004-07-11 17:28:43 +0000348 (&*I - &FunctionTypes[0]);
Reid Spencer060d25d2004-06-29 23:29:38 +0000349
Chris Lattnereebac5f2005-10-03 21:26:53 +0000350 // If we don't have our cache yet, build it now.
351 if (ModuleTypeIDCache.empty()) {
352 unsigned N = 0;
353 ModuleTypeIDCache.reserve(ModuleTypes.size());
354 for (TypeListTy::iterator I = ModuleTypes.begin(), E = ModuleTypes.end();
355 I != E; ++I, ++N)
356 ModuleTypeIDCache.push_back(std::make_pair(*I, N));
357
358 std::sort(ModuleTypeIDCache.begin(), ModuleTypeIDCache.end());
359 }
360
361 // Binary search the cache for the entry.
362 std::vector<std::pair<const Type*, unsigned> >::iterator IT =
363 std::lower_bound(ModuleTypeIDCache.begin(), ModuleTypeIDCache.end(),
364 std::make_pair(Ty, 0U));
365 if (IT == ModuleTypeIDCache.end() || IT->first != Ty)
Reid Spencer24399722004-07-09 22:21:33 +0000366 error("Didn't find type in ModuleTypes.");
Chris Lattnereebac5f2005-10-03 21:26:53 +0000367
368 return Type::FirstDerivedTyID + IT->second;
Chris Lattner80b97342004-01-17 23:25:43 +0000369}
370
Reid Spencer04cde2c2004-07-04 11:33:49 +0000371/// This is just like getType, but when a compaction table is in use, it is
372/// ignored. It also ignores function level types.
373/// @see getType
Reid Spencer060d25d2004-06-29 23:29:38 +0000374const Type *BytecodeReader::getGlobalTableType(unsigned Slot) {
375 if (Slot < Type::FirstDerivedTyID) {
376 const Type *Ty = Type::getPrimitiveType((Type::TypeID)Slot);
Reid Spencer46b002c2004-07-11 17:28:43 +0000377 if (!Ty)
Reid Spencer24399722004-07-09 22:21:33 +0000378 error("Not a primitive type ID?");
Reid Spencer060d25d2004-06-29 23:29:38 +0000379 return Ty;
380 }
381 Slot -= Type::FirstDerivedTyID;
382 if (Slot >= ModuleTypes.size())
Reid Spencer24399722004-07-09 22:21:33 +0000383 error("Illegal compaction table type reference!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000384 return ModuleTypes[Slot];
Chris Lattner52e20b02003-03-19 20:54:26 +0000385}
386
Reid Spencer04cde2c2004-07-04 11:33:49 +0000387/// This is just like getTypeSlot, but when a compaction table is in use, it
388/// is ignored. It also ignores function level types.
Reid Spencer060d25d2004-06-29 23:29:38 +0000389unsigned BytecodeReader::getGlobalTableTypeSlot(const Type *Ty) {
390 if (Ty->isPrimitiveType())
391 return Ty->getTypeID();
Chris Lattnereebac5f2005-10-03 21:26:53 +0000392
393 // If we don't have our cache yet, build it now.
394 if (ModuleTypeIDCache.empty()) {
395 unsigned N = 0;
396 ModuleTypeIDCache.reserve(ModuleTypes.size());
397 for (TypeListTy::iterator I = ModuleTypes.begin(), E = ModuleTypes.end();
398 I != E; ++I, ++N)
399 ModuleTypeIDCache.push_back(std::make_pair(*I, N));
400
401 std::sort(ModuleTypeIDCache.begin(), ModuleTypeIDCache.end());
402 }
403
404 // Binary search the cache for the entry.
405 std::vector<std::pair<const Type*, unsigned> >::iterator IT =
406 std::lower_bound(ModuleTypeIDCache.begin(), ModuleTypeIDCache.end(),
407 std::make_pair(Ty, 0U));
408 if (IT == ModuleTypeIDCache.end() || IT->first != Ty)
Reid Spencer24399722004-07-09 22:21:33 +0000409 error("Didn't find type in ModuleTypes.");
Chris Lattnereebac5f2005-10-03 21:26:53 +0000410
411 return Type::FirstDerivedTyID + IT->second;
Reid Spencer060d25d2004-06-29 23:29:38 +0000412}
413
Misha Brukman8a96c532005-04-21 21:44:41 +0000414/// Retrieve a value of a given type and slot number, possibly creating
415/// it if it doesn't already exist.
Reid Spencer060d25d2004-06-29 23:29:38 +0000416Value * BytecodeReader::getValue(unsigned type, unsigned oNum, bool Create) {
Chris Lattner4ee8ef22003-10-08 22:52:54 +0000417 assert(type != Type::LabelTyID && "getValue() cannot get blocks!");
Chris Lattner00950542001-06-06 20:29:01 +0000418 unsigned Num = oNum;
Chris Lattner00950542001-06-06 20:29:01 +0000419
Chris Lattner89e02532004-01-18 21:08:15 +0000420 // If there is a compaction table active, it defines the low-level numbers.
421 // If not, the module values define the low-level numbers.
Reid Spencer060d25d2004-06-29 23:29:38 +0000422 if (CompactionValues.size() > type && !CompactionValues[type].empty()) {
423 if (Num < CompactionValues[type].size())
424 return CompactionValues[type][Num];
425 Num -= CompactionValues[type].size();
Chris Lattner89e02532004-01-18 21:08:15 +0000426 } else {
Reid Spencer060d25d2004-06-29 23:29:38 +0000427 // By default, the global type id is the type id passed in
Chris Lattner52f86d62004-01-20 00:54:06 +0000428 unsigned GlobalTyID = type;
Reid Spencer060d25d2004-06-29 23:29:38 +0000429
Chris Lattner45b5dd22004-08-03 23:41:28 +0000430 // If the type plane was compactified, figure out the global type ID by
431 // adding the derived type ids and the distance.
432 if (!CompactionTypes.empty() && type >= Type::FirstDerivedTyID)
433 GlobalTyID = CompactionTypes[type-Type::FirstDerivedTyID].second;
Chris Lattner00950542001-06-06 20:29:01 +0000434
Reid Spencer060d25d2004-06-29 23:29:38 +0000435 if (hasImplicitNull(GlobalTyID)) {
Chris Lattneraba5ff52005-05-05 20:57:00 +0000436 const Type *Ty = getType(type);
437 if (!isa<OpaqueType>(Ty)) {
438 if (Num == 0)
439 return Constant::getNullValue(Ty);
440 --Num;
441 }
Chris Lattner89e02532004-01-18 21:08:15 +0000442 }
443
Chris Lattner52f86d62004-01-20 00:54:06 +0000444 if (GlobalTyID < ModuleValues.size() && ModuleValues[GlobalTyID]) {
445 if (Num < ModuleValues[GlobalTyID]->size())
Reid Spencer04cde2c2004-07-04 11:33:49 +0000446 return ModuleValues[GlobalTyID]->getOperand(Num);
Chris Lattner52f86d62004-01-20 00:54:06 +0000447 Num -= ModuleValues[GlobalTyID]->size();
Chris Lattner89e02532004-01-18 21:08:15 +0000448 }
Chris Lattner52e20b02003-03-19 20:54:26 +0000449 }
450
Misha Brukman8a96c532005-04-21 21:44:41 +0000451 if (FunctionValues.size() > type &&
452 FunctionValues[type] &&
Reid Spencer060d25d2004-06-29 23:29:38 +0000453 Num < FunctionValues[type]->size())
454 return FunctionValues[type]->getOperand(Num);
Chris Lattner00950542001-06-06 20:29:01 +0000455
Chris Lattner74734132002-08-17 22:01:27 +0000456 if (!Create) return 0; // Do not create a placeholder?
Chris Lattner00950542001-06-06 20:29:01 +0000457
Reid Spencer551ccae2004-09-01 22:55:40 +0000458 // Did we already create a place holder?
Chris Lattner8eb10ce2003-10-09 06:05:40 +0000459 std::pair<unsigned,unsigned> KeyValue(type, oNum);
Reid Spencer060d25d2004-06-29 23:29:38 +0000460 ForwardReferenceMap::iterator I = ForwardReferences.lower_bound(KeyValue);
Chris Lattner8eb10ce2003-10-09 06:05:40 +0000461 if (I != ForwardReferences.end() && I->first == KeyValue)
462 return I->second; // We have already created this placeholder
463
Reid Spencer551ccae2004-09-01 22:55:40 +0000464 // If the type exists (it should)
465 if (const Type* Ty = getType(type)) {
466 // Create the place holder
467 Value *Val = new Argument(Ty);
468 ForwardReferences.insert(I, std::make_pair(KeyValue, Val));
469 return Val;
470 }
471 throw "Can't create placeholder for value of type slot #" + utostr(type);
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 assert((!isa<Constant>(Val) || !cast<Constant>(Val)->isNullValue()) ||
Reid Spencer04cde2c2004-07-04 11:33:49 +0000546 !hasImplicitNull(type) &&
547 "Cannot read null values from bytecode!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000548
549 if (ValueTab.size() <= type)
550 ValueTab.resize(type+1);
551
552 if (!ValueTab[type]) ValueTab[type] = new ValueList();
553
554 ValueTab[type]->push_back(Val);
555
Chris Lattneraba5ff52005-05-05 20:57:00 +0000556 bool HasOffset = hasImplicitNull(type) && !isa<OpaqueType>(Val->getType());
Reid Spencer060d25d2004-06-29 23:29:38 +0000557 return ValueTab[type]->size()-1 + HasOffset;
558}
559
Reid Spencer04cde2c2004-07-04 11:33:49 +0000560/// Insert the arguments of a function as new values in the reader.
Reid Spencer46b002c2004-07-11 17:28:43 +0000561void BytecodeReader::insertArguments(Function* F) {
Reid Spencer060d25d2004-06-29 23:29:38 +0000562 const FunctionType *FT = F->getFunctionType();
Chris Lattnere4d5c442005-03-15 04:54:21 +0000563 Function::arg_iterator AI = F->arg_begin();
Reid Spencer060d25d2004-06-29 23:29:38 +0000564 for (FunctionType::param_iterator It = FT->param_begin();
565 It != FT->param_end(); ++It, ++AI)
566 insertValue(AI, getTypeSlot(AI->getType()), FunctionValues);
567}
568
569//===----------------------------------------------------------------------===//
570// Bytecode Parsing Methods
571//===----------------------------------------------------------------------===//
572
Reid Spencer04cde2c2004-07-04 11:33:49 +0000573/// This method parses a single instruction. The instruction is
574/// inserted at the end of the \p BB provided. The arguments of
Misha Brukman44666b12004-09-28 16:57:46 +0000575/// the instruction are provided in the \p Oprnds vector.
Reid Spencer060d25d2004-06-29 23:29:38 +0000576void BytecodeReader::ParseInstruction(std::vector<unsigned> &Oprnds,
Reid Spencer46b002c2004-07-11 17:28:43 +0000577 BasicBlock* BB) {
Reid Spencer060d25d2004-06-29 23:29:38 +0000578 BufPtr SaveAt = At;
579
580 // Clear instruction data
581 Oprnds.clear();
582 unsigned iType = 0;
583 unsigned Opcode = 0;
584 unsigned Op = read_uint();
585
586 // bits Instruction format: Common to all formats
587 // --------------------------
588 // 01-00: Opcode type, fixed to 1.
589 // 07-02: Opcode
590 Opcode = (Op >> 2) & 63;
591 Oprnds.resize((Op >> 0) & 03);
592
593 // Extract the operands
594 switch (Oprnds.size()) {
595 case 1:
596 // bits Instruction format:
597 // --------------------------
598 // 19-08: Resulting type plane
599 // 31-20: Operand #1 (if set to (2^12-1), then zero operands)
600 //
601 iType = (Op >> 8) & 4095;
602 Oprnds[0] = (Op >> 20) & 4095;
603 if (Oprnds[0] == 4095) // Handle special encoding for 0 operands...
604 Oprnds.resize(0);
605 break;
606 case 2:
607 // bits Instruction format:
608 // --------------------------
609 // 15-08: Resulting type plane
610 // 23-16: Operand #1
Misha Brukman8a96c532005-04-21 21:44:41 +0000611 // 31-24: Operand #2
Reid Spencer060d25d2004-06-29 23:29:38 +0000612 //
613 iType = (Op >> 8) & 255;
614 Oprnds[0] = (Op >> 16) & 255;
615 Oprnds[1] = (Op >> 24) & 255;
616 break;
617 case 3:
618 // bits Instruction format:
619 // --------------------------
620 // 13-08: Resulting type plane
621 // 19-14: Operand #1
622 // 25-20: Operand #2
623 // 31-26: Operand #3
624 //
625 iType = (Op >> 8) & 63;
626 Oprnds[0] = (Op >> 14) & 63;
627 Oprnds[1] = (Op >> 20) & 63;
628 Oprnds[2] = (Op >> 26) & 63;
629 break;
630 case 0:
631 At -= 4; // Hrm, try this again...
632 Opcode = read_vbr_uint();
633 Opcode >>= 2;
634 iType = read_vbr_uint();
635
636 unsigned NumOprnds = read_vbr_uint();
637 Oprnds.resize(NumOprnds);
638
639 if (NumOprnds == 0)
Reid Spencer24399722004-07-09 22:21:33 +0000640 error("Zero-argument instruction found; this is invalid.");
Reid Spencer060d25d2004-06-29 23:29:38 +0000641
642 for (unsigned i = 0; i != NumOprnds; ++i)
643 Oprnds[i] = read_vbr_uint();
644 align32();
645 break;
646 }
647
Reid Spencer04cde2c2004-07-04 11:33:49 +0000648 const Type *InstTy = getSanitizedType(iType);
Reid Spencer060d25d2004-06-29 23:29:38 +0000649
Reid Spencer46b002c2004-07-11 17:28:43 +0000650 // We have enough info to inform the handler now.
Reid Spencer04cde2c2004-07-04 11:33:49 +0000651 if (Handler) Handler->handleInstruction(Opcode, InstTy, Oprnds, At-SaveAt);
Reid Spencer060d25d2004-06-29 23:29:38 +0000652
653 // Declare the resulting instruction we'll build.
654 Instruction *Result = 0;
655
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000656 // If this is a bytecode format that did not include the unreachable
657 // instruction, bump up all opcodes numbers to make space.
658 if (hasNoUnreachableInst) {
659 if (Opcode >= Instruction::Unreachable &&
660 Opcode < 62) {
661 ++Opcode;
662 }
663 }
664
Reid Spencer060d25d2004-06-29 23:29:38 +0000665 // Handle binary operators
666 if (Opcode >= Instruction::BinaryOpsBegin &&
667 Opcode < Instruction::BinaryOpsEnd && Oprnds.size() == 2)
668 Result = BinaryOperator::create((Instruction::BinaryOps)Opcode,
669 getValue(iType, Oprnds[0]),
670 getValue(iType, Oprnds[1]));
671
672 switch (Opcode) {
Misha Brukman8a96c532005-04-21 21:44:41 +0000673 default:
674 if (Result == 0)
Reid Spencer24399722004-07-09 22:21:33 +0000675 error("Illegal instruction read!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000676 break;
677 case Instruction::VAArg:
Misha Brukman8a96c532005-04-21 21:44:41 +0000678 Result = new VAArgInst(getValue(iType, Oprnds[0]),
Reid Spencer46b002c2004-07-11 17:28:43 +0000679 getSanitizedType(Oprnds[1]));
Reid Spencer060d25d2004-06-29 23:29:38 +0000680 break;
Andrew Lenharth558bc882005-06-18 18:34:52 +0000681 case 32: { //VANext_old
682 const Type* ArgTy = getValue(iType, Oprnds[0])->getType();
683 Function* NF = TheModule->getOrInsertFunction("llvm.va_copy", ArgTy, ArgTy, 0);
684
685 //b = vanext a, t ->
686 //foo = alloca 1 of t
687 //bar = vacopy a
688 //store bar -> foo
689 //tmp = vaarg foo, t
690 //b = load foo
691 AllocaInst* foo = new AllocaInst(ArgTy, 0, "vanext.fix");
692 BB->getInstList().push_back(foo);
693 CallInst* bar = new CallInst(NF, getValue(iType, Oprnds[0]));
694 BB->getInstList().push_back(bar);
695 BB->getInstList().push_back(new StoreInst(bar, foo));
696 Instruction* tmp = new VAArgInst(foo, getSanitizedType(Oprnds[1]));
697 BB->getInstList().push_back(tmp);
698 Result = new LoadInst(foo);
Reid Spencer060d25d2004-06-29 23:29:38 +0000699 break;
Andrew Lenharth558bc882005-06-18 18:34:52 +0000700 }
701 case 33: { //VAArg_old
702 const Type* ArgTy = getValue(iType, Oprnds[0])->getType();
703 Function* NF = TheModule->getOrInsertFunction("llvm.va_copy", ArgTy, ArgTy, 0);
704
Jeff Cohen00b168892005-07-27 06:12:32 +0000705 //b = vaarg a, t ->
Andrew Lenharth558bc882005-06-18 18:34:52 +0000706 //foo = alloca 1 of t
Jeff Cohen00b168892005-07-27 06:12:32 +0000707 //bar = vacopy a
Andrew Lenharth558bc882005-06-18 18:34:52 +0000708 //store bar -> foo
709 //b = vaarg foo, t
710 AllocaInst* foo = new AllocaInst(ArgTy, 0, "vaarg.fix");
711 BB->getInstList().push_back(foo);
712 CallInst* bar = new CallInst(NF, getValue(iType, Oprnds[0]));
713 BB->getInstList().push_back(bar);
714 BB->getInstList().push_back(new StoreInst(bar, foo));
715 Result = new VAArgInst(foo, getSanitizedType(Oprnds[1]));
716 break;
717 }
Reid Spencer060d25d2004-06-29 23:29:38 +0000718 case Instruction::Cast:
Misha Brukman8a96c532005-04-21 21:44:41 +0000719 Result = new CastInst(getValue(iType, Oprnds[0]),
Reid Spencer46b002c2004-07-11 17:28:43 +0000720 getSanitizedType(Oprnds[1]));
Reid Spencer060d25d2004-06-29 23:29:38 +0000721 break;
722 case Instruction::Select:
723 Result = new SelectInst(getValue(Type::BoolTyID, Oprnds[0]),
724 getValue(iType, Oprnds[1]),
725 getValue(iType, Oprnds[2]));
726 break;
727 case Instruction::PHI: {
728 if (Oprnds.size() == 0 || (Oprnds.size() & 1))
Reid Spencer24399722004-07-09 22:21:33 +0000729 error("Invalid phi node encountered!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000730
731 PHINode *PN = new PHINode(InstTy);
Chris Lattnercad28bd2005-01-29 00:36:19 +0000732 PN->reserveOperandSpace(Oprnds.size());
Reid Spencer060d25d2004-06-29 23:29:38 +0000733 for (unsigned i = 0, e = Oprnds.size(); i != e; i += 2)
734 PN->addIncoming(getValue(iType, Oprnds[i]), getBasicBlock(Oprnds[i+1]));
735 Result = PN;
736 break;
737 }
738
739 case Instruction::Shl:
740 case Instruction::Shr:
741 Result = new ShiftInst((Instruction::OtherOps)Opcode,
742 getValue(iType, Oprnds[0]),
743 getValue(Type::UByteTyID, Oprnds[1]));
744 break;
745 case Instruction::Ret:
746 if (Oprnds.size() == 0)
747 Result = new ReturnInst();
748 else if (Oprnds.size() == 1)
749 Result = new ReturnInst(getValue(iType, Oprnds[0]));
750 else
Reid Spencer24399722004-07-09 22:21:33 +0000751 error("Unrecognized instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000752 break;
753
754 case Instruction::Br:
755 if (Oprnds.size() == 1)
756 Result = new BranchInst(getBasicBlock(Oprnds[0]));
757 else if (Oprnds.size() == 3)
Misha Brukman8a96c532005-04-21 21:44:41 +0000758 Result = new BranchInst(getBasicBlock(Oprnds[0]),
Reid Spencer04cde2c2004-07-04 11:33:49 +0000759 getBasicBlock(Oprnds[1]), getValue(Type::BoolTyID , Oprnds[2]));
Reid Spencer060d25d2004-06-29 23:29:38 +0000760 else
Reid Spencer24399722004-07-09 22:21:33 +0000761 error("Invalid number of operands for a 'br' instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000762 break;
763 case Instruction::Switch: {
764 if (Oprnds.size() & 1)
Reid Spencer24399722004-07-09 22:21:33 +0000765 error("Switch statement with odd number of arguments!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000766
767 SwitchInst *I = new SwitchInst(getValue(iType, Oprnds[0]),
Chris Lattnercad28bd2005-01-29 00:36:19 +0000768 getBasicBlock(Oprnds[1]),
769 Oprnds.size()/2-1);
Reid Spencer060d25d2004-06-29 23:29:38 +0000770 for (unsigned i = 2, e = Oprnds.size(); i != e; i += 2)
Chris Lattner7e618232005-02-24 05:26:04 +0000771 I->addCase(cast<ConstantInt>(getValue(iType, Oprnds[i])),
Reid Spencer060d25d2004-06-29 23:29:38 +0000772 getBasicBlock(Oprnds[i+1]));
773 Result = I;
774 break;
775 }
776
Chris Lattnerdee199f2005-05-06 22:34:01 +0000777 case 58: // Call with extra operand for calling conv
778 case 59: // tail call, Fast CC
779 case 60: // normal call, Fast CC
780 case 61: // tail call, C Calling Conv
781 case Instruction::Call: { // Normal Call, C Calling Convention
Reid Spencer060d25d2004-06-29 23:29:38 +0000782 if (Oprnds.size() == 0)
Reid Spencer24399722004-07-09 22:21:33 +0000783 error("Invalid call instruction encountered!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000784
785 Value *F = getValue(iType, Oprnds[0]);
786
Chris Lattnerdee199f2005-05-06 22:34:01 +0000787 unsigned CallingConv = CallingConv::C;
788 bool isTailCall = false;
789
790 if (Opcode == 61 || Opcode == 59)
791 isTailCall = true;
792
Reid Spencer060d25d2004-06-29 23:29:38 +0000793 // Check to make sure we have a pointer to function type
794 const PointerType *PTy = dyn_cast<PointerType>(F->getType());
Reid Spencer24399722004-07-09 22:21:33 +0000795 if (PTy == 0) error("Call to non function pointer value!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000796 const FunctionType *FTy = dyn_cast<FunctionType>(PTy->getElementType());
Reid Spencer24399722004-07-09 22:21:33 +0000797 if (FTy == 0) error("Call to non function pointer value!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000798
799 std::vector<Value *> Params;
800 if (!FTy->isVarArg()) {
801 FunctionType::param_iterator It = FTy->param_begin();
802
Chris Lattnerdee199f2005-05-06 22:34:01 +0000803 if (Opcode == 58) {
804 isTailCall = Oprnds.back() & 1;
805 CallingConv = Oprnds.back() >> 1;
806 Oprnds.pop_back();
807 } else if (Opcode == 59 || Opcode == 60)
808 CallingConv = CallingConv::Fast;
809
Reid Spencer060d25d2004-06-29 23:29:38 +0000810 for (unsigned i = 1, e = Oprnds.size(); i != e; ++i) {
811 if (It == FTy->param_end())
Reid Spencer24399722004-07-09 22:21:33 +0000812 error("Invalid call instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000813 Params.push_back(getValue(getTypeSlot(*It++), Oprnds[i]));
814 }
815 if (It != FTy->param_end())
Reid Spencer24399722004-07-09 22:21:33 +0000816 error("Invalid call instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000817 } else {
818 Oprnds.erase(Oprnds.begin(), Oprnds.begin()+1);
819
820 unsigned FirstVariableOperand;
821 if (Oprnds.size() < FTy->getNumParams())
Reid Spencer24399722004-07-09 22:21:33 +0000822 error("Call instruction missing operands!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000823
824 // Read all of the fixed arguments
825 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
826 Params.push_back(getValue(getTypeSlot(FTy->getParamType(i)),Oprnds[i]));
Misha Brukman8a96c532005-04-21 21:44:41 +0000827
Reid Spencer060d25d2004-06-29 23:29:38 +0000828 FirstVariableOperand = FTy->getNumParams();
829
Misha Brukman8a96c532005-04-21 21:44:41 +0000830 if ((Oprnds.size()-FirstVariableOperand) & 1)
Chris Lattner4a242b32004-10-14 01:39:18 +0000831 error("Invalid call instruction!"); // Must be pairs of type/value
Misha Brukman8a96c532005-04-21 21:44:41 +0000832
833 for (unsigned i = FirstVariableOperand, e = Oprnds.size();
Reid Spencer04cde2c2004-07-04 11:33:49 +0000834 i != e; i += 2)
Reid Spencer060d25d2004-06-29 23:29:38 +0000835 Params.push_back(getValue(Oprnds[i], Oprnds[i+1]));
836 }
837
838 Result = new CallInst(F, Params);
Chris Lattnerdee199f2005-05-06 22:34:01 +0000839 if (isTailCall) cast<CallInst>(Result)->setTailCall();
840 if (CallingConv) cast<CallInst>(Result)->setCallingConv(CallingConv);
Reid Spencer060d25d2004-06-29 23:29:38 +0000841 break;
842 }
Chris Lattnerdee199f2005-05-06 22:34:01 +0000843 case 56: // Invoke with encoded CC
844 case 57: // Invoke Fast CC
845 case Instruction::Invoke: { // Invoke C CC
Misha Brukman8a96c532005-04-21 21:44:41 +0000846 if (Oprnds.size() < 3)
Reid Spencer24399722004-07-09 22:21:33 +0000847 error("Invalid invoke instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000848 Value *F = getValue(iType, Oprnds[0]);
849
850 // Check to make sure we have a pointer to function type
851 const PointerType *PTy = dyn_cast<PointerType>(F->getType());
Misha Brukman8a96c532005-04-21 21:44:41 +0000852 if (PTy == 0)
Reid Spencer24399722004-07-09 22:21:33 +0000853 error("Invoke to non function pointer value!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000854 const FunctionType *FTy = dyn_cast<FunctionType>(PTy->getElementType());
Misha Brukman8a96c532005-04-21 21:44:41 +0000855 if (FTy == 0)
Reid Spencer24399722004-07-09 22:21:33 +0000856 error("Invoke to non function pointer value!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000857
858 std::vector<Value *> Params;
859 BasicBlock *Normal, *Except;
Chris Lattnerdee199f2005-05-06 22:34:01 +0000860 unsigned CallingConv = CallingConv::C;
861
862 if (Opcode == 57)
863 CallingConv = CallingConv::Fast;
864 else if (Opcode == 56) {
865 CallingConv = Oprnds.back();
866 Oprnds.pop_back();
867 }
Reid Spencer060d25d2004-06-29 23:29:38 +0000868
869 if (!FTy->isVarArg()) {
870 Normal = getBasicBlock(Oprnds[1]);
871 Except = getBasicBlock(Oprnds[2]);
872
873 FunctionType::param_iterator It = FTy->param_begin();
874 for (unsigned i = 3, e = Oprnds.size(); i != e; ++i) {
875 if (It == FTy->param_end())
Reid Spencer24399722004-07-09 22:21:33 +0000876 error("Invalid invoke instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000877 Params.push_back(getValue(getTypeSlot(*It++), Oprnds[i]));
878 }
879 if (It != FTy->param_end())
Reid Spencer24399722004-07-09 22:21:33 +0000880 error("Invalid invoke instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000881 } else {
882 Oprnds.erase(Oprnds.begin(), Oprnds.begin()+1);
883
884 Normal = getBasicBlock(Oprnds[0]);
885 Except = getBasicBlock(Oprnds[1]);
Misha Brukman8a96c532005-04-21 21:44:41 +0000886
Reid Spencer060d25d2004-06-29 23:29:38 +0000887 unsigned FirstVariableArgument = FTy->getNumParams()+2;
888 for (unsigned i = 2; i != FirstVariableArgument; ++i)
889 Params.push_back(getValue(getTypeSlot(FTy->getParamType(i-2)),
890 Oprnds[i]));
Misha Brukman8a96c532005-04-21 21:44:41 +0000891
Reid Spencer060d25d2004-06-29 23:29:38 +0000892 if (Oprnds.size()-FirstVariableArgument & 1) // Must be type/value pairs
Reid Spencer24399722004-07-09 22:21:33 +0000893 error("Invalid invoke instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000894
895 for (unsigned i = FirstVariableArgument; i < Oprnds.size(); i += 2)
896 Params.push_back(getValue(Oprnds[i], Oprnds[i+1]));
897 }
898
899 Result = new InvokeInst(F, Normal, Except, Params);
Chris Lattnerdee199f2005-05-06 22:34:01 +0000900 if (CallingConv) cast<InvokeInst>(Result)->setCallingConv(CallingConv);
Reid Spencer060d25d2004-06-29 23:29:38 +0000901 break;
902 }
903 case Instruction::Malloc:
Misha Brukman8a96c532005-04-21 21:44:41 +0000904 if (Oprnds.size() > 2)
Reid Spencer24399722004-07-09 22:21:33 +0000905 error("Invalid malloc instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000906 if (!isa<PointerType>(InstTy))
Reid Spencer24399722004-07-09 22:21:33 +0000907 error("Invalid malloc instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000908
909 Result = new MallocInst(cast<PointerType>(InstTy)->getElementType(),
910 Oprnds.size() ? getValue(Type::UIntTyID,
911 Oprnds[0]) : 0);
912 break;
913
914 case Instruction::Alloca:
Misha Brukman8a96c532005-04-21 21:44:41 +0000915 if (Oprnds.size() > 2)
Reid Spencer24399722004-07-09 22:21:33 +0000916 error("Invalid alloca instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000917 if (!isa<PointerType>(InstTy))
Reid Spencer24399722004-07-09 22:21:33 +0000918 error("Invalid alloca instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000919
920 Result = new AllocaInst(cast<PointerType>(InstTy)->getElementType(),
Misha Brukman8a96c532005-04-21 21:44:41 +0000921 Oprnds.size() ? getValue(Type::UIntTyID,
Reid Spencer04cde2c2004-07-04 11:33:49 +0000922 Oprnds[0]) :0);
Reid Spencer060d25d2004-06-29 23:29:38 +0000923 break;
924 case Instruction::Free:
925 if (!isa<PointerType>(InstTy))
Reid Spencer24399722004-07-09 22:21:33 +0000926 error("Invalid free instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000927 Result = new FreeInst(getValue(iType, Oprnds[0]));
928 break;
929 case Instruction::GetElementPtr: {
930 if (Oprnds.size() == 0 || !isa<PointerType>(InstTy))
Reid Spencer24399722004-07-09 22:21:33 +0000931 error("Invalid getelementptr instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000932
933 std::vector<Value*> Idx;
934
935 const Type *NextTy = InstTy;
936 for (unsigned i = 1, e = Oprnds.size(); i != e; ++i) {
937 const CompositeType *TopTy = dyn_cast_or_null<CompositeType>(NextTy);
Misha Brukman8a96c532005-04-21 21:44:41 +0000938 if (!TopTy)
939 error("Invalid getelementptr instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000940
941 unsigned ValIdx = Oprnds[i];
942 unsigned IdxTy = 0;
943 if (!hasRestrictedGEPTypes) {
944 // Struct indices are always uints, sequential type indices can be any
945 // of the 32 or 64-bit integer types. The actual choice of type is
946 // encoded in the low two bits of the slot number.
947 if (isa<StructType>(TopTy))
948 IdxTy = Type::UIntTyID;
949 else {
950 switch (ValIdx & 3) {
951 default:
952 case 0: IdxTy = Type::UIntTyID; break;
953 case 1: IdxTy = Type::IntTyID; break;
954 case 2: IdxTy = Type::ULongTyID; break;
955 case 3: IdxTy = Type::LongTyID; break;
956 }
957 ValIdx >>= 2;
958 }
959 } else {
960 IdxTy = isa<StructType>(TopTy) ? Type::UByteTyID : Type::LongTyID;
961 }
962
963 Idx.push_back(getValue(IdxTy, ValIdx));
964
965 // Convert ubyte struct indices into uint struct indices.
966 if (isa<StructType>(TopTy) && hasRestrictedGEPTypes)
967 if (ConstantUInt *C = dyn_cast<ConstantUInt>(Idx.back()))
968 Idx[Idx.size()-1] = ConstantExpr::getCast(C, Type::UIntTy);
969
970 NextTy = GetElementPtrInst::getIndexedType(InstTy, Idx, true);
971 }
972
973 Result = new GetElementPtrInst(getValue(iType, Oprnds[0]), Idx);
974 break;
975 }
976
977 case 62: // volatile load
978 case Instruction::Load:
979 if (Oprnds.size() != 1 || !isa<PointerType>(InstTy))
Reid Spencer24399722004-07-09 22:21:33 +0000980 error("Invalid load instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000981 Result = new LoadInst(getValue(iType, Oprnds[0]), "", Opcode == 62);
982 break;
983
Misha Brukman8a96c532005-04-21 21:44:41 +0000984 case 63: // volatile store
Reid Spencer060d25d2004-06-29 23:29:38 +0000985 case Instruction::Store: {
986 if (!isa<PointerType>(InstTy) || Oprnds.size() != 2)
Reid Spencer24399722004-07-09 22:21:33 +0000987 error("Invalid store instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000988
989 Value *Ptr = getValue(iType, Oprnds[1]);
990 const Type *ValTy = cast<PointerType>(Ptr->getType())->getElementType();
991 Result = new StoreInst(getValue(getTypeSlot(ValTy), Oprnds[0]), Ptr,
992 Opcode == 63);
993 break;
994 }
995 case Instruction::Unwind:
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000996 if (Oprnds.size() != 0) error("Invalid unwind instruction!");
Reid Spencer060d25d2004-06-29 23:29:38 +0000997 Result = new UnwindInst();
998 break;
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000999 case Instruction::Unreachable:
1000 if (Oprnds.size() != 0) error("Invalid unreachable instruction!");
1001 Result = new UnreachableInst();
1002 break;
Misha Brukman8a96c532005-04-21 21:44:41 +00001003 } // end switch(Opcode)
Reid Spencer060d25d2004-06-29 23:29:38 +00001004
1005 unsigned TypeSlot;
1006 if (Result->getType() == InstTy)
1007 TypeSlot = iType;
1008 else
1009 TypeSlot = getTypeSlot(Result->getType());
1010
1011 insertValue(Result, TypeSlot, FunctionValues);
1012 BB->getInstList().push_back(Result);
1013}
1014
Reid Spencer04cde2c2004-07-04 11:33:49 +00001015/// Get a particular numbered basic block, which might be a forward reference.
1016/// This works together with ParseBasicBlock to handle these forward references
Chris Lattner4a242b32004-10-14 01:39:18 +00001017/// in a clean manner. This function is used when constructing phi, br, switch,
1018/// and other instructions that reference basic blocks. Blocks are numbered
Reid Spencer04cde2c2004-07-04 11:33:49 +00001019/// sequentially as they appear in the function.
Reid Spencer060d25d2004-06-29 23:29:38 +00001020BasicBlock *BytecodeReader::getBasicBlock(unsigned ID) {
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001021 // Make sure there is room in the table...
1022 if (ParsedBasicBlocks.size() <= ID) ParsedBasicBlocks.resize(ID+1);
1023
1024 // First check to see if this is a backwards reference, i.e., ParseBasicBlock
1025 // has already created this block, or if the forward reference has already
1026 // been created.
1027 if (ParsedBasicBlocks[ID])
1028 return ParsedBasicBlocks[ID];
1029
1030 // Otherwise, the basic block has not yet been created. Do so and add it to
1031 // the ParsedBasicBlocks list.
1032 return ParsedBasicBlocks[ID] = new BasicBlock();
1033}
1034
Misha Brukman8a96c532005-04-21 21:44:41 +00001035/// In LLVM 1.0 bytecode files, we used to output one basicblock at a time.
Reid Spencer04cde2c2004-07-04 11:33:49 +00001036/// This method reads in one of the basicblock packets. This method is not used
1037/// for bytecode files after LLVM 1.0
1038/// @returns The basic block constructed.
Reid Spencer46b002c2004-07-11 17:28:43 +00001039BasicBlock *BytecodeReader::ParseBasicBlock(unsigned BlockNo) {
1040 if (Handler) Handler->handleBasicBlockBegin(BlockNo);
Reid Spencer060d25d2004-06-29 23:29:38 +00001041
1042 BasicBlock *BB = 0;
1043
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001044 if (ParsedBasicBlocks.size() == BlockNo)
1045 ParsedBasicBlocks.push_back(BB = new BasicBlock());
1046 else if (ParsedBasicBlocks[BlockNo] == 0)
1047 BB = ParsedBasicBlocks[BlockNo] = new BasicBlock();
1048 else
1049 BB = ParsedBasicBlocks[BlockNo];
Chris Lattner00950542001-06-06 20:29:01 +00001050
Reid Spencer060d25d2004-06-29 23:29:38 +00001051 std::vector<unsigned> Operands;
Reid Spencer46b002c2004-07-11 17:28:43 +00001052 while (moreInBlock())
Reid Spencer060d25d2004-06-29 23:29:38 +00001053 ParseInstruction(Operands, BB);
Chris Lattner00950542001-06-06 20:29:01 +00001054
Reid Spencer46b002c2004-07-11 17:28:43 +00001055 if (Handler) Handler->handleBasicBlockEnd(BlockNo);
Misha Brukman12c29d12003-09-22 23:38:23 +00001056 return BB;
Chris Lattner00950542001-06-06 20:29:01 +00001057}
1058
Reid Spencer04cde2c2004-07-04 11:33:49 +00001059/// Parse all of the BasicBlock's & Instruction's in the body of a function.
Misha Brukman8a96c532005-04-21 21:44:41 +00001060/// In post 1.0 bytecode files, we no longer emit basic block individually,
Reid Spencer04cde2c2004-07-04 11:33:49 +00001061/// in order to avoid per-basic-block overhead.
1062/// @returns Rhe number of basic blocks encountered.
Reid Spencer060d25d2004-06-29 23:29:38 +00001063unsigned BytecodeReader::ParseInstructionList(Function* F) {
Chris Lattner8d1dbd22003-12-01 07:05:31 +00001064 unsigned BlockNo = 0;
1065 std::vector<unsigned> Args;
1066
Reid Spencer46b002c2004-07-11 17:28:43 +00001067 while (moreInBlock()) {
1068 if (Handler) Handler->handleBasicBlockBegin(BlockNo);
Chris Lattner8d1dbd22003-12-01 07:05:31 +00001069 BasicBlock *BB;
1070 if (ParsedBasicBlocks.size() == BlockNo)
1071 ParsedBasicBlocks.push_back(BB = new BasicBlock());
1072 else if (ParsedBasicBlocks[BlockNo] == 0)
1073 BB = ParsedBasicBlocks[BlockNo] = new BasicBlock();
1074 else
1075 BB = ParsedBasicBlocks[BlockNo];
1076 ++BlockNo;
1077 F->getBasicBlockList().push_back(BB);
1078
1079 // Read instructions into this basic block until we get to a terminator
Reid Spencer46b002c2004-07-11 17:28:43 +00001080 while (moreInBlock() && !BB->getTerminator())
Reid Spencer060d25d2004-06-29 23:29:38 +00001081 ParseInstruction(Args, BB);
Chris Lattner8d1dbd22003-12-01 07:05:31 +00001082
1083 if (!BB->getTerminator())
Reid Spencer24399722004-07-09 22:21:33 +00001084 error("Non-terminated basic block found!");
Reid Spencer5c15fe52004-07-05 00:57:50 +00001085
Reid Spencer46b002c2004-07-11 17:28:43 +00001086 if (Handler) Handler->handleBasicBlockEnd(BlockNo-1);
Chris Lattner8d1dbd22003-12-01 07:05:31 +00001087 }
1088
1089 return BlockNo;
1090}
1091
Reid Spencer04cde2c2004-07-04 11:33:49 +00001092/// Parse a symbol table. This works for both module level and function
1093/// level symbol tables. For function level symbol tables, the CurrentFunction
1094/// parameter must be non-zero and the ST parameter must correspond to
1095/// CurrentFunction's symbol table. For Module level symbol tables, the
1096/// CurrentFunction argument must be zero.
Reid Spencer060d25d2004-06-29 23:29:38 +00001097void BytecodeReader::ParseSymbolTable(Function *CurrentFunction,
Reid Spencer04cde2c2004-07-04 11:33:49 +00001098 SymbolTable *ST) {
1099 if (Handler) Handler->handleSymbolTableBegin(CurrentFunction,ST);
Reid Spencer060d25d2004-06-29 23:29:38 +00001100
Chris Lattner39cacce2003-10-10 05:43:47 +00001101 // Allow efficient basic block lookup by number.
1102 std::vector<BasicBlock*> BBMap;
1103 if (CurrentFunction)
1104 for (Function::iterator I = CurrentFunction->begin(),
1105 E = CurrentFunction->end(); I != E; ++I)
1106 BBMap.push_back(I);
1107
Reid Spencer04cde2c2004-07-04 11:33:49 +00001108 /// In LLVM 1.3 we write types separately from values so
1109 /// The types are always first in the symbol table. This is
1110 /// because Type no longer derives from Value.
Reid Spencer46b002c2004-07-11 17:28:43 +00001111 if (!hasTypeDerivedFromValue) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001112 // Symtab block header: [num entries]
1113 unsigned NumEntries = read_vbr_uint();
Reid Spencer46b002c2004-07-11 17:28:43 +00001114 for (unsigned i = 0; i < NumEntries; ++i) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001115 // Symtab entry: [def slot #][name]
1116 unsigned slot = read_vbr_uint();
1117 std::string Name = read_str();
1118 const Type* T = getType(slot);
1119 ST->insert(Name, T);
1120 }
1121 }
1122
Reid Spencer46b002c2004-07-11 17:28:43 +00001123 while (moreInBlock()) {
Chris Lattner00950542001-06-06 20:29:01 +00001124 // Symtab block header: [num entries][type id number]
Reid Spencer060d25d2004-06-29 23:29:38 +00001125 unsigned NumEntries = read_vbr_uint();
Reid Spencer04cde2c2004-07-04 11:33:49 +00001126 unsigned Typ = 0;
1127 bool isTypeType = read_typeid(Typ);
Chris Lattner00950542001-06-06 20:29:01 +00001128 const Type *Ty = getType(Typ);
Chris Lattner1d670cc2001-09-07 16:37:43 +00001129
Chris Lattner7dc3a2e2003-10-13 14:57:53 +00001130 for (unsigned i = 0; i != NumEntries; ++i) {
Chris Lattner00950542001-06-06 20:29:01 +00001131 // Symtab entry: [def slot #][name]
Reid Spencer060d25d2004-06-29 23:29:38 +00001132 unsigned slot = read_vbr_uint();
1133 std::string Name = read_str();
Chris Lattner00950542001-06-06 20:29:01 +00001134
Reid Spencer04cde2c2004-07-04 11:33:49 +00001135 // if we're reading a pre 1.3 bytecode file and the type plane
1136 // is the "type type", handle it here
Reid Spencer46b002c2004-07-11 17:28:43 +00001137 if (isTypeType) {
1138 const Type* T = getType(slot);
1139 if (T == 0)
1140 error("Failed type look-up for name '" + Name + "'");
1141 ST->insert(Name, T);
1142 continue; // code below must be short circuited
Chris Lattner39cacce2003-10-10 05:43:47 +00001143 } else {
Reid Spencer46b002c2004-07-11 17:28:43 +00001144 Value *V = 0;
1145 if (Typ == Type::LabelTyID) {
1146 if (slot < BBMap.size())
1147 V = BBMap[slot];
1148 } else {
1149 V = getValue(Typ, slot, false); // Find mapping...
1150 }
1151 if (V == 0)
1152 error("Failed value look-up for name '" + Name + "'");
Chris Lattner7acff252005-03-05 19:05:20 +00001153 V->setName(Name);
Chris Lattner39cacce2003-10-10 05:43:47 +00001154 }
Chris Lattner00950542001-06-06 20:29:01 +00001155 }
1156 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001157 checkPastBlockEnd("Symbol Table");
Reid Spencer04cde2c2004-07-04 11:33:49 +00001158 if (Handler) Handler->handleSymbolTableEnd();
Chris Lattner00950542001-06-06 20:29:01 +00001159}
1160
Misha Brukman8a96c532005-04-21 21:44:41 +00001161/// Read in the types portion of a compaction table.
Reid Spencer46b002c2004-07-11 17:28:43 +00001162void BytecodeReader::ParseCompactionTypes(unsigned NumEntries) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001163 for (unsigned i = 0; i != NumEntries; ++i) {
1164 unsigned TypeSlot = 0;
Reid Spencer46b002c2004-07-11 17:28:43 +00001165 if (read_typeid(TypeSlot))
Reid Spencer24399722004-07-09 22:21:33 +00001166 error("Invalid type in compaction table: type type");
Reid Spencer04cde2c2004-07-04 11:33:49 +00001167 const Type *Typ = getGlobalTableType(TypeSlot);
Chris Lattner45b5dd22004-08-03 23:41:28 +00001168 CompactionTypes.push_back(std::make_pair(Typ, TypeSlot));
Reid Spencer46b002c2004-07-11 17:28:43 +00001169 if (Handler) Handler->handleCompactionTableType(i, TypeSlot, Typ);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001170 }
1171}
1172
1173/// Parse a compaction table.
Reid Spencer060d25d2004-06-29 23:29:38 +00001174void BytecodeReader::ParseCompactionTable() {
1175
Reid Spencer46b002c2004-07-11 17:28:43 +00001176 // Notify handler that we're beginning a compaction table.
Reid Spencer04cde2c2004-07-04 11:33:49 +00001177 if (Handler) Handler->handleCompactionTableBegin();
1178
Misha Brukman8a96c532005-04-21 21:44:41 +00001179 // In LLVM 1.3 Type no longer derives from Value. So,
Reid Spencer46b002c2004-07-11 17:28:43 +00001180 // we always write them first in the compaction table
1181 // because they can't occupy a "type plane" where the
1182 // Values reside.
1183 if (! hasTypeDerivedFromValue) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001184 unsigned NumEntries = read_vbr_uint();
Reid Spencer46b002c2004-07-11 17:28:43 +00001185 ParseCompactionTypes(NumEntries);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001186 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001187
Reid Spencer46b002c2004-07-11 17:28:43 +00001188 // Compaction tables live in separate blocks so we have to loop
1189 // until we've read the whole thing.
1190 while (moreInBlock()) {
1191 // Read the number of Value* entries in the compaction table
Reid Spencer060d25d2004-06-29 23:29:38 +00001192 unsigned NumEntries = read_vbr_uint();
Reid Spencer04cde2c2004-07-04 11:33:49 +00001193 unsigned Ty = 0;
1194 unsigned isTypeType = false;
Reid Spencer060d25d2004-06-29 23:29:38 +00001195
Reid Spencer46b002c2004-07-11 17:28:43 +00001196 // Decode the type from value read in. Most compaction table
1197 // planes will have one or two entries in them. If that's the
1198 // case then the length is encoded in the bottom two bits and
1199 // the higher bits encode the type. This saves another VBR value.
Reid Spencer060d25d2004-06-29 23:29:38 +00001200 if ((NumEntries & 3) == 3) {
Reid Spencer46b002c2004-07-11 17:28:43 +00001201 // In this case, both low-order bits are set (value 3). This
1202 // is a signal that the typeid follows.
Reid Spencer060d25d2004-06-29 23:29:38 +00001203 NumEntries >>= 2;
Reid Spencer04cde2c2004-07-04 11:33:49 +00001204 isTypeType = read_typeid(Ty);
Reid Spencer060d25d2004-06-29 23:29:38 +00001205 } else {
Reid Spencer46b002c2004-07-11 17:28:43 +00001206 // In this case, the low-order bits specify the number of entries
1207 // and the high order bits specify the type.
Reid Spencer060d25d2004-06-29 23:29:38 +00001208 Ty = NumEntries >> 2;
Reid Spencer04cde2c2004-07-04 11:33:49 +00001209 isTypeType = sanitizeTypeId(Ty);
Reid Spencer060d25d2004-06-29 23:29:38 +00001210 NumEntries &= 3;
1211 }
1212
Reid Spencer04cde2c2004-07-04 11:33:49 +00001213 // if we're reading a pre 1.3 bytecode file and the type plane
1214 // is the "type type", handle it here
Reid Spencer46b002c2004-07-11 17:28:43 +00001215 if (isTypeType) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001216 ParseCompactionTypes(NumEntries);
Reid Spencer060d25d2004-06-29 23:29:38 +00001217 } else {
Chris Lattner2c6c14d2004-08-04 00:19:23 +00001218 // Make sure we have enough room for the plane.
Reid Spencer04cde2c2004-07-04 11:33:49 +00001219 if (Ty >= CompactionValues.size())
Reid Spencer46b002c2004-07-11 17:28:43 +00001220 CompactionValues.resize(Ty+1);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001221
Chris Lattner2c6c14d2004-08-04 00:19:23 +00001222 // Make sure the plane is empty or we have some kind of error.
Reid Spencer04cde2c2004-07-04 11:33:49 +00001223 if (!CompactionValues[Ty].empty())
Reid Spencer46b002c2004-07-11 17:28:43 +00001224 error("Compaction table plane contains multiple entries!");
Reid Spencer04cde2c2004-07-04 11:33:49 +00001225
Chris Lattner2c6c14d2004-08-04 00:19:23 +00001226 // Notify handler about the plane.
Reid Spencer46b002c2004-07-11 17:28:43 +00001227 if (Handler) Handler->handleCompactionTablePlane(Ty, NumEntries);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001228
Chris Lattner2c6c14d2004-08-04 00:19:23 +00001229 // Push the implicit zero.
1230 CompactionValues[Ty].push_back(Constant::getNullValue(getType(Ty)));
Reid Spencer46b002c2004-07-11 17:28:43 +00001231
1232 // Read in each of the entries, put them in the compaction table
1233 // and notify the handler that we have a new compaction table value.
Reid Spencer060d25d2004-06-29 23:29:38 +00001234 for (unsigned i = 0; i != NumEntries; ++i) {
Reid Spencer46b002c2004-07-11 17:28:43 +00001235 unsigned ValSlot = read_vbr_uint();
Chris Lattner2c6c14d2004-08-04 00:19:23 +00001236 Value *V = getGlobalTableValue(Ty, ValSlot);
Reid Spencer46b002c2004-07-11 17:28:43 +00001237 CompactionValues[Ty].push_back(V);
Chris Lattner2c6c14d2004-08-04 00:19:23 +00001238 if (Handler) Handler->handleCompactionTableValue(i, Ty, ValSlot);
Reid Spencer060d25d2004-06-29 23:29:38 +00001239 }
1240 }
1241 }
Reid Spencer46b002c2004-07-11 17:28:43 +00001242 // Notify handler that the compaction table is done.
Reid Spencer04cde2c2004-07-04 11:33:49 +00001243 if (Handler) Handler->handleCompactionTableEnd();
Reid Spencer060d25d2004-06-29 23:29:38 +00001244}
Misha Brukman8a96c532005-04-21 21:44:41 +00001245
Reid Spencer46b002c2004-07-11 17:28:43 +00001246// Parse a single type. The typeid is read in first. If its a primitive type
1247// then nothing else needs to be read, we know how to instantiate it. If its
Misha Brukman8a96c532005-04-21 21:44:41 +00001248// a derived type, then additional data is read to fill out the type
Reid Spencer46b002c2004-07-11 17:28:43 +00001249// definition.
1250const Type *BytecodeReader::ParseType() {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001251 unsigned PrimType = 0;
Reid Spencer46b002c2004-07-11 17:28:43 +00001252 if (read_typeid(PrimType))
Reid Spencer24399722004-07-09 22:21:33 +00001253 error("Invalid type (type type) in type constants!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001254
1255 const Type *Result = 0;
1256 if ((Result = Type::getPrimitiveType((Type::TypeID)PrimType)))
1257 return Result;
Misha Brukman8a96c532005-04-21 21:44:41 +00001258
Reid Spencer060d25d2004-06-29 23:29:38 +00001259 switch (PrimType) {
1260 case Type::FunctionTyID: {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001261 const Type *RetType = readSanitizedType();
Reid Spencer060d25d2004-06-29 23:29:38 +00001262
1263 unsigned NumParams = read_vbr_uint();
1264
1265 std::vector<const Type*> Params;
Misha Brukman8a96c532005-04-21 21:44:41 +00001266 while (NumParams--)
Reid Spencer04cde2c2004-07-04 11:33:49 +00001267 Params.push_back(readSanitizedType());
Reid Spencer060d25d2004-06-29 23:29:38 +00001268
1269 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1270 if (isVarArg) Params.pop_back();
1271
1272 Result = FunctionType::get(RetType, Params, isVarArg);
1273 break;
1274 }
1275 case Type::ArrayTyID: {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001276 const Type *ElementType = readSanitizedType();
Reid Spencer060d25d2004-06-29 23:29:38 +00001277 unsigned NumElements = read_vbr_uint();
Reid Spencer060d25d2004-06-29 23:29:38 +00001278 Result = ArrayType::get(ElementType, NumElements);
1279 break;
1280 }
Brian Gaeke715c90b2004-08-20 06:00:58 +00001281 case Type::PackedTyID: {
1282 const Type *ElementType = readSanitizedType();
1283 unsigned NumElements = read_vbr_uint();
1284 Result = PackedType::get(ElementType, NumElements);
1285 break;
1286 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001287 case Type::StructTyID: {
1288 std::vector<const Type*> Elements;
Reid Spencer04cde2c2004-07-04 11:33:49 +00001289 unsigned Typ = 0;
Reid Spencer46b002c2004-07-11 17:28:43 +00001290 if (read_typeid(Typ))
Reid Spencer24399722004-07-09 22:21:33 +00001291 error("Invalid element type (type type) for structure!");
1292
Reid Spencer060d25d2004-06-29 23:29:38 +00001293 while (Typ) { // List is terminated by void/0 typeid
1294 Elements.push_back(getType(Typ));
Reid Spencer46b002c2004-07-11 17:28:43 +00001295 if (read_typeid(Typ))
1296 error("Invalid element type (type type) for structure!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001297 }
1298
1299 Result = StructType::get(Elements);
1300 break;
1301 }
1302 case Type::PointerTyID: {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001303 Result = PointerType::get(readSanitizedType());
Reid Spencer060d25d2004-06-29 23:29:38 +00001304 break;
1305 }
1306
1307 case Type::OpaqueTyID: {
1308 Result = OpaqueType::get();
1309 break;
1310 }
1311
1312 default:
Reid Spencer24399722004-07-09 22:21:33 +00001313 error("Don't know how to deserialize primitive type " + utostr(PrimType));
Reid Spencer060d25d2004-06-29 23:29:38 +00001314 break;
1315 }
Reid Spencer46b002c2004-07-11 17:28:43 +00001316 if (Handler) Handler->handleType(Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001317 return Result;
1318}
1319
Reid Spencer5b472d92004-08-21 20:49:23 +00001320// ParseTypes - We have to use this weird code to handle recursive
Reid Spencer060d25d2004-06-29 23:29:38 +00001321// types. We know that recursive types will only reference the current slab of
1322// values in the type plane, but they can forward reference types before they
1323// have been read. For example, Type #0 might be '{ Ty#1 }' and Type #1 might
1324// be 'Ty#0*'. When reading Type #0, type number one doesn't exist. To fix
1325// this ugly problem, we pessimistically insert an opaque type for each type we
1326// are about to read. This means that forward references will resolve to
1327// something and when we reread the type later, we can replace the opaque type
1328// with a new resolved concrete type.
1329//
Reid Spencer46b002c2004-07-11 17:28:43 +00001330void BytecodeReader::ParseTypes(TypeListTy &Tab, unsigned NumEntries){
Reid Spencer060d25d2004-06-29 23:29:38 +00001331 assert(Tab.size() == 0 && "should not have read type constants in before!");
1332
1333 // Insert a bunch of opaque types to be resolved later...
1334 Tab.reserve(NumEntries);
1335 for (unsigned i = 0; i != NumEntries; ++i)
1336 Tab.push_back(OpaqueType::get());
1337
Misha Brukman8a96c532005-04-21 21:44:41 +00001338 if (Handler)
Reid Spencer5b472d92004-08-21 20:49:23 +00001339 Handler->handleTypeList(NumEntries);
1340
Chris Lattnereebac5f2005-10-03 21:26:53 +00001341 // If we are about to resolve types, make sure the type cache is clear.
1342 if (NumEntries)
1343 ModuleTypeIDCache.clear();
1344
Reid Spencer060d25d2004-06-29 23:29:38 +00001345 // Loop through reading all of the types. Forward types will make use of the
1346 // opaque types just inserted.
1347 //
1348 for (unsigned i = 0; i != NumEntries; ++i) {
Reid Spencer46b002c2004-07-11 17:28:43 +00001349 const Type* NewTy = ParseType();
Reid Spencer04cde2c2004-07-04 11:33:49 +00001350 const Type* OldTy = Tab[i].get();
Misha Brukman8a96c532005-04-21 21:44:41 +00001351 if (NewTy == 0)
Reid Spencer24399722004-07-09 22:21:33 +00001352 error("Couldn't parse type!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001353
Misha Brukman8a96c532005-04-21 21:44:41 +00001354 // Don't directly push the new type on the Tab. Instead we want to replace
Reid Spencer060d25d2004-06-29 23:29:38 +00001355 // the opaque type we previously inserted with the new concrete value. This
1356 // approach helps with forward references to types. The refinement from the
1357 // abstract (opaque) type to the new type causes all uses of the abstract
1358 // type to use the concrete type (NewTy). This will also cause the opaque
1359 // type to be deleted.
1360 cast<DerivedType>(const_cast<Type*>(OldTy))->refineAbstractTypeTo(NewTy);
1361
1362 // This should have replaced the old opaque type with the new type in the
1363 // value table... or with a preexisting type that was already in the system.
1364 // Let's just make sure it did.
1365 assert(Tab[i] != OldTy && "refineAbstractType didn't work!");
1366 }
1367}
1368
Reid Spencer04cde2c2004-07-04 11:33:49 +00001369/// Parse a single constant value
Reid Spencer46b002c2004-07-11 17:28:43 +00001370Constant *BytecodeReader::ParseConstantValue(unsigned TypeID) {
Reid Spencer060d25d2004-06-29 23:29:38 +00001371 // We must check for a ConstantExpr before switching by type because
1372 // a ConstantExpr can be of any type, and has no explicit value.
Misha Brukman8a96c532005-04-21 21:44:41 +00001373 //
Reid Spencer060d25d2004-06-29 23:29:38 +00001374 // 0 if not expr; numArgs if is expr
1375 unsigned isExprNumArgs = read_vbr_uint();
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001376
Reid Spencer060d25d2004-06-29 23:29:38 +00001377 if (isExprNumArgs) {
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001378 // 'undef' is encoded with 'exprnumargs' == 1.
1379 if (!hasNoUndefValue)
1380 if (--isExprNumArgs == 0)
1381 return UndefValue::get(getType(TypeID));
Misha Brukman8a96c532005-04-21 21:44:41 +00001382
Reid Spencer060d25d2004-06-29 23:29:38 +00001383 // FIXME: Encoding of constant exprs could be much more compact!
1384 std::vector<Constant*> ArgVec;
1385 ArgVec.reserve(isExprNumArgs);
1386 unsigned Opcode = read_vbr_uint();
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001387
1388 // Bytecode files before LLVM 1.4 need have a missing terminator inst.
1389 if (hasNoUnreachableInst) Opcode++;
Misha Brukman8a96c532005-04-21 21:44:41 +00001390
Reid Spencer060d25d2004-06-29 23:29:38 +00001391 // Read the slot number and types of each of the arguments
1392 for (unsigned i = 0; i != isExprNumArgs; ++i) {
1393 unsigned ArgValSlot = read_vbr_uint();
Reid Spencer04cde2c2004-07-04 11:33:49 +00001394 unsigned ArgTypeSlot = 0;
Reid Spencer46b002c2004-07-11 17:28:43 +00001395 if (read_typeid(ArgTypeSlot))
1396 error("Invalid argument type (type type) for constant value");
Misha Brukman8a96c532005-04-21 21:44:41 +00001397
Reid Spencer060d25d2004-06-29 23:29:38 +00001398 // Get the arg value from its slot if it exists, otherwise a placeholder
1399 ArgVec.push_back(getConstantValue(ArgTypeSlot, ArgValSlot));
1400 }
Misha Brukman8a96c532005-04-21 21:44:41 +00001401
Reid Spencer060d25d2004-06-29 23:29:38 +00001402 // Construct a ConstantExpr of the appropriate kind
1403 if (isExprNumArgs == 1) { // All one-operand expressions
Reid Spencer46b002c2004-07-11 17:28:43 +00001404 if (Opcode != Instruction::Cast)
Chris Lattner02dce162004-12-04 05:28:27 +00001405 error("Only cast instruction has one argument for ConstantExpr");
Reid Spencer46b002c2004-07-11 17:28:43 +00001406
Reid Spencer060d25d2004-06-29 23:29:38 +00001407 Constant* Result = ConstantExpr::getCast(ArgVec[0], getType(TypeID));
Reid Spencer04cde2c2004-07-04 11:33:49 +00001408 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001409 return Result;
1410 } else if (Opcode == Instruction::GetElementPtr) { // GetElementPtr
1411 std::vector<Constant*> IdxList(ArgVec.begin()+1, ArgVec.end());
1412
1413 if (hasRestrictedGEPTypes) {
1414 const Type *BaseTy = ArgVec[0]->getType();
1415 generic_gep_type_iterator<std::vector<Constant*>::iterator>
1416 GTI = gep_type_begin(BaseTy, IdxList.begin(), IdxList.end()),
1417 E = gep_type_end(BaseTy, IdxList.begin(), IdxList.end());
1418 for (unsigned i = 0; GTI != E; ++GTI, ++i)
1419 if (isa<StructType>(*GTI)) {
1420 if (IdxList[i]->getType() != Type::UByteTy)
Reid Spencer24399722004-07-09 22:21:33 +00001421 error("Invalid index for getelementptr!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001422 IdxList[i] = ConstantExpr::getCast(IdxList[i], Type::UIntTy);
1423 }
1424 }
1425
1426 Constant* Result = ConstantExpr::getGetElementPtr(ArgVec[0], IdxList);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001427 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001428 return Result;
1429 } else if (Opcode == Instruction::Select) {
Reid Spencer46b002c2004-07-11 17:28:43 +00001430 if (ArgVec.size() != 3)
1431 error("Select instruction must have three arguments.");
Misha Brukman8a96c532005-04-21 21:44:41 +00001432 Constant* Result = ConstantExpr::getSelect(ArgVec[0], ArgVec[1],
Reid Spencer04cde2c2004-07-04 11:33:49 +00001433 ArgVec[2]);
1434 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001435 return Result;
1436 } else { // All other 2-operand expressions
1437 Constant* Result = ConstantExpr::get(Opcode, ArgVec[0], ArgVec[1]);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001438 if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001439 return Result;
1440 }
1441 }
Misha Brukman8a96c532005-04-21 21:44:41 +00001442
Reid Spencer060d25d2004-06-29 23:29:38 +00001443 // Ok, not an ConstantExpr. We now know how to read the given type...
1444 const Type *Ty = getType(TypeID);
1445 switch (Ty->getTypeID()) {
1446 case Type::BoolTyID: {
1447 unsigned Val = read_vbr_uint();
Misha Brukman8a96c532005-04-21 21:44:41 +00001448 if (Val != 0 && Val != 1)
Reid Spencer24399722004-07-09 22:21:33 +00001449 error("Invalid boolean value read.");
Reid Spencer060d25d2004-06-29 23:29:38 +00001450 Constant* Result = ConstantBool::get(Val == 1);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001451 if (Handler) Handler->handleConstantValue(Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001452 return Result;
1453 }
1454
1455 case Type::UByteTyID: // Unsigned integer types...
1456 case Type::UShortTyID:
1457 case Type::UIntTyID: {
1458 unsigned Val = read_vbr_uint();
Misha Brukman8a96c532005-04-21 21:44:41 +00001459 if (!ConstantUInt::isValueValidForType(Ty, Val))
Reid Spencer24399722004-07-09 22:21:33 +00001460 error("Invalid unsigned byte/short/int read.");
Reid Spencer060d25d2004-06-29 23:29:38 +00001461 Constant* Result = ConstantUInt::get(Ty, Val);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001462 if (Handler) Handler->handleConstantValue(Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001463 return Result;
1464 }
1465
1466 case Type::ULongTyID: {
1467 Constant* Result = ConstantUInt::get(Ty, read_vbr_uint64());
Reid Spencer04cde2c2004-07-04 11:33:49 +00001468 if (Handler) Handler->handleConstantValue(Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001469 return Result;
1470 }
1471
1472 case Type::SByteTyID: // Signed integer types...
1473 case Type::ShortTyID:
1474 case Type::IntTyID: {
1475 case Type::LongTyID:
1476 int64_t Val = read_vbr_int64();
Misha Brukman8a96c532005-04-21 21:44:41 +00001477 if (!ConstantSInt::isValueValidForType(Ty, Val))
Reid Spencer24399722004-07-09 22:21:33 +00001478 error("Invalid signed byte/short/int/long read.");
Reid Spencer060d25d2004-06-29 23:29:38 +00001479 Constant* Result = ConstantSInt::get(Ty, Val);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001480 if (Handler) Handler->handleConstantValue(Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001481 return Result;
1482 }
1483
1484 case Type::FloatTyID: {
Reid Spencer46b002c2004-07-11 17:28:43 +00001485 float Val;
1486 read_float(Val);
1487 Constant* Result = ConstantFP::get(Ty, Val);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001488 if (Handler) Handler->handleConstantValue(Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001489 return Result;
1490 }
1491
1492 case Type::DoubleTyID: {
1493 double Val;
Reid Spencer46b002c2004-07-11 17:28:43 +00001494 read_double(Val);
Reid Spencer060d25d2004-06-29 23:29:38 +00001495 Constant* Result = ConstantFP::get(Ty, Val);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001496 if (Handler) Handler->handleConstantValue(Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001497 return Result;
1498 }
1499
Reid Spencer060d25d2004-06-29 23:29:38 +00001500 case Type::ArrayTyID: {
1501 const ArrayType *AT = cast<ArrayType>(Ty);
1502 unsigned NumElements = AT->getNumElements();
1503 unsigned TypeSlot = getTypeSlot(AT->getElementType());
1504 std::vector<Constant*> Elements;
1505 Elements.reserve(NumElements);
1506 while (NumElements--) // Read all of the elements of the constant.
1507 Elements.push_back(getConstantValue(TypeSlot,
1508 read_vbr_uint()));
1509 Constant* Result = ConstantArray::get(AT, Elements);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001510 if (Handler) Handler->handleConstantArray(AT, Elements, TypeSlot, Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001511 return Result;
1512 }
1513
1514 case Type::StructTyID: {
1515 const StructType *ST = cast<StructType>(Ty);
1516
1517 std::vector<Constant *> Elements;
1518 Elements.reserve(ST->getNumElements());
1519 for (unsigned i = 0; i != ST->getNumElements(); ++i)
1520 Elements.push_back(getConstantValue(ST->getElementType(i),
1521 read_vbr_uint()));
1522
1523 Constant* Result = ConstantStruct::get(ST, Elements);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001524 if (Handler) Handler->handleConstantStruct(ST, Elements, Result);
Reid Spencer060d25d2004-06-29 23:29:38 +00001525 return Result;
Misha Brukman8a96c532005-04-21 21:44:41 +00001526 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001527
Brian Gaeke715c90b2004-08-20 06:00:58 +00001528 case Type::PackedTyID: {
1529 const PackedType *PT = cast<PackedType>(Ty);
1530 unsigned NumElements = PT->getNumElements();
1531 unsigned TypeSlot = getTypeSlot(PT->getElementType());
1532 std::vector<Constant*> Elements;
1533 Elements.reserve(NumElements);
1534 while (NumElements--) // Read all of the elements of the constant.
1535 Elements.push_back(getConstantValue(TypeSlot,
1536 read_vbr_uint()));
1537 Constant* Result = ConstantPacked::get(PT, Elements);
1538 if (Handler) Handler->handleConstantPacked(PT, Elements, TypeSlot, Result);
1539 return Result;
1540 }
1541
Chris Lattner638c3812004-11-19 16:24:05 +00001542 case Type::PointerTyID: { // ConstantPointerRef value (backwards compat).
Reid Spencer060d25d2004-06-29 23:29:38 +00001543 const PointerType *PT = cast<PointerType>(Ty);
1544 unsigned Slot = read_vbr_uint();
Misha Brukman8a96c532005-04-21 21:44:41 +00001545
Reid Spencer060d25d2004-06-29 23:29:38 +00001546 // Check to see if we have already read this global variable...
1547 Value *Val = getValue(TypeID, Slot, false);
Reid Spencer060d25d2004-06-29 23:29:38 +00001548 if (Val) {
Chris Lattnerbcb11cf2004-07-27 02:34:49 +00001549 GlobalValue *GV = dyn_cast<GlobalValue>(Val);
1550 if (!GV) error("GlobalValue not in ValueTable!");
1551 if (Handler) Handler->handleConstantPointer(PT, Slot, GV);
1552 return GV;
Reid Spencer060d25d2004-06-29 23:29:38 +00001553 } else {
Reid Spencer24399722004-07-09 22:21:33 +00001554 error("Forward references are not allowed here.");
Reid Spencer060d25d2004-06-29 23:29:38 +00001555 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001556 }
1557
1558 default:
Reid Spencer24399722004-07-09 22:21:33 +00001559 error("Don't know how to deserialize constant value of type '" +
Reid Spencer060d25d2004-06-29 23:29:38 +00001560 Ty->getDescription());
1561 break;
1562 }
Reid Spencer24399722004-07-09 22:21:33 +00001563 return 0;
Reid Spencer060d25d2004-06-29 23:29:38 +00001564}
1565
Misha Brukman8a96c532005-04-21 21:44:41 +00001566/// Resolve references for constants. This function resolves the forward
1567/// referenced constants in the ConstantFwdRefs map. It uses the
Reid Spencer04cde2c2004-07-04 11:33:49 +00001568/// replaceAllUsesWith method of Value class to substitute the placeholder
1569/// instance with the actual instance.
Chris Lattner389bd042004-12-09 06:19:44 +00001570void BytecodeReader::ResolveReferencesToConstant(Constant *NewV, unsigned Typ,
1571 unsigned Slot) {
Chris Lattner29b789b2003-11-19 17:27:18 +00001572 ConstantRefsType::iterator I =
Chris Lattner389bd042004-12-09 06:19:44 +00001573 ConstantFwdRefs.find(std::make_pair(Typ, Slot));
Chris Lattner29b789b2003-11-19 17:27:18 +00001574 if (I == ConstantFwdRefs.end()) return; // Never forward referenced?
Chris Lattner00950542001-06-06 20:29:01 +00001575
Chris Lattner29b789b2003-11-19 17:27:18 +00001576 Value *PH = I->second; // Get the placeholder...
1577 PH->replaceAllUsesWith(NewV);
1578 delete PH; // Delete the old placeholder
1579 ConstantFwdRefs.erase(I); // Remove the map entry for it
Vikram S. Advec1e4a812002-07-14 23:04:18 +00001580}
1581
Reid Spencer04cde2c2004-07-04 11:33:49 +00001582/// Parse the constant strings section.
Reid Spencer060d25d2004-06-29 23:29:38 +00001583void BytecodeReader::ParseStringConstants(unsigned NumEntries, ValueTable &Tab){
1584 for (; NumEntries; --NumEntries) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001585 unsigned Typ = 0;
Reid Spencer46b002c2004-07-11 17:28:43 +00001586 if (read_typeid(Typ))
Reid Spencer24399722004-07-09 22:21:33 +00001587 error("Invalid type (type type) for string constant");
Reid Spencer060d25d2004-06-29 23:29:38 +00001588 const Type *Ty = getType(Typ);
1589 if (!isa<ArrayType>(Ty))
Reid Spencer24399722004-07-09 22:21:33 +00001590 error("String constant data invalid!");
Misha Brukman8a96c532005-04-21 21:44:41 +00001591
Reid Spencer060d25d2004-06-29 23:29:38 +00001592 const ArrayType *ATy = cast<ArrayType>(Ty);
1593 if (ATy->getElementType() != Type::SByteTy &&
1594 ATy->getElementType() != Type::UByteTy)
Reid Spencer24399722004-07-09 22:21:33 +00001595 error("String constant data invalid!");
Misha Brukman8a96c532005-04-21 21:44:41 +00001596
Reid Spencer060d25d2004-06-29 23:29:38 +00001597 // Read character data. The type tells us how long the string is.
Misha Brukman8a96c532005-04-21 21:44:41 +00001598 char *Data = reinterpret_cast<char *>(alloca(ATy->getNumElements()));
Reid Spencer060d25d2004-06-29 23:29:38 +00001599 read_data(Data, Data+ATy->getNumElements());
Chris Lattner52e20b02003-03-19 20:54:26 +00001600
Reid Spencer060d25d2004-06-29 23:29:38 +00001601 std::vector<Constant*> Elements(ATy->getNumElements());
1602 if (ATy->getElementType() == Type::SByteTy)
1603 for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
1604 Elements[i] = ConstantSInt::get(Type::SByteTy, (signed char)Data[i]);
1605 else
1606 for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
1607 Elements[i] = ConstantUInt::get(Type::UByteTy, (unsigned char)Data[i]);
Misha Brukman12c29d12003-09-22 23:38:23 +00001608
Reid Spencer060d25d2004-06-29 23:29:38 +00001609 // Create the constant, inserting it as needed.
1610 Constant *C = ConstantArray::get(ATy, Elements);
1611 unsigned Slot = insertValue(C, Typ, Tab);
Chris Lattner389bd042004-12-09 06:19:44 +00001612 ResolveReferencesToConstant(C, Typ, Slot);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001613 if (Handler) Handler->handleConstantString(cast<ConstantArray>(C));
Reid Spencer060d25d2004-06-29 23:29:38 +00001614 }
Misha Brukman12c29d12003-09-22 23:38:23 +00001615}
1616
Reid Spencer04cde2c2004-07-04 11:33:49 +00001617/// Parse the constant pool.
Misha Brukman8a96c532005-04-21 21:44:41 +00001618void BytecodeReader::ParseConstantPool(ValueTable &Tab,
Reid Spencer04cde2c2004-07-04 11:33:49 +00001619 TypeListTy &TypeTab,
Reid Spencer46b002c2004-07-11 17:28:43 +00001620 bool isFunction) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001621 if (Handler) Handler->handleGlobalConstantsBegin();
1622
1623 /// In LLVM 1.3 Type does not derive from Value so the types
1624 /// do not occupy a plane. Consequently, we read the types
1625 /// first in the constant pool.
Reid Spencer46b002c2004-07-11 17:28:43 +00001626 if (isFunction && !hasTypeDerivedFromValue) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001627 unsigned NumEntries = read_vbr_uint();
Reid Spencer46b002c2004-07-11 17:28:43 +00001628 ParseTypes(TypeTab, NumEntries);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001629 }
1630
Reid Spencer46b002c2004-07-11 17:28:43 +00001631 while (moreInBlock()) {
Reid Spencer060d25d2004-06-29 23:29:38 +00001632 unsigned NumEntries = read_vbr_uint();
Reid Spencer04cde2c2004-07-04 11:33:49 +00001633 unsigned Typ = 0;
1634 bool isTypeType = read_typeid(Typ);
1635
1636 /// In LLVM 1.2 and before, Types were written to the
1637 /// bytecode file in the "Type Type" plane (#12).
1638 /// In 1.3 plane 12 is now the label plane. Handle this here.
Reid Spencer46b002c2004-07-11 17:28:43 +00001639 if (isTypeType) {
1640 ParseTypes(TypeTab, NumEntries);
Reid Spencer060d25d2004-06-29 23:29:38 +00001641 } else if (Typ == Type::VoidTyID) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001642 /// Use of Type::VoidTyID is a misnomer. It actually means
1643 /// that the following plane is constant strings
Reid Spencer060d25d2004-06-29 23:29:38 +00001644 assert(&Tab == &ModuleValues && "Cannot read strings in functions!");
1645 ParseStringConstants(NumEntries, Tab);
1646 } else {
1647 for (unsigned i = 0; i < NumEntries; ++i) {
1648 Constant *C = ParseConstantValue(Typ);
1649 assert(C && "ParseConstantValue returned NULL!");
1650 unsigned Slot = insertValue(C, Typ, Tab);
Chris Lattner29b789b2003-11-19 17:27:18 +00001651
Reid Spencer060d25d2004-06-29 23:29:38 +00001652 // If we are reading a function constant table, make sure that we adjust
1653 // the slot number to be the real global constant number.
1654 //
1655 if (&Tab != &ModuleValues && Typ < ModuleValues.size() &&
1656 ModuleValues[Typ])
1657 Slot += ModuleValues[Typ]->size();
Chris Lattner389bd042004-12-09 06:19:44 +00001658 ResolveReferencesToConstant(C, Typ, Slot);
Reid Spencer060d25d2004-06-29 23:29:38 +00001659 }
1660 }
1661 }
Chris Lattner02dce162004-12-04 05:28:27 +00001662
1663 // After we have finished parsing the constant pool, we had better not have
1664 // any dangling references left.
Reid Spencer3c391272004-12-04 22:19:53 +00001665 if (!ConstantFwdRefs.empty()) {
Reid Spencer3c391272004-12-04 22:19:53 +00001666 ConstantRefsType::const_iterator I = ConstantFwdRefs.begin();
Reid Spencer3c391272004-12-04 22:19:53 +00001667 Constant* missingConst = I->second;
Misha Brukman8a96c532005-04-21 21:44:41 +00001668 error(utostr(ConstantFwdRefs.size()) +
1669 " unresolved constant reference exist. First one is '" +
1670 missingConst->getName() + "' of type '" +
Chris Lattner389bd042004-12-09 06:19:44 +00001671 missingConst->getType()->getDescription() + "'.");
Reid Spencer3c391272004-12-04 22:19:53 +00001672 }
Chris Lattner02dce162004-12-04 05:28:27 +00001673
Reid Spencer060d25d2004-06-29 23:29:38 +00001674 checkPastBlockEnd("Constant Pool");
Reid Spencer04cde2c2004-07-04 11:33:49 +00001675 if (Handler) Handler->handleGlobalConstantsEnd();
Reid Spencer060d25d2004-06-29 23:29:38 +00001676}
Chris Lattner00950542001-06-06 20:29:01 +00001677
Reid Spencer04cde2c2004-07-04 11:33:49 +00001678/// Parse the contents of a function. Note that this function can be
1679/// called lazily by materializeFunction
1680/// @see materializeFunction
Reid Spencer46b002c2004-07-11 17:28:43 +00001681void BytecodeReader::ParseFunctionBody(Function* F) {
Reid Spencer060d25d2004-06-29 23:29:38 +00001682
1683 unsigned FuncSize = BlockEnd - At;
Chris Lattnere3869c82003-04-16 21:16:05 +00001684 GlobalValue::LinkageTypes Linkage = GlobalValue::ExternalLinkage;
1685
Reid Spencer060d25d2004-06-29 23:29:38 +00001686 unsigned LinkageType = read_vbr_uint();
Chris Lattnerc08912f2004-01-14 16:44:44 +00001687 switch (LinkageType) {
1688 case 0: Linkage = GlobalValue::ExternalLinkage; break;
1689 case 1: Linkage = GlobalValue::WeakLinkage; break;
1690 case 2: Linkage = GlobalValue::AppendingLinkage; break;
1691 case 3: Linkage = GlobalValue::InternalLinkage; break;
1692 case 4: Linkage = GlobalValue::LinkOnceLinkage; break;
Reid Spencer060d25d2004-06-29 23:29:38 +00001693 default:
Reid Spencer24399722004-07-09 22:21:33 +00001694 error("Invalid linkage type for Function.");
Reid Spencer060d25d2004-06-29 23:29:38 +00001695 Linkage = GlobalValue::InternalLinkage;
1696 break;
Chris Lattnere3869c82003-04-16 21:16:05 +00001697 }
Chris Lattnerd23b1d32001-11-26 18:56:10 +00001698
Reid Spencer46b002c2004-07-11 17:28:43 +00001699 F->setLinkage(Linkage);
Reid Spencer04cde2c2004-07-04 11:33:49 +00001700 if (Handler) Handler->handleFunctionBegin(F,FuncSize);
Chris Lattner00950542001-06-06 20:29:01 +00001701
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001702 // Keep track of how many basic blocks we have read in...
1703 unsigned BlockNum = 0;
Chris Lattner89e02532004-01-18 21:08:15 +00001704 bool InsertedArguments = false;
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001705
Reid Spencer060d25d2004-06-29 23:29:38 +00001706 BufPtr MyEnd = BlockEnd;
Reid Spencer46b002c2004-07-11 17:28:43 +00001707 while (At < MyEnd) {
Chris Lattner00950542001-06-06 20:29:01 +00001708 unsigned Type, Size;
Reid Spencer060d25d2004-06-29 23:29:38 +00001709 BufPtr OldAt = At;
1710 read_block(Type, Size);
Chris Lattner00950542001-06-06 20:29:01 +00001711
1712 switch (Type) {
Reid Spencerad89bd62004-07-25 18:07:36 +00001713 case BytecodeFormat::ConstantPoolBlockID:
Chris Lattner89e02532004-01-18 21:08:15 +00001714 if (!InsertedArguments) {
1715 // Insert arguments into the value table before we parse the first basic
1716 // block in the function, but after we potentially read in the
1717 // compaction table.
Reid Spencer04cde2c2004-07-04 11:33:49 +00001718 insertArguments(F);
Chris Lattner89e02532004-01-18 21:08:15 +00001719 InsertedArguments = true;
1720 }
1721
Reid Spencer04cde2c2004-07-04 11:33:49 +00001722 ParseConstantPool(FunctionValues, FunctionTypes, true);
Chris Lattner00950542001-06-06 20:29:01 +00001723 break;
1724
Reid Spencerad89bd62004-07-25 18:07:36 +00001725 case BytecodeFormat::CompactionTableBlockID:
Reid Spencer060d25d2004-06-29 23:29:38 +00001726 ParseCompactionTable();
Chris Lattner89e02532004-01-18 21:08:15 +00001727 break;
1728
Chris Lattner00950542001-06-06 20:29:01 +00001729 case BytecodeFormat::BasicBlock: {
Chris Lattner89e02532004-01-18 21:08:15 +00001730 if (!InsertedArguments) {
1731 // Insert arguments into the value table before we parse the first basic
1732 // block in the function, but after we potentially read in the
1733 // compaction table.
Reid Spencer04cde2c2004-07-04 11:33:49 +00001734 insertArguments(F);
Chris Lattner89e02532004-01-18 21:08:15 +00001735 InsertedArguments = true;
1736 }
1737
Reid Spencer060d25d2004-06-29 23:29:38 +00001738 BasicBlock *BB = ParseBasicBlock(BlockNum++);
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001739 F->getBasicBlockList().push_back(BB);
Chris Lattner00950542001-06-06 20:29:01 +00001740 break;
1741 }
1742
Reid Spencerad89bd62004-07-25 18:07:36 +00001743 case BytecodeFormat::InstructionListBlockID: {
Chris Lattner89e02532004-01-18 21:08:15 +00001744 // Insert arguments into the value table before we parse the instruction
1745 // list for the function, but after we potentially read in the compaction
1746 // table.
1747 if (!InsertedArguments) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001748 insertArguments(F);
Chris Lattner89e02532004-01-18 21:08:15 +00001749 InsertedArguments = true;
1750 }
1751
Misha Brukman8a96c532005-04-21 21:44:41 +00001752 if (BlockNum)
Reid Spencer24399722004-07-09 22:21:33 +00001753 error("Already parsed basic blocks!");
Reid Spencer060d25d2004-06-29 23:29:38 +00001754 BlockNum = ParseInstructionList(F);
Chris Lattner8d1dbd22003-12-01 07:05:31 +00001755 break;
1756 }
1757
Reid Spencerad89bd62004-07-25 18:07:36 +00001758 case BytecodeFormat::SymbolTableBlockID:
Reid Spencer060d25d2004-06-29 23:29:38 +00001759 ParseSymbolTable(F, &F->getSymbolTable());
Chris Lattner00950542001-06-06 20:29:01 +00001760 break;
1761
1762 default:
Reid Spencer060d25d2004-06-29 23:29:38 +00001763 At += Size;
Misha Brukman8a96c532005-04-21 21:44:41 +00001764 if (OldAt > At)
Reid Spencer24399722004-07-09 22:21:33 +00001765 error("Wrapped around reading bytecode.");
Chris Lattner00950542001-06-06 20:29:01 +00001766 break;
1767 }
Reid Spencer060d25d2004-06-29 23:29:38 +00001768 BlockEnd = MyEnd;
Chris Lattner1d670cc2001-09-07 16:37:43 +00001769
Misha Brukman12c29d12003-09-22 23:38:23 +00001770 // Malformed bc file if read past end of block.
Reid Spencer060d25d2004-06-29 23:29:38 +00001771 align32();
Chris Lattner00950542001-06-06 20:29:01 +00001772 }
1773
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001774 // Make sure there were no references to non-existant basic blocks.
1775 if (BlockNum != ParsedBasicBlocks.size())
Reid Spencer24399722004-07-09 22:21:33 +00001776 error("Illegal basic block operand reference");
Reid Spencer060d25d2004-06-29 23:29:38 +00001777
Chris Lattner4ee8ef22003-10-08 22:52:54 +00001778 ParsedBasicBlocks.clear();
1779
Chris Lattner97330cf2003-10-09 23:10:14 +00001780 // Resolve forward references. Replace any uses of a forward reference value
1781 // with the real value.
Chris Lattner8eb10ce2003-10-09 06:05:40 +00001782 while (!ForwardReferences.empty()) {
Chris Lattnerc4d69162004-12-09 04:51:50 +00001783 std::map<std::pair<unsigned,unsigned>, Value*>::iterator
1784 I = ForwardReferences.begin();
1785 Value *V = getValue(I->first.first, I->first.second, false);
Chris Lattner8eb10ce2003-10-09 06:05:40 +00001786 Value *PlaceHolder = I->second;
Chris Lattnerc4d69162004-12-09 04:51:50 +00001787 PlaceHolder->replaceAllUsesWith(V);
Chris Lattner8eb10ce2003-10-09 06:05:40 +00001788 ForwardReferences.erase(I);
Chris Lattner8eb10ce2003-10-09 06:05:40 +00001789 delete PlaceHolder;
Chris Lattner6e448022003-10-08 21:51:46 +00001790 }
Chris Lattner00950542001-06-06 20:29:01 +00001791
Misha Brukman12c29d12003-09-22 23:38:23 +00001792 // Clear out function-level types...
Reid Spencer060d25d2004-06-29 23:29:38 +00001793 FunctionTypes.clear();
1794 CompactionTypes.clear();
1795 CompactionValues.clear();
1796 freeTable(FunctionValues);
1797
Reid Spencer04cde2c2004-07-04 11:33:49 +00001798 if (Handler) Handler->handleFunctionEnd(F);
Chris Lattner00950542001-06-06 20:29:01 +00001799}
1800
Reid Spencer04cde2c2004-07-04 11:33:49 +00001801/// This function parses LLVM functions lazily. It obtains the type of the
1802/// function and records where the body of the function is in the bytecode
Misha Brukman8a96c532005-04-21 21:44:41 +00001803/// buffer. The caller can then use the ParseNextFunction and
Reid Spencer04cde2c2004-07-04 11:33:49 +00001804/// ParseAllFunctionBodies to get handler events for the functions.
Reid Spencer060d25d2004-06-29 23:29:38 +00001805void BytecodeReader::ParseFunctionLazily() {
1806 if (FunctionSignatureList.empty())
Reid Spencer24399722004-07-09 22:21:33 +00001807 error("FunctionSignatureList empty!");
Chris Lattner89e02532004-01-18 21:08:15 +00001808
Reid Spencer060d25d2004-06-29 23:29:38 +00001809 Function *Func = FunctionSignatureList.back();
1810 FunctionSignatureList.pop_back();
Chris Lattner24102432004-01-18 22:35:34 +00001811
Reid Spencer060d25d2004-06-29 23:29:38 +00001812 // Save the information for future reading of the function
1813 LazyFunctionLoadMap[Func] = LazyFunctionInfo(BlockStart, BlockEnd);
Chris Lattner89e02532004-01-18 21:08:15 +00001814
Misha Brukmana3e6ad62004-11-14 21:02:55 +00001815 // This function has a body but it's not loaded so it appears `External'.
1816 // Mark it as a `Ghost' instead to notify the users that it has a body.
1817 Func->setLinkage(GlobalValue::GhostLinkage);
1818
Reid Spencer060d25d2004-06-29 23:29:38 +00001819 // Pretend we've `parsed' this function
1820 At = BlockEnd;
1821}
Chris Lattner89e02532004-01-18 21:08:15 +00001822
Misha Brukman8a96c532005-04-21 21:44:41 +00001823/// The ParserFunction method lazily parses one function. Use this method to
1824/// casue the parser to parse a specific function in the module. Note that
1825/// this will remove the function from what is to be included by
Reid Spencer04cde2c2004-07-04 11:33:49 +00001826/// ParseAllFunctionBodies.
1827/// @see ParseAllFunctionBodies
1828/// @see ParseBytecode
Reid Spencer060d25d2004-06-29 23:29:38 +00001829void BytecodeReader::ParseFunction(Function* Func) {
1830 // Find {start, end} pointers and slot in the map. If not there, we're done.
1831 LazyFunctionMap::iterator Fi = LazyFunctionLoadMap.find(Func);
Chris Lattner89e02532004-01-18 21:08:15 +00001832
Reid Spencer060d25d2004-06-29 23:29:38 +00001833 // Make sure we found it
Reid Spencer46b002c2004-07-11 17:28:43 +00001834 if (Fi == LazyFunctionLoadMap.end()) {
Reid Spencer24399722004-07-09 22:21:33 +00001835 error("Unrecognized function of type " + Func->getType()->getDescription());
Reid Spencer060d25d2004-06-29 23:29:38 +00001836 return;
Chris Lattner89e02532004-01-18 21:08:15 +00001837 }
1838
Reid Spencer060d25d2004-06-29 23:29:38 +00001839 BlockStart = At = Fi->second.Buf;
1840 BlockEnd = Fi->second.EndBuf;
Reid Spencer24399722004-07-09 22:21:33 +00001841 assert(Fi->first == Func && "Found wrong function?");
Reid Spencer060d25d2004-06-29 23:29:38 +00001842
1843 LazyFunctionLoadMap.erase(Fi);
1844
Reid Spencer46b002c2004-07-11 17:28:43 +00001845 this->ParseFunctionBody(Func);
Chris Lattner89e02532004-01-18 21:08:15 +00001846}
1847
Reid Spencer04cde2c2004-07-04 11:33:49 +00001848/// The ParseAllFunctionBodies method parses through all the previously
1849/// unparsed functions in the bytecode file. If you want to completely parse
1850/// a bytecode file, this method should be called after Parsebytecode because
1851/// Parsebytecode only records the locations in the bytecode file of where
1852/// the function definitions are located. This function uses that information
1853/// to materialize the functions.
1854/// @see ParseBytecode
Reid Spencer060d25d2004-06-29 23:29:38 +00001855void BytecodeReader::ParseAllFunctionBodies() {
1856 LazyFunctionMap::iterator Fi = LazyFunctionLoadMap.begin();
1857 LazyFunctionMap::iterator Fe = LazyFunctionLoadMap.end();
Chris Lattner89e02532004-01-18 21:08:15 +00001858
Reid Spencer46b002c2004-07-11 17:28:43 +00001859 while (Fi != Fe) {
Reid Spencer060d25d2004-06-29 23:29:38 +00001860 Function* Func = Fi->first;
1861 BlockStart = At = Fi->second.Buf;
1862 BlockEnd = Fi->second.EndBuf;
Chris Lattnerb52f1c22005-02-13 17:48:18 +00001863 ParseFunctionBody(Func);
Reid Spencer060d25d2004-06-29 23:29:38 +00001864 ++Fi;
1865 }
Chris Lattnerb52f1c22005-02-13 17:48:18 +00001866 LazyFunctionLoadMap.clear();
Reid Spencer060d25d2004-06-29 23:29:38 +00001867}
Chris Lattner89e02532004-01-18 21:08:15 +00001868
Reid Spencer04cde2c2004-07-04 11:33:49 +00001869/// Parse the global type list
Reid Spencer060d25d2004-06-29 23:29:38 +00001870void BytecodeReader::ParseGlobalTypes() {
Reid Spencer04cde2c2004-07-04 11:33:49 +00001871 // Read the number of types
1872 unsigned NumEntries = read_vbr_uint();
Reid Spencer011bed52004-07-09 21:13:53 +00001873
1874 // Ignore the type plane identifier for types if the bc file is pre 1.3
1875 if (hasTypeDerivedFromValue)
1876 read_vbr_uint();
1877
Reid Spencer46b002c2004-07-11 17:28:43 +00001878 ParseTypes(ModuleTypes, NumEntries);
Reid Spencer060d25d2004-06-29 23:29:38 +00001879}
1880
Reid Spencer04cde2c2004-07-04 11:33:49 +00001881/// Parse the Global info (types, global vars, constants)
Reid Spencer060d25d2004-06-29 23:29:38 +00001882void BytecodeReader::ParseModuleGlobalInfo() {
1883
Reid Spencer04cde2c2004-07-04 11:33:49 +00001884 if (Handler) Handler->handleModuleGlobalsBegin();
Chris Lattner00950542001-06-06 20:29:01 +00001885
Chris Lattner70cc3392001-09-10 07:58:01 +00001886 // Read global variables...
Reid Spencer060d25d2004-06-29 23:29:38 +00001887 unsigned VarType = read_vbr_uint();
Chris Lattner70cc3392001-09-10 07:58:01 +00001888 while (VarType != Type::VoidTyID) { // List is terminated by Void
Chris Lattner9dd87702004-04-03 23:43:42 +00001889 // VarType Fields: bit0 = isConstant, bit1 = hasInitializer, bit2,3,4 =
1890 // Linkage, bit4+ = slot#
1891 unsigned SlotNo = VarType >> 5;
Reid Spencer46b002c2004-07-11 17:28:43 +00001892 if (sanitizeTypeId(SlotNo))
Reid Spencer24399722004-07-09 22:21:33 +00001893 error("Invalid type (type type) for global var!");
Chris Lattner9dd87702004-04-03 23:43:42 +00001894 unsigned LinkageID = (VarType >> 2) & 7;
Reid Spencer060d25d2004-06-29 23:29:38 +00001895 bool isConstant = VarType & 1;
1896 bool hasInitializer = VarType & 2;
Chris Lattnere3869c82003-04-16 21:16:05 +00001897 GlobalValue::LinkageTypes Linkage;
1898
Chris Lattnerc08912f2004-01-14 16:44:44 +00001899 switch (LinkageID) {
Chris Lattnerc08912f2004-01-14 16:44:44 +00001900 case 0: Linkage = GlobalValue::ExternalLinkage; break;
1901 case 1: Linkage = GlobalValue::WeakLinkage; break;
1902 case 2: Linkage = GlobalValue::AppendingLinkage; break;
1903 case 3: Linkage = GlobalValue::InternalLinkage; break;
1904 case 4: Linkage = GlobalValue::LinkOnceLinkage; break;
Misha Brukman8a96c532005-04-21 21:44:41 +00001905 default:
Reid Spencer24399722004-07-09 22:21:33 +00001906 error("Unknown linkage type: " + utostr(LinkageID));
Reid Spencer060d25d2004-06-29 23:29:38 +00001907 Linkage = GlobalValue::InternalLinkage;
1908 break;
Chris Lattnere3869c82003-04-16 21:16:05 +00001909 }
1910
1911 const Type *Ty = getType(SlotNo);
Reid Spencer46b002c2004-07-11 17:28:43 +00001912 if (!Ty) {
Reid Spencer24399722004-07-09 22:21:33 +00001913 error("Global has no type! SlotNo=" + utostr(SlotNo));
Reid Spencer060d25d2004-06-29 23:29:38 +00001914 }
1915
Reid Spencer46b002c2004-07-11 17:28:43 +00001916 if (!isa<PointerType>(Ty)) {
Reid Spencer24399722004-07-09 22:21:33 +00001917 error("Global not a pointer type! Ty= " + Ty->getDescription());
Reid Spencer060d25d2004-06-29 23:29:38 +00001918 }
Chris Lattner70cc3392001-09-10 07:58:01 +00001919
Chris Lattner52e20b02003-03-19 20:54:26 +00001920 const Type *ElTy = cast<PointerType>(Ty)->getElementType();
Chris Lattnerd70684f2001-09-18 04:01:05 +00001921
Chris Lattner70cc3392001-09-10 07:58:01 +00001922 // Create the global variable...
Reid Spencer060d25d2004-06-29 23:29:38 +00001923 GlobalVariable *GV = new GlobalVariable(ElTy, isConstant, Linkage,
Chris Lattner52e20b02003-03-19 20:54:26 +00001924 0, "", TheModule);
Chris Lattner29b789b2003-11-19 17:27:18 +00001925 insertValue(GV, SlotNo, ModuleValues);
Chris Lattner05950c32001-10-13 06:47:01 +00001926
Reid Spencer060d25d2004-06-29 23:29:38 +00001927 unsigned initSlot = 0;
Misha Brukman8a96c532005-04-21 21:44:41 +00001928 if (hasInitializer) {
Reid Spencer060d25d2004-06-29 23:29:38 +00001929 initSlot = read_vbr_uint();
1930 GlobalInits.push_back(std::make_pair(GV, initSlot));
1931 }
1932
1933 // Notify handler about the global value.
Chris Lattner4a242b32004-10-14 01:39:18 +00001934 if (Handler)
1935 Handler->handleGlobalVariable(ElTy, isConstant, Linkage, SlotNo,initSlot);
Reid Spencer060d25d2004-06-29 23:29:38 +00001936
1937 // Get next item
1938 VarType = read_vbr_uint();
Chris Lattner70cc3392001-09-10 07:58:01 +00001939 }
1940
Chris Lattner52e20b02003-03-19 20:54:26 +00001941 // Read the function objects for all of the functions that are coming
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001942 unsigned FnSignature = read_vbr_uint();
Reid Spencer24399722004-07-09 22:21:33 +00001943
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001944 if (hasNoFlagsForFunctions)
1945 FnSignature = (FnSignature << 5) + 1;
1946
1947 // List is terminated by VoidTy.
1948 while ((FnSignature >> 5) != Type::VoidTyID) {
1949 const Type *Ty = getType(FnSignature >> 5);
Chris Lattner927b1852003-10-09 20:22:47 +00001950 if (!isa<PointerType>(Ty) ||
Reid Spencer060d25d2004-06-29 23:29:38 +00001951 !isa<FunctionType>(cast<PointerType>(Ty)->getElementType())) {
Misha Brukman8a96c532005-04-21 21:44:41 +00001952 error("Function not a pointer to function type! Ty = " +
Reid Spencer46b002c2004-07-11 17:28:43 +00001953 Ty->getDescription());
Reid Spencer060d25d2004-06-29 23:29:38 +00001954 }
Chris Lattner8cdc6b72002-10-23 00:51:54 +00001955
Chris Lattner2a7b6ba2003-03-06 17:15:19 +00001956 // We create functions by passing the underlying FunctionType to create...
Misha Brukman8a96c532005-04-21 21:44:41 +00001957 const FunctionType* FTy =
Reid Spencer060d25d2004-06-29 23:29:38 +00001958 cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
Chris Lattner00950542001-06-06 20:29:01 +00001959
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001960
Chris Lattner18549c22004-11-15 21:43:03 +00001961 // Insert the place holder.
Misha Brukman8a96c532005-04-21 21:44:41 +00001962 Function* Func = new Function(FTy, GlobalValue::ExternalLinkage,
Reid Spencer04cde2c2004-07-04 11:33:49 +00001963 "", TheModule);
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001964 insertValue(Func, FnSignature >> 5, ModuleValues);
1965
1966 // Flags are not used yet.
Chris Lattner97fbc502004-11-15 22:38:52 +00001967 unsigned Flags = FnSignature & 31;
Chris Lattner00950542001-06-06 20:29:01 +00001968
Chris Lattner97fbc502004-11-15 22:38:52 +00001969 // Save this for later so we know type of lazily instantiated functions.
1970 // Note that known-external functions do not have FunctionInfo blocks, so we
1971 // do not add them to the FunctionSignatureList.
1972 if ((Flags & (1 << 4)) == 0)
1973 FunctionSignatureList.push_back(Func);
Chris Lattner52e20b02003-03-19 20:54:26 +00001974
Chris Lattner479ffeb2005-05-06 20:42:57 +00001975 // Look at the low bits. If there is a calling conv here, apply it,
1976 // read it as a vbr.
1977 Flags &= 15;
1978 if (Flags)
1979 Func->setCallingConv(Flags-1);
1980 else
1981 Func->setCallingConv(read_vbr_uint());
1982
Reid Spencer04cde2c2004-07-04 11:33:49 +00001983 if (Handler) Handler->handleFunctionDeclaration(Func);
Reid Spencer060d25d2004-06-29 23:29:38 +00001984
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001985 // Get the next function signature.
1986 FnSignature = read_vbr_uint();
1987 if (hasNoFlagsForFunctions)
1988 FnSignature = (FnSignature << 5) + 1;
Chris Lattner00950542001-06-06 20:29:01 +00001989 }
1990
Misha Brukman8a96c532005-04-21 21:44:41 +00001991 // Now that the function signature list is set up, reverse it so that we can
Chris Lattner74734132002-08-17 22:01:27 +00001992 // remove elements efficiently from the back of the vector.
1993 std::reverse(FunctionSignatureList.begin(), FunctionSignatureList.end());
Chris Lattner00950542001-06-06 20:29:01 +00001994
Reid Spencerad89bd62004-07-25 18:07:36 +00001995 // If this bytecode format has dependent library information in it ..
1996 if (!hasNoDependentLibraries) {
1997 // Read in the number of dependent library items that follow
1998 unsigned num_dep_libs = read_vbr_uint();
1999 std::string dep_lib;
2000 while( num_dep_libs-- ) {
2001 dep_lib = read_str();
Reid Spencerada16182004-07-25 21:36:26 +00002002 TheModule->addLibrary(dep_lib);
Reid Spencer5b472d92004-08-21 20:49:23 +00002003 if (Handler)
2004 Handler->handleDependentLibrary(dep_lib);
Reid Spencerad89bd62004-07-25 18:07:36 +00002005 }
2006
Reid Spencer5b472d92004-08-21 20:49:23 +00002007
Reid Spencerad89bd62004-07-25 18:07:36 +00002008 // Read target triple and place into the module
2009 std::string triple = read_str();
2010 TheModule->setTargetTriple(triple);
Reid Spencer5b472d92004-08-21 20:49:23 +00002011 if (Handler)
2012 Handler->handleTargetTriple(triple);
Reid Spencerad89bd62004-07-25 18:07:36 +00002013 }
2014
2015 if (hasInconsistentModuleGlobalInfo)
2016 align32();
2017
Chris Lattner00950542001-06-06 20:29:01 +00002018 // This is for future proofing... in the future extra fields may be added that
2019 // we don't understand, so we transparently ignore them.
2020 //
Reid Spencer060d25d2004-06-29 23:29:38 +00002021 At = BlockEnd;
2022
Reid Spencer04cde2c2004-07-04 11:33:49 +00002023 if (Handler) Handler->handleModuleGlobalsEnd();
Chris Lattner00950542001-06-06 20:29:01 +00002024}
2025
Reid Spencer04cde2c2004-07-04 11:33:49 +00002026/// Parse the version information and decode it by setting flags on the
2027/// Reader that enable backward compatibility of the reader.
Reid Spencer060d25d2004-06-29 23:29:38 +00002028void BytecodeReader::ParseVersionInfo() {
2029 unsigned Version = read_vbr_uint();
Chris Lattner036b8aa2003-03-06 17:55:45 +00002030
2031 // Unpack version number: low four bits are for flags, top bits = version
Chris Lattnerd445c6b2003-08-24 13:47:36 +00002032 Module::Endianness Endianness;
2033 Module::PointerSize PointerSize;
2034 Endianness = (Version & 1) ? Module::BigEndian : Module::LittleEndian;
2035 PointerSize = (Version & 2) ? Module::Pointer64 : Module::Pointer32;
2036
2037 bool hasNoEndianness = Version & 4;
2038 bool hasNoPointerSize = Version & 8;
Misha Brukman8a96c532005-04-21 21:44:41 +00002039
Chris Lattnerd445c6b2003-08-24 13:47:36 +00002040 RevisionNum = Version >> 4;
Chris Lattnere3869c82003-04-16 21:16:05 +00002041
2042 // Default values for the current bytecode version
Chris Lattner44d0eeb2004-01-15 17:55:01 +00002043 hasInconsistentModuleGlobalInfo = false;
Chris Lattner80b97342004-01-17 23:25:43 +00002044 hasExplicitPrimitiveZeros = false;
Chris Lattner5fa428f2004-04-05 01:27:26 +00002045 hasRestrictedGEPTypes = false;
Reid Spencer04cde2c2004-07-04 11:33:49 +00002046 hasTypeDerivedFromValue = false;
Reid Spencerad89bd62004-07-25 18:07:36 +00002047 hasLongBlockHeaders = false;
Reid Spencerad89bd62004-07-25 18:07:36 +00002048 has32BitTypes = false;
2049 hasNoDependentLibraries = false;
Reid Spencer38d54be2004-08-17 07:45:14 +00002050 hasAlignment = false;
Chris Lattnera79e7cc2004-10-16 18:18:16 +00002051 hasNoUndefValue = false;
2052 hasNoFlagsForFunctions = false;
2053 hasNoUnreachableInst = false;
Chris Lattner036b8aa2003-03-06 17:55:45 +00002054
2055 switch (RevisionNum) {
Reid Spencer5b472d92004-08-21 20:49:23 +00002056 case 0: // LLVM 1.0, 1.1 (Released)
Chris Lattner9e893e82004-01-14 23:35:21 +00002057 // Base LLVM 1.0 bytecode format.
Chris Lattner44d0eeb2004-01-15 17:55:01 +00002058 hasInconsistentModuleGlobalInfo = true;
Chris Lattner80b97342004-01-17 23:25:43 +00002059 hasExplicitPrimitiveZeros = true;
Reid Spencer04cde2c2004-07-04 11:33:49 +00002060
Chris Lattner80b97342004-01-17 23:25:43 +00002061 // FALL THROUGH
Reid Spencer5b472d92004-08-21 20:49:23 +00002062
2063 case 1: // LLVM 1.2 (Released)
Chris Lattner9e893e82004-01-14 23:35:21 +00002064 // LLVM 1.2 added explicit support for emitting strings efficiently.
Chris Lattner44d0eeb2004-01-15 17:55:01 +00002065
2066 // Also, it fixed the problem where the size of the ModuleGlobalInfo block
2067 // included the size for the alignment at the end, where the rest of the
2068 // blocks did not.
Chris Lattner5fa428f2004-04-05 01:27:26 +00002069
2070 // LLVM 1.2 and before required that GEP indices be ubyte constants for
2071 // structures and longs for sequential types.
2072 hasRestrictedGEPTypes = true;
2073
Reid Spencer04cde2c2004-07-04 11:33:49 +00002074 // LLVM 1.2 and before had the Type class derive from Value class. This
2075 // changed in release 1.3 and consequently LLVM 1.3 bytecode files are
Misha Brukman8a96c532005-04-21 21:44:41 +00002076 // written differently because Types can no longer be part of the
Reid Spencer04cde2c2004-07-04 11:33:49 +00002077 // type planes for Values.
2078 hasTypeDerivedFromValue = true;
2079
Chris Lattner5fa428f2004-04-05 01:27:26 +00002080 // FALL THROUGH
Misha Brukman8a96c532005-04-21 21:44:41 +00002081
Reid Spencer5b472d92004-08-21 20:49:23 +00002082 case 2: // 1.2.5 (Not Released)
Reid Spencerad89bd62004-07-25 18:07:36 +00002083
Reid Spencer5b472d92004-08-21 20:49:23 +00002084 // LLVM 1.2 and earlier had two-word block headers. This is a bit wasteful,
Chris Lattner4a242b32004-10-14 01:39:18 +00002085 // especially for small files where the 8 bytes per block is a large
2086 // fraction of the total block size. In LLVM 1.3, the block type and length
2087 // are compressed into a single 32-bit unsigned integer. 27 bits for length,
2088 // 5 bits for block type.
Reid Spencerad89bd62004-07-25 18:07:36 +00002089 hasLongBlockHeaders = true;
2090
Reid Spencer5b472d92004-08-21 20:49:23 +00002091 // LLVM 1.2 and earlier wrote type slot numbers as vbr_uint32. In LLVM 1.3
Chris Lattner4a242b32004-10-14 01:39:18 +00002092 // this has been reduced to vbr_uint24. It shouldn't make much difference
2093 // since we haven't run into a module with > 24 million types, but for
2094 // safety the 24-bit restriction has been enforced in 1.3 to free some bits
2095 // in various places and to ensure consistency.
Reid Spencerad89bd62004-07-25 18:07:36 +00002096 has32BitTypes = true;
2097
Misha Brukman8a96c532005-04-21 21:44:41 +00002098 // LLVM 1.2 and earlier did not provide a target triple nor a list of
Reid Spencer5b472d92004-08-21 20:49:23 +00002099 // libraries on which the bytecode is dependent. LLVM 1.3 provides these
2100 // features, for use in future versions of LLVM.
Reid Spencerad89bd62004-07-25 18:07:36 +00002101 hasNoDependentLibraries = true;
2102
2103 // FALL THROUGH
Reid Spencer5b472d92004-08-21 20:49:23 +00002104
2105 case 3: // LLVM 1.3 (Released)
2106 // LLVM 1.3 and earlier caused alignment bytes to be written on some block
Misha Brukman8a96c532005-04-21 21:44:41 +00002107 // boundaries and at the end of some strings. In extreme cases (e.g. lots
Reid Spencer5b472d92004-08-21 20:49:23 +00002108 // of GEP references to a constant array), this can increase the file size
2109 // by 30% or more. In version 1.4 alignment is done away with completely.
Reid Spencer38d54be2004-08-17 07:45:14 +00002110 hasAlignment = true;
2111
2112 // FALL THROUGH
Misha Brukman8a96c532005-04-21 21:44:41 +00002113
Reid Spencer5b472d92004-08-21 20:49:23 +00002114 case 4: // 1.3.1 (Not Released)
Chris Lattnera79e7cc2004-10-16 18:18:16 +00002115 // In version 4, we did not support the 'undef' constant.
2116 hasNoUndefValue = true;
2117
2118 // In version 4 and above, we did not include space for flags for functions
2119 // in the module info block.
2120 hasNoFlagsForFunctions = true;
2121
2122 // In version 4 and above, we did not include the 'unreachable' instruction
2123 // in the opcode numbering in the bytecode file.
2124 hasNoUnreachableInst = true;
Chris Lattner2e7ec122004-10-16 18:56:02 +00002125 break;
Chris Lattnera79e7cc2004-10-16 18:18:16 +00002126
2127 // FALL THROUGH
2128
Chris Lattnerdee199f2005-05-06 22:34:01 +00002129 case 5: // 1.4 (Released)
Chris Lattnera79e7cc2004-10-16 18:18:16 +00002130 break;
2131
Chris Lattner036b8aa2003-03-06 17:55:45 +00002132 default:
Reid Spencer24399722004-07-09 22:21:33 +00002133 error("Unknown bytecode version number: " + itostr(RevisionNum));
Chris Lattner036b8aa2003-03-06 17:55:45 +00002134 }
2135
Chris Lattnerd445c6b2003-08-24 13:47:36 +00002136 if (hasNoEndianness) Endianness = Module::AnyEndianness;
2137 if (hasNoPointerSize) PointerSize = Module::AnyPointerSize;
Chris Lattner76e38962003-04-22 18:15:10 +00002138
Brian Gaekefe2102b2004-07-14 20:33:13 +00002139 TheModule->setEndianness(Endianness);
2140 TheModule->setPointerSize(PointerSize);
2141
Reid Spencer46b002c2004-07-11 17:28:43 +00002142 if (Handler) Handler->handleVersionInfo(RevisionNum, Endianness, PointerSize);
Chris Lattner036b8aa2003-03-06 17:55:45 +00002143}
2144
Reid Spencer04cde2c2004-07-04 11:33:49 +00002145/// Parse a whole module.
Reid Spencer060d25d2004-06-29 23:29:38 +00002146void BytecodeReader::ParseModule() {
Chris Lattner00950542001-06-06 20:29:01 +00002147 unsigned Type, Size;
Chris Lattner00950542001-06-06 20:29:01 +00002148
Reid Spencer060d25d2004-06-29 23:29:38 +00002149 FunctionSignatureList.clear(); // Just in case...
Chris Lattner00950542001-06-06 20:29:01 +00002150
2151 // Read into instance variables...
Reid Spencer060d25d2004-06-29 23:29:38 +00002152 ParseVersionInfo();
Reid Spencerad89bd62004-07-25 18:07:36 +00002153 align32();
Chris Lattner00950542001-06-06 20:29:01 +00002154
Reid Spencer060d25d2004-06-29 23:29:38 +00002155 bool SeenModuleGlobalInfo = false;
2156 bool SeenGlobalTypePlane = false;
2157 BufPtr MyEnd = BlockEnd;
2158 while (At < MyEnd) {
2159 BufPtr OldAt = At;
2160 read_block(Type, Size);
2161
Chris Lattner00950542001-06-06 20:29:01 +00002162 switch (Type) {
Reid Spencer060d25d2004-06-29 23:29:38 +00002163
Reid Spencerad89bd62004-07-25 18:07:36 +00002164 case BytecodeFormat::GlobalTypePlaneBlockID:
Reid Spencer46b002c2004-07-11 17:28:43 +00002165 if (SeenGlobalTypePlane)
Reid Spencer24399722004-07-09 22:21:33 +00002166 error("Two GlobalTypePlane Blocks Encountered!");
Reid Spencer060d25d2004-06-29 23:29:38 +00002167
Reid Spencer5b472d92004-08-21 20:49:23 +00002168 if (Size > 0)
2169 ParseGlobalTypes();
Reid Spencer060d25d2004-06-29 23:29:38 +00002170 SeenGlobalTypePlane = true;
Chris Lattner52e20b02003-03-19 20:54:26 +00002171 break;
2172
Misha Brukman8a96c532005-04-21 21:44:41 +00002173 case BytecodeFormat::ModuleGlobalInfoBlockID:
Reid Spencer46b002c2004-07-11 17:28:43 +00002174 if (SeenModuleGlobalInfo)
Reid Spencer24399722004-07-09 22:21:33 +00002175 error("Two ModuleGlobalInfo Blocks Encountered!");
Reid Spencer060d25d2004-06-29 23:29:38 +00002176 ParseModuleGlobalInfo();
2177 SeenModuleGlobalInfo = true;
Chris Lattner52e20b02003-03-19 20:54:26 +00002178 break;
2179
Reid Spencerad89bd62004-07-25 18:07:36 +00002180 case BytecodeFormat::ConstantPoolBlockID:
Reid Spencer04cde2c2004-07-04 11:33:49 +00002181 ParseConstantPool(ModuleValues, ModuleTypes,false);
Chris Lattner00950542001-06-06 20:29:01 +00002182 break;
2183
Reid Spencerad89bd62004-07-25 18:07:36 +00002184 case BytecodeFormat::FunctionBlockID:
Reid Spencer060d25d2004-06-29 23:29:38 +00002185 ParseFunctionLazily();
Chris Lattner00950542001-06-06 20:29:01 +00002186 break;
Chris Lattner00950542001-06-06 20:29:01 +00002187
Reid Spencerad89bd62004-07-25 18:07:36 +00002188 case BytecodeFormat::SymbolTableBlockID:
Reid Spencer060d25d2004-06-29 23:29:38 +00002189 ParseSymbolTable(0, &TheModule->getSymbolTable());
Chris Lattner00950542001-06-06 20:29:01 +00002190 break;
Reid Spencer060d25d2004-06-29 23:29:38 +00002191
Chris Lattner00950542001-06-06 20:29:01 +00002192 default:
Reid Spencer060d25d2004-06-29 23:29:38 +00002193 At += Size;
2194 if (OldAt > At) {
Reid Spencer46b002c2004-07-11 17:28:43 +00002195 error("Unexpected Block of Type #" + utostr(Type) + " encountered!");
Reid Spencer060d25d2004-06-29 23:29:38 +00002196 }
Chris Lattner00950542001-06-06 20:29:01 +00002197 break;
2198 }
Reid Spencer060d25d2004-06-29 23:29:38 +00002199 BlockEnd = MyEnd;
2200 align32();
Chris Lattner00950542001-06-06 20:29:01 +00002201 }
2202
Chris Lattner52e20b02003-03-19 20:54:26 +00002203 // After the module constant pool has been read, we can safely initialize
2204 // global variables...
2205 while (!GlobalInits.empty()) {
2206 GlobalVariable *GV = GlobalInits.back().first;
2207 unsigned Slot = GlobalInits.back().second;
2208 GlobalInits.pop_back();
2209
2210 // Look up the initializer value...
Chris Lattner29b789b2003-11-19 17:27:18 +00002211 // FIXME: Preserve this type ID!
Reid Spencer060d25d2004-06-29 23:29:38 +00002212
2213 const llvm::PointerType* GVType = GV->getType();
2214 unsigned TypeSlot = getTypeSlot(GVType->getElementType());
Chris Lattner93361992004-01-15 18:45:25 +00002215 if (Constant *CV = getConstantValue(TypeSlot, Slot)) {
Misha Brukman8a96c532005-04-21 21:44:41 +00002216 if (GV->hasInitializer())
Reid Spencer24399722004-07-09 22:21:33 +00002217 error("Global *already* has an initializer?!");
Reid Spencer04cde2c2004-07-04 11:33:49 +00002218 if (Handler) Handler->handleGlobalInitializer(GV,CV);
Chris Lattner93361992004-01-15 18:45:25 +00002219 GV->setInitializer(CV);
Chris Lattner52e20b02003-03-19 20:54:26 +00002220 } else
Reid Spencer24399722004-07-09 22:21:33 +00002221 error("Cannot find initializer value.");
Chris Lattner52e20b02003-03-19 20:54:26 +00002222 }
2223
Chris Lattneraba5ff52005-05-05 20:57:00 +00002224 if (!ConstantFwdRefs.empty())
2225 error("Use of undefined constants in a module");
2226
Reid Spencer060d25d2004-06-29 23:29:38 +00002227 /// Make sure we pulled them all out. If we didn't then there's a declaration
2228 /// but a missing body. That's not allowed.
Misha Brukman12c29d12003-09-22 23:38:23 +00002229 if (!FunctionSignatureList.empty())
Reid Spencer24399722004-07-09 22:21:33 +00002230 error("Function declared, but bytecode stream ended before definition");
Chris Lattner00950542001-06-06 20:29:01 +00002231}
2232
Reid Spencer04cde2c2004-07-04 11:33:49 +00002233/// This function completely parses a bytecode buffer given by the \p Buf
2234/// and \p Length parameters.
Misha Brukman8a96c532005-04-21 21:44:41 +00002235void BytecodeReader::ParseBytecode(BufPtr Buf, unsigned Length,
Reid Spencer5b472d92004-08-21 20:49:23 +00002236 const std::string &ModuleID) {
Misha Brukmane0dd0d42003-09-23 16:15:29 +00002237
Reid Spencer060d25d2004-06-29 23:29:38 +00002238 try {
Chris Lattner3af4b4f2004-11-30 16:58:18 +00002239 RevisionNum = 0;
Reid Spencer060d25d2004-06-29 23:29:38 +00002240 At = MemStart = BlockStart = Buf;
2241 MemEnd = BlockEnd = Buf + Length;
Misha Brukmane0dd0d42003-09-23 16:15:29 +00002242
Reid Spencer060d25d2004-06-29 23:29:38 +00002243 // Create the module
2244 TheModule = new Module(ModuleID);
Chris Lattner00950542001-06-06 20:29:01 +00002245
Reid Spencer04cde2c2004-07-04 11:33:49 +00002246 if (Handler) Handler->handleStart(TheModule, Length);
Reid Spencer060d25d2004-06-29 23:29:38 +00002247
Reid Spencerf0c977c2004-11-07 18:20:55 +00002248 // Read the four bytes of the signature.
2249 unsigned Sig = read_uint();
Reid Spencer17f52c52004-11-06 23:17:23 +00002250
Reid Spencerf0c977c2004-11-07 18:20:55 +00002251 // If this is a compressed file
2252 if (Sig == ('l' | ('l' << 8) | ('v' << 16) | ('c' << 24))) {
Reid Spencer17f52c52004-11-06 23:17:23 +00002253
Reid Spencerf0c977c2004-11-07 18:20:55 +00002254 // Invoke the decompression of the bytecode. Note that we have to skip the
2255 // file's magic number which is not part of the compressed block. Hence,
Reid Spencer61aaf2e2004-11-14 21:59:21 +00002256 // the Buf+4 and Length-4. The result goes into decompressedBlock, a data
2257 // member for retention until BytecodeReader is destructed.
2258 unsigned decompressedLength = Compressor::decompressToNewBuffer(
2259 (char*)Buf+4,Length-4,decompressedBlock);
Reid Spencerf0c977c2004-11-07 18:20:55 +00002260
2261 // We must adjust the buffer pointers used by the bytecode reader to point
Reid Spencer61aaf2e2004-11-14 21:59:21 +00002262 // into the new decompressed block. After decompression, the
2263 // decompressedBlock will point to a contiguous memory area that has
Reid Spencerf0c977c2004-11-07 18:20:55 +00002264 // the decompressed data.
Reid Spencer61aaf2e2004-11-14 21:59:21 +00002265 At = MemStart = BlockStart = Buf = (BufPtr) decompressedBlock;
Reid Spencerf0c977c2004-11-07 18:20:55 +00002266 MemEnd = BlockEnd = Buf + decompressedLength;
Reid Spencer17f52c52004-11-06 23:17:23 +00002267
Reid Spencerf0c977c2004-11-07 18:20:55 +00002268 // else if this isn't a regular (uncompressed) bytecode file, then its
2269 // and error, generate that now.
2270 } else if (Sig != ('l' | ('l' << 8) | ('v' << 16) | ('m' << 24))) {
2271 error("Invalid bytecode signature: " + utohexstr(Sig));
Reid Spencer060d25d2004-06-29 23:29:38 +00002272 }
2273
Reid Spencer060d25d2004-06-29 23:29:38 +00002274 // Tell the handler we're starting a module
Reid Spencer04cde2c2004-07-04 11:33:49 +00002275 if (Handler) Handler->handleModuleBegin(ModuleID);
Reid Spencer060d25d2004-06-29 23:29:38 +00002276
Reid Spencerad89bd62004-07-25 18:07:36 +00002277 // Get the module block and size and verify. This is handled specially
2278 // because the module block/size is always written in long format. Other
2279 // blocks are written in short format so the read_block method is used.
Reid Spencer060d25d2004-06-29 23:29:38 +00002280 unsigned Type, Size;
Reid Spencerad89bd62004-07-25 18:07:36 +00002281 Type = read_uint();
2282 Size = read_uint();
2283 if (Type != BytecodeFormat::ModuleBlockID) {
Misha Brukman8a96c532005-04-21 21:44:41 +00002284 error("Expected Module Block! Type:" + utostr(Type) + ", Size:"
Reid Spencer46b002c2004-07-11 17:28:43 +00002285 + utostr(Size));
Reid Spencer060d25d2004-06-29 23:29:38 +00002286 }
Chris Lattner56bc8942004-09-27 16:59:06 +00002287
2288 // It looks like the darwin ranlib program is broken, and adds trailing
2289 // garbage to the end of some bytecode files. This hack allows the bc
2290 // reader to ignore trailing garbage on bytecode files.
2291 if (At + Size < MemEnd)
2292 MemEnd = BlockEnd = At+Size;
2293
2294 if (At + Size != MemEnd)
Reid Spencer24399722004-07-09 22:21:33 +00002295 error("Invalid Top Level Block Length! Type:" + utostr(Type)
Reid Spencer46b002c2004-07-11 17:28:43 +00002296 + ", Size:" + utostr(Size));
Reid Spencer060d25d2004-06-29 23:29:38 +00002297
2298 // Parse the module contents
2299 this->ParseModule();
2300
Reid Spencer060d25d2004-06-29 23:29:38 +00002301 // Check for missing functions
Reid Spencer46b002c2004-07-11 17:28:43 +00002302 if (hasFunctions())
Reid Spencer24399722004-07-09 22:21:33 +00002303 error("Function expected, but bytecode stream ended!");
Reid Spencer060d25d2004-06-29 23:29:38 +00002304
Reid Spencer5c15fe52004-07-05 00:57:50 +00002305 // Tell the handler we're done with the module
Misha Brukman8a96c532005-04-21 21:44:41 +00002306 if (Handler)
Reid Spencer5c15fe52004-07-05 00:57:50 +00002307 Handler->handleModuleEnd(ModuleID);
2308
2309 // Tell the handler we're finished the parse
Reid Spencer04cde2c2004-07-04 11:33:49 +00002310 if (Handler) Handler->handleFinish();
Reid Spencer060d25d2004-06-29 23:29:38 +00002311
Reid Spencer46b002c2004-07-11 17:28:43 +00002312 } catch (std::string& errstr) {
Reid Spencer04cde2c2004-07-04 11:33:49 +00002313 if (Handler) Handler->handleError(errstr);
Reid Spencer060d25d2004-06-29 23:29:38 +00002314 freeState();
Chris Lattner2a7b6ba2003-03-06 17:15:19 +00002315 delete TheModule;
2316 TheModule = 0;
Chris Lattner3bdad692004-11-15 21:55:33 +00002317 if (decompressedBlock != 0 ) {
Reid Spencer61aaf2e2004-11-14 21:59:21 +00002318 ::free(decompressedBlock);
Chris Lattner3bdad692004-11-15 21:55:33 +00002319 decompressedBlock = 0;
2320 }
Chris Lattnerb0b7c0d2003-09-26 14:44:52 +00002321 throw;
Reid Spencer060d25d2004-06-29 23:29:38 +00002322 } catch (...) {
2323 std::string msg("Unknown Exception Occurred");
Reid Spencer04cde2c2004-07-04 11:33:49 +00002324 if (Handler) Handler->handleError(msg);
Reid Spencer060d25d2004-06-29 23:29:38 +00002325 freeState();
2326 delete TheModule;
2327 TheModule = 0;
Chris Lattner3bdad692004-11-15 21:55:33 +00002328 if (decompressedBlock != 0) {
Reid Spencer61aaf2e2004-11-14 21:59:21 +00002329 ::free(decompressedBlock);
Chris Lattner3bdad692004-11-15 21:55:33 +00002330 decompressedBlock = 0;
2331 }
Reid Spencer060d25d2004-06-29 23:29:38 +00002332 throw msg;
Chris Lattner2a7b6ba2003-03-06 17:15:19 +00002333 }
Chris Lattner00950542001-06-06 20:29:01 +00002334}
Reid Spencer060d25d2004-06-29 23:29:38 +00002335
2336//===----------------------------------------------------------------------===//
2337//=== Default Implementations of Handler Methods
2338//===----------------------------------------------------------------------===//
2339
2340BytecodeHandler::~BytecodeHandler() {}
Reid Spencer060d25d2004-06-29 23:29:38 +00002341