blob: 4ec6b2a41e85a56a08215719e4d3ae1053413ee8 [file] [log] [blame]
Chris Lattnerb0a59642004-01-10 19:07:06 +00001//===-- Writer.cpp - Library for writing LLVM bytecode files --------------===//
Misha Brukmanb47d28b2005-04-21 21:48:46 +00002//
John Criswell482202a2003-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 Brukmanb47d28b2005-04-21 21:48:46 +00007//
John Criswell482202a2003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner2f7c9632001-06-06 20:29:01 +00009//
10// This library implements the functionality defined in llvm/Bytecode/Writer.h
11//
Chris Lattner2f7c9632001-06-06 20:29:01 +000012// Note that this file uses an unusual technique of outputting all the bytecode
Reid Spencerb2bdb942004-07-25 18:07:36 +000013// to a vector of unsigned char, then copies the vector to an ostream. The
Chris Lattner2f7c9632001-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 Lattner2f7c9632001-06-06 20:29:01 +000018//===----------------------------------------------------------------------===//
19
20#include "WriterInternals.h"
Chris Lattner36d2c7c2002-07-23 19:56:44 +000021#include "llvm/Bytecode/WriteBytecodePass.h"
Chris Lattner129535c2005-05-06 22:34:01 +000022#include "llvm/CallingConv.h"
Chris Lattner6229fbf2004-01-14 23:36:54 +000023#include "llvm/Constants.h"
24#include "llvm/DerivedTypes.h"
Chris Lattner44706912006-01-25 23:08:15 +000025#include "llvm/InlineAsm.h"
Reid Spencerb2bdb942004-07-25 18:07:36 +000026#include "llvm/Instructions.h"
Chris Lattner2f7c9632001-06-06 20:29:01 +000027#include "llvm/Module.h"
Chris Lattner2f7c9632001-06-06 20:29:01 +000028#include "llvm/SymbolTable.h"
Reid Spencerb2bdb942004-07-25 18:07:36 +000029#include "llvm/Support/GetElementPtrTypeIterator.h"
Reid Spencer2e492042004-11-06 23:17:23 +000030#include "llvm/Support/Compressor.h"
Jim Laskeyb74c6662005-08-17 19:34:49 +000031#include "llvm/Support/MathExtras.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000032#include "llvm/ADT/STLExtras.h"
33#include "llvm/ADT/Statistic.h"
Chris Lattner0c530312004-01-10 19:10:01 +000034#include <cstring>
Chris Lattner2f7c9632001-06-06 20:29:01 +000035#include <algorithm>
Chris Lattnerdfe03462004-01-10 18:49:43 +000036using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000037
Reid Spencerc3e43642004-08-17 07:45:14 +000038/// This value needs to be incremented every time the bytecode format changes
39/// so that the reader can distinguish which format of the bytecode file has
40/// been written.
41/// @brief The bytecode version number
Chris Lattner770709b2004-10-16 18:18:16 +000042const unsigned BCVersionNum = 5;
Reid Spencerc3e43642004-08-17 07:45:14 +000043
Chris Lattner36d2c7c2002-07-23 19:56:44 +000044static RegisterPass<WriteBytecodePass> X("emitbytecode", "Bytecode Writer");
45
Misha Brukmanb47d28b2005-04-21 21:48:46 +000046static Statistic<>
Chris Lattnerbf3a0992002-10-01 22:38:41 +000047BytesWritten("bytecodewriter", "Number of bytecode bytes written");
Chris Lattner36d2c7c2002-07-23 19:56:44 +000048
Reid Spencerb2bdb942004-07-25 18:07:36 +000049//===----------------------------------------------------------------------===//
50//=== Output Primitives ===//
51//===----------------------------------------------------------------------===//
52
53// output - If a position is specified, it must be in the valid portion of the
Misha Brukmanb47d28b2005-04-21 21:48:46 +000054// string... note that this should be inlined always so only the relevant IF
Reid Spencerb2bdb942004-07-25 18:07:36 +000055// body should be included.
56inline void BytecodeWriter::output(unsigned i, int pos) {
57 if (pos == -1) { // Be endian clean, little endian is our friend
Misha Brukmanb47d28b2005-04-21 21:48:46 +000058 Out.push_back((unsigned char)i);
Reid Spencerb2bdb942004-07-25 18:07:36 +000059 Out.push_back((unsigned char)(i >> 8));
60 Out.push_back((unsigned char)(i >> 16));
61 Out.push_back((unsigned char)(i >> 24));
62 } else {
63 Out[pos ] = (unsigned char)i;
64 Out[pos+1] = (unsigned char)(i >> 8);
65 Out[pos+2] = (unsigned char)(i >> 16);
66 Out[pos+3] = (unsigned char)(i >> 24);
67 }
68}
69
70inline void BytecodeWriter::output(int i) {
71 output((unsigned)i);
72}
73
74/// output_vbr - Output an unsigned value, by using the least number of bytes
75/// possible. This is useful because many of our "infinite" values are really
76/// very small most of the time; but can be large a few times.
Misha Brukmanb47d28b2005-04-21 21:48:46 +000077/// Data format used: If you read a byte with the high bit set, use the low
78/// seven bits as data and then read another byte.
Reid Spencerb2bdb942004-07-25 18:07:36 +000079inline void BytecodeWriter::output_vbr(uint64_t i) {
80 while (1) {
81 if (i < 0x80) { // done?
82 Out.push_back((unsigned char)i); // We know the high bit is clear...
83 return;
84 }
Misha Brukmanb47d28b2005-04-21 21:48:46 +000085
Reid Spencerb2bdb942004-07-25 18:07:36 +000086 // Nope, we are bigger than a character, output the next 7 bits and set the
87 // high bit to say that there is more coming...
88 Out.push_back(0x80 | ((unsigned char)i & 0x7F));
89 i >>= 7; // Shift out 7 bits now...
90 }
91}
92
93inline void BytecodeWriter::output_vbr(unsigned i) {
94 while (1) {
95 if (i < 0x80) { // done?
96 Out.push_back((unsigned char)i); // We know the high bit is clear...
97 return;
98 }
Misha Brukmanb47d28b2005-04-21 21:48:46 +000099
Reid Spencerb2bdb942004-07-25 18:07:36 +0000100 // Nope, we are bigger than a character, output the next 7 bits and set the
101 // high bit to say that there is more coming...
102 Out.push_back(0x80 | ((unsigned char)i & 0x7F));
103 i >>= 7; // Shift out 7 bits now...
104 }
105}
106
107inline void BytecodeWriter::output_typeid(unsigned i) {
108 if (i <= 0x00FFFFFF)
109 this->output_vbr(i);
110 else {
111 this->output_vbr(0x00FFFFFF);
112 this->output_vbr(i);
113 }
114}
115
116inline void BytecodeWriter::output_vbr(int64_t i) {
Misha Brukmanb47d28b2005-04-21 21:48:46 +0000117 if (i < 0)
Reid Spencerb2bdb942004-07-25 18:07:36 +0000118 output_vbr(((uint64_t)(-i) << 1) | 1); // Set low order sign bit...
119 else
120 output_vbr((uint64_t)i << 1); // Low order bit is clear.
121}
122
123
124inline void BytecodeWriter::output_vbr(int i) {
Misha Brukmanb47d28b2005-04-21 21:48:46 +0000125 if (i < 0)
Reid Spencerb2bdb942004-07-25 18:07:36 +0000126 output_vbr(((unsigned)(-i) << 1) | 1); // Set low order sign bit...
127 else
128 output_vbr((unsigned)i << 1); // Low order bit is clear.
129}
130
Reid Spencerc3e43642004-08-17 07:45:14 +0000131inline void BytecodeWriter::output(const std::string &s) {
Reid Spencerb2bdb942004-07-25 18:07:36 +0000132 unsigned Len = s.length();
133 output_vbr(Len ); // Strings may have an arbitrary length...
134 Out.insert(Out.end(), s.begin(), s.end());
Reid Spencerb2bdb942004-07-25 18:07:36 +0000135}
136
137inline void BytecodeWriter::output_data(const void *Ptr, const void *End) {
138 Out.insert(Out.end(), (const unsigned char*)Ptr, (const unsigned char*)End);
139}
140
141inline void BytecodeWriter::output_float(float& FloatVal) {
142 /// FIXME: This isn't optimal, it has size problems on some platforms
143 /// where FP is not IEEE.
Jim Laskeyb74c6662005-08-17 19:34:49 +0000144 uint32_t i = FloatToBits(FloatVal);
145 Out.push_back( static_cast<unsigned char>( (i & 0xFF )));
146 Out.push_back( static_cast<unsigned char>( (i >> 8) & 0xFF));
147 Out.push_back( static_cast<unsigned char>( (i >> 16) & 0xFF));
148 Out.push_back( static_cast<unsigned char>( (i >> 24) & 0xFF));
Reid Spencerb2bdb942004-07-25 18:07:36 +0000149}
150
151inline void BytecodeWriter::output_double(double& DoubleVal) {
152 /// FIXME: This isn't optimal, it has size problems on some platforms
153 /// where FP is not IEEE.
Jim Laskeyb74c6662005-08-17 19:34:49 +0000154 uint64_t i = DoubleToBits(DoubleVal);
155 Out.push_back( static_cast<unsigned char>( (i & 0xFF )));
156 Out.push_back( static_cast<unsigned char>( (i >> 8) & 0xFF));
157 Out.push_back( static_cast<unsigned char>( (i >> 16) & 0xFF));
158 Out.push_back( static_cast<unsigned char>( (i >> 24) & 0xFF));
159 Out.push_back( static_cast<unsigned char>( (i >> 32) & 0xFF));
160 Out.push_back( static_cast<unsigned char>( (i >> 40) & 0xFF));
161 Out.push_back( static_cast<unsigned char>( (i >> 48) & 0xFF));
162 Out.push_back( static_cast<unsigned char>( (i >> 56) & 0xFF));
Reid Spencerb2bdb942004-07-25 18:07:36 +0000163}
164
Chris Lattner026a5ef2005-11-12 18:34:09 +0000165inline BytecodeBlock::BytecodeBlock(unsigned ID, BytecodeWriter &w,
166 bool elideIfEmpty, bool hasLongFormat)
Reid Spencerb2bdb942004-07-25 18:07:36 +0000167 : Id(ID), Writer(w), ElideIfEmpty(elideIfEmpty), HasLongFormat(hasLongFormat){
168
169 if (HasLongFormat) {
170 w.output(ID);
171 w.output(0U); // For length in long format
172 } else {
173 w.output(0U); /// Place holder for ID and length for this block
174 }
175 Loc = w.size();
176}
177
Chris Lattnereddbc202004-10-14 01:35:17 +0000178inline BytecodeBlock::~BytecodeBlock() { // Do backpatch when block goes out
Misha Brukmanb47d28b2005-04-21 21:48:46 +0000179 // of scope...
Reid Spencerb2bdb942004-07-25 18:07:36 +0000180 if (Loc == Writer.size() && ElideIfEmpty) {
181 // If the block is empty, and we are allowed to, do not emit the block at
182 // all!
183 Writer.resize(Writer.size()-(HasLongFormat?8:4));
184 return;
185 }
186
Reid Spencerb2bdb942004-07-25 18:07:36 +0000187 if (HasLongFormat)
188 Writer.output(unsigned(Writer.size()-Loc), int(Loc-4));
189 else
190 Writer.output(unsigned(Writer.size()-Loc) << 5 | (Id & 0x1F), int(Loc-4));
Reid Spencerb2bdb942004-07-25 18:07:36 +0000191}
192
193//===----------------------------------------------------------------------===//
194//=== Constant Output ===//
195//===----------------------------------------------------------------------===//
196
197void BytecodeWriter::outputType(const Type *T) {
198 output_vbr((unsigned)T->getTypeID());
Misha Brukmanb47d28b2005-04-21 21:48:46 +0000199
Reid Spencerb2bdb942004-07-25 18:07:36 +0000200 // That's all there is to handling primitive types...
201 if (T->isPrimitiveType()) {
202 return; // We might do this if we alias a prim type: %x = type int
203 }
204
205 switch (T->getTypeID()) { // Handle derived types now.
206 case Type::FunctionTyID: {
207 const FunctionType *MT = cast<FunctionType>(T);
208 int Slot = Table.getSlot(MT->getReturnType());
209 assert(Slot != -1 && "Type used but not available!!");
210 output_typeid((unsigned)Slot);
211
212 // Output the number of arguments to function (+1 if varargs):
213 output_vbr((unsigned)MT->getNumParams()+MT->isVarArg());
214
215 // Output all of the arguments...
216 FunctionType::param_iterator I = MT->param_begin();
217 for (; I != MT->param_end(); ++I) {
218 Slot = Table.getSlot(*I);
219 assert(Slot != -1 && "Type used but not available!!");
220 output_typeid((unsigned)Slot);
221 }
222
223 // Terminate list with VoidTy if we are a varargs function...
224 if (MT->isVarArg())
225 output_typeid((unsigned)Type::VoidTyID);
226 break;
227 }
228
229 case Type::ArrayTyID: {
230 const ArrayType *AT = cast<ArrayType>(T);
231 int Slot = Table.getSlot(AT->getElementType());
232 assert(Slot != -1 && "Type used but not available!!");
233 output_typeid((unsigned)Slot);
Reid Spencerb2bdb942004-07-25 18:07:36 +0000234 output_vbr(AT->getNumElements());
235 break;
236 }
237
Brian Gaeke02209042004-08-20 06:00:58 +0000238 case Type::PackedTyID: {
239 const PackedType *PT = cast<PackedType>(T);
240 int Slot = Table.getSlot(PT->getElementType());
241 assert(Slot != -1 && "Type used but not available!!");
242 output_typeid((unsigned)Slot);
243 output_vbr(PT->getNumElements());
244 break;
245 }
246
247
Reid Spencerb2bdb942004-07-25 18:07:36 +0000248 case Type::StructTyID: {
249 const StructType *ST = cast<StructType>(T);
250
251 // Output all of the element types...
252 for (StructType::element_iterator I = ST->element_begin(),
253 E = ST->element_end(); I != E; ++I) {
254 int Slot = Table.getSlot(*I);
255 assert(Slot != -1 && "Type used but not available!!");
256 output_typeid((unsigned)Slot);
257 }
258
259 // Terminate list with VoidTy
260 output_typeid((unsigned)Type::VoidTyID);
261 break;
262 }
263
264 case Type::PointerTyID: {
265 const PointerType *PT = cast<PointerType>(T);
266 int Slot = Table.getSlot(PT->getElementType());
267 assert(Slot != -1 && "Type used but not available!!");
268 output_typeid((unsigned)Slot);
269 break;
270 }
271
Chris Lattnereddbc202004-10-14 01:35:17 +0000272 case Type::OpaqueTyID:
Reid Spencerb2bdb942004-07-25 18:07:36 +0000273 // No need to emit anything, just the count of opaque types is enough.
274 break;
Reid Spencerb2bdb942004-07-25 18:07:36 +0000275
Reid Spencerb2bdb942004-07-25 18:07:36 +0000276 default:
277 std::cerr << __FILE__ << ":" << __LINE__ << ": Don't know how to serialize"
278 << " Type '" << T->getDescription() << "'\n";
279 break;
280 }
281}
282
283void BytecodeWriter::outputConstant(const Constant *CPV) {
284 assert((CPV->getType()->isPrimitiveType() || !CPV->isNullValue()) &&
285 "Shouldn't output null constants!");
286
287 // We must check for a ConstantExpr before switching by type because
288 // a ConstantExpr can be of any type, and has no explicit value.
Misha Brukmanb47d28b2005-04-21 21:48:46 +0000289 //
Reid Spencerb2bdb942004-07-25 18:07:36 +0000290 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
291 // FIXME: Encoding of constant exprs could be much more compact!
292 assert(CE->getNumOperands() > 0 && "ConstantExpr with 0 operands");
Chris Lattner8145bd52004-12-04 21:28:47 +0000293 assert(CE->getNumOperands() != 1 || CE->getOpcode() == Instruction::Cast);
Chris Lattner770709b2004-10-16 18:18:16 +0000294 output_vbr(1+CE->getNumOperands()); // flags as an expr
Reid Spencerb2bdb942004-07-25 18:07:36 +0000295 output_vbr(CE->getOpcode()); // flags as an expr
Misha Brukmanb47d28b2005-04-21 21:48:46 +0000296
Reid Spencerb2bdb942004-07-25 18:07:36 +0000297 for (User::const_op_iterator OI = CE->op_begin(); OI != CE->op_end(); ++OI){
298 int Slot = Table.getSlot(*OI);
299 assert(Slot != -1 && "Unknown constant used in ConstantExpr!!");
300 output_vbr((unsigned)Slot);
301 Slot = Table.getSlot((*OI)->getType());
302 output_typeid((unsigned)Slot);
303 }
304 return;
Chris Lattner770709b2004-10-16 18:18:16 +0000305 } else if (isa<UndefValue>(CPV)) {
306 output_vbr(1U); // 1 -> UndefValue constant.
307 return;
Reid Spencerb2bdb942004-07-25 18:07:36 +0000308 } else {
309 output_vbr(0U); // flag as not a ConstantExpr
310 }
Misha Brukmanb47d28b2005-04-21 21:48:46 +0000311
Reid Spencerb2bdb942004-07-25 18:07:36 +0000312 switch (CPV->getType()->getTypeID()) {
313 case Type::BoolTyID: // Boolean Types
314 if (cast<ConstantBool>(CPV)->getValue())
315 output_vbr(1U);
316 else
317 output_vbr(0U);
318 break;
319
320 case Type::UByteTyID: // Unsigned integer types...
321 case Type::UShortTyID:
322 case Type::UIntTyID:
323 case Type::ULongTyID:
324 output_vbr(cast<ConstantUInt>(CPV)->getValue());
325 break;
326
327 case Type::SByteTyID: // Signed integer types...
328 case Type::ShortTyID:
329 case Type::IntTyID:
330 case Type::LongTyID:
331 output_vbr(cast<ConstantSInt>(CPV)->getValue());
332 break;
333
334 case Type::ArrayTyID: {
335 const ConstantArray *CPA = cast<ConstantArray>(CPV);
336 assert(!CPA->isString() && "Constant strings should be handled specially!");
337
Alkis Evlogimenos83243722004-08-04 08:44:43 +0000338 for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i) {
Reid Spencerb2bdb942004-07-25 18:07:36 +0000339 int Slot = Table.getSlot(CPA->getOperand(i));
340 assert(Slot != -1 && "Constant used but not available!!");
341 output_vbr((unsigned)Slot);
342 }
343 break;
344 }
345
Brian Gaeke02209042004-08-20 06:00:58 +0000346 case Type::PackedTyID: {
347 const ConstantPacked *CP = cast<ConstantPacked>(CPV);
348
349 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i) {
350 int Slot = Table.getSlot(CP->getOperand(i));
351 assert(Slot != -1 && "Constant used but not available!!");
352 output_vbr((unsigned)Slot);
353 }
354 break;
355 }
356
Reid Spencerb2bdb942004-07-25 18:07:36 +0000357 case Type::StructTyID: {
358 const ConstantStruct *CPS = cast<ConstantStruct>(CPV);
Reid Spencerb2bdb942004-07-25 18:07:36 +0000359
Alkis Evlogimenos83243722004-08-04 08:44:43 +0000360 for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i) {
361 int Slot = Table.getSlot(CPS->getOperand(i));
Reid Spencerb2bdb942004-07-25 18:07:36 +0000362 assert(Slot != -1 && "Constant used but not available!!");
363 output_vbr((unsigned)Slot);
364 }
365 break;
366 }
367
368 case Type::PointerTyID:
369 assert(0 && "No non-null, non-constant-expr constants allowed!");
370 abort();
371
372 case Type::FloatTyID: { // Floating point types...
373 float Tmp = (float)cast<ConstantFP>(CPV)->getValue();
374 output_float(Tmp);
375 break;
376 }
377 case Type::DoubleTyID: {
378 double Tmp = cast<ConstantFP>(CPV)->getValue();
379 output_double(Tmp);
380 break;
381 }
382
Misha Brukmanb47d28b2005-04-21 21:48:46 +0000383 case Type::VoidTyID:
Reid Spencerb2bdb942004-07-25 18:07:36 +0000384 case Type::LabelTyID:
385 default:
386 std::cerr << __FILE__ << ":" << __LINE__ << ": Don't know how to serialize"
387 << " type '" << *CPV->getType() << "'\n";
388 break;
389 }
390 return;
391}
392
Chris Lattner44706912006-01-25 23:08:15 +0000393/// outputInlineAsm - InlineAsm's get emitted to the constant pool, so they can
394/// be shared by multiple uses.
395void BytecodeWriter::outputInlineAsm(const InlineAsm *IA) {
396 // Output a marker, so we know when we have one one parsing the constant pool.
397 // Note that this encoding is 5 bytes: not very efficient for a marker. Since
398 // unique inline asms are rare, this should hardly matter.
399 output_vbr(~0U);
400
401 output(IA->getAsmString());
402 output(IA->getConstraintString());
403 output_vbr(unsigned(IA->hasSideEffects()));
404}
405
Reid Spencerb2bdb942004-07-25 18:07:36 +0000406void BytecodeWriter::outputConstantStrings() {
407 SlotCalculator::string_iterator I = Table.string_begin();
408 SlotCalculator::string_iterator E = Table.string_end();
409 if (I == E) return; // No strings to emit
410
411 // If we have != 0 strings to emit, output them now. Strings are emitted into
412 // the 'void' type plane.
413 output_vbr(unsigned(E-I));
414 output_typeid(Type::VoidTyID);
Misha Brukmanb47d28b2005-04-21 21:48:46 +0000415
Reid Spencerb2bdb942004-07-25 18:07:36 +0000416 // Emit all of the strings.
417 for (I = Table.string_begin(); I != E; ++I) {
418 const ConstantArray *Str = *I;
419 int Slot = Table.getSlot(Str->getType());
420 assert(Slot != -1 && "Constant string of unknown type?");
421 output_typeid((unsigned)Slot);
Misha Brukmanb47d28b2005-04-21 21:48:46 +0000422
Reid Spencerb2bdb942004-07-25 18:07:36 +0000423 // Now that we emitted the type (which indicates the size of the string),
424 // emit all of the characters.
425 std::string Val = Str->getAsString();
426 output_data(Val.c_str(), Val.c_str()+Val.size());
427 }
428}
429
430//===----------------------------------------------------------------------===//
431//=== Instruction Output ===//
432//===----------------------------------------------------------------------===//
Reid Spencerb2bdb942004-07-25 18:07:36 +0000433
Chris Lattner0ce80cd2005-02-27 06:18:25 +0000434// outputInstructionFormat0 - Output those weird instructions that have a large
Chris Lattner129535c2005-05-06 22:34:01 +0000435// number of operands or have large operands themselves.
Reid Spencerb2bdb942004-07-25 18:07:36 +0000436//
437// Format: [opcode] [type] [numargs] [arg0] [arg1] ... [arg<numargs-1>]
438//
Chris Lattner3d980082004-10-14 01:46:07 +0000439void BytecodeWriter::outputInstructionFormat0(const Instruction *I,
440 unsigned Opcode,
441 const SlotCalculator &Table,
442 unsigned Type) {
Reid Spencerb2bdb942004-07-25 18:07:36 +0000443 // Opcode must have top two bits clear...
444 output_vbr(Opcode << 2); // Instruction Opcode ID
445 output_typeid(Type); // Result type
446
447 unsigned NumArgs = I->getNumOperands();
Andrew Lenharth9144ec42005-06-18 18:34:52 +0000448 output_vbr(NumArgs + (isa<CastInst>(I) ||
Chris Lattner129535c2005-05-06 22:34:01 +0000449 isa<VAArgInst>(I) || Opcode == 56 || Opcode == 58));
Reid Spencerb2bdb942004-07-25 18:07:36 +0000450
451 if (!isa<GetElementPtrInst>(&I)) {
452 for (unsigned i = 0; i < NumArgs; ++i) {
453 int Slot = Table.getSlot(I->getOperand(i));
Misha Brukmanb47d28b2005-04-21 21:48:46 +0000454 assert(Slot >= 0 && "No slot number for value!?!?");
Reid Spencerb2bdb942004-07-25 18:07:36 +0000455 output_vbr((unsigned)Slot);
456 }
457
458 if (isa<CastInst>(I) || isa<VAArgInst>(I)) {
459 int Slot = Table.getSlot(I->getType());
460 assert(Slot != -1 && "Cast return type unknown?");
461 output_typeid((unsigned)Slot);
Chris Lattner129535c2005-05-06 22:34:01 +0000462 } else if (Opcode == 56) { // Invoke escape sequence
463 output_vbr(cast<InvokeInst>(I)->getCallingConv());
464 } else if (Opcode == 58) { // Call escape sequence
465 output_vbr((cast<CallInst>(I)->getCallingConv() << 1) |
Jeff Cohen6dc66722005-05-07 02:44:04 +0000466 unsigned(cast<CallInst>(I)->isTailCall()));
Reid Spencerb2bdb942004-07-25 18:07:36 +0000467 }
Reid Spencerb2bdb942004-07-25 18:07:36 +0000468 } else {
469 int Slot = Table.getSlot(I->getOperand(0));
Misha Brukmanb47d28b2005-04-21 21:48:46 +0000470 assert(Slot >= 0 && "No slot number for value!?!?");
Reid Spencerb2bdb942004-07-25 18:07:36 +0000471 output_vbr(unsigned(Slot));
472
473 // We need to encode the type of sequential type indices into their slot #
474 unsigned Idx = 1;
475 for (gep_type_iterator TI = gep_type_begin(I), E = gep_type_end(I);
476 Idx != NumArgs; ++TI, ++Idx) {
477 Slot = Table.getSlot(I->getOperand(Idx));
Misha Brukmanb47d28b2005-04-21 21:48:46 +0000478 assert(Slot >= 0 && "No slot number for value!?!?");
479
Reid Spencerb2bdb942004-07-25 18:07:36 +0000480 if (isa<SequentialType>(*TI)) {
481 unsigned IdxId;
482 switch (I->getOperand(Idx)->getType()->getTypeID()) {
483 default: assert(0 && "Unknown index type!");
484 case Type::UIntTyID: IdxId = 0; break;
485 case Type::IntTyID: IdxId = 1; break;
486 case Type::ULongTyID: IdxId = 2; break;
487 case Type::LongTyID: IdxId = 3; break;
488 }
489 Slot = (Slot << 2) | IdxId;
490 }
491 output_vbr(unsigned(Slot));
492 }
493 }
Reid Spencerb2bdb942004-07-25 18:07:36 +0000494}
495
496
497// outputInstrVarArgsCall - Output the absurdly annoying varargs function calls.
498// This are more annoying than most because the signature of the call does not
499// tell us anything about the types of the arguments in the varargs portion.
500// Because of this, we encode (as type 0) all of the argument types explicitly
501// before the argument value. This really sucks, but you shouldn't be using
502// varargs functions in your code! *death to printf*!
503//
504// Format: [opcode] [type] [numargs] [arg0] [arg1] ... [arg<numargs-1>]
505//
Misha Brukmanb47d28b2005-04-21 21:48:46 +0000506void BytecodeWriter::outputInstrVarArgsCall(const Instruction *I,
507 unsigned Opcode,
508 const SlotCalculator &Table,
509 unsigned Type) {
Reid Spencerb2bdb942004-07-25 18:07:36 +0000510 assert(isa<CallInst>(I) || isa<InvokeInst>(I));
511 // Opcode must have top two bits clear...
512 output_vbr(Opcode << 2); // Instruction Opcode ID
513 output_typeid(Type); // Result type (varargs type)
514
515 const PointerType *PTy = cast<PointerType>(I->getOperand(0)->getType());
516 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
517 unsigned NumParams = FTy->getNumParams();
518
519 unsigned NumFixedOperands;
520 if (isa<CallInst>(I)) {
521 // Output an operand for the callee and each fixed argument, then two for
522 // each variable argument.
523 NumFixedOperands = 1+NumParams;
524 } else {
525 assert(isa<InvokeInst>(I) && "Not call or invoke??");
526 // Output an operand for the callee and destinations, then two for each
527 // variable argument.
528 NumFixedOperands = 3+NumParams;
529 }
530 output_vbr(2 * I->getNumOperands()-NumFixedOperands);
531
532 // The type for the function has already been emitted in the type field of the
533 // instruction. Just emit the slot # now.
534 for (unsigned i = 0; i != NumFixedOperands; ++i) {
535 int Slot = Table.getSlot(I->getOperand(i));
Misha Brukmanb47d28b2005-04-21 21:48:46 +0000536 assert(Slot >= 0 && "No slot number for value!?!?");
Reid Spencerb2bdb942004-07-25 18:07:36 +0000537 output_vbr((unsigned)Slot);
538 }
539
540 for (unsigned i = NumFixedOperands, e = I->getNumOperands(); i != e; ++i) {
541 // Output Arg Type ID
542 int Slot = Table.getSlot(I->getOperand(i)->getType());
Misha Brukmanb47d28b2005-04-21 21:48:46 +0000543 assert(Slot >= 0 && "No slot number for value!?!?");
Reid Spencerb2bdb942004-07-25 18:07:36 +0000544 output_typeid((unsigned)Slot);
Misha Brukmanb47d28b2005-04-21 21:48:46 +0000545
Reid Spencerb2bdb942004-07-25 18:07:36 +0000546 // Output arg ID itself
547 Slot = Table.getSlot(I->getOperand(i));
Misha Brukmanb47d28b2005-04-21 21:48:46 +0000548 assert(Slot >= 0 && "No slot number for value!?!?");
Reid Spencerb2bdb942004-07-25 18:07:36 +0000549 output_vbr((unsigned)Slot);
550 }
Reid Spencerb2bdb942004-07-25 18:07:36 +0000551}
552
553
554// outputInstructionFormat1 - Output one operand instructions, knowing that no
555// operand index is >= 2^12.
556//
Misha Brukmanb47d28b2005-04-21 21:48:46 +0000557inline void BytecodeWriter::outputInstructionFormat1(const Instruction *I,
558 unsigned Opcode,
559 unsigned *Slots,
560 unsigned Type) {
Reid Spencerb2bdb942004-07-25 18:07:36 +0000561 // bits Instruction format:
562 // --------------------------
563 // 01-00: Opcode type, fixed to 1.
564 // 07-02: Opcode
565 // 19-08: Resulting type plane
566 // 31-20: Operand #1 (if set to (2^12-1), then zero operands)
567 //
Chris Lattner3d980082004-10-14 01:46:07 +0000568 output(1 | (Opcode << 2) | (Type << 8) | (Slots[0] << 20));
Reid Spencerb2bdb942004-07-25 18:07:36 +0000569}
570
571
572// outputInstructionFormat2 - Output two operand instructions, knowing that no
573// operand index is >= 2^8.
574//
Misha Brukmanb47d28b2005-04-21 21:48:46 +0000575inline void BytecodeWriter::outputInstructionFormat2(const Instruction *I,
576 unsigned Opcode,
577 unsigned *Slots,
578 unsigned Type) {
Reid Spencerb2bdb942004-07-25 18:07:36 +0000579 // bits Instruction format:
580 // --------------------------
581 // 01-00: Opcode type, fixed to 2.
582 // 07-02: Opcode
583 // 15-08: Resulting type plane
584 // 23-16: Operand #1
Misha Brukmanb47d28b2005-04-21 21:48:46 +0000585 // 31-24: Operand #2
Reid Spencerb2bdb942004-07-25 18:07:36 +0000586 //
Chris Lattner3d980082004-10-14 01:46:07 +0000587 output(2 | (Opcode << 2) | (Type << 8) | (Slots[0] << 16) | (Slots[1] << 24));
Reid Spencerb2bdb942004-07-25 18:07:36 +0000588}
589
590
591// outputInstructionFormat3 - Output three operand instructions, knowing that no
592// operand index is >= 2^6.
593//
Misha Brukmanb47d28b2005-04-21 21:48:46 +0000594inline void BytecodeWriter::outputInstructionFormat3(const Instruction *I,
Reid Spencerb2bdb942004-07-25 18:07:36 +0000595 unsigned Opcode,
Misha Brukmanb47d28b2005-04-21 21:48:46 +0000596 unsigned *Slots,
597 unsigned Type) {
Reid Spencerb2bdb942004-07-25 18:07:36 +0000598 // bits Instruction format:
599 // --------------------------
600 // 01-00: Opcode type, fixed to 3.
601 // 07-02: Opcode
602 // 13-08: Resulting type plane
603 // 19-14: Operand #1
604 // 25-20: Operand #2
605 // 31-26: Operand #3
606 //
Chris Lattner3d980082004-10-14 01:46:07 +0000607 output(3 | (Opcode << 2) | (Type << 8) |
Chris Lattnere8fe2c22004-10-14 01:57:28 +0000608 (Slots[0] << 14) | (Slots[1] << 20) | (Slots[2] << 26));
Reid Spencerb2bdb942004-07-25 18:07:36 +0000609}
610
611void BytecodeWriter::outputInstruction(const Instruction &I) {
Chris Lattner4e63e3f2005-05-13 23:35:47 +0000612 assert(I.getOpcode() < 56 && "Opcode too big???");
Reid Spencerb2bdb942004-07-25 18:07:36 +0000613 unsigned Opcode = I.getOpcode();
614 unsigned NumOperands = I.getNumOperands();
615
Chris Lattnerfb6f1742005-05-06 06:13:34 +0000616 // Encode 'tail call' as 61, 'volatile load' as 62, and 'volatile store' as
617 // 63.
Chris Lattner129535c2005-05-06 22:34:01 +0000618 if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
619 if (CI->getCallingConv() == CallingConv::C) {
620 if (CI->isTailCall())
621 Opcode = 61; // CCC + Tail Call
622 else
623 ; // Opcode = Instruction::Call
624 } else if (CI->getCallingConv() == CallingConv::Fast) {
625 if (CI->isTailCall())
626 Opcode = 59; // FastCC + TailCall
627 else
628 Opcode = 60; // FastCC + Not Tail Call
629 } else {
630 Opcode = 58; // Call escape sequence.
631 }
632 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
633 if (II->getCallingConv() == CallingConv::Fast)
634 Opcode = 57; // FastCC invoke.
635 else if (II->getCallingConv() != CallingConv::C)
636 Opcode = 56; // Invoke escape sequence.
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000637
Chris Lattner129535c2005-05-06 22:34:01 +0000638 } else if (isa<LoadInst>(I) && cast<LoadInst>(I).isVolatile()) {
Reid Spencerb2bdb942004-07-25 18:07:36 +0000639 Opcode = 62;
Chris Lattner129535c2005-05-06 22:34:01 +0000640 } else if (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile()) {
Reid Spencerb2bdb942004-07-25 18:07:36 +0000641 Opcode = 63;
Chris Lattner129535c2005-05-06 22:34:01 +0000642 }
Reid Spencerb2bdb942004-07-25 18:07:36 +0000643
644 // Figure out which type to encode with the instruction. Typically we want
645 // the type of the first parameter, as opposed to the type of the instruction
646 // (for example, with setcc, we always know it returns bool, but the type of
647 // the first param is actually interesting). But if we have no arguments
Misha Brukmanb47d28b2005-04-21 21:48:46 +0000648 // we take the type of the instruction itself.
Reid Spencerb2bdb942004-07-25 18:07:36 +0000649 //
650 const Type *Ty;
651 switch (I.getOpcode()) {
652 case Instruction::Select:
653 case Instruction::Malloc:
654 case Instruction::Alloca:
655 Ty = I.getType(); // These ALWAYS want to encode the return type
656 break;
657 case Instruction::Store:
658 Ty = I.getOperand(1)->getType(); // Encode the pointer type...
659 assert(isa<PointerType>(Ty) && "Store to nonpointer type!?!?");
660 break;
661 default: // Otherwise use the default behavior...
662 Ty = NumOperands ? I.getOperand(0)->getType() : I.getType();
663 break;
664 }
665
666 unsigned Type;
667 int Slot = Table.getSlot(Ty);
668 assert(Slot != -1 && "Type not available!!?!");
669 Type = (unsigned)Slot;
670
671 // Varargs calls and invokes are encoded entirely different from any other
672 // instructions.
673 if (const CallInst *CI = dyn_cast<CallInst>(&I)){
674 const PointerType *Ty =cast<PointerType>(CI->getCalledValue()->getType());
675 if (cast<FunctionType>(Ty->getElementType())->isVarArg()) {
676 outputInstrVarArgsCall(CI, Opcode, Table, Type);
677 return;
678 }
679 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
680 const PointerType *Ty =cast<PointerType>(II->getCalledValue()->getType());
681 if (cast<FunctionType>(Ty->getElementType())->isVarArg()) {
682 outputInstrVarArgsCall(II, Opcode, Table, Type);
683 return;
684 }
685 }
686
687 if (NumOperands <= 3) {
688 // Make sure that we take the type number into consideration. We don't want
689 // to overflow the field size for the instruction format we select.
690 //
691 unsigned MaxOpSlot = Type;
692 unsigned Slots[3]; Slots[0] = (1 << 12)-1; // Marker to signify 0 operands
Misha Brukmanb47d28b2005-04-21 21:48:46 +0000693
Reid Spencerb2bdb942004-07-25 18:07:36 +0000694 for (unsigned i = 0; i != NumOperands; ++i) {
695 int slot = Table.getSlot(I.getOperand(i));
696 assert(slot != -1 && "Broken bytecode!");
697 if (unsigned(slot) > MaxOpSlot) MaxOpSlot = unsigned(slot);
698 Slots[i] = unsigned(slot);
699 }
700
701 // Handle the special cases for various instructions...
702 if (isa<CastInst>(I) || isa<VAArgInst>(I)) {
703 // Cast has to encode the destination type as the second argument in the
704 // packet, or else we won't know what type to cast to!
705 Slots[1] = Table.getSlot(I.getType());
706 assert(Slots[1] != ~0U && "Cast return type unknown?");
707 if (Slots[1] > MaxOpSlot) MaxOpSlot = Slots[1];
708 NumOperands++;
Chris Lattner575e8282005-11-05 22:08:14 +0000709 } else if (const AllocationInst *AI = dyn_cast<AllocationInst>(&I)) {
710 assert(NumOperands == 1 && "Bogus allocation!");
711 if (AI->getAlignment()) {
712 Slots[1] = Log2_32(AI->getAlignment())+1;
713 if (Slots[1] > MaxOpSlot) MaxOpSlot = Slots[1];
714 NumOperands = 2;
715 }
Reid Spencerb2bdb942004-07-25 18:07:36 +0000716 } else if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&I)) {
717 // We need to encode the type of sequential type indices into their slot #
718 unsigned Idx = 1;
719 for (gep_type_iterator I = gep_type_begin(GEP), E = gep_type_end(GEP);
720 I != E; ++I, ++Idx)
721 if (isa<SequentialType>(*I)) {
722 unsigned IdxId;
723 switch (GEP->getOperand(Idx)->getType()->getTypeID()) {
724 default: assert(0 && "Unknown index type!");
725 case Type::UIntTyID: IdxId = 0; break;
726 case Type::IntTyID: IdxId = 1; break;
727 case Type::ULongTyID: IdxId = 2; break;
728 case Type::LongTyID: IdxId = 3; break;
729 }
730 Slots[Idx] = (Slots[Idx] << 2) | IdxId;
731 if (Slots[Idx] > MaxOpSlot) MaxOpSlot = Slots[Idx];
732 }
Chris Lattner129535c2005-05-06 22:34:01 +0000733 } else if (Opcode == 58) {
734 // If this is the escape sequence for call, emit the tailcall/cc info.
735 const CallInst &CI = cast<CallInst>(I);
736 ++NumOperands;
Chris Lattner620895a2006-05-19 21:57:37 +0000737 if (NumOperands <= 3) {
738 Slots[NumOperands-1] =
739 (CI.getCallingConv() << 1)|unsigned(CI.isTailCall());
Chris Lattner129535c2005-05-06 22:34:01 +0000740 if (Slots[NumOperands-1] > MaxOpSlot)
741 MaxOpSlot = Slots[NumOperands-1];
742 }
743 } else if (Opcode == 56) {
744 // Invoke escape seq has at least 4 operands to encode.
745 ++NumOperands;
Reid Spencerb2bdb942004-07-25 18:07:36 +0000746 }
747
748 // Decide which instruction encoding to use. This is determined primarily
749 // by the number of operands, and secondarily by whether or not the max
750 // operand will fit into the instruction encoding. More operands == fewer
751 // bits per operand.
752 //
753 switch (NumOperands) {
754 case 0:
755 case 1:
756 if (MaxOpSlot < (1 << 12)-1) { // -1 because we use 4095 to indicate 0 ops
757 outputInstructionFormat1(&I, Opcode, Slots, Type);
758 return;
759 }
760 break;
761
762 case 2:
763 if (MaxOpSlot < (1 << 8)) {
764 outputInstructionFormat2(&I, Opcode, Slots, Type);
765 return;
766 }
767 break;
768
769 case 3:
770 if (MaxOpSlot < (1 << 6)) {
771 outputInstructionFormat3(&I, Opcode, Slots, Type);
772 return;
773 }
774 break;
775 default:
776 break;
777 }
778 }
779
780 // If we weren't handled before here, we either have a large number of
781 // operands or a large operand index that we are referring to.
782 outputInstructionFormat0(&I, Opcode, Table, Type);
783}
784
785//===----------------------------------------------------------------------===//
786//=== Block Output ===//
787//===----------------------------------------------------------------------===//
788
Misha Brukmanb47d28b2005-04-21 21:48:46 +0000789BytecodeWriter::BytecodeWriter(std::vector<unsigned char> &o, const Module *M)
Reid Spencer0aff01a2004-05-26 07:37:11 +0000790 : Out(o), Table(M) {
Chris Lattner2f7c9632001-06-06 20:29:01 +0000791
Chris Lattner6229fbf2004-01-14 23:36:54 +0000792 // Emit the signature...
793 static const unsigned char *Sig = (const unsigned char*)"llvm";
Reid Spencerb2bdb942004-07-25 18:07:36 +0000794 output_data(Sig, Sig+4);
Chris Lattner2f7c9632001-06-06 20:29:01 +0000795
796 // Emit the top level CLASS block.
Reid Spencerb2bdb942004-07-25 18:07:36 +0000797 BytecodeBlock ModuleBlock(BytecodeFormat::ModuleBlockID, *this, false, true);
Chris Lattner2f7c9632001-06-06 20:29:01 +0000798
Chris Lattner55a07ad2003-08-24 13:47:36 +0000799 bool isBigEndian = M->getEndianness() == Module::BigEndian;
800 bool hasLongPointers = M->getPointerSize() == Module::Pointer64;
801 bool hasNoEndianness = M->getEndianness() == Module::AnyEndianness;
802 bool hasNoPointerSize = M->getPointerSize() == Module::AnyPointerSize;
Chris Lattner428bf5a2003-03-19 20:56:46 +0000803
Chris Lattner770709b2004-10-16 18:18:16 +0000804 // Output the version identifier and other information.
Misha Brukmanb47d28b2005-04-21 21:48:46 +0000805 unsigned Version = (BCVersionNum << 4) |
Reid Spencerc3e43642004-08-17 07:45:14 +0000806 (unsigned)isBigEndian | (hasLongPointers << 1) |
Misha Brukmanb47d28b2005-04-21 21:48:46 +0000807 (hasNoEndianness << 2) |
Reid Spencerc3e43642004-08-17 07:45:14 +0000808 (hasNoPointerSize << 3);
Reid Spencerb2bdb942004-07-25 18:07:36 +0000809 output_vbr(Version);
Chris Lattner2f7c9632001-06-06 20:29:01 +0000810
Reid Spencera52b0002004-07-04 11:45:47 +0000811 // The Global type plane comes first
Chris Lattner428bf5a2003-03-19 20:56:46 +0000812 {
Reid Spencerb2bdb942004-07-25 18:07:36 +0000813 BytecodeBlock CPool(BytecodeFormat::GlobalTypePlaneBlockID, *this );
Reid Spencera52b0002004-07-04 11:45:47 +0000814 outputTypes(Type::FirstDerivedTyID);
Chris Lattner428bf5a2003-03-19 20:56:46 +0000815 }
Chris Lattner2f7c9632001-06-06 20:29:01 +0000816
Chris Lattner428bf5a2003-03-19 20:56:46 +0000817 // The ModuleInfoBlock follows directly after the type information
Chris Lattnerb97ef9f2001-09-07 16:39:41 +0000818 outputModuleInfoBlock(M);
819
Chris Lattner428bf5a2003-03-19 20:56:46 +0000820 // Output module level constants, used for global variable initializers
821 outputConstants(false);
822
Chris Lattner6915f8f2002-04-07 22:49:37 +0000823 // Do the whole module now! Process each function at a time...
Chris Lattner7076ff22002-06-25 16:13:21 +0000824 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
Chris Lattner428bf5a2003-03-19 20:56:46 +0000825 outputFunction(I);
Chris Lattnerb97ef9f2001-09-07 16:39:41 +0000826
827 // If needed, output the symbol table for the module...
Chris Lattner98cf1f52002-11-20 18:36:02 +0000828 outputSymbolTable(M->getSymbolTable());
Chris Lattner2f7c9632001-06-06 20:29:01 +0000829}
830
Chris Lattner3d980082004-10-14 01:46:07 +0000831void BytecodeWriter::outputTypes(unsigned TypeNum) {
Reid Spencera52b0002004-07-04 11:45:47 +0000832 // Write the type plane for types first because earlier planes (e.g. for a
833 // primitive type like float) may have constants constructed using types
834 // coming later (e.g., via getelementptr from a pointer type). The type
835 // plane is needed before types can be fwd or bkwd referenced.
836 const std::vector<const Type*>& Types = Table.getTypes();
837 assert(!Types.empty() && "No types at all?");
838 assert(TypeNum <= Types.size() && "Invalid TypeNo index");
839
840 unsigned NumEntries = Types.size() - TypeNum;
Misha Brukmanb47d28b2005-04-21 21:48:46 +0000841
Reid Spencera52b0002004-07-04 11:45:47 +0000842 // Output type header: [num entries]
Reid Spencerb2bdb942004-07-25 18:07:36 +0000843 output_vbr(NumEntries);
Reid Spencera52b0002004-07-04 11:45:47 +0000844
845 for (unsigned i = TypeNum; i < TypeNum+NumEntries; ++i)
846 outputType(Types[i]);
847}
848
Vikram S. Advec1b6474a2002-07-14 23:07:51 +0000849// Helper function for outputConstants().
850// Writes out all the constants in the plane Plane starting at entry StartNo.
Misha Brukmanb47d28b2005-04-21 21:48:46 +0000851//
Vikram S. Advec1b6474a2002-07-14 23:07:51 +0000852void BytecodeWriter::outputConstantsInPlane(const std::vector<const Value*>
853 &Plane, unsigned StartNo) {
854 unsigned ValNo = StartNo;
Misha Brukmanb47d28b2005-04-21 21:48:46 +0000855
Chris Lattner6229fbf2004-01-14 23:36:54 +0000856 // Scan through and ignore function arguments, global values, and constant
857 // strings.
858 for (; ValNo < Plane.size() &&
859 (isa<Argument>(Plane[ValNo]) || isa<GlobalValue>(Plane[ValNo]) ||
860 (isa<ConstantArray>(Plane[ValNo]) &&
861 cast<ConstantArray>(Plane[ValNo])->isString())); ValNo++)
Vikram S. Advec1b6474a2002-07-14 23:07:51 +0000862 /*empty*/;
863
864 unsigned NC = ValNo; // Number of constants
Chris Lattner44706912006-01-25 23:08:15 +0000865 for (; NC < Plane.size() && (isa<Constant>(Plane[NC]) ||
866 isa<InlineAsm>(Plane[NC])); NC++)
Vikram S. Advec1b6474a2002-07-14 23:07:51 +0000867 /*empty*/;
868 NC -= ValNo; // Convert from index into count
869 if (NC == 0) return; // Skip empty type planes...
870
Chris Lattner9a38c78f2004-01-14 16:54:21 +0000871 // FIXME: Most slabs only have 1 or 2 entries! We should encode this much
872 // more compactly.
873
Vikram S. Advec1b6474a2002-07-14 23:07:51 +0000874 // Output type header: [num entries][type id number]
875 //
Reid Spencerb2bdb942004-07-25 18:07:36 +0000876 output_vbr(NC);
Vikram S. Advec1b6474a2002-07-14 23:07:51 +0000877
878 // Output the Type ID Number...
Alkis Evlogimenos8faf8d92003-10-17 02:02:40 +0000879 int Slot = Table.getSlot(Plane.front()->getType());
Vikram S. Advec1b6474a2002-07-14 23:07:51 +0000880 assert (Slot != -1 && "Type in constant pool but not in function!!");
Reid Spencerb2bdb942004-07-25 18:07:36 +0000881 output_typeid((unsigned)Slot);
Vikram S. Advec1b6474a2002-07-14 23:07:51 +0000882
Vikram S. Advec1b6474a2002-07-14 23:07:51 +0000883 for (unsigned i = ValNo; i < ValNo+NC; ++i) {
884 const Value *V = Plane[i];
Chris Lattner44706912006-01-25 23:08:15 +0000885 if (const Constant *C = dyn_cast<Constant>(V))
Reid Spencer51fe3362004-07-18 00:16:21 +0000886 outputConstant(C);
Chris Lattner44706912006-01-25 23:08:15 +0000887 else
888 outputInlineAsm(cast<InlineAsm>(V));
Vikram S. Advec1b6474a2002-07-14 23:07:51 +0000889 }
890}
891
Chris Lattner1243e1c2005-05-05 22:21:19 +0000892static inline bool hasNullValue(const Type *Ty) {
893 return Ty != Type::LabelTy && Ty != Type::VoidTy && !isa<OpaqueType>(Ty);
Chris Lattner677af4a2004-01-17 23:25:43 +0000894}
895
Chris Lattner57698e22002-03-26 18:01:55 +0000896void BytecodeWriter::outputConstants(bool isFunction) {
Reid Spencerb2bdb942004-07-25 18:07:36 +0000897 BytecodeBlock CPool(BytecodeFormat::ConstantPoolBlockID, *this,
Chris Lattner4c572672004-01-15 21:06:57 +0000898 true /* Elide block if empty */);
Chris Lattner2f7c9632001-06-06 20:29:01 +0000899
900 unsigned NumPlanes = Table.getNumPlanes();
Chris Lattner4a207912003-05-22 18:35:38 +0000901
Reid Spencer51fe3362004-07-18 00:16:21 +0000902 if (isFunction)
903 // Output the type plane before any constants!
Chris Lattner770709b2004-10-16 18:18:16 +0000904 outputTypes(Table.getModuleTypeLevel());
Reid Spencer51fe3362004-07-18 00:16:21 +0000905 else
Chris Lattner3d980082004-10-14 01:46:07 +0000906 // Output module-level string constants before any other constants.
Chris Lattner6229fbf2004-01-14 23:36:54 +0000907 outputConstantStrings();
908
Reid Spencera52b0002004-07-04 11:45:47 +0000909 for (unsigned pno = 0; pno != NumPlanes; pno++) {
910 const std::vector<const Value*> &Plane = Table.getPlane(pno);
911 if (!Plane.empty()) { // Skip empty type planes...
912 unsigned ValNo = 0;
913 if (isFunction) // Don't re-emit module constants
Reid Spencer2fa95bc2004-07-04 11:46:15 +0000914 ValNo += Table.getModuleLevel(pno);
Misha Brukmanb47d28b2005-04-21 21:48:46 +0000915
Chris Lattner1243e1c2005-05-05 22:21:19 +0000916 if (hasNullValue(Plane[0]->getType())) {
Reid Spencer2fa95bc2004-07-04 11:46:15 +0000917 // Skip zero initializer
918 if (ValNo == 0)
919 ValNo = 1;
Chris Lattner4a207912003-05-22 18:35:38 +0000920 }
Misha Brukmanb47d28b2005-04-21 21:48:46 +0000921
Reid Spencera52b0002004-07-04 11:45:47 +0000922 // Write out constants in the plane
923 outputConstantsInPlane(Plane, ValNo);
Chris Lattner4a207912003-05-22 18:35:38 +0000924 }
Reid Spencera52b0002004-07-04 11:45:47 +0000925 }
Chris Lattner2f7c9632001-06-06 20:29:01 +0000926}
927
Chris Lattner2d05c602003-10-16 18:28:50 +0000928static unsigned getEncodedLinkage(const GlobalValue *GV) {
929 switch (GV->getLinkage()) {
930 default: assert(0 && "Invalid linkage!");
931 case GlobalValue::ExternalLinkage: return 0;
Chris Lattner2d05c602003-10-16 18:28:50 +0000932 case GlobalValue::WeakLinkage: return 1;
933 case GlobalValue::AppendingLinkage: return 2;
934 case GlobalValue::InternalLinkage: return 3;
Chris Lattnerdc832932003-10-18 06:30:21 +0000935 case GlobalValue::LinkOnceLinkage: return 4;
Chris Lattner2d05c602003-10-16 18:28:50 +0000936 }
937}
938
Chris Lattner2f7c9632001-06-06 20:29:01 +0000939void BytecodeWriter::outputModuleInfoBlock(const Module *M) {
Reid Spencerb2bdb942004-07-25 18:07:36 +0000940 BytecodeBlock ModuleInfoBlock(BytecodeFormat::ModuleGlobalInfoBlockID, *this);
Misha Brukmanb47d28b2005-04-21 21:48:46 +0000941
Chris Lattner8e1e6112005-11-12 01:33:40 +0000942 // Give numbers to sections as we encounter them.
943 unsigned SectionIDCounter = 0;
944 std::vector<std::string> SectionNames;
945 std::map<std::string, unsigned> SectionID;
946
Chris Lattnerda975502001-09-10 07:58:01 +0000947 // Output the types for the global variables in the module...
Chris Lattnerb25b6302005-05-06 20:27:03 +0000948 for (Module::const_global_iterator I = M->global_begin(),
Chris Lattner547f20c2005-11-06 07:11:04 +0000949 End = M->global_end(); I != End; ++I) {
Alkis Evlogimenos8faf8d92003-10-17 02:02:40 +0000950 int Slot = Table.getSlot(I->getType());
Chris Lattnerda975502001-09-10 07:58:01 +0000951 assert(Slot != -1 && "Module global vars is broken!");
Chris Lattner37798642001-09-18 04:01:05 +0000952
Chris Lattner547f20c2005-11-06 07:11:04 +0000953 assert((I->hasInitializer() || !I->hasInternalLinkage()) &&
954 "Global must have an initializer or have external linkage!");
955
Chris Lattnerdc832932003-10-18 06:30:21 +0000956 // Fields: bit0 = isConstant, bit1 = hasInitializer, bit2-4=Linkage,
Chris Lattner547f20c2005-11-06 07:11:04 +0000957 // bit5+ = Slot # for type.
Chris Lattner8e1e6112005-11-12 01:33:40 +0000958 bool HasExtensionWord = (I->getAlignment() != 0) || I->hasSection();
Chris Lattner547f20c2005-11-06 07:11:04 +0000959
960 // If we need to use the extension byte, set linkage=3(internal) and
961 // initializer = 0 (impossible!).
962 if (!HasExtensionWord) {
963 unsigned oSlot = ((unsigned)Slot << 5) | (getEncodedLinkage(I) << 2) |
964 (I->hasInitializer() << 1) | (unsigned)I->isConstant();
965 output_vbr(oSlot);
966 } else {
967 unsigned oSlot = ((unsigned)Slot << 5) | (3 << 2) |
968 (0 << 1) | (unsigned)I->isConstant();
969 output_vbr(oSlot);
970
971 // The extension word has this format: bit 0 = has initializer, bit 1-3 =
Chris Lattner8e1e6112005-11-12 01:33:40 +0000972 // linkage, bit 4-8 = alignment (log2), bit 9 = has SectionID,
973 // bits 10+ = future use.
Jeff Cohen045f0962005-11-12 01:01:50 +0000974 unsigned ExtWord = (unsigned)I->hasInitializer() |
975 (getEncodedLinkage(I) << 1) |
Chris Lattner8e1e6112005-11-12 01:33:40 +0000976 ((Log2_32(I->getAlignment())+1) << 4) |
977 ((unsigned)I->hasSection() << 9);
Chris Lattner547f20c2005-11-06 07:11:04 +0000978 output_vbr(ExtWord);
Chris Lattner8e1e6112005-11-12 01:33:40 +0000979 if (I->hasSection()) {
980 // Give section names unique ID's.
981 unsigned &Entry = SectionID[I->getSection()];
982 if (Entry == 0) {
983 Entry = ++SectionIDCounter;
984 SectionNames.push_back(I->getSection());
985 }
986 output_vbr(Entry);
987 }
Chris Lattner547f20c2005-11-06 07:11:04 +0000988 }
Chris Lattner37798642001-09-18 04:01:05 +0000989
Chris Lattner81125b62001-10-13 06:48:38 +0000990 // If we have an initializer, output it now.
Chris Lattner7076ff22002-06-25 16:13:21 +0000991 if (I->hasInitializer()) {
Alkis Evlogimenos8faf8d92003-10-17 02:02:40 +0000992 Slot = Table.getSlot((Value*)I->getInitializer());
Chris Lattner37798642001-09-18 04:01:05 +0000993 assert(Slot != -1 && "No slot for global var initializer!");
Reid Spencerb2bdb942004-07-25 18:07:36 +0000994 output_vbr((unsigned)Slot);
Chris Lattner37798642001-09-18 04:01:05 +0000995 }
Chris Lattnerda975502001-09-10 07:58:01 +0000996 }
Reid Spencerb2bdb942004-07-25 18:07:36 +0000997 output_typeid((unsigned)Table.getSlot(Type::VoidTy));
Chris Lattnerda975502001-09-10 07:58:01 +0000998
Chris Lattner770709b2004-10-16 18:18:16 +0000999 // Output the types of the functions in this module.
Chris Lattner4cee8d82001-06-27 23:41:11 +00001000 for (Module::const_iterator I = M->begin(), End = M->end(); I != End; ++I) {
Alkis Evlogimenos8faf8d92003-10-17 02:02:40 +00001001 int Slot = Table.getSlot(I->getType());
Chris Lattner770709b2004-10-16 18:18:16 +00001002 assert(Slot != -1 && "Module slot calculator is broken!");
Chris Lattner2f7c9632001-06-06 20:29:01 +00001003 assert(Slot >= Type::FirstDerivedTyID && "Derived type not in range!");
Chris Lattner49d19082005-11-06 07:43:39 +00001004 assert(((Slot << 6) >> 6) == Slot && "Slot # too big!");
Chris Lattner05c64d12005-11-06 07:46:13 +00001005 unsigned CC = I->getCallingConv()+1;
1006 unsigned ID = (Slot << 5) | (CC & 15);
Chris Lattnerf2e1c192005-05-06 20:42:57 +00001007
Chris Lattner3b6bb482004-11-15 22:39:49 +00001008 if (I->isExternal()) // If external, we don't have an FunctionInfo block.
1009 ID |= 1 << 4;
Chris Lattner49d19082005-11-06 07:43:39 +00001010
Chris Lattner8e1e6112005-11-12 01:33:40 +00001011 if (I->getAlignment() || I->hasSection() || (CC & ~15) != 0)
Chris Lattner49d19082005-11-06 07:43:39 +00001012 ID |= 1 << 31; // Do we need an extension word?
1013
Chris Lattner770709b2004-10-16 18:18:16 +00001014 output_vbr(ID);
Chris Lattner49d19082005-11-06 07:43:39 +00001015
1016 if (ID & (1 << 31)) {
1017 // Extension byte: bits 0-4 = alignment, bits 5-9 = top nibble of calling
Chris Lattner8e1e6112005-11-12 01:33:40 +00001018 // convention, bit 10 = hasSectionID.
1019 ID = (Log2_32(I->getAlignment())+1) | ((CC >> 4) << 5) |
1020 (I->hasSection() << 10);
Chris Lattner49d19082005-11-06 07:43:39 +00001021 output_vbr(ID);
Chris Lattner8e1e6112005-11-12 01:33:40 +00001022
1023 // Give section names unique ID's.
1024 if (I->hasSection()) {
1025 unsigned &Entry = SectionID[I->getSection()];
1026 if (Entry == 0) {
1027 Entry = ++SectionIDCounter;
1028 SectionNames.push_back(I->getSection());
1029 }
1030 output_vbr(Entry);
1031 }
Chris Lattner49d19082005-11-06 07:43:39 +00001032 }
Chris Lattner2f7c9632001-06-06 20:29:01 +00001033 }
Chris Lattner770709b2004-10-16 18:18:16 +00001034 output_vbr((unsigned)Table.getSlot(Type::VoidTy) << 5);
Reid Spencerb2bdb942004-07-25 18:07:36 +00001035
Chris Lattner770709b2004-10-16 18:18:16 +00001036 // Emit the list of dependent libraries for the Module.
Reid Spencerb95885b2004-07-25 21:32:02 +00001037 Module::lib_iterator LI = M->lib_begin();
1038 Module::lib_iterator LE = M->lib_end();
Chris Lattner770709b2004-10-16 18:18:16 +00001039 output_vbr(unsigned(LE - LI)); // Emit the number of dependent libraries.
1040 for (; LI != LE; ++LI)
Reid Spencerc3e43642004-08-17 07:45:14 +00001041 output(*LI);
Reid Spencerb2bdb942004-07-25 18:07:36 +00001042
1043 // Output the target triple from the module
Reid Spencerc3e43642004-08-17 07:45:14 +00001044 output(M->getTargetTriple());
Chris Lattner8e1e6112005-11-12 01:33:40 +00001045
1046 // Emit the table of section names.
1047 output_vbr((unsigned)SectionNames.size());
1048 for (unsigned i = 0, e = SectionNames.size(); i != e; ++i)
1049 output(SectionNames[i]);
Chris Lattnerbc7b2582006-01-23 23:43:17 +00001050
1051 // Output the inline asm string.
Chris Lattner8ebd2162006-01-24 04:14:29 +00001052 output(M->getModuleInlineAsm());
Chris Lattner2f7c9632001-06-06 20:29:01 +00001053}
1054
Chris Lattnerbc02f4c2004-01-18 21:08:52 +00001055void BytecodeWriter::outputInstructions(const Function *F) {
Reid Spencerb2bdb942004-07-25 18:07:36 +00001056 BytecodeBlock ILBlock(BytecodeFormat::InstructionListBlockID, *this);
Chris Lattnerbc02f4c2004-01-18 21:08:52 +00001057 for (Function::const_iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
1058 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I)
1059 outputInstruction(*I);
Chris Lattnerbc02f4c2004-01-18 21:08:52 +00001060}
1061
Chris Lattner428bf5a2003-03-19 20:56:46 +00001062void BytecodeWriter::outputFunction(const Function *F) {
Chris Lattner9b457e12004-11-15 21:56:33 +00001063 // If this is an external function, there is nothing else to emit!
1064 if (F->isExternal()) return;
1065
Chris Lattner3b6bb482004-11-15 22:39:49 +00001066 BytecodeBlock FunctionBlock(BytecodeFormat::FunctionBlockID, *this);
1067 output_vbr(getEncodedLinkage(F));
1068
Chris Lattnerbc02f4c2004-01-18 21:08:52 +00001069 // Get slot information about the function...
1070 Table.incorporateFunction(F);
1071
1072 if (Table.getCompactionTable().empty()) {
1073 // Output information about the constants in the function if the compaction
1074 // table is not being used.
Chris Lattnerb97ef9f2001-09-07 16:39:41 +00001075 outputConstants(true);
Chris Lattnerbc02f4c2004-01-18 21:08:52 +00001076 } else {
1077 // Otherwise, emit the compaction table.
1078 outputCompactionTable();
Chris Lattnerb97ef9f2001-09-07 16:39:41 +00001079 }
Misha Brukmanb47d28b2005-04-21 21:48:46 +00001080
Chris Lattnerbc02f4c2004-01-18 21:08:52 +00001081 // Output all of the instructions in the body of the function
1082 outputInstructions(F);
Misha Brukmanb47d28b2005-04-21 21:48:46 +00001083
Chris Lattnerbc02f4c2004-01-18 21:08:52 +00001084 // If needed, output the symbol table for the function...
1085 outputSymbolTable(F->getSymbolTable());
Misha Brukmanb47d28b2005-04-21 21:48:46 +00001086
Chris Lattnerbc02f4c2004-01-18 21:08:52 +00001087 Table.purgeFunction();
1088}
1089
1090void BytecodeWriter::outputCompactionTablePlane(unsigned PlaneNo,
1091 const std::vector<const Value*> &Plane,
1092 unsigned StartNo) {
1093 unsigned End = Table.getModuleLevel(PlaneNo);
Chris Lattnera3953242004-01-20 00:54:06 +00001094 if (Plane.empty() || StartNo == End || End == 0) return; // Nothing to emit
Chris Lattnerbc02f4c2004-01-18 21:08:52 +00001095 assert(StartNo < End && "Cannot emit negative range!");
1096 assert(StartNo < Plane.size() && End <= Plane.size());
1097
Chris Lattnerbc02f4c2004-01-18 21:08:52 +00001098 // Do not emit the null initializer!
Reid Spencera52b0002004-07-04 11:45:47 +00001099 ++StartNo;
Chris Lattnerbc02f4c2004-01-18 21:08:52 +00001100
Chris Lattner5a66bb72004-01-18 22:35:34 +00001101 // Figure out which encoding to use. By far the most common case we have is
1102 // to emit 0-2 entries in a compaction table plane.
1103 switch (End-StartNo) {
1104 case 0: // Avoid emitting two vbr's if possible.
1105 case 1:
1106 case 2:
Reid Spencerb2bdb942004-07-25 18:07:36 +00001107 output_vbr((PlaneNo << 2) | End-StartNo);
Chris Lattner5a66bb72004-01-18 22:35:34 +00001108 break;
1109 default:
1110 // Output the number of things.
Reid Spencerb2bdb942004-07-25 18:07:36 +00001111 output_vbr((unsigned(End-StartNo) << 2) | 3);
1112 output_typeid(PlaneNo); // Emit the type plane this is
Chris Lattner5a66bb72004-01-18 22:35:34 +00001113 break;
1114 }
1115
Chris Lattnerbc02f4c2004-01-18 21:08:52 +00001116 for (unsigned i = StartNo; i != End; ++i)
Reid Spencerb2bdb942004-07-25 18:07:36 +00001117 output_vbr(Table.getGlobalSlot(Plane[i]));
Chris Lattnerbc02f4c2004-01-18 21:08:52 +00001118}
1119
Reid Spencera52b0002004-07-04 11:45:47 +00001120void BytecodeWriter::outputCompactionTypes(unsigned StartNo) {
1121 // Get the compaction type table from the slot calculator
1122 const std::vector<const Type*> &CTypes = Table.getCompactionTypes();
1123
1124 // The compaction types may have been uncompactified back to the
1125 // global types. If so, we just write an empty table
1126 if (CTypes.size() == 0 ) {
Reid Spencerb2bdb942004-07-25 18:07:36 +00001127 output_vbr(0U);
Reid Spencera52b0002004-07-04 11:45:47 +00001128 return;
1129 }
1130
1131 assert(CTypes.size() >= StartNo && "Invalid compaction types start index");
1132
1133 // Determine how many types to write
1134 unsigned NumTypes = CTypes.size() - StartNo;
1135
1136 // Output the number of types.
Reid Spencerb2bdb942004-07-25 18:07:36 +00001137 output_vbr(NumTypes);
Reid Spencera52b0002004-07-04 11:45:47 +00001138
1139 for (unsigned i = StartNo; i < StartNo+NumTypes; ++i)
Reid Spencerb2bdb942004-07-25 18:07:36 +00001140 output_typeid(Table.getGlobalSlot(CTypes[i]));
Reid Spencera52b0002004-07-04 11:45:47 +00001141}
1142
Chris Lattnerbc02f4c2004-01-18 21:08:52 +00001143void BytecodeWriter::outputCompactionTable() {
Reid Spencer248c06d2004-08-27 00:38:44 +00001144 // Avoid writing the compaction table at all if there is no content.
1145 if (Table.getCompactionTypes().size() >= Type::FirstDerivedTyID ||
1146 (!Table.CompactionTableIsEmpty())) {
Misha Brukmanb47d28b2005-04-21 21:48:46 +00001147 BytecodeBlock CTB(BytecodeFormat::CompactionTableBlockID, *this,
Reid Spencer248c06d2004-08-27 00:38:44 +00001148 true/*ElideIfEmpty*/);
Chris Lattner3d980082004-10-14 01:46:07 +00001149 const std::vector<std::vector<const Value*> > &CT =
1150 Table.getCompactionTable();
Misha Brukmanb47d28b2005-04-21 21:48:46 +00001151
Reid Spencer248c06d2004-08-27 00:38:44 +00001152 // First things first, emit the type compaction table if there is one.
1153 outputCompactionTypes(Type::FirstDerivedTyID);
Chris Lattnerbc02f4c2004-01-18 21:08:52 +00001154
Reid Spencer248c06d2004-08-27 00:38:44 +00001155 for (unsigned i = 0, e = CT.size(); i != e; ++i)
1156 outputCompactionTablePlane(i, CT[i], 0);
1157 }
Chris Lattner2f7c9632001-06-06 20:29:01 +00001158}
1159
Chris Lattner2f7c9632001-06-06 20:29:01 +00001160void BytecodeWriter::outputSymbolTable(const SymbolTable &MST) {
Chris Lattnera2bfab82004-01-10 19:56:59 +00001161 // Do not output the Bytecode block for an empty symbol table, it just wastes
1162 // space!
Chris Lattner3d980082004-10-14 01:46:07 +00001163 if (MST.isEmpty()) return;
Chris Lattnera2bfab82004-01-10 19:56:59 +00001164
Reid Spencerb2bdb942004-07-25 18:07:36 +00001165 BytecodeBlock SymTabBlock(BytecodeFormat::SymbolTableBlockID, *this,
Chris Lattner3d980082004-10-14 01:46:07 +00001166 true/*ElideIfEmpty*/);
Chris Lattner2f7c9632001-06-06 20:29:01 +00001167
Misha Brukmanb47d28b2005-04-21 21:48:46 +00001168 // Write the number of types
Reid Spencerb2bdb942004-07-25 18:07:36 +00001169 output_vbr(MST.num_types());
Reid Spencerf8a18092004-08-17 02:59:02 +00001170
1171 // Write each of the types
Reid Spencer660ea5f2004-05-25 17:29:59 +00001172 for (SymbolTable::type_const_iterator TI = MST.type_begin(),
1173 TE = MST.type_end(); TI != TE; ++TI ) {
Reid Spencerf8a18092004-08-17 02:59:02 +00001174 // Symtab entry:[def slot #][name]
Reid Spencerb2bdb942004-07-25 18:07:36 +00001175 output_typeid((unsigned)Table.getSlot(TI->second));
Misha Brukmanb47d28b2005-04-21 21:48:46 +00001176 output(TI->first);
Reid Spencer660ea5f2004-05-25 17:29:59 +00001177 }
1178
1179 // Now do each of the type planes in order.
Misha Brukmanb47d28b2005-04-21 21:48:46 +00001180 for (SymbolTable::plane_const_iterator PI = MST.plane_begin(),
Reid Spencer660ea5f2004-05-25 17:29:59 +00001181 PE = MST.plane_end(); PI != PE; ++PI) {
1182 SymbolTable::value_const_iterator I = MST.value_begin(PI->first);
1183 SymbolTable::value_const_iterator End = MST.value_end(PI->first);
Chris Lattner2f7c9632001-06-06 20:29:01 +00001184 int Slot;
Misha Brukmanb47d28b2005-04-21 21:48:46 +00001185
Chris Lattner2f7c9632001-06-06 20:29:01 +00001186 if (I == End) continue; // Don't mess with an absent type...
1187
Reid Spencerf8a18092004-08-17 02:59:02 +00001188 // Write the number of values in this plane
Chris Lattnere9328b32005-03-07 02:59:36 +00001189 output_vbr((unsigned)PI->second.size());
Chris Lattner2f7c9632001-06-06 20:29:01 +00001190
Reid Spencerf8a18092004-08-17 02:59:02 +00001191 // Write the slot number of the type for this plane
Reid Spencer660ea5f2004-05-25 17:29:59 +00001192 Slot = Table.getSlot(PI->first);
Chris Lattner2f7c9632001-06-06 20:29:01 +00001193 assert(Slot != -1 && "Type in symtab, but not in table!");
Reid Spencerb2bdb942004-07-25 18:07:36 +00001194 output_typeid((unsigned)Slot);
Chris Lattner2f7c9632001-06-06 20:29:01 +00001195
Reid Spencerf8a18092004-08-17 02:59:02 +00001196 // Write each of the values in this plane
Chris Lattner4cee8d82001-06-27 23:41:11 +00001197 for (; I != End; ++I) {
Chris Lattner2f7c9632001-06-06 20:29:01 +00001198 // Symtab entry: [def slot #][name]
Alkis Evlogimenos8faf8d92003-10-17 02:02:40 +00001199 Slot = Table.getSlot(I->second);
Chris Lattnerb97ef9f2001-09-07 16:39:41 +00001200 assert(Slot != -1 && "Value in symtab but has no slot number!!");
Reid Spencerb2bdb942004-07-25 18:07:36 +00001201 output_vbr((unsigned)Slot);
Reid Spencerc3e43642004-08-17 07:45:14 +00001202 output(I->first);
Chris Lattner2f7c9632001-06-06 20:29:01 +00001203 }
1204 }
1205}
1206
Reid Spencer2e492042004-11-06 23:17:23 +00001207void llvm::WriteBytecodeToFile(const Module *M, std::ostream &Out,
1208 bool compress ) {
Reid Spencerb2bdb942004-07-25 18:07:36 +00001209 assert(M && "You can't write a null module!!");
Chris Lattner2f7c9632001-06-06 20:29:01 +00001210
Reid Spencer2e492042004-11-06 23:17:23 +00001211 // Create a vector of unsigned char for the bytecode output. We
1212 // reserve 256KBytes of space in the vector so that we avoid doing
1213 // lots of little allocations. 256KBytes is sufficient for a large
1214 // proportion of the bytecode files we will encounter. Larger files
1215 // will be automatically doubled in size as needed (std::vector
1216 // behavior).
Reid Spencerb2bdb942004-07-25 18:07:36 +00001217 std::vector<unsigned char> Buffer;
Reid Spencer2e492042004-11-06 23:17:23 +00001218 Buffer.reserve(256 * 1024);
Chris Lattner2f7c9632001-06-06 20:29:01 +00001219
Reid Spencer2e492042004-11-06 23:17:23 +00001220 // The BytecodeWriter populates Buffer for us.
Reid Spencerb2bdb942004-07-25 18:07:36 +00001221 BytecodeWriter BCW(Buffer, M);
Chris Lattner2f7c9632001-06-06 20:29:01 +00001222
Reid Spencer2e492042004-11-06 23:17:23 +00001223 // Keep track of how much we've written
Chris Lattner64eea742002-07-26 18:40:14 +00001224 BytesWritten += Buffer.size();
1225
Reid Spencer2e492042004-11-06 23:17:23 +00001226 // Determine start and end points of the Buffer
Reid Spencerf3e639f2004-11-07 18:17:38 +00001227 const unsigned char *FirstByte = &Buffer.front();
Reid Spencer2e492042004-11-06 23:17:23 +00001228
1229 // If we're supposed to compress this mess ...
1230 if (compress) {
1231
1232 // We signal compression by using an alternate magic number for the
Reid Spencerf3e639f2004-11-07 18:17:38 +00001233 // file. The compressed bytecode file's magic number is "llvc" instead
Misha Brukmanb47d28b2005-04-21 21:48:46 +00001234 // of "llvm".
Reid Spencerf3e639f2004-11-07 18:17:38 +00001235 char compressed_magic[4];
1236 compressed_magic[0] = 'l';
1237 compressed_magic[1] = 'l';
1238 compressed_magic[2] = 'v';
1239 compressed_magic[3] = 'c';
Reid Spencer2e492042004-11-06 23:17:23 +00001240
Reid Spencerf3e639f2004-11-07 18:17:38 +00001241 Out.write(compressed_magic,4);
Reid Spencer2e492042004-11-06 23:17:23 +00001242
Reid Spencer71f51e62004-11-14 22:01:41 +00001243 // Compress everything after the magic number (which we altered)
1244 uint64_t zipSize = Compressor::compressToStream(
Reid Spencer2e492042004-11-06 23:17:23 +00001245 (char*)(FirstByte+4), // Skip the magic number
1246 Buffer.size()-4, // Skip the magic number
Reid Spenceraf6fd292004-11-25 19:38:05 +00001247 Out // Where to write compressed data
Reid Spencer2e492042004-11-06 23:17:23 +00001248 );
1249
Reid Spencer2e492042004-11-06 23:17:23 +00001250 } else {
1251
1252 // We're not compressing, so just write the entire block.
Reid Spencerf3e639f2004-11-07 18:17:38 +00001253 Out.write((char*)FirstByte, Buffer.size());
Chris Lattnerb97ef9f2001-09-07 16:39:41 +00001254 }
Reid Spencer2e492042004-11-06 23:17:23 +00001255
1256 // make sure it hits disk now
Chris Lattner2f7c9632001-06-06 20:29:01 +00001257 Out.flush();
1258}
Reid Spencer51fe3362004-07-18 00:16:21 +00001259