blob: b1f2634296f1c2ab104733258e1c4160914707e7 [file] [log] [blame]
Chris Lattner14999342004-01-10 19:07:06 +00001//===-- Writer.cpp - Library for writing LLVM bytecode files --------------===//
Misha Brukman23c6d2c2005-04-21 21:48:46 +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 Brukman23c6d2c2005-04-21 21:48:46 +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/Writer.h
11//
Chris Lattner00950542001-06-06 20:29:01 +000012// Note that this file uses an unusual technique of outputting all the bytecode
Reid Spencerad89bd62004-07-25 18:07:36 +000013// to a vector of unsigned char, then copies the vector to an ostream. The
Chris Lattner00950542001-06-06 20:29:01 +000014// reason for this is that we must do "seeking" in the stream to do back-
15// patching, and some very important ostreams that we want to support (like
16// pipes) do not support seeking. :( :( :(
17//
Chris Lattner00950542001-06-06 20:29:01 +000018//===----------------------------------------------------------------------===//
19
20#include "WriterInternals.h"
Chris Lattner635cd932002-07-23 19:56:44 +000021#include "llvm/Bytecode/WriteBytecodePass.h"
Chris Lattnerdee199f2005-05-06 22:34:01 +000022#include "llvm/CallingConv.h"
Chris Lattner83bb3d22004-01-14 23:36:54 +000023#include "llvm/Constants.h"
24#include "llvm/DerivedTypes.h"
Reid Spencerad89bd62004-07-25 18:07:36 +000025#include "llvm/Instructions.h"
Chris Lattner00950542001-06-06 20:29:01 +000026#include "llvm/Module.h"
Chris Lattner00950542001-06-06 20:29:01 +000027#include "llvm/SymbolTable.h"
Reid Spencerad89bd62004-07-25 18:07:36 +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/STLExtras.h"
32#include "llvm/ADT/Statistic.h"
Chris Lattner32abce62004-01-10 19:10:01 +000033#include <cstring>
Chris Lattner00950542001-06-06 20:29:01 +000034#include <algorithm>
Chris Lattner44f549b2004-01-10 18:49:43 +000035using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000036
Reid Spencer38d54be2004-08-17 07:45:14 +000037/// This value needs to be incremented every time the bytecode format changes
38/// so that the reader can distinguish which format of the bytecode file has
39/// been written.
40/// @brief The bytecode version number
Chris Lattnera79e7cc2004-10-16 18:18:16 +000041const unsigned BCVersionNum = 5;
Reid Spencer38d54be2004-08-17 07:45:14 +000042
Chris Lattner635cd932002-07-23 19:56:44 +000043static RegisterPass<WriteBytecodePass> X("emitbytecode", "Bytecode Writer");
44
Misha Brukman23c6d2c2005-04-21 21:48:46 +000045static Statistic<>
Chris Lattnera92f6962002-10-01 22:38:41 +000046BytesWritten("bytecodewriter", "Number of bytecode bytes written");
Chris Lattner635cd932002-07-23 19:56:44 +000047
Reid Spencerad89bd62004-07-25 18:07:36 +000048//===----------------------------------------------------------------------===//
49//=== Output Primitives ===//
50//===----------------------------------------------------------------------===//
51
52// output - If a position is specified, it must be in the valid portion of the
Misha Brukman23c6d2c2005-04-21 21:48:46 +000053// string... note that this should be inlined always so only the relevant IF
Reid Spencerad89bd62004-07-25 18:07:36 +000054// body should be included.
55inline void BytecodeWriter::output(unsigned i, int pos) {
56 if (pos == -1) { // Be endian clean, little endian is our friend
Misha Brukman23c6d2c2005-04-21 21:48:46 +000057 Out.push_back((unsigned char)i);
Reid Spencerad89bd62004-07-25 18:07:36 +000058 Out.push_back((unsigned char)(i >> 8));
59 Out.push_back((unsigned char)(i >> 16));
60 Out.push_back((unsigned char)(i >> 24));
61 } else {
62 Out[pos ] = (unsigned char)i;
63 Out[pos+1] = (unsigned char)(i >> 8);
64 Out[pos+2] = (unsigned char)(i >> 16);
65 Out[pos+3] = (unsigned char)(i >> 24);
66 }
67}
68
69inline void BytecodeWriter::output(int i) {
70 output((unsigned)i);
71}
72
73/// output_vbr - Output an unsigned value, by using the least number of bytes
74/// possible. This is useful because many of our "infinite" values are really
75/// very small most of the time; but can be large a few times.
Misha Brukman23c6d2c2005-04-21 21:48:46 +000076/// Data format used: If you read a byte with the high bit set, use the low
77/// seven bits as data and then read another byte.
Reid Spencerad89bd62004-07-25 18:07:36 +000078inline void BytecodeWriter::output_vbr(uint64_t i) {
79 while (1) {
80 if (i < 0x80) { // done?
81 Out.push_back((unsigned char)i); // We know the high bit is clear...
82 return;
83 }
Misha Brukman23c6d2c2005-04-21 21:48:46 +000084
Reid Spencerad89bd62004-07-25 18:07:36 +000085 // Nope, we are bigger than a character, output the next 7 bits and set the
86 // high bit to say that there is more coming...
87 Out.push_back(0x80 | ((unsigned char)i & 0x7F));
88 i >>= 7; // Shift out 7 bits now...
89 }
90}
91
92inline void BytecodeWriter::output_vbr(unsigned i) {
93 while (1) {
94 if (i < 0x80) { // done?
95 Out.push_back((unsigned char)i); // We know the high bit is clear...
96 return;
97 }
Misha Brukman23c6d2c2005-04-21 21:48:46 +000098
Reid Spencerad89bd62004-07-25 18:07:36 +000099 // Nope, we are bigger than a character, output the next 7 bits and set the
100 // high bit to say that there is more coming...
101 Out.push_back(0x80 | ((unsigned char)i & 0x7F));
102 i >>= 7; // Shift out 7 bits now...
103 }
104}
105
106inline void BytecodeWriter::output_typeid(unsigned i) {
107 if (i <= 0x00FFFFFF)
108 this->output_vbr(i);
109 else {
110 this->output_vbr(0x00FFFFFF);
111 this->output_vbr(i);
112 }
113}
114
115inline void BytecodeWriter::output_vbr(int64_t i) {
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000116 if (i < 0)
Reid Spencerad89bd62004-07-25 18:07:36 +0000117 output_vbr(((uint64_t)(-i) << 1) | 1); // Set low order sign bit...
118 else
119 output_vbr((uint64_t)i << 1); // Low order bit is clear.
120}
121
122
123inline void BytecodeWriter::output_vbr(int i) {
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000124 if (i < 0)
Reid Spencerad89bd62004-07-25 18:07:36 +0000125 output_vbr(((unsigned)(-i) << 1) | 1); // Set low order sign bit...
126 else
127 output_vbr((unsigned)i << 1); // Low order bit is clear.
128}
129
Reid Spencer38d54be2004-08-17 07:45:14 +0000130inline void BytecodeWriter::output(const std::string &s) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000131 unsigned Len = s.length();
132 output_vbr(Len ); // Strings may have an arbitrary length...
133 Out.insert(Out.end(), s.begin(), s.end());
Reid Spencerad89bd62004-07-25 18:07:36 +0000134}
135
136inline void BytecodeWriter::output_data(const void *Ptr, const void *End) {
137 Out.insert(Out.end(), (const unsigned char*)Ptr, (const unsigned char*)End);
138}
139
140inline void BytecodeWriter::output_float(float& FloatVal) {
141 /// FIXME: This isn't optimal, it has size problems on some platforms
142 /// where FP is not IEEE.
Jim Laskeycb6682f2005-08-17 19:34:49 +0000143 uint32_t i = FloatToBits(FloatVal);
144 Out.push_back( static_cast<unsigned char>( (i & 0xFF )));
145 Out.push_back( static_cast<unsigned char>( (i >> 8) & 0xFF));
146 Out.push_back( static_cast<unsigned char>( (i >> 16) & 0xFF));
147 Out.push_back( static_cast<unsigned char>( (i >> 24) & 0xFF));
Reid Spencerad89bd62004-07-25 18:07:36 +0000148}
149
150inline void BytecodeWriter::output_double(double& DoubleVal) {
151 /// FIXME: This isn't optimal, it has size problems on some platforms
152 /// where FP is not IEEE.
Jim Laskeycb6682f2005-08-17 19:34:49 +0000153 uint64_t i = DoubleToBits(DoubleVal);
154 Out.push_back( static_cast<unsigned char>( (i & 0xFF )));
155 Out.push_back( static_cast<unsigned char>( (i >> 8) & 0xFF));
156 Out.push_back( static_cast<unsigned char>( (i >> 16) & 0xFF));
157 Out.push_back( static_cast<unsigned char>( (i >> 24) & 0xFF));
158 Out.push_back( static_cast<unsigned char>( (i >> 32) & 0xFF));
159 Out.push_back( static_cast<unsigned char>( (i >> 40) & 0xFF));
160 Out.push_back( static_cast<unsigned char>( (i >> 48) & 0xFF));
161 Out.push_back( static_cast<unsigned char>( (i >> 56) & 0xFF));
Reid Spencerad89bd62004-07-25 18:07:36 +0000162}
163
164inline BytecodeBlock::BytecodeBlock(unsigned ID, BytecodeWriter& w,
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000165 bool elideIfEmpty, bool hasLongFormat )
Reid Spencerad89bd62004-07-25 18:07:36 +0000166 : Id(ID), Writer(w), ElideIfEmpty(elideIfEmpty), HasLongFormat(hasLongFormat){
167
168 if (HasLongFormat) {
169 w.output(ID);
170 w.output(0U); // For length in long format
171 } else {
172 w.output(0U); /// Place holder for ID and length for this block
173 }
174 Loc = w.size();
175}
176
Chris Lattnerb0bf6642004-10-14 01:35:17 +0000177inline BytecodeBlock::~BytecodeBlock() { // Do backpatch when block goes out
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000178 // of scope...
Reid Spencerad89bd62004-07-25 18:07:36 +0000179 if (Loc == Writer.size() && ElideIfEmpty) {
180 // If the block is empty, and we are allowed to, do not emit the block at
181 // all!
182 Writer.resize(Writer.size()-(HasLongFormat?8:4));
183 return;
184 }
185
Reid Spencerad89bd62004-07-25 18:07:36 +0000186 if (HasLongFormat)
187 Writer.output(unsigned(Writer.size()-Loc), int(Loc-4));
188 else
189 Writer.output(unsigned(Writer.size()-Loc) << 5 | (Id & 0x1F), int(Loc-4));
Reid Spencerad89bd62004-07-25 18:07:36 +0000190}
191
192//===----------------------------------------------------------------------===//
193//=== Constant Output ===//
194//===----------------------------------------------------------------------===//
195
196void BytecodeWriter::outputType(const Type *T) {
197 output_vbr((unsigned)T->getTypeID());
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000198
Reid Spencerad89bd62004-07-25 18:07:36 +0000199 // That's all there is to handling primitive types...
200 if (T->isPrimitiveType()) {
201 return; // We might do this if we alias a prim type: %x = type int
202 }
203
204 switch (T->getTypeID()) { // Handle derived types now.
205 case Type::FunctionTyID: {
206 const FunctionType *MT = cast<FunctionType>(T);
207 int Slot = Table.getSlot(MT->getReturnType());
208 assert(Slot != -1 && "Type used but not available!!");
209 output_typeid((unsigned)Slot);
210
211 // Output the number of arguments to function (+1 if varargs):
212 output_vbr((unsigned)MT->getNumParams()+MT->isVarArg());
213
214 // Output all of the arguments...
215 FunctionType::param_iterator I = MT->param_begin();
216 for (; I != MT->param_end(); ++I) {
217 Slot = Table.getSlot(*I);
218 assert(Slot != -1 && "Type used but not available!!");
219 output_typeid((unsigned)Slot);
220 }
221
222 // Terminate list with VoidTy if we are a varargs function...
223 if (MT->isVarArg())
224 output_typeid((unsigned)Type::VoidTyID);
225 break;
226 }
227
228 case Type::ArrayTyID: {
229 const ArrayType *AT = cast<ArrayType>(T);
230 int Slot = Table.getSlot(AT->getElementType());
231 assert(Slot != -1 && "Type used but not available!!");
232 output_typeid((unsigned)Slot);
Reid Spencerad89bd62004-07-25 18:07:36 +0000233 output_vbr(AT->getNumElements());
234 break;
235 }
236
Brian Gaeke715c90b2004-08-20 06:00:58 +0000237 case Type::PackedTyID: {
238 const PackedType *PT = cast<PackedType>(T);
239 int Slot = Table.getSlot(PT->getElementType());
240 assert(Slot != -1 && "Type used but not available!!");
241 output_typeid((unsigned)Slot);
242 output_vbr(PT->getNumElements());
243 break;
244 }
245
246
Reid Spencerad89bd62004-07-25 18:07:36 +0000247 case Type::StructTyID: {
248 const StructType *ST = cast<StructType>(T);
249
250 // Output all of the element types...
251 for (StructType::element_iterator I = ST->element_begin(),
252 E = ST->element_end(); I != E; ++I) {
253 int Slot = Table.getSlot(*I);
254 assert(Slot != -1 && "Type used but not available!!");
255 output_typeid((unsigned)Slot);
256 }
257
258 // Terminate list with VoidTy
259 output_typeid((unsigned)Type::VoidTyID);
260 break;
261 }
262
263 case Type::PointerTyID: {
264 const PointerType *PT = cast<PointerType>(T);
265 int Slot = Table.getSlot(PT->getElementType());
266 assert(Slot != -1 && "Type used but not available!!");
267 output_typeid((unsigned)Slot);
268 break;
269 }
270
Chris Lattnerb0bf6642004-10-14 01:35:17 +0000271 case Type::OpaqueTyID:
Reid Spencerad89bd62004-07-25 18:07:36 +0000272 // No need to emit anything, just the count of opaque types is enough.
273 break;
Reid Spencerad89bd62004-07-25 18:07:36 +0000274
Reid Spencerad89bd62004-07-25 18:07:36 +0000275 default:
276 std::cerr << __FILE__ << ":" << __LINE__ << ": Don't know how to serialize"
277 << " Type '" << T->getDescription() << "'\n";
278 break;
279 }
280}
281
282void BytecodeWriter::outputConstant(const Constant *CPV) {
283 assert((CPV->getType()->isPrimitiveType() || !CPV->isNullValue()) &&
284 "Shouldn't output null constants!");
285
286 // We must check for a ConstantExpr before switching by type because
287 // a ConstantExpr can be of any type, and has no explicit value.
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000288 //
Reid Spencerad89bd62004-07-25 18:07:36 +0000289 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
290 // FIXME: Encoding of constant exprs could be much more compact!
291 assert(CE->getNumOperands() > 0 && "ConstantExpr with 0 operands");
Chris Lattner129baf62004-12-04 21:28:47 +0000292 assert(CE->getNumOperands() != 1 || CE->getOpcode() == Instruction::Cast);
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000293 output_vbr(1+CE->getNumOperands()); // flags as an expr
Reid Spencerad89bd62004-07-25 18:07:36 +0000294 output_vbr(CE->getOpcode()); // flags as an expr
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000295
Reid Spencerad89bd62004-07-25 18:07:36 +0000296 for (User::const_op_iterator OI = CE->op_begin(); OI != CE->op_end(); ++OI){
297 int Slot = Table.getSlot(*OI);
298 assert(Slot != -1 && "Unknown constant used in ConstantExpr!!");
299 output_vbr((unsigned)Slot);
300 Slot = Table.getSlot((*OI)->getType());
301 output_typeid((unsigned)Slot);
302 }
303 return;
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000304 } else if (isa<UndefValue>(CPV)) {
305 output_vbr(1U); // 1 -> UndefValue constant.
306 return;
Reid Spencerad89bd62004-07-25 18:07:36 +0000307 } else {
308 output_vbr(0U); // flag as not a ConstantExpr
309 }
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000310
Reid Spencerad89bd62004-07-25 18:07:36 +0000311 switch (CPV->getType()->getTypeID()) {
312 case Type::BoolTyID: // Boolean Types
313 if (cast<ConstantBool>(CPV)->getValue())
314 output_vbr(1U);
315 else
316 output_vbr(0U);
317 break;
318
319 case Type::UByteTyID: // Unsigned integer types...
320 case Type::UShortTyID:
321 case Type::UIntTyID:
322 case Type::ULongTyID:
323 output_vbr(cast<ConstantUInt>(CPV)->getValue());
324 break;
325
326 case Type::SByteTyID: // Signed integer types...
327 case Type::ShortTyID:
328 case Type::IntTyID:
329 case Type::LongTyID:
330 output_vbr(cast<ConstantSInt>(CPV)->getValue());
331 break;
332
333 case Type::ArrayTyID: {
334 const ConstantArray *CPA = cast<ConstantArray>(CPV);
335 assert(!CPA->isString() && "Constant strings should be handled specially!");
336
Alkis Evlogimenos15876bb2004-08-04 08:44:43 +0000337 for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000338 int Slot = Table.getSlot(CPA->getOperand(i));
339 assert(Slot != -1 && "Constant used but not available!!");
340 output_vbr((unsigned)Slot);
341 }
342 break;
343 }
344
Brian Gaeke715c90b2004-08-20 06:00:58 +0000345 case Type::PackedTyID: {
346 const ConstantPacked *CP = cast<ConstantPacked>(CPV);
347
348 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i) {
349 int Slot = Table.getSlot(CP->getOperand(i));
350 assert(Slot != -1 && "Constant used but not available!!");
351 output_vbr((unsigned)Slot);
352 }
353 break;
354 }
355
Reid Spencerad89bd62004-07-25 18:07:36 +0000356 case Type::StructTyID: {
357 const ConstantStruct *CPS = cast<ConstantStruct>(CPV);
Reid Spencerad89bd62004-07-25 18:07:36 +0000358
Alkis Evlogimenos15876bb2004-08-04 08:44:43 +0000359 for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i) {
360 int Slot = Table.getSlot(CPS->getOperand(i));
Reid Spencerad89bd62004-07-25 18:07:36 +0000361 assert(Slot != -1 && "Constant used but not available!!");
362 output_vbr((unsigned)Slot);
363 }
364 break;
365 }
366
367 case Type::PointerTyID:
368 assert(0 && "No non-null, non-constant-expr constants allowed!");
369 abort();
370
371 case Type::FloatTyID: { // Floating point types...
372 float Tmp = (float)cast<ConstantFP>(CPV)->getValue();
373 output_float(Tmp);
374 break;
375 }
376 case Type::DoubleTyID: {
377 double Tmp = cast<ConstantFP>(CPV)->getValue();
378 output_double(Tmp);
379 break;
380 }
381
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000382 case Type::VoidTyID:
Reid Spencerad89bd62004-07-25 18:07:36 +0000383 case Type::LabelTyID:
384 default:
385 std::cerr << __FILE__ << ":" << __LINE__ << ": Don't know how to serialize"
386 << " type '" << *CPV->getType() << "'\n";
387 break;
388 }
389 return;
390}
391
392void BytecodeWriter::outputConstantStrings() {
393 SlotCalculator::string_iterator I = Table.string_begin();
394 SlotCalculator::string_iterator E = Table.string_end();
395 if (I == E) return; // No strings to emit
396
397 // If we have != 0 strings to emit, output them now. Strings are emitted into
398 // the 'void' type plane.
399 output_vbr(unsigned(E-I));
400 output_typeid(Type::VoidTyID);
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000401
Reid Spencerad89bd62004-07-25 18:07:36 +0000402 // Emit all of the strings.
403 for (I = Table.string_begin(); I != E; ++I) {
404 const ConstantArray *Str = *I;
405 int Slot = Table.getSlot(Str->getType());
406 assert(Slot != -1 && "Constant string of unknown type?");
407 output_typeid((unsigned)Slot);
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000408
Reid Spencerad89bd62004-07-25 18:07:36 +0000409 // Now that we emitted the type (which indicates the size of the string),
410 // emit all of the characters.
411 std::string Val = Str->getAsString();
412 output_data(Val.c_str(), Val.c_str()+Val.size());
413 }
414}
415
416//===----------------------------------------------------------------------===//
417//=== Instruction Output ===//
418//===----------------------------------------------------------------------===//
419typedef unsigned char uchar;
420
Chris Lattnerda895d62005-02-27 06:18:25 +0000421// outputInstructionFormat0 - Output those weird instructions that have a large
Chris Lattnerdee199f2005-05-06 22:34:01 +0000422// number of operands or have large operands themselves.
Reid Spencerad89bd62004-07-25 18:07:36 +0000423//
424// Format: [opcode] [type] [numargs] [arg0] [arg1] ... [arg<numargs-1>]
425//
Chris Lattnerf9d71782004-10-14 01:46:07 +0000426void BytecodeWriter::outputInstructionFormat0(const Instruction *I,
427 unsigned Opcode,
428 const SlotCalculator &Table,
429 unsigned Type) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000430 // Opcode must have top two bits clear...
431 output_vbr(Opcode << 2); // Instruction Opcode ID
432 output_typeid(Type); // Result type
433
434 unsigned NumArgs = I->getNumOperands();
Andrew Lenharth558bc882005-06-18 18:34:52 +0000435 output_vbr(NumArgs + (isa<CastInst>(I) ||
Chris Lattnerdee199f2005-05-06 22:34:01 +0000436 isa<VAArgInst>(I) || Opcode == 56 || Opcode == 58));
Reid Spencerad89bd62004-07-25 18:07:36 +0000437
438 if (!isa<GetElementPtrInst>(&I)) {
439 for (unsigned i = 0; i < NumArgs; ++i) {
440 int Slot = Table.getSlot(I->getOperand(i));
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000441 assert(Slot >= 0 && "No slot number for value!?!?");
Reid Spencerad89bd62004-07-25 18:07:36 +0000442 output_vbr((unsigned)Slot);
443 }
444
445 if (isa<CastInst>(I) || isa<VAArgInst>(I)) {
446 int Slot = Table.getSlot(I->getType());
447 assert(Slot != -1 && "Cast return type unknown?");
448 output_typeid((unsigned)Slot);
Chris Lattnerdee199f2005-05-06 22:34:01 +0000449 } else if (Opcode == 56) { // Invoke escape sequence
450 output_vbr(cast<InvokeInst>(I)->getCallingConv());
451 } else if (Opcode == 58) { // Call escape sequence
452 output_vbr((cast<CallInst>(I)->getCallingConv() << 1) |
Jeff Cohen39cef602005-05-07 02:44:04 +0000453 unsigned(cast<CallInst>(I)->isTailCall()));
Reid Spencerad89bd62004-07-25 18:07:36 +0000454 }
Reid Spencerad89bd62004-07-25 18:07:36 +0000455 } else {
456 int Slot = Table.getSlot(I->getOperand(0));
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000457 assert(Slot >= 0 && "No slot number for value!?!?");
Reid Spencerad89bd62004-07-25 18:07:36 +0000458 output_vbr(unsigned(Slot));
459
460 // We need to encode the type of sequential type indices into their slot #
461 unsigned Idx = 1;
462 for (gep_type_iterator TI = gep_type_begin(I), E = gep_type_end(I);
463 Idx != NumArgs; ++TI, ++Idx) {
464 Slot = Table.getSlot(I->getOperand(Idx));
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000465 assert(Slot >= 0 && "No slot number for value!?!?");
466
Reid Spencerad89bd62004-07-25 18:07:36 +0000467 if (isa<SequentialType>(*TI)) {
468 unsigned IdxId;
469 switch (I->getOperand(Idx)->getType()->getTypeID()) {
470 default: assert(0 && "Unknown index type!");
471 case Type::UIntTyID: IdxId = 0; break;
472 case Type::IntTyID: IdxId = 1; break;
473 case Type::ULongTyID: IdxId = 2; break;
474 case Type::LongTyID: IdxId = 3; break;
475 }
476 Slot = (Slot << 2) | IdxId;
477 }
478 output_vbr(unsigned(Slot));
479 }
480 }
Reid Spencerad89bd62004-07-25 18:07:36 +0000481}
482
483
484// outputInstrVarArgsCall - Output the absurdly annoying varargs function calls.
485// This are more annoying than most because the signature of the call does not
486// tell us anything about the types of the arguments in the varargs portion.
487// Because of this, we encode (as type 0) all of the argument types explicitly
488// before the argument value. This really sucks, but you shouldn't be using
489// varargs functions in your code! *death to printf*!
490//
491// Format: [opcode] [type] [numargs] [arg0] [arg1] ... [arg<numargs-1>]
492//
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000493void BytecodeWriter::outputInstrVarArgsCall(const Instruction *I,
494 unsigned Opcode,
495 const SlotCalculator &Table,
496 unsigned Type) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000497 assert(isa<CallInst>(I) || isa<InvokeInst>(I));
498 // Opcode must have top two bits clear...
499 output_vbr(Opcode << 2); // Instruction Opcode ID
500 output_typeid(Type); // Result type (varargs type)
501
502 const PointerType *PTy = cast<PointerType>(I->getOperand(0)->getType());
503 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
504 unsigned NumParams = FTy->getNumParams();
505
506 unsigned NumFixedOperands;
507 if (isa<CallInst>(I)) {
508 // Output an operand for the callee and each fixed argument, then two for
509 // each variable argument.
510 NumFixedOperands = 1+NumParams;
511 } else {
512 assert(isa<InvokeInst>(I) && "Not call or invoke??");
513 // Output an operand for the callee and destinations, then two for each
514 // variable argument.
515 NumFixedOperands = 3+NumParams;
516 }
517 output_vbr(2 * I->getNumOperands()-NumFixedOperands);
518
519 // The type for the function has already been emitted in the type field of the
520 // instruction. Just emit the slot # now.
521 for (unsigned i = 0; i != NumFixedOperands; ++i) {
522 int Slot = Table.getSlot(I->getOperand(i));
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000523 assert(Slot >= 0 && "No slot number for value!?!?");
Reid Spencerad89bd62004-07-25 18:07:36 +0000524 output_vbr((unsigned)Slot);
525 }
526
527 for (unsigned i = NumFixedOperands, e = I->getNumOperands(); i != e; ++i) {
528 // Output Arg Type ID
529 int Slot = Table.getSlot(I->getOperand(i)->getType());
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000530 assert(Slot >= 0 && "No slot number for value!?!?");
Reid Spencerad89bd62004-07-25 18:07:36 +0000531 output_typeid((unsigned)Slot);
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000532
Reid Spencerad89bd62004-07-25 18:07:36 +0000533 // Output arg ID itself
534 Slot = Table.getSlot(I->getOperand(i));
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000535 assert(Slot >= 0 && "No slot number for value!?!?");
Reid Spencerad89bd62004-07-25 18:07:36 +0000536 output_vbr((unsigned)Slot);
537 }
Reid Spencerad89bd62004-07-25 18:07:36 +0000538}
539
540
541// outputInstructionFormat1 - Output one operand instructions, knowing that no
542// operand index is >= 2^12.
543//
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000544inline void BytecodeWriter::outputInstructionFormat1(const Instruction *I,
545 unsigned Opcode,
546 unsigned *Slots,
547 unsigned Type) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000548 // bits Instruction format:
549 // --------------------------
550 // 01-00: Opcode type, fixed to 1.
551 // 07-02: Opcode
552 // 19-08: Resulting type plane
553 // 31-20: Operand #1 (if set to (2^12-1), then zero operands)
554 //
Chris Lattnerf9d71782004-10-14 01:46:07 +0000555 output(1 | (Opcode << 2) | (Type << 8) | (Slots[0] << 20));
Reid Spencerad89bd62004-07-25 18:07:36 +0000556}
557
558
559// outputInstructionFormat2 - Output two operand instructions, knowing that no
560// operand index is >= 2^8.
561//
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000562inline void BytecodeWriter::outputInstructionFormat2(const Instruction *I,
563 unsigned Opcode,
564 unsigned *Slots,
565 unsigned Type) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000566 // bits Instruction format:
567 // --------------------------
568 // 01-00: Opcode type, fixed to 2.
569 // 07-02: Opcode
570 // 15-08: Resulting type plane
571 // 23-16: Operand #1
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000572 // 31-24: Operand #2
Reid Spencerad89bd62004-07-25 18:07:36 +0000573 //
Chris Lattnerf9d71782004-10-14 01:46:07 +0000574 output(2 | (Opcode << 2) | (Type << 8) | (Slots[0] << 16) | (Slots[1] << 24));
Reid Spencerad89bd62004-07-25 18:07:36 +0000575}
576
577
578// outputInstructionFormat3 - Output three operand instructions, knowing that no
579// operand index is >= 2^6.
580//
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000581inline void BytecodeWriter::outputInstructionFormat3(const Instruction *I,
Reid Spencerad89bd62004-07-25 18:07:36 +0000582 unsigned Opcode,
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000583 unsigned *Slots,
584 unsigned Type) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000585 // bits Instruction format:
586 // --------------------------
587 // 01-00: Opcode type, fixed to 3.
588 // 07-02: Opcode
589 // 13-08: Resulting type plane
590 // 19-14: Operand #1
591 // 25-20: Operand #2
592 // 31-26: Operand #3
593 //
Chris Lattnerf9d71782004-10-14 01:46:07 +0000594 output(3 | (Opcode << 2) | (Type << 8) |
Chris Lattner84d1ced2004-10-14 01:57:28 +0000595 (Slots[0] << 14) | (Slots[1] << 20) | (Slots[2] << 26));
Reid Spencerad89bd62004-07-25 18:07:36 +0000596}
597
598void BytecodeWriter::outputInstruction(const Instruction &I) {
Chris Lattnerbfed9242005-05-13 23:35:47 +0000599 assert(I.getOpcode() < 56 && "Opcode too big???");
Reid Spencerad89bd62004-07-25 18:07:36 +0000600 unsigned Opcode = I.getOpcode();
601 unsigned NumOperands = I.getNumOperands();
602
Chris Lattner38287bd2005-05-06 06:13:34 +0000603 // Encode 'tail call' as 61, 'volatile load' as 62, and 'volatile store' as
604 // 63.
Chris Lattnerdee199f2005-05-06 22:34:01 +0000605 if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
606 if (CI->getCallingConv() == CallingConv::C) {
607 if (CI->isTailCall())
608 Opcode = 61; // CCC + Tail Call
609 else
610 ; // Opcode = Instruction::Call
611 } else if (CI->getCallingConv() == CallingConv::Fast) {
612 if (CI->isTailCall())
613 Opcode = 59; // FastCC + TailCall
614 else
615 Opcode = 60; // FastCC + Not Tail Call
616 } else {
617 Opcode = 58; // Call escape sequence.
618 }
619 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
620 if (II->getCallingConv() == CallingConv::Fast)
621 Opcode = 57; // FastCC invoke.
622 else if (II->getCallingConv() != CallingConv::C)
623 Opcode = 56; // Invoke escape sequence.
Jeff Cohen00b168892005-07-27 06:12:32 +0000624
Chris Lattnerdee199f2005-05-06 22:34:01 +0000625 } else if (isa<LoadInst>(I) && cast<LoadInst>(I).isVolatile()) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000626 Opcode = 62;
Chris Lattnerdee199f2005-05-06 22:34:01 +0000627 } else if (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile()) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000628 Opcode = 63;
Chris Lattnerdee199f2005-05-06 22:34:01 +0000629 }
Reid Spencerad89bd62004-07-25 18:07:36 +0000630
631 // Figure out which type to encode with the instruction. Typically we want
632 // the type of the first parameter, as opposed to the type of the instruction
633 // (for example, with setcc, we always know it returns bool, but the type of
634 // the first param is actually interesting). But if we have no arguments
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000635 // we take the type of the instruction itself.
Reid Spencerad89bd62004-07-25 18:07:36 +0000636 //
637 const Type *Ty;
638 switch (I.getOpcode()) {
639 case Instruction::Select:
640 case Instruction::Malloc:
641 case Instruction::Alloca:
642 Ty = I.getType(); // These ALWAYS want to encode the return type
643 break;
644 case Instruction::Store:
645 Ty = I.getOperand(1)->getType(); // Encode the pointer type...
646 assert(isa<PointerType>(Ty) && "Store to nonpointer type!?!?");
647 break;
648 default: // Otherwise use the default behavior...
649 Ty = NumOperands ? I.getOperand(0)->getType() : I.getType();
650 break;
651 }
652
653 unsigned Type;
654 int Slot = Table.getSlot(Ty);
655 assert(Slot != -1 && "Type not available!!?!");
656 Type = (unsigned)Slot;
657
658 // Varargs calls and invokes are encoded entirely different from any other
659 // instructions.
660 if (const CallInst *CI = dyn_cast<CallInst>(&I)){
661 const PointerType *Ty =cast<PointerType>(CI->getCalledValue()->getType());
662 if (cast<FunctionType>(Ty->getElementType())->isVarArg()) {
663 outputInstrVarArgsCall(CI, Opcode, Table, Type);
664 return;
665 }
666 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
667 const PointerType *Ty =cast<PointerType>(II->getCalledValue()->getType());
668 if (cast<FunctionType>(Ty->getElementType())->isVarArg()) {
669 outputInstrVarArgsCall(II, Opcode, Table, Type);
670 return;
671 }
672 }
673
674 if (NumOperands <= 3) {
675 // Make sure that we take the type number into consideration. We don't want
676 // to overflow the field size for the instruction format we select.
677 //
678 unsigned MaxOpSlot = Type;
679 unsigned Slots[3]; Slots[0] = (1 << 12)-1; // Marker to signify 0 operands
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000680
Reid Spencerad89bd62004-07-25 18:07:36 +0000681 for (unsigned i = 0; i != NumOperands; ++i) {
682 int slot = Table.getSlot(I.getOperand(i));
683 assert(slot != -1 && "Broken bytecode!");
684 if (unsigned(slot) > MaxOpSlot) MaxOpSlot = unsigned(slot);
685 Slots[i] = unsigned(slot);
686 }
687
688 // Handle the special cases for various instructions...
689 if (isa<CastInst>(I) || isa<VAArgInst>(I)) {
690 // Cast has to encode the destination type as the second argument in the
691 // packet, or else we won't know what type to cast to!
692 Slots[1] = Table.getSlot(I.getType());
693 assert(Slots[1] != ~0U && "Cast return type unknown?");
694 if (Slots[1] > MaxOpSlot) MaxOpSlot = Slots[1];
695 NumOperands++;
Reid Spencerad89bd62004-07-25 18:07:36 +0000696 } else if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&I)) {
697 // We need to encode the type of sequential type indices into their slot #
698 unsigned Idx = 1;
699 for (gep_type_iterator I = gep_type_begin(GEP), E = gep_type_end(GEP);
700 I != E; ++I, ++Idx)
701 if (isa<SequentialType>(*I)) {
702 unsigned IdxId;
703 switch (GEP->getOperand(Idx)->getType()->getTypeID()) {
704 default: assert(0 && "Unknown index type!");
705 case Type::UIntTyID: IdxId = 0; break;
706 case Type::IntTyID: IdxId = 1; break;
707 case Type::ULongTyID: IdxId = 2; break;
708 case Type::LongTyID: IdxId = 3; break;
709 }
710 Slots[Idx] = (Slots[Idx] << 2) | IdxId;
711 if (Slots[Idx] > MaxOpSlot) MaxOpSlot = Slots[Idx];
712 }
Chris Lattnerdee199f2005-05-06 22:34:01 +0000713 } else if (Opcode == 58) {
714 // If this is the escape sequence for call, emit the tailcall/cc info.
715 const CallInst &CI = cast<CallInst>(I);
716 ++NumOperands;
717 if (NumOperands < 3) {
Jeff Cohen39cef602005-05-07 02:44:04 +0000718 Slots[NumOperands-1] = (CI.getCallingConv() << 1)|unsigned(CI.isTailCall());
Chris Lattnerdee199f2005-05-06 22:34:01 +0000719 if (Slots[NumOperands-1] > MaxOpSlot)
720 MaxOpSlot = Slots[NumOperands-1];
721 }
722 } else if (Opcode == 56) {
723 // Invoke escape seq has at least 4 operands to encode.
724 ++NumOperands;
Reid Spencerad89bd62004-07-25 18:07:36 +0000725 }
726
727 // Decide which instruction encoding to use. This is determined primarily
728 // by the number of operands, and secondarily by whether or not the max
729 // operand will fit into the instruction encoding. More operands == fewer
730 // bits per operand.
731 //
732 switch (NumOperands) {
733 case 0:
734 case 1:
735 if (MaxOpSlot < (1 << 12)-1) { // -1 because we use 4095 to indicate 0 ops
736 outputInstructionFormat1(&I, Opcode, Slots, Type);
737 return;
738 }
739 break;
740
741 case 2:
742 if (MaxOpSlot < (1 << 8)) {
743 outputInstructionFormat2(&I, Opcode, Slots, Type);
744 return;
745 }
746 break;
747
748 case 3:
749 if (MaxOpSlot < (1 << 6)) {
750 outputInstructionFormat3(&I, Opcode, Slots, Type);
751 return;
752 }
753 break;
754 default:
755 break;
756 }
757 }
758
759 // If we weren't handled before here, we either have a large number of
760 // operands or a large operand index that we are referring to.
761 outputInstructionFormat0(&I, Opcode, Table, Type);
762}
763
764//===----------------------------------------------------------------------===//
765//=== Block Output ===//
766//===----------------------------------------------------------------------===//
767
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000768BytecodeWriter::BytecodeWriter(std::vector<unsigned char> &o, const Module *M)
Reid Spencer798ff642004-05-26 07:37:11 +0000769 : Out(o), Table(M) {
Chris Lattner00950542001-06-06 20:29:01 +0000770
Chris Lattner83bb3d22004-01-14 23:36:54 +0000771 // Emit the signature...
772 static const unsigned char *Sig = (const unsigned char*)"llvm";
Reid Spencerad89bd62004-07-25 18:07:36 +0000773 output_data(Sig, Sig+4);
Chris Lattner00950542001-06-06 20:29:01 +0000774
775 // Emit the top level CLASS block.
Reid Spencerad89bd62004-07-25 18:07:36 +0000776 BytecodeBlock ModuleBlock(BytecodeFormat::ModuleBlockID, *this, false, true);
Chris Lattner00950542001-06-06 20:29:01 +0000777
Chris Lattnerd445c6b2003-08-24 13:47:36 +0000778 bool isBigEndian = M->getEndianness() == Module::BigEndian;
779 bool hasLongPointers = M->getPointerSize() == Module::Pointer64;
780 bool hasNoEndianness = M->getEndianness() == Module::AnyEndianness;
781 bool hasNoPointerSize = M->getPointerSize() == Module::AnyPointerSize;
Chris Lattner186a1f72003-03-19 20:56:46 +0000782
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000783 // Output the version identifier and other information.
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000784 unsigned Version = (BCVersionNum << 4) |
Reid Spencer38d54be2004-08-17 07:45:14 +0000785 (unsigned)isBigEndian | (hasLongPointers << 1) |
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000786 (hasNoEndianness << 2) |
Reid Spencer38d54be2004-08-17 07:45:14 +0000787 (hasNoPointerSize << 3);
Reid Spencerad89bd62004-07-25 18:07:36 +0000788 output_vbr(Version);
Chris Lattner00950542001-06-06 20:29:01 +0000789
Reid Spencercb3595c2004-07-04 11:45:47 +0000790 // The Global type plane comes first
Chris Lattner186a1f72003-03-19 20:56:46 +0000791 {
Reid Spencerad89bd62004-07-25 18:07:36 +0000792 BytecodeBlock CPool(BytecodeFormat::GlobalTypePlaneBlockID, *this );
Reid Spencercb3595c2004-07-04 11:45:47 +0000793 outputTypes(Type::FirstDerivedTyID);
Chris Lattner186a1f72003-03-19 20:56:46 +0000794 }
Chris Lattner00950542001-06-06 20:29:01 +0000795
Chris Lattner186a1f72003-03-19 20:56:46 +0000796 // The ModuleInfoBlock follows directly after the type information
Chris Lattnere8fdde12001-09-07 16:39:41 +0000797 outputModuleInfoBlock(M);
798
Chris Lattner186a1f72003-03-19 20:56:46 +0000799 // Output module level constants, used for global variable initializers
800 outputConstants(false);
801
Chris Lattnerb5794002002-04-07 22:49:37 +0000802 // Do the whole module now! Process each function at a time...
Chris Lattner0b12b5f2002-06-25 16:13:21 +0000803 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
Chris Lattner186a1f72003-03-19 20:56:46 +0000804 outputFunction(I);
Chris Lattnere8fdde12001-09-07 16:39:41 +0000805
806 // If needed, output the symbol table for the module...
Chris Lattner6e6026b2002-11-20 18:36:02 +0000807 outputSymbolTable(M->getSymbolTable());
Chris Lattner00950542001-06-06 20:29:01 +0000808}
809
Chris Lattnerf9d71782004-10-14 01:46:07 +0000810void BytecodeWriter::outputTypes(unsigned TypeNum) {
Reid Spencercb3595c2004-07-04 11:45:47 +0000811 // Write the type plane for types first because earlier planes (e.g. for a
812 // primitive type like float) may have constants constructed using types
813 // coming later (e.g., via getelementptr from a pointer type). The type
814 // plane is needed before types can be fwd or bkwd referenced.
815 const std::vector<const Type*>& Types = Table.getTypes();
816 assert(!Types.empty() && "No types at all?");
817 assert(TypeNum <= Types.size() && "Invalid TypeNo index");
818
819 unsigned NumEntries = Types.size() - TypeNum;
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000820
Reid Spencercb3595c2004-07-04 11:45:47 +0000821 // Output type header: [num entries]
Reid Spencerad89bd62004-07-25 18:07:36 +0000822 output_vbr(NumEntries);
Reid Spencercb3595c2004-07-04 11:45:47 +0000823
824 for (unsigned i = TypeNum; i < TypeNum+NumEntries; ++i)
825 outputType(Types[i]);
826}
827
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000828// Helper function for outputConstants().
829// Writes out all the constants in the plane Plane starting at entry StartNo.
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000830//
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000831void BytecodeWriter::outputConstantsInPlane(const std::vector<const Value*>
832 &Plane, unsigned StartNo) {
833 unsigned ValNo = StartNo;
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000834
Chris Lattner83bb3d22004-01-14 23:36:54 +0000835 // Scan through and ignore function arguments, global values, and constant
836 // strings.
837 for (; ValNo < Plane.size() &&
838 (isa<Argument>(Plane[ValNo]) || isa<GlobalValue>(Plane[ValNo]) ||
839 (isa<ConstantArray>(Plane[ValNo]) &&
840 cast<ConstantArray>(Plane[ValNo])->isString())); ValNo++)
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000841 /*empty*/;
842
843 unsigned NC = ValNo; // Number of constants
Reid Spencercb3595c2004-07-04 11:45:47 +0000844 for (; NC < Plane.size() && (isa<Constant>(Plane[NC])); NC++)
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000845 /*empty*/;
846 NC -= ValNo; // Convert from index into count
847 if (NC == 0) return; // Skip empty type planes...
848
Chris Lattnerd6942d72004-01-14 16:54:21 +0000849 // FIXME: Most slabs only have 1 or 2 entries! We should encode this much
850 // more compactly.
851
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000852 // Output type header: [num entries][type id number]
853 //
Reid Spencerad89bd62004-07-25 18:07:36 +0000854 output_vbr(NC);
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000855
856 // Output the Type ID Number...
Alkis Evlogimenos60596382003-10-17 02:02:40 +0000857 int Slot = Table.getSlot(Plane.front()->getType());
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000858 assert (Slot != -1 && "Type in constant pool but not in function!!");
Reid Spencerad89bd62004-07-25 18:07:36 +0000859 output_typeid((unsigned)Slot);
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000860
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000861 for (unsigned i = ValNo; i < ValNo+NC; ++i) {
862 const Value *V = Plane[i];
Reid Spencere0125b62004-07-18 00:16:21 +0000863 if (const Constant *C = dyn_cast<Constant>(V)) {
864 outputConstant(C);
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000865 }
866 }
867}
868
Chris Lattner9e60d8d2005-05-05 22:21:19 +0000869static inline bool hasNullValue(const Type *Ty) {
870 return Ty != Type::LabelTy && Ty != Type::VoidTy && !isa<OpaqueType>(Ty);
Chris Lattner80b97342004-01-17 23:25:43 +0000871}
872
Chris Lattner79df7c02002-03-26 18:01:55 +0000873void BytecodeWriter::outputConstants(bool isFunction) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000874 BytecodeBlock CPool(BytecodeFormat::ConstantPoolBlockID, *this,
Chris Lattner0baa0af2004-01-15 21:06:57 +0000875 true /* Elide block if empty */);
Chris Lattner00950542001-06-06 20:29:01 +0000876
877 unsigned NumPlanes = Table.getNumPlanes();
Chris Lattnerf69315b2003-05-22 18:35:38 +0000878
Reid Spencere0125b62004-07-18 00:16:21 +0000879 if (isFunction)
880 // Output the type plane before any constants!
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000881 outputTypes(Table.getModuleTypeLevel());
Reid Spencere0125b62004-07-18 00:16:21 +0000882 else
Chris Lattnerf9d71782004-10-14 01:46:07 +0000883 // Output module-level string constants before any other constants.
Chris Lattner83bb3d22004-01-14 23:36:54 +0000884 outputConstantStrings();
885
Reid Spencercb3595c2004-07-04 11:45:47 +0000886 for (unsigned pno = 0; pno != NumPlanes; pno++) {
887 const std::vector<const Value*> &Plane = Table.getPlane(pno);
888 if (!Plane.empty()) { // Skip empty type planes...
889 unsigned ValNo = 0;
890 if (isFunction) // Don't re-emit module constants
Reid Spencer0852c802004-07-04 11:46:15 +0000891 ValNo += Table.getModuleLevel(pno);
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000892
Chris Lattner9e60d8d2005-05-05 22:21:19 +0000893 if (hasNullValue(Plane[0]->getType())) {
Reid Spencer0852c802004-07-04 11:46:15 +0000894 // Skip zero initializer
895 if (ValNo == 0)
896 ValNo = 1;
Chris Lattnerf69315b2003-05-22 18:35:38 +0000897 }
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000898
Reid Spencercb3595c2004-07-04 11:45:47 +0000899 // Write out constants in the plane
900 outputConstantsInPlane(Plane, ValNo);
Chris Lattnerf69315b2003-05-22 18:35:38 +0000901 }
Reid Spencercb3595c2004-07-04 11:45:47 +0000902 }
Chris Lattner00950542001-06-06 20:29:01 +0000903}
904
Chris Lattner6b252422003-10-16 18:28:50 +0000905static unsigned getEncodedLinkage(const GlobalValue *GV) {
906 switch (GV->getLinkage()) {
907 default: assert(0 && "Invalid linkage!");
908 case GlobalValue::ExternalLinkage: return 0;
Chris Lattner6b252422003-10-16 18:28:50 +0000909 case GlobalValue::WeakLinkage: return 1;
910 case GlobalValue::AppendingLinkage: return 2;
911 case GlobalValue::InternalLinkage: return 3;
Chris Lattner22482a12003-10-18 06:30:21 +0000912 case GlobalValue::LinkOnceLinkage: return 4;
Chris Lattner6b252422003-10-16 18:28:50 +0000913 }
914}
915
Chris Lattner00950542001-06-06 20:29:01 +0000916void BytecodeWriter::outputModuleInfoBlock(const Module *M) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000917 BytecodeBlock ModuleInfoBlock(BytecodeFormat::ModuleGlobalInfoBlockID, *this);
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000918
Chris Lattner70cc3392001-09-10 07:58:01 +0000919 // Output the types for the global variables in the module...
Chris Lattner28caccf2005-05-06 20:27:03 +0000920 for (Module::const_global_iterator I = M->global_begin(),
921 End = M->global_end(); I != End;++I) {
Alkis Evlogimenos60596382003-10-17 02:02:40 +0000922 int Slot = Table.getSlot(I->getType());
Chris Lattner70cc3392001-09-10 07:58:01 +0000923 assert(Slot != -1 && "Module global vars is broken!");
Chris Lattnerd70684f2001-09-18 04:01:05 +0000924
Chris Lattner22482a12003-10-18 06:30:21 +0000925 // Fields: bit0 = isConstant, bit1 = hasInitializer, bit2-4=Linkage,
926 // bit5+ = Slot # for type
Chris Lattnerf74acc72004-10-14 02:31:35 +0000927 unsigned oSlot = ((unsigned)Slot << 5) | (getEncodedLinkage(I) << 2) |
Chris Lattner036de032004-06-25 20:52:10 +0000928 (I->hasInitializer() << 1) | (unsigned)I->isConstant();
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000929 output_vbr(oSlot);
Chris Lattnerd70684f2001-09-18 04:01:05 +0000930
Chris Lattner1b98c5c2001-10-13 06:48:38 +0000931 // If we have an initializer, output it now.
Chris Lattner0b12b5f2002-06-25 16:13:21 +0000932 if (I->hasInitializer()) {
Alkis Evlogimenos60596382003-10-17 02:02:40 +0000933 Slot = Table.getSlot((Value*)I->getInitializer());
Chris Lattnerd70684f2001-09-18 04:01:05 +0000934 assert(Slot != -1 && "No slot for global var initializer!");
Reid Spencerad89bd62004-07-25 18:07:36 +0000935 output_vbr((unsigned)Slot);
Chris Lattnerd70684f2001-09-18 04:01:05 +0000936 }
Chris Lattner70cc3392001-09-10 07:58:01 +0000937 }
Reid Spencerad89bd62004-07-25 18:07:36 +0000938 output_typeid((unsigned)Table.getSlot(Type::VoidTy));
Chris Lattner70cc3392001-09-10 07:58:01 +0000939
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000940 // Output the types of the functions in this module.
Chris Lattner7fc9fe32001-06-27 23:41:11 +0000941 for (Module::const_iterator I = M->begin(), End = M->end(); I != End; ++I) {
Alkis Evlogimenos60596382003-10-17 02:02:40 +0000942 int Slot = Table.getSlot(I->getType());
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000943 assert(Slot != -1 && "Module slot calculator is broken!");
Chris Lattner00950542001-06-06 20:29:01 +0000944 assert(Slot >= Type::FirstDerivedTyID && "Derived type not in range!");
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000945 assert(((Slot << 5) >> 5) == Slot && "Slot # too big!");
Chris Lattner479ffeb2005-05-06 20:42:57 +0000946 unsigned ID = (Slot << 5);
947
948 if (I->getCallingConv() < 15)
949 ID += I->getCallingConv()+1;
950
Chris Lattnerd6e431f2004-11-15 22:39:49 +0000951 if (I->isExternal()) // If external, we don't have an FunctionInfo block.
952 ID |= 1 << 4;
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000953 output_vbr(ID);
Chris Lattner479ffeb2005-05-06 20:42:57 +0000954
955 if (I->getCallingConv() >= 15)
956 output_vbr(I->getCallingConv());
Chris Lattner00950542001-06-06 20:29:01 +0000957 }
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000958 output_vbr((unsigned)Table.getSlot(Type::VoidTy) << 5);
Reid Spencerad89bd62004-07-25 18:07:36 +0000959
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000960 // Emit the list of dependent libraries for the Module.
Reid Spencer5ac88122004-07-25 21:32:02 +0000961 Module::lib_iterator LI = M->lib_begin();
962 Module::lib_iterator LE = M->lib_end();
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000963 output_vbr(unsigned(LE - LI)); // Emit the number of dependent libraries.
964 for (; LI != LE; ++LI)
Reid Spencer38d54be2004-08-17 07:45:14 +0000965 output(*LI);
Reid Spencerad89bd62004-07-25 18:07:36 +0000966
967 // Output the target triple from the module
Reid Spencer38d54be2004-08-17 07:45:14 +0000968 output(M->getTargetTriple());
Chris Lattner00950542001-06-06 20:29:01 +0000969}
970
Chris Lattnercf3e67f2004-01-18 21:08:52 +0000971void BytecodeWriter::outputInstructions(const Function *F) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000972 BytecodeBlock ILBlock(BytecodeFormat::InstructionListBlockID, *this);
Chris Lattnercf3e67f2004-01-18 21:08:52 +0000973 for (Function::const_iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
974 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I)
975 outputInstruction(*I);
Chris Lattnercf3e67f2004-01-18 21:08:52 +0000976}
977
Chris Lattner186a1f72003-03-19 20:56:46 +0000978void BytecodeWriter::outputFunction(const Function *F) {
Chris Lattnerfd7f8fe2004-11-15 21:56:33 +0000979 // If this is an external function, there is nothing else to emit!
980 if (F->isExternal()) return;
981
Chris Lattnerd6e431f2004-11-15 22:39:49 +0000982 BytecodeBlock FunctionBlock(BytecodeFormat::FunctionBlockID, *this);
983 output_vbr(getEncodedLinkage(F));
984
Chris Lattnercf3e67f2004-01-18 21:08:52 +0000985 // Get slot information about the function...
986 Table.incorporateFunction(F);
987
988 if (Table.getCompactionTable().empty()) {
989 // Output information about the constants in the function if the compaction
990 // table is not being used.
Chris Lattnere8fdde12001-09-07 16:39:41 +0000991 outputConstants(true);
Chris Lattnercf3e67f2004-01-18 21:08:52 +0000992 } else {
993 // Otherwise, emit the compaction table.
994 outputCompactionTable();
Chris Lattnere8fdde12001-09-07 16:39:41 +0000995 }
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000996
Chris Lattnercf3e67f2004-01-18 21:08:52 +0000997 // Output all of the instructions in the body of the function
998 outputInstructions(F);
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000999
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001000 // If needed, output the symbol table for the function...
1001 outputSymbolTable(F->getSymbolTable());
Misha Brukman23c6d2c2005-04-21 21:48:46 +00001002
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001003 Table.purgeFunction();
1004}
1005
1006void BytecodeWriter::outputCompactionTablePlane(unsigned PlaneNo,
1007 const std::vector<const Value*> &Plane,
1008 unsigned StartNo) {
1009 unsigned End = Table.getModuleLevel(PlaneNo);
Chris Lattner52f86d62004-01-20 00:54:06 +00001010 if (Plane.empty() || StartNo == End || End == 0) return; // Nothing to emit
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001011 assert(StartNo < End && "Cannot emit negative range!");
1012 assert(StartNo < Plane.size() && End <= Plane.size());
1013
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001014 // Do not emit the null initializer!
Reid Spencercb3595c2004-07-04 11:45:47 +00001015 ++StartNo;
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001016
Chris Lattner24102432004-01-18 22:35:34 +00001017 // Figure out which encoding to use. By far the most common case we have is
1018 // to emit 0-2 entries in a compaction table plane.
1019 switch (End-StartNo) {
1020 case 0: // Avoid emitting two vbr's if possible.
1021 case 1:
1022 case 2:
Reid Spencerad89bd62004-07-25 18:07:36 +00001023 output_vbr((PlaneNo << 2) | End-StartNo);
Chris Lattner24102432004-01-18 22:35:34 +00001024 break;
1025 default:
1026 // Output the number of things.
Reid Spencerad89bd62004-07-25 18:07:36 +00001027 output_vbr((unsigned(End-StartNo) << 2) | 3);
1028 output_typeid(PlaneNo); // Emit the type plane this is
Chris Lattner24102432004-01-18 22:35:34 +00001029 break;
1030 }
1031
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001032 for (unsigned i = StartNo; i != End; ++i)
Reid Spencerad89bd62004-07-25 18:07:36 +00001033 output_vbr(Table.getGlobalSlot(Plane[i]));
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001034}
1035
Reid Spencercb3595c2004-07-04 11:45:47 +00001036void BytecodeWriter::outputCompactionTypes(unsigned StartNo) {
1037 // Get the compaction type table from the slot calculator
1038 const std::vector<const Type*> &CTypes = Table.getCompactionTypes();
1039
1040 // The compaction types may have been uncompactified back to the
1041 // global types. If so, we just write an empty table
1042 if (CTypes.size() == 0 ) {
Reid Spencerad89bd62004-07-25 18:07:36 +00001043 output_vbr(0U);
Reid Spencercb3595c2004-07-04 11:45:47 +00001044 return;
1045 }
1046
1047 assert(CTypes.size() >= StartNo && "Invalid compaction types start index");
1048
1049 // Determine how many types to write
1050 unsigned NumTypes = CTypes.size() - StartNo;
1051
1052 // Output the number of types.
Reid Spencerad89bd62004-07-25 18:07:36 +00001053 output_vbr(NumTypes);
Reid Spencercb3595c2004-07-04 11:45:47 +00001054
1055 for (unsigned i = StartNo; i < StartNo+NumTypes; ++i)
Reid Spencerad89bd62004-07-25 18:07:36 +00001056 output_typeid(Table.getGlobalSlot(CTypes[i]));
Reid Spencercb3595c2004-07-04 11:45:47 +00001057}
1058
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001059void BytecodeWriter::outputCompactionTable() {
Reid Spencer0033c182004-08-27 00:38:44 +00001060 // Avoid writing the compaction table at all if there is no content.
1061 if (Table.getCompactionTypes().size() >= Type::FirstDerivedTyID ||
1062 (!Table.CompactionTableIsEmpty())) {
Misha Brukman23c6d2c2005-04-21 21:48:46 +00001063 BytecodeBlock CTB(BytecodeFormat::CompactionTableBlockID, *this,
Reid Spencer0033c182004-08-27 00:38:44 +00001064 true/*ElideIfEmpty*/);
Chris Lattnerf9d71782004-10-14 01:46:07 +00001065 const std::vector<std::vector<const Value*> > &CT =
1066 Table.getCompactionTable();
Misha Brukman23c6d2c2005-04-21 21:48:46 +00001067
Reid Spencer0033c182004-08-27 00:38:44 +00001068 // First things first, emit the type compaction table if there is one.
1069 outputCompactionTypes(Type::FirstDerivedTyID);
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001070
Reid Spencer0033c182004-08-27 00:38:44 +00001071 for (unsigned i = 0, e = CT.size(); i != e; ++i)
1072 outputCompactionTablePlane(i, CT[i], 0);
1073 }
Chris Lattner00950542001-06-06 20:29:01 +00001074}
1075
Chris Lattner00950542001-06-06 20:29:01 +00001076void BytecodeWriter::outputSymbolTable(const SymbolTable &MST) {
Chris Lattner737d3cd2004-01-10 19:56:59 +00001077 // Do not output the Bytecode block for an empty symbol table, it just wastes
1078 // space!
Chris Lattnerf9d71782004-10-14 01:46:07 +00001079 if (MST.isEmpty()) return;
Chris Lattner737d3cd2004-01-10 19:56:59 +00001080
Reid Spencerad89bd62004-07-25 18:07:36 +00001081 BytecodeBlock SymTabBlock(BytecodeFormat::SymbolTableBlockID, *this,
Chris Lattnerf9d71782004-10-14 01:46:07 +00001082 true/*ElideIfEmpty*/);
Chris Lattner00950542001-06-06 20:29:01 +00001083
Misha Brukman23c6d2c2005-04-21 21:48:46 +00001084 // Write the number of types
Reid Spencerad89bd62004-07-25 18:07:36 +00001085 output_vbr(MST.num_types());
Reid Spencer250c4182004-08-17 02:59:02 +00001086
1087 // Write each of the types
Reid Spencer94f2df22004-05-25 17:29:59 +00001088 for (SymbolTable::type_const_iterator TI = MST.type_begin(),
1089 TE = MST.type_end(); TI != TE; ++TI ) {
Reid Spencer250c4182004-08-17 02:59:02 +00001090 // Symtab entry:[def slot #][name]
Reid Spencerad89bd62004-07-25 18:07:36 +00001091 output_typeid((unsigned)Table.getSlot(TI->second));
Misha Brukman23c6d2c2005-04-21 21:48:46 +00001092 output(TI->first);
Reid Spencer94f2df22004-05-25 17:29:59 +00001093 }
1094
1095 // Now do each of the type planes in order.
Misha Brukman23c6d2c2005-04-21 21:48:46 +00001096 for (SymbolTable::plane_const_iterator PI = MST.plane_begin(),
Reid Spencer94f2df22004-05-25 17:29:59 +00001097 PE = MST.plane_end(); PI != PE; ++PI) {
1098 SymbolTable::value_const_iterator I = MST.value_begin(PI->first);
1099 SymbolTable::value_const_iterator End = MST.value_end(PI->first);
Chris Lattner00950542001-06-06 20:29:01 +00001100 int Slot;
Misha Brukman23c6d2c2005-04-21 21:48:46 +00001101
Chris Lattner00950542001-06-06 20:29:01 +00001102 if (I == End) continue; // Don't mess with an absent type...
1103
Reid Spencer250c4182004-08-17 02:59:02 +00001104 // Write the number of values in this plane
Chris Lattner001d16a2005-03-07 02:59:36 +00001105 output_vbr((unsigned)PI->second.size());
Chris Lattner00950542001-06-06 20:29:01 +00001106
Reid Spencer250c4182004-08-17 02:59:02 +00001107 // Write the slot number of the type for this plane
Reid Spencer94f2df22004-05-25 17:29:59 +00001108 Slot = Table.getSlot(PI->first);
Chris Lattner00950542001-06-06 20:29:01 +00001109 assert(Slot != -1 && "Type in symtab, but not in table!");
Reid Spencerad89bd62004-07-25 18:07:36 +00001110 output_typeid((unsigned)Slot);
Chris Lattner00950542001-06-06 20:29:01 +00001111
Reid Spencer250c4182004-08-17 02:59:02 +00001112 // Write each of the values in this plane
Chris Lattner7fc9fe32001-06-27 23:41:11 +00001113 for (; I != End; ++I) {
Chris Lattner00950542001-06-06 20:29:01 +00001114 // Symtab entry: [def slot #][name]
Alkis Evlogimenos60596382003-10-17 02:02:40 +00001115 Slot = Table.getSlot(I->second);
Chris Lattnere8fdde12001-09-07 16:39:41 +00001116 assert(Slot != -1 && "Value in symtab but has no slot number!!");
Reid Spencerad89bd62004-07-25 18:07:36 +00001117 output_vbr((unsigned)Slot);
Reid Spencer38d54be2004-08-17 07:45:14 +00001118 output(I->first);
Chris Lattner00950542001-06-06 20:29:01 +00001119 }
1120 }
1121}
1122
Reid Spencer17f52c52004-11-06 23:17:23 +00001123void llvm::WriteBytecodeToFile(const Module *M, std::ostream &Out,
1124 bool compress ) {
Reid Spencerad89bd62004-07-25 18:07:36 +00001125 assert(M && "You can't write a null module!!");
Chris Lattner00950542001-06-06 20:29:01 +00001126
Reid Spencer17f52c52004-11-06 23:17:23 +00001127 // Create a vector of unsigned char for the bytecode output. We
1128 // reserve 256KBytes of space in the vector so that we avoid doing
1129 // lots of little allocations. 256KBytes is sufficient for a large
1130 // proportion of the bytecode files we will encounter. Larger files
1131 // will be automatically doubled in size as needed (std::vector
1132 // behavior).
Reid Spencerad89bd62004-07-25 18:07:36 +00001133 std::vector<unsigned char> Buffer;
Reid Spencer17f52c52004-11-06 23:17:23 +00001134 Buffer.reserve(256 * 1024);
Chris Lattner00950542001-06-06 20:29:01 +00001135
Reid Spencer17f52c52004-11-06 23:17:23 +00001136 // The BytecodeWriter populates Buffer for us.
Reid Spencerad89bd62004-07-25 18:07:36 +00001137 BytecodeWriter BCW(Buffer, M);
Chris Lattner00950542001-06-06 20:29:01 +00001138
Reid Spencer17f52c52004-11-06 23:17:23 +00001139 // Keep track of how much we've written
Chris Lattnerce6ef112002-07-26 18:40:14 +00001140 BytesWritten += Buffer.size();
1141
Reid Spencer17f52c52004-11-06 23:17:23 +00001142 // Determine start and end points of the Buffer
Reid Spencer83296f52004-11-07 18:17:38 +00001143 const unsigned char *FirstByte = &Buffer.front();
Reid Spencer17f52c52004-11-06 23:17:23 +00001144
1145 // If we're supposed to compress this mess ...
1146 if (compress) {
1147
1148 // We signal compression by using an alternate magic number for the
Reid Spencer83296f52004-11-07 18:17:38 +00001149 // file. The compressed bytecode file's magic number is "llvc" instead
Misha Brukman23c6d2c2005-04-21 21:48:46 +00001150 // of "llvm".
Reid Spencer83296f52004-11-07 18:17:38 +00001151 char compressed_magic[4];
1152 compressed_magic[0] = 'l';
1153 compressed_magic[1] = 'l';
1154 compressed_magic[2] = 'v';
1155 compressed_magic[3] = 'c';
Reid Spencer17f52c52004-11-06 23:17:23 +00001156
Reid Spencer83296f52004-11-07 18:17:38 +00001157 Out.write(compressed_magic,4);
Reid Spencer17f52c52004-11-06 23:17:23 +00001158
Reid Spencera70d84d2004-11-14 22:01:41 +00001159 // Compress everything after the magic number (which we altered)
1160 uint64_t zipSize = Compressor::compressToStream(
Reid Spencer17f52c52004-11-06 23:17:23 +00001161 (char*)(FirstByte+4), // Skip the magic number
1162 Buffer.size()-4, // Skip the magic number
Reid Spencer84472d62004-11-25 19:38:05 +00001163 Out // Where to write compressed data
Reid Spencer17f52c52004-11-06 23:17:23 +00001164 );
1165
Reid Spencer17f52c52004-11-06 23:17:23 +00001166 } else {
1167
1168 // We're not compressing, so just write the entire block.
Reid Spencer83296f52004-11-07 18:17:38 +00001169 Out.write((char*)FirstByte, Buffer.size());
Chris Lattnere8fdde12001-09-07 16:39:41 +00001170 }
Reid Spencer17f52c52004-11-06 23:17:23 +00001171
1172 // make sure it hits disk now
Chris Lattner00950542001-06-06 20:29:01 +00001173 Out.flush();
1174}
Reid Spencere0125b62004-07-18 00:16:21 +00001175