blob: fb5a1aa60317e710eb1605d75f1994b03d30ec8b [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"
Reid Spencer551ccae2004-09-01 22:55:40 +000030#include "llvm/ADT/STLExtras.h"
31#include "llvm/ADT/Statistic.h"
Chris Lattner32abce62004-01-10 19:10:01 +000032#include <cstring>
Chris Lattner00950542001-06-06 20:29:01 +000033#include <algorithm>
Chris Lattner44f549b2004-01-10 18:49:43 +000034using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000035
Reid Spencer38d54be2004-08-17 07:45:14 +000036/// This value needs to be incremented every time the bytecode format changes
37/// so that the reader can distinguish which format of the bytecode file has
38/// been written.
39/// @brief The bytecode version number
Chris Lattnera79e7cc2004-10-16 18:18:16 +000040const unsigned BCVersionNum = 5;
Reid Spencer38d54be2004-08-17 07:45:14 +000041
Chris Lattner635cd932002-07-23 19:56:44 +000042static RegisterPass<WriteBytecodePass> X("emitbytecode", "Bytecode Writer");
43
Misha Brukman23c6d2c2005-04-21 21:48:46 +000044static Statistic<>
Chris Lattnera92f6962002-10-01 22:38:41 +000045BytesWritten("bytecodewriter", "Number of bytecode bytes written");
Chris Lattner635cd932002-07-23 19:56:44 +000046
Reid Spencerad89bd62004-07-25 18:07:36 +000047//===----------------------------------------------------------------------===//
48//=== Output Primitives ===//
49//===----------------------------------------------------------------------===//
50
51// output - If a position is specified, it must be in the valid portion of the
Misha Brukman23c6d2c2005-04-21 21:48:46 +000052// string... note that this should be inlined always so only the relevant IF
Reid Spencerad89bd62004-07-25 18:07:36 +000053// body should be included.
54inline void BytecodeWriter::output(unsigned i, int pos) {
55 if (pos == -1) { // Be endian clean, little endian is our friend
Misha Brukman23c6d2c2005-04-21 21:48:46 +000056 Out.push_back((unsigned char)i);
Reid Spencerad89bd62004-07-25 18:07:36 +000057 Out.push_back((unsigned char)(i >> 8));
58 Out.push_back((unsigned char)(i >> 16));
59 Out.push_back((unsigned char)(i >> 24));
60 } else {
61 Out[pos ] = (unsigned char)i;
62 Out[pos+1] = (unsigned char)(i >> 8);
63 Out[pos+2] = (unsigned char)(i >> 16);
64 Out[pos+3] = (unsigned char)(i >> 24);
65 }
66}
67
68inline void BytecodeWriter::output(int i) {
69 output((unsigned)i);
70}
71
72/// output_vbr - Output an unsigned value, by using the least number of bytes
73/// possible. This is useful because many of our "infinite" values are really
74/// very small most of the time; but can be large a few times.
Misha Brukman23c6d2c2005-04-21 21:48:46 +000075/// Data format used: If you read a byte with the high bit set, use the low
76/// seven bits as data and then read another byte.
Reid Spencerad89bd62004-07-25 18:07:36 +000077inline void BytecodeWriter::output_vbr(uint64_t i) {
78 while (1) {
79 if (i < 0x80) { // done?
80 Out.push_back((unsigned char)i); // We know the high bit is clear...
81 return;
82 }
Misha Brukman23c6d2c2005-04-21 21:48:46 +000083
Reid Spencerad89bd62004-07-25 18:07:36 +000084 // Nope, we are bigger than a character, output the next 7 bits and set the
85 // high bit to say that there is more coming...
86 Out.push_back(0x80 | ((unsigned char)i & 0x7F));
87 i >>= 7; // Shift out 7 bits now...
88 }
89}
90
91inline void BytecodeWriter::output_vbr(unsigned i) {
92 while (1) {
93 if (i < 0x80) { // done?
94 Out.push_back((unsigned char)i); // We know the high bit is clear...
95 return;
96 }
Misha Brukman23c6d2c2005-04-21 21:48:46 +000097
Reid Spencerad89bd62004-07-25 18:07:36 +000098 // Nope, we are bigger than a character, output the next 7 bits and set the
99 // high bit to say that there is more coming...
100 Out.push_back(0x80 | ((unsigned char)i & 0x7F));
101 i >>= 7; // Shift out 7 bits now...
102 }
103}
104
105inline void BytecodeWriter::output_typeid(unsigned i) {
106 if (i <= 0x00FFFFFF)
107 this->output_vbr(i);
108 else {
109 this->output_vbr(0x00FFFFFF);
110 this->output_vbr(i);
111 }
112}
113
114inline void BytecodeWriter::output_vbr(int64_t i) {
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000115 if (i < 0)
Reid Spencerad89bd62004-07-25 18:07:36 +0000116 output_vbr(((uint64_t)(-i) << 1) | 1); // Set low order sign bit...
117 else
118 output_vbr((uint64_t)i << 1); // Low order bit is clear.
119}
120
121
122inline void BytecodeWriter::output_vbr(int i) {
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000123 if (i < 0)
Reid Spencerad89bd62004-07-25 18:07:36 +0000124 output_vbr(((unsigned)(-i) << 1) | 1); // Set low order sign bit...
125 else
126 output_vbr((unsigned)i << 1); // Low order bit is clear.
127}
128
Reid Spencer38d54be2004-08-17 07:45:14 +0000129inline void BytecodeWriter::output(const std::string &s) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000130 unsigned Len = s.length();
131 output_vbr(Len ); // Strings may have an arbitrary length...
132 Out.insert(Out.end(), s.begin(), s.end());
Reid Spencerad89bd62004-07-25 18:07:36 +0000133}
134
135inline void BytecodeWriter::output_data(const void *Ptr, const void *End) {
136 Out.insert(Out.end(), (const unsigned char*)Ptr, (const unsigned char*)End);
137}
138
139inline void BytecodeWriter::output_float(float& FloatVal) {
140 /// FIXME: This isn't optimal, it has size problems on some platforms
141 /// where FP is not IEEE.
142 union {
143 float f;
144 uint32_t i;
145 } FloatUnion;
146 FloatUnion.f = FloatVal;
147 Out.push_back( static_cast<unsigned char>( (FloatUnion.i & 0xFF )));
148 Out.push_back( static_cast<unsigned char>( (FloatUnion.i >> 8) & 0xFF));
149 Out.push_back( static_cast<unsigned char>( (FloatUnion.i >> 16) & 0xFF));
150 Out.push_back( static_cast<unsigned char>( (FloatUnion.i >> 24) & 0xFF));
151}
152
153inline void BytecodeWriter::output_double(double& DoubleVal) {
154 /// FIXME: This isn't optimal, it has size problems on some platforms
155 /// where FP is not IEEE.
156 union {
157 double d;
158 uint64_t i;
159 } DoubleUnion;
160 DoubleUnion.d = DoubleVal;
161 Out.push_back( static_cast<unsigned char>( (DoubleUnion.i & 0xFF )));
162 Out.push_back( static_cast<unsigned char>( (DoubleUnion.i >> 8) & 0xFF));
163 Out.push_back( static_cast<unsigned char>( (DoubleUnion.i >> 16) & 0xFF));
164 Out.push_back( static_cast<unsigned char>( (DoubleUnion.i >> 24) & 0xFF));
165 Out.push_back( static_cast<unsigned char>( (DoubleUnion.i >> 32) & 0xFF));
166 Out.push_back( static_cast<unsigned char>( (DoubleUnion.i >> 40) & 0xFF));
167 Out.push_back( static_cast<unsigned char>( (DoubleUnion.i >> 48) & 0xFF));
168 Out.push_back( static_cast<unsigned char>( (DoubleUnion.i >> 56) & 0xFF));
169}
170
171inline BytecodeBlock::BytecodeBlock(unsigned ID, BytecodeWriter& w,
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000172 bool elideIfEmpty, bool hasLongFormat )
Reid Spencerad89bd62004-07-25 18:07:36 +0000173 : Id(ID), Writer(w), ElideIfEmpty(elideIfEmpty), HasLongFormat(hasLongFormat){
174
175 if (HasLongFormat) {
176 w.output(ID);
177 w.output(0U); // For length in long format
178 } else {
179 w.output(0U); /// Place holder for ID and length for this block
180 }
181 Loc = w.size();
182}
183
Chris Lattnerb0bf6642004-10-14 01:35:17 +0000184inline BytecodeBlock::~BytecodeBlock() { // Do backpatch when block goes out
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000185 // of scope...
Reid Spencerad89bd62004-07-25 18:07:36 +0000186 if (Loc == Writer.size() && ElideIfEmpty) {
187 // If the block is empty, and we are allowed to, do not emit the block at
188 // all!
189 Writer.resize(Writer.size()-(HasLongFormat?8:4));
190 return;
191 }
192
Reid Spencerad89bd62004-07-25 18:07:36 +0000193 if (HasLongFormat)
194 Writer.output(unsigned(Writer.size()-Loc), int(Loc-4));
195 else
196 Writer.output(unsigned(Writer.size()-Loc) << 5 | (Id & 0x1F), int(Loc-4));
Reid Spencerad89bd62004-07-25 18:07:36 +0000197}
198
199//===----------------------------------------------------------------------===//
200//=== Constant Output ===//
201//===----------------------------------------------------------------------===//
202
203void BytecodeWriter::outputType(const Type *T) {
204 output_vbr((unsigned)T->getTypeID());
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000205
Reid Spencerad89bd62004-07-25 18:07:36 +0000206 // That's all there is to handling primitive types...
207 if (T->isPrimitiveType()) {
208 return; // We might do this if we alias a prim type: %x = type int
209 }
210
211 switch (T->getTypeID()) { // Handle derived types now.
212 case Type::FunctionTyID: {
213 const FunctionType *MT = cast<FunctionType>(T);
214 int Slot = Table.getSlot(MT->getReturnType());
215 assert(Slot != -1 && "Type used but not available!!");
216 output_typeid((unsigned)Slot);
217
218 // Output the number of arguments to function (+1 if varargs):
219 output_vbr((unsigned)MT->getNumParams()+MT->isVarArg());
220
221 // Output all of the arguments...
222 FunctionType::param_iterator I = MT->param_begin();
223 for (; I != MT->param_end(); ++I) {
224 Slot = Table.getSlot(*I);
225 assert(Slot != -1 && "Type used but not available!!");
226 output_typeid((unsigned)Slot);
227 }
228
229 // Terminate list with VoidTy if we are a varargs function...
230 if (MT->isVarArg())
231 output_typeid((unsigned)Type::VoidTyID);
232 break;
233 }
234
235 case Type::ArrayTyID: {
236 const ArrayType *AT = cast<ArrayType>(T);
237 int Slot = Table.getSlot(AT->getElementType());
238 assert(Slot != -1 && "Type used but not available!!");
239 output_typeid((unsigned)Slot);
Reid Spencerad89bd62004-07-25 18:07:36 +0000240 output_vbr(AT->getNumElements());
241 break;
242 }
243
Brian Gaeke715c90b2004-08-20 06:00:58 +0000244 case Type::PackedTyID: {
245 const PackedType *PT = cast<PackedType>(T);
246 int Slot = Table.getSlot(PT->getElementType());
247 assert(Slot != -1 && "Type used but not available!!");
248 output_typeid((unsigned)Slot);
249 output_vbr(PT->getNumElements());
250 break;
251 }
252
253
Reid Spencerad89bd62004-07-25 18:07:36 +0000254 case Type::StructTyID: {
255 const StructType *ST = cast<StructType>(T);
256
257 // Output all of the element types...
258 for (StructType::element_iterator I = ST->element_begin(),
259 E = ST->element_end(); I != E; ++I) {
260 int Slot = Table.getSlot(*I);
261 assert(Slot != -1 && "Type used but not available!!");
262 output_typeid((unsigned)Slot);
263 }
264
265 // Terminate list with VoidTy
266 output_typeid((unsigned)Type::VoidTyID);
267 break;
268 }
269
270 case Type::PointerTyID: {
271 const PointerType *PT = cast<PointerType>(T);
272 int Slot = Table.getSlot(PT->getElementType());
273 assert(Slot != -1 && "Type used but not available!!");
274 output_typeid((unsigned)Slot);
275 break;
276 }
277
Chris Lattnerb0bf6642004-10-14 01:35:17 +0000278 case Type::OpaqueTyID:
Reid Spencerad89bd62004-07-25 18:07:36 +0000279 // No need to emit anything, just the count of opaque types is enough.
280 break;
Reid Spencerad89bd62004-07-25 18:07:36 +0000281
Reid Spencerad89bd62004-07-25 18:07:36 +0000282 default:
283 std::cerr << __FILE__ << ":" << __LINE__ << ": Don't know how to serialize"
284 << " Type '" << T->getDescription() << "'\n";
285 break;
286 }
287}
288
289void BytecodeWriter::outputConstant(const Constant *CPV) {
290 assert((CPV->getType()->isPrimitiveType() || !CPV->isNullValue()) &&
291 "Shouldn't output null constants!");
292
293 // We must check for a ConstantExpr before switching by type because
294 // a ConstantExpr can be of any type, and has no explicit value.
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000295 //
Reid Spencerad89bd62004-07-25 18:07:36 +0000296 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
297 // FIXME: Encoding of constant exprs could be much more compact!
298 assert(CE->getNumOperands() > 0 && "ConstantExpr with 0 operands");
Chris Lattner129baf62004-12-04 21:28:47 +0000299 assert(CE->getNumOperands() != 1 || CE->getOpcode() == Instruction::Cast);
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000300 output_vbr(1+CE->getNumOperands()); // flags as an expr
Reid Spencerad89bd62004-07-25 18:07:36 +0000301 output_vbr(CE->getOpcode()); // flags as an expr
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000302
Reid Spencerad89bd62004-07-25 18:07:36 +0000303 for (User::const_op_iterator OI = CE->op_begin(); OI != CE->op_end(); ++OI){
304 int Slot = Table.getSlot(*OI);
305 assert(Slot != -1 && "Unknown constant used in ConstantExpr!!");
306 output_vbr((unsigned)Slot);
307 Slot = Table.getSlot((*OI)->getType());
308 output_typeid((unsigned)Slot);
309 }
310 return;
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000311 } else if (isa<UndefValue>(CPV)) {
312 output_vbr(1U); // 1 -> UndefValue constant.
313 return;
Reid Spencerad89bd62004-07-25 18:07:36 +0000314 } else {
315 output_vbr(0U); // flag as not a ConstantExpr
316 }
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000317
Reid Spencerad89bd62004-07-25 18:07:36 +0000318 switch (CPV->getType()->getTypeID()) {
319 case Type::BoolTyID: // Boolean Types
320 if (cast<ConstantBool>(CPV)->getValue())
321 output_vbr(1U);
322 else
323 output_vbr(0U);
324 break;
325
326 case Type::UByteTyID: // Unsigned integer types...
327 case Type::UShortTyID:
328 case Type::UIntTyID:
329 case Type::ULongTyID:
330 output_vbr(cast<ConstantUInt>(CPV)->getValue());
331 break;
332
333 case Type::SByteTyID: // Signed integer types...
334 case Type::ShortTyID:
335 case Type::IntTyID:
336 case Type::LongTyID:
337 output_vbr(cast<ConstantSInt>(CPV)->getValue());
338 break;
339
340 case Type::ArrayTyID: {
341 const ConstantArray *CPA = cast<ConstantArray>(CPV);
342 assert(!CPA->isString() && "Constant strings should be handled specially!");
343
Alkis Evlogimenos15876bb2004-08-04 08:44:43 +0000344 for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000345 int Slot = Table.getSlot(CPA->getOperand(i));
346 assert(Slot != -1 && "Constant used but not available!!");
347 output_vbr((unsigned)Slot);
348 }
349 break;
350 }
351
Brian Gaeke715c90b2004-08-20 06:00:58 +0000352 case Type::PackedTyID: {
353 const ConstantPacked *CP = cast<ConstantPacked>(CPV);
354
355 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i) {
356 int Slot = Table.getSlot(CP->getOperand(i));
357 assert(Slot != -1 && "Constant used but not available!!");
358 output_vbr((unsigned)Slot);
359 }
360 break;
361 }
362
Reid Spencerad89bd62004-07-25 18:07:36 +0000363 case Type::StructTyID: {
364 const ConstantStruct *CPS = cast<ConstantStruct>(CPV);
Reid Spencerad89bd62004-07-25 18:07:36 +0000365
Alkis Evlogimenos15876bb2004-08-04 08:44:43 +0000366 for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i) {
367 int Slot = Table.getSlot(CPS->getOperand(i));
Reid Spencerad89bd62004-07-25 18:07:36 +0000368 assert(Slot != -1 && "Constant used but not available!!");
369 output_vbr((unsigned)Slot);
370 }
371 break;
372 }
373
374 case Type::PointerTyID:
375 assert(0 && "No non-null, non-constant-expr constants allowed!");
376 abort();
377
378 case Type::FloatTyID: { // Floating point types...
379 float Tmp = (float)cast<ConstantFP>(CPV)->getValue();
380 output_float(Tmp);
381 break;
382 }
383 case Type::DoubleTyID: {
384 double Tmp = cast<ConstantFP>(CPV)->getValue();
385 output_double(Tmp);
386 break;
387 }
388
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000389 case Type::VoidTyID:
Reid Spencerad89bd62004-07-25 18:07:36 +0000390 case Type::LabelTyID:
391 default:
392 std::cerr << __FILE__ << ":" << __LINE__ << ": Don't know how to serialize"
393 << " type '" << *CPV->getType() << "'\n";
394 break;
395 }
396 return;
397}
398
399void BytecodeWriter::outputConstantStrings() {
400 SlotCalculator::string_iterator I = Table.string_begin();
401 SlotCalculator::string_iterator E = Table.string_end();
402 if (I == E) return; // No strings to emit
403
404 // If we have != 0 strings to emit, output them now. Strings are emitted into
405 // the 'void' type plane.
406 output_vbr(unsigned(E-I));
407 output_typeid(Type::VoidTyID);
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000408
Reid Spencerad89bd62004-07-25 18:07:36 +0000409 // Emit all of the strings.
410 for (I = Table.string_begin(); I != E; ++I) {
411 const ConstantArray *Str = *I;
412 int Slot = Table.getSlot(Str->getType());
413 assert(Slot != -1 && "Constant string of unknown type?");
414 output_typeid((unsigned)Slot);
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000415
Reid Spencerad89bd62004-07-25 18:07:36 +0000416 // Now that we emitted the type (which indicates the size of the string),
417 // emit all of the characters.
418 std::string Val = Str->getAsString();
419 output_data(Val.c_str(), Val.c_str()+Val.size());
420 }
421}
422
423//===----------------------------------------------------------------------===//
424//=== Instruction Output ===//
425//===----------------------------------------------------------------------===//
426typedef unsigned char uchar;
427
Chris Lattnerda895d62005-02-27 06:18:25 +0000428// outputInstructionFormat0 - Output those weird instructions that have a large
Chris Lattnerdee199f2005-05-06 22:34:01 +0000429// number of operands or have large operands themselves.
Reid Spencerad89bd62004-07-25 18:07:36 +0000430//
431// Format: [opcode] [type] [numargs] [arg0] [arg1] ... [arg<numargs-1>]
432//
Chris Lattnerf9d71782004-10-14 01:46:07 +0000433void BytecodeWriter::outputInstructionFormat0(const Instruction *I,
434 unsigned Opcode,
435 const SlotCalculator &Table,
436 unsigned Type) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000437 // Opcode must have top two bits clear...
438 output_vbr(Opcode << 2); // Instruction Opcode ID
439 output_typeid(Type); // Result type
440
441 unsigned NumArgs = I->getNumOperands();
442 output_vbr(NumArgs + (isa<CastInst>(I) || isa<VANextInst>(I) ||
Chris Lattnerdee199f2005-05-06 22:34:01 +0000443 isa<VAArgInst>(I) || Opcode == 56 || Opcode == 58));
Reid Spencerad89bd62004-07-25 18:07:36 +0000444
445 if (!isa<GetElementPtrInst>(&I)) {
446 for (unsigned i = 0; i < NumArgs; ++i) {
447 int Slot = Table.getSlot(I->getOperand(i));
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000448 assert(Slot >= 0 && "No slot number for value!?!?");
Reid Spencerad89bd62004-07-25 18:07:36 +0000449 output_vbr((unsigned)Slot);
450 }
451
452 if (isa<CastInst>(I) || isa<VAArgInst>(I)) {
453 int Slot = Table.getSlot(I->getType());
454 assert(Slot != -1 && "Cast return type unknown?");
455 output_typeid((unsigned)Slot);
456 } else if (const VANextInst *VAI = dyn_cast<VANextInst>(I)) {
457 int Slot = Table.getSlot(VAI->getArgType());
458 assert(Slot != -1 && "VarArg argument type unknown?");
459 output_typeid((unsigned)Slot);
Chris Lattnerdee199f2005-05-06 22:34:01 +0000460 } else if (Opcode == 56) { // Invoke escape sequence
461 output_vbr(cast<InvokeInst>(I)->getCallingConv());
462 } else if (Opcode == 58) { // Call escape sequence
463 output_vbr((cast<CallInst>(I)->getCallingConv() << 1) |
Jeff Cohen39cef602005-05-07 02:44:04 +0000464 unsigned(cast<CallInst>(I)->isTailCall()));
Reid Spencerad89bd62004-07-25 18:07:36 +0000465 }
Reid Spencerad89bd62004-07-25 18:07:36 +0000466 } else {
467 int Slot = Table.getSlot(I->getOperand(0));
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000468 assert(Slot >= 0 && "No slot number for value!?!?");
Reid Spencerad89bd62004-07-25 18:07:36 +0000469 output_vbr(unsigned(Slot));
470
471 // We need to encode the type of sequential type indices into their slot #
472 unsigned Idx = 1;
473 for (gep_type_iterator TI = gep_type_begin(I), E = gep_type_end(I);
474 Idx != NumArgs; ++TI, ++Idx) {
475 Slot = Table.getSlot(I->getOperand(Idx));
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000476 assert(Slot >= 0 && "No slot number for value!?!?");
477
Reid Spencerad89bd62004-07-25 18:07:36 +0000478 if (isa<SequentialType>(*TI)) {
479 unsigned IdxId;
480 switch (I->getOperand(Idx)->getType()->getTypeID()) {
481 default: assert(0 && "Unknown index type!");
482 case Type::UIntTyID: IdxId = 0; break;
483 case Type::IntTyID: IdxId = 1; break;
484 case Type::ULongTyID: IdxId = 2; break;
485 case Type::LongTyID: IdxId = 3; break;
486 }
487 Slot = (Slot << 2) | IdxId;
488 }
489 output_vbr(unsigned(Slot));
490 }
491 }
Reid Spencerad89bd62004-07-25 18:07:36 +0000492}
493
494
495// outputInstrVarArgsCall - Output the absurdly annoying varargs function calls.
496// This are more annoying than most because the signature of the call does not
497// tell us anything about the types of the arguments in the varargs portion.
498// Because of this, we encode (as type 0) all of the argument types explicitly
499// before the argument value. This really sucks, but you shouldn't be using
500// varargs functions in your code! *death to printf*!
501//
502// Format: [opcode] [type] [numargs] [arg0] [arg1] ... [arg<numargs-1>]
503//
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000504void BytecodeWriter::outputInstrVarArgsCall(const Instruction *I,
505 unsigned Opcode,
506 const SlotCalculator &Table,
507 unsigned Type) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000508 assert(isa<CallInst>(I) || isa<InvokeInst>(I));
509 // Opcode must have top two bits clear...
510 output_vbr(Opcode << 2); // Instruction Opcode ID
511 output_typeid(Type); // Result type (varargs type)
512
513 const PointerType *PTy = cast<PointerType>(I->getOperand(0)->getType());
514 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
515 unsigned NumParams = FTy->getNumParams();
516
517 unsigned NumFixedOperands;
518 if (isa<CallInst>(I)) {
519 // Output an operand for the callee and each fixed argument, then two for
520 // each variable argument.
521 NumFixedOperands = 1+NumParams;
522 } else {
523 assert(isa<InvokeInst>(I) && "Not call or invoke??");
524 // Output an operand for the callee and destinations, then two for each
525 // variable argument.
526 NumFixedOperands = 3+NumParams;
527 }
528 output_vbr(2 * I->getNumOperands()-NumFixedOperands);
529
530 // The type for the function has already been emitted in the type field of the
531 // instruction. Just emit the slot # now.
532 for (unsigned i = 0; i != NumFixedOperands; ++i) {
533 int Slot = Table.getSlot(I->getOperand(i));
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000534 assert(Slot >= 0 && "No slot number for value!?!?");
Reid Spencerad89bd62004-07-25 18:07:36 +0000535 output_vbr((unsigned)Slot);
536 }
537
538 for (unsigned i = NumFixedOperands, e = I->getNumOperands(); i != e; ++i) {
539 // Output Arg Type ID
540 int Slot = Table.getSlot(I->getOperand(i)->getType());
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000541 assert(Slot >= 0 && "No slot number for value!?!?");
Reid Spencerad89bd62004-07-25 18:07:36 +0000542 output_typeid((unsigned)Slot);
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000543
Reid Spencerad89bd62004-07-25 18:07:36 +0000544 // Output arg ID itself
545 Slot = Table.getSlot(I->getOperand(i));
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000546 assert(Slot >= 0 && "No slot number for value!?!?");
Reid Spencerad89bd62004-07-25 18:07:36 +0000547 output_vbr((unsigned)Slot);
548 }
Reid Spencerad89bd62004-07-25 18:07:36 +0000549}
550
551
552// outputInstructionFormat1 - Output one operand instructions, knowing that no
553// operand index is >= 2^12.
554//
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000555inline void BytecodeWriter::outputInstructionFormat1(const Instruction *I,
556 unsigned Opcode,
557 unsigned *Slots,
558 unsigned Type) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000559 // bits Instruction format:
560 // --------------------------
561 // 01-00: Opcode type, fixed to 1.
562 // 07-02: Opcode
563 // 19-08: Resulting type plane
564 // 31-20: Operand #1 (if set to (2^12-1), then zero operands)
565 //
Chris Lattnerf9d71782004-10-14 01:46:07 +0000566 output(1 | (Opcode << 2) | (Type << 8) | (Slots[0] << 20));
Reid Spencerad89bd62004-07-25 18:07:36 +0000567}
568
569
570// outputInstructionFormat2 - Output two operand instructions, knowing that no
571// operand index is >= 2^8.
572//
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000573inline void BytecodeWriter::outputInstructionFormat2(const Instruction *I,
574 unsigned Opcode,
575 unsigned *Slots,
576 unsigned Type) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000577 // bits Instruction format:
578 // --------------------------
579 // 01-00: Opcode type, fixed to 2.
580 // 07-02: Opcode
581 // 15-08: Resulting type plane
582 // 23-16: Operand #1
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000583 // 31-24: Operand #2
Reid Spencerad89bd62004-07-25 18:07:36 +0000584 //
Chris Lattnerf9d71782004-10-14 01:46:07 +0000585 output(2 | (Opcode << 2) | (Type << 8) | (Slots[0] << 16) | (Slots[1] << 24));
Reid Spencerad89bd62004-07-25 18:07:36 +0000586}
587
588
589// outputInstructionFormat3 - Output three operand instructions, knowing that no
590// operand index is >= 2^6.
591//
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000592inline void BytecodeWriter::outputInstructionFormat3(const Instruction *I,
Reid Spencerad89bd62004-07-25 18:07:36 +0000593 unsigned Opcode,
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000594 unsigned *Slots,
595 unsigned Type) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000596 // bits Instruction format:
597 // --------------------------
598 // 01-00: Opcode type, fixed to 3.
599 // 07-02: Opcode
600 // 13-08: Resulting type plane
601 // 19-14: Operand #1
602 // 25-20: Operand #2
603 // 31-26: Operand #3
604 //
Chris Lattnerf9d71782004-10-14 01:46:07 +0000605 output(3 | (Opcode << 2) | (Type << 8) |
Chris Lattner84d1ced2004-10-14 01:57:28 +0000606 (Slots[0] << 14) | (Slots[1] << 20) | (Slots[2] << 26));
Reid Spencerad89bd62004-07-25 18:07:36 +0000607}
608
609void BytecodeWriter::outputInstruction(const Instruction &I) {
Chris Lattnerbfed9242005-05-13 23:35:47 +0000610 assert(I.getOpcode() < 56 && "Opcode too big???");
Reid Spencerad89bd62004-07-25 18:07:36 +0000611 unsigned Opcode = I.getOpcode();
612 unsigned NumOperands = I.getNumOperands();
613
Chris Lattner38287bd2005-05-06 06:13:34 +0000614 // Encode 'tail call' as 61, 'volatile load' as 62, and 'volatile store' as
615 // 63.
Chris Lattnerdee199f2005-05-06 22:34:01 +0000616 if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
617 if (CI->getCallingConv() == CallingConv::C) {
618 if (CI->isTailCall())
619 Opcode = 61; // CCC + Tail Call
620 else
621 ; // Opcode = Instruction::Call
622 } else if (CI->getCallingConv() == CallingConv::Fast) {
623 if (CI->isTailCall())
624 Opcode = 59; // FastCC + TailCall
625 else
626 Opcode = 60; // FastCC + Not Tail Call
627 } else {
628 Opcode = 58; // Call escape sequence.
629 }
630 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
631 if (II->getCallingConv() == CallingConv::Fast)
632 Opcode = 57; // FastCC invoke.
633 else if (II->getCallingConv() != CallingConv::C)
634 Opcode = 56; // Invoke escape sequence.
635
636 } else if (isa<LoadInst>(I) && cast<LoadInst>(I).isVolatile()) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000637 Opcode = 62;
Chris Lattnerdee199f2005-05-06 22:34:01 +0000638 } else if (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile()) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000639 Opcode = 63;
Chris Lattnerdee199f2005-05-06 22:34:01 +0000640 }
Reid Spencerad89bd62004-07-25 18:07:36 +0000641
642 // Figure out which type to encode with the instruction. Typically we want
643 // the type of the first parameter, as opposed to the type of the instruction
644 // (for example, with setcc, we always know it returns bool, but the type of
645 // the first param is actually interesting). But if we have no arguments
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000646 // we take the type of the instruction itself.
Reid Spencerad89bd62004-07-25 18:07:36 +0000647 //
648 const Type *Ty;
649 switch (I.getOpcode()) {
650 case Instruction::Select:
651 case Instruction::Malloc:
652 case Instruction::Alloca:
653 Ty = I.getType(); // These ALWAYS want to encode the return type
654 break;
655 case Instruction::Store:
656 Ty = I.getOperand(1)->getType(); // Encode the pointer type...
657 assert(isa<PointerType>(Ty) && "Store to nonpointer type!?!?");
658 break;
659 default: // Otherwise use the default behavior...
660 Ty = NumOperands ? I.getOperand(0)->getType() : I.getType();
661 break;
662 }
663
664 unsigned Type;
665 int Slot = Table.getSlot(Ty);
666 assert(Slot != -1 && "Type not available!!?!");
667 Type = (unsigned)Slot;
668
669 // Varargs calls and invokes are encoded entirely different from any other
670 // instructions.
671 if (const CallInst *CI = dyn_cast<CallInst>(&I)){
672 const PointerType *Ty =cast<PointerType>(CI->getCalledValue()->getType());
673 if (cast<FunctionType>(Ty->getElementType())->isVarArg()) {
674 outputInstrVarArgsCall(CI, Opcode, Table, Type);
675 return;
676 }
677 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
678 const PointerType *Ty =cast<PointerType>(II->getCalledValue()->getType());
679 if (cast<FunctionType>(Ty->getElementType())->isVarArg()) {
680 outputInstrVarArgsCall(II, Opcode, Table, Type);
681 return;
682 }
683 }
684
685 if (NumOperands <= 3) {
686 // Make sure that we take the type number into consideration. We don't want
687 // to overflow the field size for the instruction format we select.
688 //
689 unsigned MaxOpSlot = Type;
690 unsigned Slots[3]; Slots[0] = (1 << 12)-1; // Marker to signify 0 operands
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000691
Reid Spencerad89bd62004-07-25 18:07:36 +0000692 for (unsigned i = 0; i != NumOperands; ++i) {
693 int slot = Table.getSlot(I.getOperand(i));
694 assert(slot != -1 && "Broken bytecode!");
695 if (unsigned(slot) > MaxOpSlot) MaxOpSlot = unsigned(slot);
696 Slots[i] = unsigned(slot);
697 }
698
699 // Handle the special cases for various instructions...
700 if (isa<CastInst>(I) || isa<VAArgInst>(I)) {
701 // Cast has to encode the destination type as the second argument in the
702 // packet, or else we won't know what type to cast to!
703 Slots[1] = Table.getSlot(I.getType());
704 assert(Slots[1] != ~0U && "Cast return type unknown?");
705 if (Slots[1] > MaxOpSlot) MaxOpSlot = Slots[1];
706 NumOperands++;
707 } else if (const VANextInst *VANI = dyn_cast<VANextInst>(&I)) {
708 Slots[1] = Table.getSlot(VANI->getArgType());
709 assert(Slots[1] != ~0U && "va_next return type unknown?");
710 if (Slots[1] > MaxOpSlot) MaxOpSlot = Slots[1];
711 NumOperands++;
712 } else if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&I)) {
713 // We need to encode the type of sequential type indices into their slot #
714 unsigned Idx = 1;
715 for (gep_type_iterator I = gep_type_begin(GEP), E = gep_type_end(GEP);
716 I != E; ++I, ++Idx)
717 if (isa<SequentialType>(*I)) {
718 unsigned IdxId;
719 switch (GEP->getOperand(Idx)->getType()->getTypeID()) {
720 default: assert(0 && "Unknown index type!");
721 case Type::UIntTyID: IdxId = 0; break;
722 case Type::IntTyID: IdxId = 1; break;
723 case Type::ULongTyID: IdxId = 2; break;
724 case Type::LongTyID: IdxId = 3; break;
725 }
726 Slots[Idx] = (Slots[Idx] << 2) | IdxId;
727 if (Slots[Idx] > MaxOpSlot) MaxOpSlot = Slots[Idx];
728 }
Chris Lattnerdee199f2005-05-06 22:34:01 +0000729 } else if (Opcode == 58) {
730 // If this is the escape sequence for call, emit the tailcall/cc info.
731 const CallInst &CI = cast<CallInst>(I);
732 ++NumOperands;
733 if (NumOperands < 3) {
Jeff Cohen39cef602005-05-07 02:44:04 +0000734 Slots[NumOperands-1] = (CI.getCallingConv() << 1)|unsigned(CI.isTailCall());
Chris Lattnerdee199f2005-05-06 22:34:01 +0000735 if (Slots[NumOperands-1] > MaxOpSlot)
736 MaxOpSlot = Slots[NumOperands-1];
737 }
738 } else if (Opcode == 56) {
739 // Invoke escape seq has at least 4 operands to encode.
740 ++NumOperands;
Reid Spencerad89bd62004-07-25 18:07:36 +0000741 }
742
743 // Decide which instruction encoding to use. This is determined primarily
744 // by the number of operands, and secondarily by whether or not the max
745 // operand will fit into the instruction encoding. More operands == fewer
746 // bits per operand.
747 //
748 switch (NumOperands) {
749 case 0:
750 case 1:
751 if (MaxOpSlot < (1 << 12)-1) { // -1 because we use 4095 to indicate 0 ops
752 outputInstructionFormat1(&I, Opcode, Slots, Type);
753 return;
754 }
755 break;
756
757 case 2:
758 if (MaxOpSlot < (1 << 8)) {
759 outputInstructionFormat2(&I, Opcode, Slots, Type);
760 return;
761 }
762 break;
763
764 case 3:
765 if (MaxOpSlot < (1 << 6)) {
766 outputInstructionFormat3(&I, Opcode, Slots, Type);
767 return;
768 }
769 break;
770 default:
771 break;
772 }
773 }
774
775 // If we weren't handled before here, we either have a large number of
776 // operands or a large operand index that we are referring to.
777 outputInstructionFormat0(&I, Opcode, Table, Type);
778}
779
780//===----------------------------------------------------------------------===//
781//=== Block Output ===//
782//===----------------------------------------------------------------------===//
783
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000784BytecodeWriter::BytecodeWriter(std::vector<unsigned char> &o, const Module *M)
Reid Spencer798ff642004-05-26 07:37:11 +0000785 : Out(o), Table(M) {
Chris Lattner00950542001-06-06 20:29:01 +0000786
Chris Lattner83bb3d22004-01-14 23:36:54 +0000787 // Emit the signature...
788 static const unsigned char *Sig = (const unsigned char*)"llvm";
Reid Spencerad89bd62004-07-25 18:07:36 +0000789 output_data(Sig, Sig+4);
Chris Lattner00950542001-06-06 20:29:01 +0000790
791 // Emit the top level CLASS block.
Reid Spencerad89bd62004-07-25 18:07:36 +0000792 BytecodeBlock ModuleBlock(BytecodeFormat::ModuleBlockID, *this, false, true);
Chris Lattner00950542001-06-06 20:29:01 +0000793
Chris Lattnerd445c6b2003-08-24 13:47:36 +0000794 bool isBigEndian = M->getEndianness() == Module::BigEndian;
795 bool hasLongPointers = M->getPointerSize() == Module::Pointer64;
796 bool hasNoEndianness = M->getEndianness() == Module::AnyEndianness;
797 bool hasNoPointerSize = M->getPointerSize() == Module::AnyPointerSize;
Chris Lattner186a1f72003-03-19 20:56:46 +0000798
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000799 // Output the version identifier and other information.
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000800 unsigned Version = (BCVersionNum << 4) |
Reid Spencer38d54be2004-08-17 07:45:14 +0000801 (unsigned)isBigEndian | (hasLongPointers << 1) |
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000802 (hasNoEndianness << 2) |
Reid Spencer38d54be2004-08-17 07:45:14 +0000803 (hasNoPointerSize << 3);
Reid Spencerad89bd62004-07-25 18:07:36 +0000804 output_vbr(Version);
Chris Lattner00950542001-06-06 20:29:01 +0000805
Reid Spencercb3595c2004-07-04 11:45:47 +0000806 // The Global type plane comes first
Chris Lattner186a1f72003-03-19 20:56:46 +0000807 {
Reid Spencerad89bd62004-07-25 18:07:36 +0000808 BytecodeBlock CPool(BytecodeFormat::GlobalTypePlaneBlockID, *this );
Reid Spencercb3595c2004-07-04 11:45:47 +0000809 outputTypes(Type::FirstDerivedTyID);
Chris Lattner186a1f72003-03-19 20:56:46 +0000810 }
Chris Lattner00950542001-06-06 20:29:01 +0000811
Chris Lattner186a1f72003-03-19 20:56:46 +0000812 // The ModuleInfoBlock follows directly after the type information
Chris Lattnere8fdde12001-09-07 16:39:41 +0000813 outputModuleInfoBlock(M);
814
Chris Lattner186a1f72003-03-19 20:56:46 +0000815 // Output module level constants, used for global variable initializers
816 outputConstants(false);
817
Chris Lattnerb5794002002-04-07 22:49:37 +0000818 // Do the whole module now! Process each function at a time...
Chris Lattner0b12b5f2002-06-25 16:13:21 +0000819 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
Chris Lattner186a1f72003-03-19 20:56:46 +0000820 outputFunction(I);
Chris Lattnere8fdde12001-09-07 16:39:41 +0000821
822 // If needed, output the symbol table for the module...
Chris Lattner6e6026b2002-11-20 18:36:02 +0000823 outputSymbolTable(M->getSymbolTable());
Chris Lattner00950542001-06-06 20:29:01 +0000824}
825
Chris Lattnerf9d71782004-10-14 01:46:07 +0000826void BytecodeWriter::outputTypes(unsigned TypeNum) {
Reid Spencercb3595c2004-07-04 11:45:47 +0000827 // Write the type plane for types first because earlier planes (e.g. for a
828 // primitive type like float) may have constants constructed using types
829 // coming later (e.g., via getelementptr from a pointer type). The type
830 // plane is needed before types can be fwd or bkwd referenced.
831 const std::vector<const Type*>& Types = Table.getTypes();
832 assert(!Types.empty() && "No types at all?");
833 assert(TypeNum <= Types.size() && "Invalid TypeNo index");
834
835 unsigned NumEntries = Types.size() - TypeNum;
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000836
Reid Spencercb3595c2004-07-04 11:45:47 +0000837 // Output type header: [num entries]
Reid Spencerad89bd62004-07-25 18:07:36 +0000838 output_vbr(NumEntries);
Reid Spencercb3595c2004-07-04 11:45:47 +0000839
840 for (unsigned i = TypeNum; i < TypeNum+NumEntries; ++i)
841 outputType(Types[i]);
842}
843
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000844// Helper function for outputConstants().
845// Writes out all the constants in the plane Plane starting at entry StartNo.
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000846//
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000847void BytecodeWriter::outputConstantsInPlane(const std::vector<const Value*>
848 &Plane, unsigned StartNo) {
849 unsigned ValNo = StartNo;
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000850
Chris Lattner83bb3d22004-01-14 23:36:54 +0000851 // Scan through and ignore function arguments, global values, and constant
852 // strings.
853 for (; ValNo < Plane.size() &&
854 (isa<Argument>(Plane[ValNo]) || isa<GlobalValue>(Plane[ValNo]) ||
855 (isa<ConstantArray>(Plane[ValNo]) &&
856 cast<ConstantArray>(Plane[ValNo])->isString())); ValNo++)
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000857 /*empty*/;
858
859 unsigned NC = ValNo; // Number of constants
Reid Spencercb3595c2004-07-04 11:45:47 +0000860 for (; NC < Plane.size() && (isa<Constant>(Plane[NC])); NC++)
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000861 /*empty*/;
862 NC -= ValNo; // Convert from index into count
863 if (NC == 0) return; // Skip empty type planes...
864
Chris Lattnerd6942d72004-01-14 16:54:21 +0000865 // FIXME: Most slabs only have 1 or 2 entries! We should encode this much
866 // more compactly.
867
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000868 // Output type header: [num entries][type id number]
869 //
Reid Spencerad89bd62004-07-25 18:07:36 +0000870 output_vbr(NC);
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000871
872 // Output the Type ID Number...
Alkis Evlogimenos60596382003-10-17 02:02:40 +0000873 int Slot = Table.getSlot(Plane.front()->getType());
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000874 assert (Slot != -1 && "Type in constant pool but not in function!!");
Reid Spencerad89bd62004-07-25 18:07:36 +0000875 output_typeid((unsigned)Slot);
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000876
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000877 for (unsigned i = ValNo; i < ValNo+NC; ++i) {
878 const Value *V = Plane[i];
Reid Spencere0125b62004-07-18 00:16:21 +0000879 if (const Constant *C = dyn_cast<Constant>(V)) {
880 outputConstant(C);
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000881 }
882 }
883}
884
Chris Lattner9e60d8d2005-05-05 22:21:19 +0000885static inline bool hasNullValue(const Type *Ty) {
886 return Ty != Type::LabelTy && Ty != Type::VoidTy && !isa<OpaqueType>(Ty);
Chris Lattner80b97342004-01-17 23:25:43 +0000887}
888
Chris Lattner79df7c02002-03-26 18:01:55 +0000889void BytecodeWriter::outputConstants(bool isFunction) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000890 BytecodeBlock CPool(BytecodeFormat::ConstantPoolBlockID, *this,
Chris Lattner0baa0af2004-01-15 21:06:57 +0000891 true /* Elide block if empty */);
Chris Lattner00950542001-06-06 20:29:01 +0000892
893 unsigned NumPlanes = Table.getNumPlanes();
Chris Lattnerf69315b2003-05-22 18:35:38 +0000894
Reid Spencere0125b62004-07-18 00:16:21 +0000895 if (isFunction)
896 // Output the type plane before any constants!
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000897 outputTypes(Table.getModuleTypeLevel());
Reid Spencere0125b62004-07-18 00:16:21 +0000898 else
Chris Lattnerf9d71782004-10-14 01:46:07 +0000899 // Output module-level string constants before any other constants.
Chris Lattner83bb3d22004-01-14 23:36:54 +0000900 outputConstantStrings();
901
Reid Spencercb3595c2004-07-04 11:45:47 +0000902 for (unsigned pno = 0; pno != NumPlanes; pno++) {
903 const std::vector<const Value*> &Plane = Table.getPlane(pno);
904 if (!Plane.empty()) { // Skip empty type planes...
905 unsigned ValNo = 0;
906 if (isFunction) // Don't re-emit module constants
Reid Spencer0852c802004-07-04 11:46:15 +0000907 ValNo += Table.getModuleLevel(pno);
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000908
Chris Lattner9e60d8d2005-05-05 22:21:19 +0000909 if (hasNullValue(Plane[0]->getType())) {
Reid Spencer0852c802004-07-04 11:46:15 +0000910 // Skip zero initializer
911 if (ValNo == 0)
912 ValNo = 1;
Chris Lattnerf69315b2003-05-22 18:35:38 +0000913 }
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000914
Reid Spencercb3595c2004-07-04 11:45:47 +0000915 // Write out constants in the plane
916 outputConstantsInPlane(Plane, ValNo);
Chris Lattnerf69315b2003-05-22 18:35:38 +0000917 }
Reid Spencercb3595c2004-07-04 11:45:47 +0000918 }
Chris Lattner00950542001-06-06 20:29:01 +0000919}
920
Chris Lattner6b252422003-10-16 18:28:50 +0000921static unsigned getEncodedLinkage(const GlobalValue *GV) {
922 switch (GV->getLinkage()) {
923 default: assert(0 && "Invalid linkage!");
924 case GlobalValue::ExternalLinkage: return 0;
Chris Lattner6b252422003-10-16 18:28:50 +0000925 case GlobalValue::WeakLinkage: return 1;
926 case GlobalValue::AppendingLinkage: return 2;
927 case GlobalValue::InternalLinkage: return 3;
Chris Lattner22482a12003-10-18 06:30:21 +0000928 case GlobalValue::LinkOnceLinkage: return 4;
Chris Lattner6b252422003-10-16 18:28:50 +0000929 }
930}
931
Chris Lattner00950542001-06-06 20:29:01 +0000932void BytecodeWriter::outputModuleInfoBlock(const Module *M) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000933 BytecodeBlock ModuleInfoBlock(BytecodeFormat::ModuleGlobalInfoBlockID, *this);
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000934
Chris Lattner70cc3392001-09-10 07:58:01 +0000935 // Output the types for the global variables in the module...
Chris Lattner28caccf2005-05-06 20:27:03 +0000936 for (Module::const_global_iterator I = M->global_begin(),
937 End = M->global_end(); I != End;++I) {
Alkis Evlogimenos60596382003-10-17 02:02:40 +0000938 int Slot = Table.getSlot(I->getType());
Chris Lattner70cc3392001-09-10 07:58:01 +0000939 assert(Slot != -1 && "Module global vars is broken!");
Chris Lattnerd70684f2001-09-18 04:01:05 +0000940
Chris Lattner22482a12003-10-18 06:30:21 +0000941 // Fields: bit0 = isConstant, bit1 = hasInitializer, bit2-4=Linkage,
942 // bit5+ = Slot # for type
Chris Lattnerf74acc72004-10-14 02:31:35 +0000943 unsigned oSlot = ((unsigned)Slot << 5) | (getEncodedLinkage(I) << 2) |
Chris Lattner036de032004-06-25 20:52:10 +0000944 (I->hasInitializer() << 1) | (unsigned)I->isConstant();
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000945 output_vbr(oSlot);
Chris Lattnerd70684f2001-09-18 04:01:05 +0000946
Chris Lattner1b98c5c2001-10-13 06:48:38 +0000947 // If we have an initializer, output it now.
Chris Lattner0b12b5f2002-06-25 16:13:21 +0000948 if (I->hasInitializer()) {
Alkis Evlogimenos60596382003-10-17 02:02:40 +0000949 Slot = Table.getSlot((Value*)I->getInitializer());
Chris Lattnerd70684f2001-09-18 04:01:05 +0000950 assert(Slot != -1 && "No slot for global var initializer!");
Reid Spencerad89bd62004-07-25 18:07:36 +0000951 output_vbr((unsigned)Slot);
Chris Lattnerd70684f2001-09-18 04:01:05 +0000952 }
Chris Lattner70cc3392001-09-10 07:58:01 +0000953 }
Reid Spencerad89bd62004-07-25 18:07:36 +0000954 output_typeid((unsigned)Table.getSlot(Type::VoidTy));
Chris Lattner70cc3392001-09-10 07:58:01 +0000955
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000956 // Output the types of the functions in this module.
Chris Lattner7fc9fe32001-06-27 23:41:11 +0000957 for (Module::const_iterator I = M->begin(), End = M->end(); I != End; ++I) {
Alkis Evlogimenos60596382003-10-17 02:02:40 +0000958 int Slot = Table.getSlot(I->getType());
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000959 assert(Slot != -1 && "Module slot calculator is broken!");
Chris Lattner00950542001-06-06 20:29:01 +0000960 assert(Slot >= Type::FirstDerivedTyID && "Derived type not in range!");
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000961 assert(((Slot << 5) >> 5) == Slot && "Slot # too big!");
Chris Lattner479ffeb2005-05-06 20:42:57 +0000962 unsigned ID = (Slot << 5);
963
964 if (I->getCallingConv() < 15)
965 ID += I->getCallingConv()+1;
966
Chris Lattnerd6e431f2004-11-15 22:39:49 +0000967 if (I->isExternal()) // If external, we don't have an FunctionInfo block.
968 ID |= 1 << 4;
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000969 output_vbr(ID);
Chris Lattner479ffeb2005-05-06 20:42:57 +0000970
971 if (I->getCallingConv() >= 15)
972 output_vbr(I->getCallingConv());
Chris Lattner00950542001-06-06 20:29:01 +0000973 }
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000974 output_vbr((unsigned)Table.getSlot(Type::VoidTy) << 5);
Reid Spencerad89bd62004-07-25 18:07:36 +0000975
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000976 // Emit the list of dependent libraries for the Module.
Reid Spencer5ac88122004-07-25 21:32:02 +0000977 Module::lib_iterator LI = M->lib_begin();
978 Module::lib_iterator LE = M->lib_end();
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000979 output_vbr(unsigned(LE - LI)); // Emit the number of dependent libraries.
980 for (; LI != LE; ++LI)
Reid Spencer38d54be2004-08-17 07:45:14 +0000981 output(*LI);
Reid Spencerad89bd62004-07-25 18:07:36 +0000982
983 // Output the target triple from the module
Reid Spencer38d54be2004-08-17 07:45:14 +0000984 output(M->getTargetTriple());
Chris Lattner00950542001-06-06 20:29:01 +0000985}
986
Chris Lattnercf3e67f2004-01-18 21:08:52 +0000987void BytecodeWriter::outputInstructions(const Function *F) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000988 BytecodeBlock ILBlock(BytecodeFormat::InstructionListBlockID, *this);
Chris Lattnercf3e67f2004-01-18 21:08:52 +0000989 for (Function::const_iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
990 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I)
991 outputInstruction(*I);
Chris Lattnercf3e67f2004-01-18 21:08:52 +0000992}
993
Chris Lattner186a1f72003-03-19 20:56:46 +0000994void BytecodeWriter::outputFunction(const Function *F) {
Chris Lattnerfd7f8fe2004-11-15 21:56:33 +0000995 // If this is an external function, there is nothing else to emit!
996 if (F->isExternal()) return;
997
Chris Lattnerd6e431f2004-11-15 22:39:49 +0000998 BytecodeBlock FunctionBlock(BytecodeFormat::FunctionBlockID, *this);
999 output_vbr(getEncodedLinkage(F));
1000
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001001 // Get slot information about the function...
1002 Table.incorporateFunction(F);
1003
1004 if (Table.getCompactionTable().empty()) {
1005 // Output information about the constants in the function if the compaction
1006 // table is not being used.
Chris Lattnere8fdde12001-09-07 16:39:41 +00001007 outputConstants(true);
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001008 } else {
1009 // Otherwise, emit the compaction table.
1010 outputCompactionTable();
Chris Lattnere8fdde12001-09-07 16:39:41 +00001011 }
Misha Brukman23c6d2c2005-04-21 21:48:46 +00001012
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001013 // Output all of the instructions in the body of the function
1014 outputInstructions(F);
Misha Brukman23c6d2c2005-04-21 21:48:46 +00001015
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001016 // If needed, output the symbol table for the function...
1017 outputSymbolTable(F->getSymbolTable());
Misha Brukman23c6d2c2005-04-21 21:48:46 +00001018
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001019 Table.purgeFunction();
1020}
1021
1022void BytecodeWriter::outputCompactionTablePlane(unsigned PlaneNo,
1023 const std::vector<const Value*> &Plane,
1024 unsigned StartNo) {
1025 unsigned End = Table.getModuleLevel(PlaneNo);
Chris Lattner52f86d62004-01-20 00:54:06 +00001026 if (Plane.empty() || StartNo == End || End == 0) return; // Nothing to emit
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001027 assert(StartNo < End && "Cannot emit negative range!");
1028 assert(StartNo < Plane.size() && End <= Plane.size());
1029
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001030 // Do not emit the null initializer!
Reid Spencercb3595c2004-07-04 11:45:47 +00001031 ++StartNo;
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001032
Chris Lattner24102432004-01-18 22:35:34 +00001033 // Figure out which encoding to use. By far the most common case we have is
1034 // to emit 0-2 entries in a compaction table plane.
1035 switch (End-StartNo) {
1036 case 0: // Avoid emitting two vbr's if possible.
1037 case 1:
1038 case 2:
Reid Spencerad89bd62004-07-25 18:07:36 +00001039 output_vbr((PlaneNo << 2) | End-StartNo);
Chris Lattner24102432004-01-18 22:35:34 +00001040 break;
1041 default:
1042 // Output the number of things.
Reid Spencerad89bd62004-07-25 18:07:36 +00001043 output_vbr((unsigned(End-StartNo) << 2) | 3);
1044 output_typeid(PlaneNo); // Emit the type plane this is
Chris Lattner24102432004-01-18 22:35:34 +00001045 break;
1046 }
1047
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001048 for (unsigned i = StartNo; i != End; ++i)
Reid Spencerad89bd62004-07-25 18:07:36 +00001049 output_vbr(Table.getGlobalSlot(Plane[i]));
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001050}
1051
Reid Spencercb3595c2004-07-04 11:45:47 +00001052void BytecodeWriter::outputCompactionTypes(unsigned StartNo) {
1053 // Get the compaction type table from the slot calculator
1054 const std::vector<const Type*> &CTypes = Table.getCompactionTypes();
1055
1056 // The compaction types may have been uncompactified back to the
1057 // global types. If so, we just write an empty table
1058 if (CTypes.size() == 0 ) {
Reid Spencerad89bd62004-07-25 18:07:36 +00001059 output_vbr(0U);
Reid Spencercb3595c2004-07-04 11:45:47 +00001060 return;
1061 }
1062
1063 assert(CTypes.size() >= StartNo && "Invalid compaction types start index");
1064
1065 // Determine how many types to write
1066 unsigned NumTypes = CTypes.size() - StartNo;
1067
1068 // Output the number of types.
Reid Spencerad89bd62004-07-25 18:07:36 +00001069 output_vbr(NumTypes);
Reid Spencercb3595c2004-07-04 11:45:47 +00001070
1071 for (unsigned i = StartNo; i < StartNo+NumTypes; ++i)
Reid Spencerad89bd62004-07-25 18:07:36 +00001072 output_typeid(Table.getGlobalSlot(CTypes[i]));
Reid Spencercb3595c2004-07-04 11:45:47 +00001073}
1074
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001075void BytecodeWriter::outputCompactionTable() {
Reid Spencer0033c182004-08-27 00:38:44 +00001076 // Avoid writing the compaction table at all if there is no content.
1077 if (Table.getCompactionTypes().size() >= Type::FirstDerivedTyID ||
1078 (!Table.CompactionTableIsEmpty())) {
Misha Brukman23c6d2c2005-04-21 21:48:46 +00001079 BytecodeBlock CTB(BytecodeFormat::CompactionTableBlockID, *this,
Reid Spencer0033c182004-08-27 00:38:44 +00001080 true/*ElideIfEmpty*/);
Chris Lattnerf9d71782004-10-14 01:46:07 +00001081 const std::vector<std::vector<const Value*> > &CT =
1082 Table.getCompactionTable();
Misha Brukman23c6d2c2005-04-21 21:48:46 +00001083
Reid Spencer0033c182004-08-27 00:38:44 +00001084 // First things first, emit the type compaction table if there is one.
1085 outputCompactionTypes(Type::FirstDerivedTyID);
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001086
Reid Spencer0033c182004-08-27 00:38:44 +00001087 for (unsigned i = 0, e = CT.size(); i != e; ++i)
1088 outputCompactionTablePlane(i, CT[i], 0);
1089 }
Chris Lattner00950542001-06-06 20:29:01 +00001090}
1091
Chris Lattner00950542001-06-06 20:29:01 +00001092void BytecodeWriter::outputSymbolTable(const SymbolTable &MST) {
Chris Lattner737d3cd2004-01-10 19:56:59 +00001093 // Do not output the Bytecode block for an empty symbol table, it just wastes
1094 // space!
Chris Lattnerf9d71782004-10-14 01:46:07 +00001095 if (MST.isEmpty()) return;
Chris Lattner737d3cd2004-01-10 19:56:59 +00001096
Reid Spencerad89bd62004-07-25 18:07:36 +00001097 BytecodeBlock SymTabBlock(BytecodeFormat::SymbolTableBlockID, *this,
Chris Lattnerf9d71782004-10-14 01:46:07 +00001098 true/*ElideIfEmpty*/);
Chris Lattner00950542001-06-06 20:29:01 +00001099
Misha Brukman23c6d2c2005-04-21 21:48:46 +00001100 // Write the number of types
Reid Spencerad89bd62004-07-25 18:07:36 +00001101 output_vbr(MST.num_types());
Reid Spencer250c4182004-08-17 02:59:02 +00001102
1103 // Write each of the types
Reid Spencer94f2df22004-05-25 17:29:59 +00001104 for (SymbolTable::type_const_iterator TI = MST.type_begin(),
1105 TE = MST.type_end(); TI != TE; ++TI ) {
Reid Spencer250c4182004-08-17 02:59:02 +00001106 // Symtab entry:[def slot #][name]
Reid Spencerad89bd62004-07-25 18:07:36 +00001107 output_typeid((unsigned)Table.getSlot(TI->second));
Misha Brukman23c6d2c2005-04-21 21:48:46 +00001108 output(TI->first);
Reid Spencer94f2df22004-05-25 17:29:59 +00001109 }
1110
1111 // Now do each of the type planes in order.
Misha Brukman23c6d2c2005-04-21 21:48:46 +00001112 for (SymbolTable::plane_const_iterator PI = MST.plane_begin(),
Reid Spencer94f2df22004-05-25 17:29:59 +00001113 PE = MST.plane_end(); PI != PE; ++PI) {
1114 SymbolTable::value_const_iterator I = MST.value_begin(PI->first);
1115 SymbolTable::value_const_iterator End = MST.value_end(PI->first);
Chris Lattner00950542001-06-06 20:29:01 +00001116 int Slot;
Misha Brukman23c6d2c2005-04-21 21:48:46 +00001117
Chris Lattner00950542001-06-06 20:29:01 +00001118 if (I == End) continue; // Don't mess with an absent type...
1119
Reid Spencer250c4182004-08-17 02:59:02 +00001120 // Write the number of values in this plane
Chris Lattner001d16a2005-03-07 02:59:36 +00001121 output_vbr((unsigned)PI->second.size());
Chris Lattner00950542001-06-06 20:29:01 +00001122
Reid Spencer250c4182004-08-17 02:59:02 +00001123 // Write the slot number of the type for this plane
Reid Spencer94f2df22004-05-25 17:29:59 +00001124 Slot = Table.getSlot(PI->first);
Chris Lattner00950542001-06-06 20:29:01 +00001125 assert(Slot != -1 && "Type in symtab, but not in table!");
Reid Spencerad89bd62004-07-25 18:07:36 +00001126 output_typeid((unsigned)Slot);
Chris Lattner00950542001-06-06 20:29:01 +00001127
Reid Spencer250c4182004-08-17 02:59:02 +00001128 // Write each of the values in this plane
Chris Lattner7fc9fe32001-06-27 23:41:11 +00001129 for (; I != End; ++I) {
Chris Lattner00950542001-06-06 20:29:01 +00001130 // Symtab entry: [def slot #][name]
Alkis Evlogimenos60596382003-10-17 02:02:40 +00001131 Slot = Table.getSlot(I->second);
Chris Lattnere8fdde12001-09-07 16:39:41 +00001132 assert(Slot != -1 && "Value in symtab but has no slot number!!");
Reid Spencerad89bd62004-07-25 18:07:36 +00001133 output_vbr((unsigned)Slot);
Reid Spencer38d54be2004-08-17 07:45:14 +00001134 output(I->first);
Chris Lattner00950542001-06-06 20:29:01 +00001135 }
1136 }
1137}
1138
Reid Spencer17f52c52004-11-06 23:17:23 +00001139void llvm::WriteBytecodeToFile(const Module *M, std::ostream &Out,
1140 bool compress ) {
Reid Spencerad89bd62004-07-25 18:07:36 +00001141 assert(M && "You can't write a null module!!");
Chris Lattner00950542001-06-06 20:29:01 +00001142
Reid Spencer17f52c52004-11-06 23:17:23 +00001143 // Create a vector of unsigned char for the bytecode output. We
1144 // reserve 256KBytes of space in the vector so that we avoid doing
1145 // lots of little allocations. 256KBytes is sufficient for a large
1146 // proportion of the bytecode files we will encounter. Larger files
1147 // will be automatically doubled in size as needed (std::vector
1148 // behavior).
Reid Spencerad89bd62004-07-25 18:07:36 +00001149 std::vector<unsigned char> Buffer;
Reid Spencer17f52c52004-11-06 23:17:23 +00001150 Buffer.reserve(256 * 1024);
Chris Lattner00950542001-06-06 20:29:01 +00001151
Reid Spencer17f52c52004-11-06 23:17:23 +00001152 // The BytecodeWriter populates Buffer for us.
Reid Spencerad89bd62004-07-25 18:07:36 +00001153 BytecodeWriter BCW(Buffer, M);
Chris Lattner00950542001-06-06 20:29:01 +00001154
Reid Spencer17f52c52004-11-06 23:17:23 +00001155 // Keep track of how much we've written
Chris Lattnerce6ef112002-07-26 18:40:14 +00001156 BytesWritten += Buffer.size();
1157
Reid Spencer17f52c52004-11-06 23:17:23 +00001158 // Determine start and end points of the Buffer
Reid Spencer83296f52004-11-07 18:17:38 +00001159 const unsigned char *FirstByte = &Buffer.front();
Reid Spencer17f52c52004-11-06 23:17:23 +00001160
1161 // If we're supposed to compress this mess ...
1162 if (compress) {
1163
1164 // We signal compression by using an alternate magic number for the
Reid Spencer83296f52004-11-07 18:17:38 +00001165 // file. The compressed bytecode file's magic number is "llvc" instead
Misha Brukman23c6d2c2005-04-21 21:48:46 +00001166 // of "llvm".
Reid Spencer83296f52004-11-07 18:17:38 +00001167 char compressed_magic[4];
1168 compressed_magic[0] = 'l';
1169 compressed_magic[1] = 'l';
1170 compressed_magic[2] = 'v';
1171 compressed_magic[3] = 'c';
Reid Spencer17f52c52004-11-06 23:17:23 +00001172
Reid Spencer83296f52004-11-07 18:17:38 +00001173 Out.write(compressed_magic,4);
Reid Spencer17f52c52004-11-06 23:17:23 +00001174
Reid Spencera70d84d2004-11-14 22:01:41 +00001175 // Compress everything after the magic number (which we altered)
1176 uint64_t zipSize = Compressor::compressToStream(
Reid Spencer17f52c52004-11-06 23:17:23 +00001177 (char*)(FirstByte+4), // Skip the magic number
1178 Buffer.size()-4, // Skip the magic number
Reid Spencer84472d62004-11-25 19:38:05 +00001179 Out // Where to write compressed data
Reid Spencer17f52c52004-11-06 23:17:23 +00001180 );
1181
Reid Spencer17f52c52004-11-06 23:17:23 +00001182 } else {
1183
1184 // We're not compressing, so just write the entire block.
Reid Spencer83296f52004-11-07 18:17:38 +00001185 Out.write((char*)FirstByte, Buffer.size());
Chris Lattnere8fdde12001-09-07 16:39:41 +00001186 }
Reid Spencer17f52c52004-11-06 23:17:23 +00001187
1188 // make sure it hits disk now
Chris Lattner00950542001-06-06 20:29:01 +00001189 Out.flush();
1190}
Reid Spencere0125b62004-07-18 00:16:21 +00001191