blob: b69c1ad8b3947157e3f50eb3b6ee2afb2d456701 [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"
Chris Lattner3bc5a602006-01-25 23:08:15 +000025#include "llvm/InlineAsm.h"
Reid Spencerad89bd62004-07-25 18:07:36 +000026#include "llvm/Instructions.h"
Chris Lattner00950542001-06-06 20:29:01 +000027#include "llvm/Module.h"
Chris Lattner00950542001-06-06 20:29:01 +000028#include "llvm/SymbolTable.h"
Reid Spencerad89bd62004-07-25 18:07:36 +000029#include "llvm/Support/GetElementPtrTypeIterator.h"
Reid Spencer17f52c52004-11-06 23:17:23 +000030#include "llvm/Support/Compressor.h"
Jim Laskeycb6682f2005-08-17 19:34:49 +000031#include "llvm/Support/MathExtras.h"
Bill Wendling68fe61d2006-11-29 00:19:40 +000032#include "llvm/Support/Streams.h"
Reid Spencer32f55532006-06-07 23:18:34 +000033#include "llvm/System/Program.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000034#include "llvm/ADT/STLExtras.h"
35#include "llvm/ADT/Statistic.h"
Chris Lattner32abce62004-01-10 19:10:01 +000036#include <cstring>
Chris Lattner00950542001-06-06 20:29:01 +000037#include <algorithm>
Chris Lattner44f549b2004-01-10 18:49:43 +000038using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000039
Reid Spencer38d54be2004-08-17 07:45:14 +000040/// This value needs to be incremented every time the bytecode format changes
41/// so that the reader can distinguish which format of the bytecode file has
42/// been written.
43/// @brief The bytecode version number
Reid Spencer6996feb2006-11-08 21:27:54 +000044const unsigned BCVersionNum = 7;
Reid Spencer38d54be2004-08-17 07:45:14 +000045
Chris Lattner635cd932002-07-23 19:56:44 +000046static RegisterPass<WriteBytecodePass> X("emitbytecode", "Bytecode Writer");
47
Chris Lattnerac0b6ae2006-12-06 17:46:33 +000048static Statistic
Chris Lattnera92f6962002-10-01 22:38:41 +000049BytesWritten("bytecodewriter", "Number of bytecode bytes written");
Chris Lattner635cd932002-07-23 19:56:44 +000050
Reid Spencerad89bd62004-07-25 18:07:36 +000051//===----------------------------------------------------------------------===//
52//=== Output Primitives ===//
53//===----------------------------------------------------------------------===//
54
55// output - If a position is specified, it must be in the valid portion of the
Misha Brukman23c6d2c2005-04-21 21:48:46 +000056// string... note that this should be inlined always so only the relevant IF
Reid Spencerad89bd62004-07-25 18:07:36 +000057// body should be included.
58inline void BytecodeWriter::output(unsigned i, int pos) {
59 if (pos == -1) { // Be endian clean, little endian is our friend
Misha Brukman23c6d2c2005-04-21 21:48:46 +000060 Out.push_back((unsigned char)i);
Reid Spencerad89bd62004-07-25 18:07:36 +000061 Out.push_back((unsigned char)(i >> 8));
62 Out.push_back((unsigned char)(i >> 16));
63 Out.push_back((unsigned char)(i >> 24));
64 } else {
65 Out[pos ] = (unsigned char)i;
66 Out[pos+1] = (unsigned char)(i >> 8);
67 Out[pos+2] = (unsigned char)(i >> 16);
68 Out[pos+3] = (unsigned char)(i >> 24);
69 }
70}
71
72inline void BytecodeWriter::output(int i) {
73 output((unsigned)i);
74}
75
76/// output_vbr - Output an unsigned value, by using the least number of bytes
77/// possible. This is useful because many of our "infinite" values are really
78/// very small most of the time; but can be large a few times.
Misha Brukman23c6d2c2005-04-21 21:48:46 +000079/// Data format used: If you read a byte with the high bit set, use the low
80/// seven bits as data and then read another byte.
Reid Spencerad89bd62004-07-25 18:07:36 +000081inline void BytecodeWriter::output_vbr(uint64_t i) {
82 while (1) {
83 if (i < 0x80) { // done?
84 Out.push_back((unsigned char)i); // We know the high bit is clear...
85 return;
86 }
Misha Brukman23c6d2c2005-04-21 21:48:46 +000087
Reid Spencerad89bd62004-07-25 18:07:36 +000088 // Nope, we are bigger than a character, output the next 7 bits and set the
89 // high bit to say that there is more coming...
90 Out.push_back(0x80 | ((unsigned char)i & 0x7F));
91 i >>= 7; // Shift out 7 bits now...
92 }
93}
94
95inline void BytecodeWriter::output_vbr(unsigned i) {
96 while (1) {
97 if (i < 0x80) { // done?
98 Out.push_back((unsigned char)i); // We know the high bit is clear...
99 return;
100 }
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000101
Reid Spencerad89bd62004-07-25 18:07:36 +0000102 // Nope, we are bigger than a character, output the next 7 bits and set the
103 // high bit to say that there is more coming...
104 Out.push_back(0x80 | ((unsigned char)i & 0x7F));
105 i >>= 7; // Shift out 7 bits now...
106 }
107}
108
109inline void BytecodeWriter::output_typeid(unsigned i) {
110 if (i <= 0x00FFFFFF)
111 this->output_vbr(i);
112 else {
113 this->output_vbr(0x00FFFFFF);
114 this->output_vbr(i);
115 }
116}
117
118inline void BytecodeWriter::output_vbr(int64_t i) {
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000119 if (i < 0)
Reid Spencerad89bd62004-07-25 18:07:36 +0000120 output_vbr(((uint64_t)(-i) << 1) | 1); // Set low order sign bit...
121 else
122 output_vbr((uint64_t)i << 1); // Low order bit is clear.
123}
124
125
126inline void BytecodeWriter::output_vbr(int i) {
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000127 if (i < 0)
Reid Spencerad89bd62004-07-25 18:07:36 +0000128 output_vbr(((unsigned)(-i) << 1) | 1); // Set low order sign bit...
129 else
130 output_vbr((unsigned)i << 1); // Low order bit is clear.
131}
132
Reid Spencer38d54be2004-08-17 07:45:14 +0000133inline void BytecodeWriter::output(const std::string &s) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000134 unsigned Len = s.length();
Chris Lattnerc847f7c2006-07-28 22:07:54 +0000135 output_vbr(Len); // Strings may have an arbitrary length.
Reid Spencerad89bd62004-07-25 18:07:36 +0000136 Out.insert(Out.end(), s.begin(), s.end());
Reid Spencerad89bd62004-07-25 18:07:36 +0000137}
138
139inline void BytecodeWriter::output_data(const void *Ptr, const void *End) {
140 Out.insert(Out.end(), (const unsigned char*)Ptr, (const unsigned char*)End);
141}
142
143inline void BytecodeWriter::output_float(float& FloatVal) {
144 /// FIXME: This isn't optimal, it has size problems on some platforms
145 /// where FP is not IEEE.
Jim Laskeycb6682f2005-08-17 19:34:49 +0000146 uint32_t i = FloatToBits(FloatVal);
Chris Lattnerc847f7c2006-07-28 22:07:54 +0000147 Out.push_back( static_cast<unsigned char>( (i ) & 0xFF));
148 Out.push_back( static_cast<unsigned char>( (i >> 8 ) & 0xFF));
Jim Laskeycb6682f2005-08-17 19:34:49 +0000149 Out.push_back( static_cast<unsigned char>( (i >> 16) & 0xFF));
150 Out.push_back( static_cast<unsigned char>( (i >> 24) & 0xFF));
Reid Spencerad89bd62004-07-25 18:07:36 +0000151}
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.
Jim Laskeycb6682f2005-08-17 19:34:49 +0000156 uint64_t i = DoubleToBits(DoubleVal);
Chris Lattnerc847f7c2006-07-28 22:07:54 +0000157 Out.push_back( static_cast<unsigned char>( (i ) & 0xFF));
158 Out.push_back( static_cast<unsigned char>( (i >> 8 ) & 0xFF));
Jim Laskeycb6682f2005-08-17 19:34:49 +0000159 Out.push_back( static_cast<unsigned char>( (i >> 16) & 0xFF));
160 Out.push_back( static_cast<unsigned char>( (i >> 24) & 0xFF));
161 Out.push_back( static_cast<unsigned char>( (i >> 32) & 0xFF));
162 Out.push_back( static_cast<unsigned char>( (i >> 40) & 0xFF));
163 Out.push_back( static_cast<unsigned char>( (i >> 48) & 0xFF));
164 Out.push_back( static_cast<unsigned char>( (i >> 56) & 0xFF));
Reid Spencerad89bd62004-07-25 18:07:36 +0000165}
166
Chris Lattnerc76ea432005-11-12 18:34:09 +0000167inline BytecodeBlock::BytecodeBlock(unsigned ID, BytecodeWriter &w,
168 bool elideIfEmpty, bool hasLongFormat)
Reid Spencerad89bd62004-07-25 18:07:36 +0000169 : Id(ID), Writer(w), ElideIfEmpty(elideIfEmpty), HasLongFormat(hasLongFormat){
170
171 if (HasLongFormat) {
172 w.output(ID);
173 w.output(0U); // For length in long format
174 } else {
175 w.output(0U); /// Place holder for ID and length for this block
176 }
177 Loc = w.size();
178}
179
Chris Lattnerb0bf6642004-10-14 01:35:17 +0000180inline BytecodeBlock::~BytecodeBlock() { // Do backpatch when block goes out
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000181 // of scope...
Reid Spencerad89bd62004-07-25 18:07:36 +0000182 if (Loc == Writer.size() && ElideIfEmpty) {
183 // If the block is empty, and we are allowed to, do not emit the block at
184 // all!
185 Writer.resize(Writer.size()-(HasLongFormat?8:4));
186 return;
187 }
188
Reid Spencerad89bd62004-07-25 18:07:36 +0000189 if (HasLongFormat)
190 Writer.output(unsigned(Writer.size()-Loc), int(Loc-4));
191 else
192 Writer.output(unsigned(Writer.size()-Loc) << 5 | (Id & 0x1F), int(Loc-4));
Reid Spencerad89bd62004-07-25 18:07:36 +0000193}
194
195//===----------------------------------------------------------------------===//
196//=== Constant Output ===//
197//===----------------------------------------------------------------------===//
198
199void BytecodeWriter::outputType(const Type *T) {
200 output_vbr((unsigned)T->getTypeID());
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000201
Reid Spencerad89bd62004-07-25 18:07:36 +0000202 // That's all there is to handling primitive types...
203 if (T->isPrimitiveType()) {
204 return; // We might do this if we alias a prim type: %x = type int
205 }
206
207 switch (T->getTypeID()) { // Handle derived types now.
208 case Type::FunctionTyID: {
209 const FunctionType *MT = cast<FunctionType>(T);
210 int Slot = Table.getSlot(MT->getReturnType());
211 assert(Slot != -1 && "Type used but not available!!");
212 output_typeid((unsigned)Slot);
213
214 // Output the number of arguments to function (+1 if varargs):
215 output_vbr((unsigned)MT->getNumParams()+MT->isVarArg());
216
217 // Output all of the arguments...
218 FunctionType::param_iterator I = MT->param_begin();
219 for (; I != MT->param_end(); ++I) {
220 Slot = Table.getSlot(*I);
221 assert(Slot != -1 && "Type used but not available!!");
222 output_typeid((unsigned)Slot);
223 }
224
225 // Terminate list with VoidTy if we are a varargs function...
226 if (MT->isVarArg())
227 output_typeid((unsigned)Type::VoidTyID);
228 break;
229 }
230
231 case Type::ArrayTyID: {
232 const ArrayType *AT = cast<ArrayType>(T);
233 int Slot = Table.getSlot(AT->getElementType());
234 assert(Slot != -1 && "Type used but not available!!");
235 output_typeid((unsigned)Slot);
Reid Spencerad89bd62004-07-25 18:07:36 +0000236 output_vbr(AT->getNumElements());
237 break;
238 }
239
Brian Gaeke715c90b2004-08-20 06:00:58 +0000240 case Type::PackedTyID: {
241 const PackedType *PT = cast<PackedType>(T);
242 int Slot = Table.getSlot(PT->getElementType());
243 assert(Slot != -1 && "Type used but not available!!");
244 output_typeid((unsigned)Slot);
245 output_vbr(PT->getNumElements());
246 break;
247 }
248
249
Reid Spencerad89bd62004-07-25 18:07:36 +0000250 case Type::StructTyID: {
251 const StructType *ST = cast<StructType>(T);
252
253 // Output all of the element types...
254 for (StructType::element_iterator I = ST->element_begin(),
255 E = ST->element_end(); I != E; ++I) {
256 int Slot = Table.getSlot(*I);
257 assert(Slot != -1 && "Type used but not available!!");
258 output_typeid((unsigned)Slot);
259 }
260
261 // Terminate list with VoidTy
262 output_typeid((unsigned)Type::VoidTyID);
263 break;
264 }
265
266 case Type::PointerTyID: {
267 const PointerType *PT = cast<PointerType>(T);
268 int Slot = Table.getSlot(PT->getElementType());
269 assert(Slot != -1 && "Type used but not available!!");
270 output_typeid((unsigned)Slot);
271 break;
272 }
273
Chris Lattnerb0bf6642004-10-14 01:35:17 +0000274 case Type::OpaqueTyID:
Reid Spencerad89bd62004-07-25 18:07:36 +0000275 // No need to emit anything, just the count of opaque types is enough.
276 break;
Reid Spencerad89bd62004-07-25 18:07:36 +0000277
Reid Spencerad89bd62004-07-25 18:07:36 +0000278 default:
Bill Wendlinge8156192006-12-07 01:30:32 +0000279 cerr << __FILE__ << ":" << __LINE__ << ": Don't know how to serialize"
280 << " Type '" << T->getDescription() << "'\n";
Reid Spencerad89bd62004-07-25 18:07:36 +0000281 break;
282 }
283}
284
285void BytecodeWriter::outputConstant(const Constant *CPV) {
286 assert((CPV->getType()->isPrimitiveType() || !CPV->isNullValue()) &&
287 "Shouldn't output null constants!");
288
289 // We must check for a ConstantExpr before switching by type because
290 // a ConstantExpr can be of any type, and has no explicit value.
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000291 //
Reid Spencerad89bd62004-07-25 18:07:36 +0000292 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
293 // FIXME: Encoding of constant exprs could be much more compact!
294 assert(CE->getNumOperands() > 0 && "ConstantExpr with 0 operands");
Reid Spencer3da59db2006-11-27 01:05:10 +0000295 assert(CE->getNumOperands() != 1 || CE->isCast());
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000296 output_vbr(1+CE->getNumOperands()); // flags as an expr
Reid Spencerb83eb642006-10-20 07:07:24 +0000297 output_vbr(CE->getOpcode()); // Put out the CE op code
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000298
Reid Spencerad89bd62004-07-25 18:07:36 +0000299 for (User::const_op_iterator OI = CE->op_begin(); OI != CE->op_end(); ++OI){
300 int Slot = Table.getSlot(*OI);
301 assert(Slot != -1 && "Unknown constant used in ConstantExpr!!");
302 output_vbr((unsigned)Slot);
303 Slot = Table.getSlot((*OI)->getType());
304 output_typeid((unsigned)Slot);
305 }
Reid Spencer595b4772006-12-04 05:23:49 +0000306 if (CE->isCompare())
307 output_vbr((unsigned)CE->getPredicate());
Reid Spencerad89bd62004-07-25 18:07:36 +0000308 return;
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000309 } else if (isa<UndefValue>(CPV)) {
310 output_vbr(1U); // 1 -> UndefValue constant.
311 return;
Reid Spencerad89bd62004-07-25 18:07:36 +0000312 } else {
Reid Spencerb83eb642006-10-20 07:07:24 +0000313 output_vbr(0U); // flag as not a ConstantExpr (i.e. 0 operands)
Reid Spencerad89bd62004-07-25 18:07:36 +0000314 }
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000315
Reid Spencerad89bd62004-07-25 18:07:36 +0000316 switch (CPV->getType()->getTypeID()) {
317 case Type::BoolTyID: // Boolean Types
318 if (cast<ConstantBool>(CPV)->getValue())
319 output_vbr(1U);
320 else
321 output_vbr(0U);
322 break;
323
324 case Type::UByteTyID: // Unsigned integer types...
325 case Type::UShortTyID:
326 case Type::UIntTyID:
327 case Type::ULongTyID:
Reid Spencerb83eb642006-10-20 07:07:24 +0000328 output_vbr(cast<ConstantInt>(CPV)->getZExtValue());
Reid Spencerad89bd62004-07-25 18:07:36 +0000329 break;
330
331 case Type::SByteTyID: // Signed integer types...
332 case Type::ShortTyID:
333 case Type::IntTyID:
334 case Type::LongTyID:
Reid Spencerb83eb642006-10-20 07:07:24 +0000335 output_vbr(cast<ConstantInt>(CPV)->getSExtValue());
Reid Spencerad89bd62004-07-25 18:07:36 +0000336 break;
337
338 case Type::ArrayTyID: {
339 const ConstantArray *CPA = cast<ConstantArray>(CPV);
340 assert(!CPA->isString() && "Constant strings should be handled specially!");
341
Alkis Evlogimenos15876bb2004-08-04 08:44:43 +0000342 for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000343 int Slot = Table.getSlot(CPA->getOperand(i));
344 assert(Slot != -1 && "Constant used but not available!!");
345 output_vbr((unsigned)Slot);
346 }
347 break;
348 }
349
Brian Gaeke715c90b2004-08-20 06:00:58 +0000350 case Type::PackedTyID: {
351 const ConstantPacked *CP = cast<ConstantPacked>(CPV);
352
353 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i) {
354 int Slot = Table.getSlot(CP->getOperand(i));
355 assert(Slot != -1 && "Constant used but not available!!");
356 output_vbr((unsigned)Slot);
357 }
358 break;
359 }
360
Reid Spencerad89bd62004-07-25 18:07:36 +0000361 case Type::StructTyID: {
362 const ConstantStruct *CPS = cast<ConstantStruct>(CPV);
Reid Spencerad89bd62004-07-25 18:07:36 +0000363
Alkis Evlogimenos15876bb2004-08-04 08:44:43 +0000364 for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i) {
365 int Slot = Table.getSlot(CPS->getOperand(i));
Reid Spencerad89bd62004-07-25 18:07:36 +0000366 assert(Slot != -1 && "Constant used but not available!!");
367 output_vbr((unsigned)Slot);
368 }
369 break;
370 }
371
372 case Type::PointerTyID:
373 assert(0 && "No non-null, non-constant-expr constants allowed!");
374 abort();
375
376 case Type::FloatTyID: { // Floating point types...
377 float Tmp = (float)cast<ConstantFP>(CPV)->getValue();
378 output_float(Tmp);
379 break;
380 }
381 case Type::DoubleTyID: {
382 double Tmp = cast<ConstantFP>(CPV)->getValue();
383 output_double(Tmp);
384 break;
385 }
386
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000387 case Type::VoidTyID:
Reid Spencerad89bd62004-07-25 18:07:36 +0000388 case Type::LabelTyID:
389 default:
Bill Wendlinge8156192006-12-07 01:30:32 +0000390 cerr << __FILE__ << ":" << __LINE__ << ": Don't know how to serialize"
391 << " type '" << *CPV->getType() << "'\n";
Reid Spencerad89bd62004-07-25 18:07:36 +0000392 break;
393 }
394 return;
395}
396
Chris Lattner3bc5a602006-01-25 23:08:15 +0000397/// outputInlineAsm - InlineAsm's get emitted to the constant pool, so they can
398/// be shared by multiple uses.
399void BytecodeWriter::outputInlineAsm(const InlineAsm *IA) {
400 // Output a marker, so we know when we have one one parsing the constant pool.
401 // Note that this encoding is 5 bytes: not very efficient for a marker. Since
402 // unique inline asms are rare, this should hardly matter.
403 output_vbr(~0U);
404
405 output(IA->getAsmString());
406 output(IA->getConstraintString());
407 output_vbr(unsigned(IA->hasSideEffects()));
408}
409
Reid Spencerad89bd62004-07-25 18:07:36 +0000410void BytecodeWriter::outputConstantStrings() {
411 SlotCalculator::string_iterator I = Table.string_begin();
412 SlotCalculator::string_iterator E = Table.string_end();
413 if (I == E) return; // No strings to emit
414
415 // If we have != 0 strings to emit, output them now. Strings are emitted into
416 // the 'void' type plane.
417 output_vbr(unsigned(E-I));
418 output_typeid(Type::VoidTyID);
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000419
Reid Spencerad89bd62004-07-25 18:07:36 +0000420 // Emit all of the strings.
421 for (I = Table.string_begin(); I != E; ++I) {
422 const ConstantArray *Str = *I;
423 int Slot = Table.getSlot(Str->getType());
424 assert(Slot != -1 && "Constant string of unknown type?");
425 output_typeid((unsigned)Slot);
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000426
Reid Spencerad89bd62004-07-25 18:07:36 +0000427 // Now that we emitted the type (which indicates the size of the string),
428 // emit all of the characters.
429 std::string Val = Str->getAsString();
430 output_data(Val.c_str(), Val.c_str()+Val.size());
431 }
432}
433
434//===----------------------------------------------------------------------===//
435//=== Instruction Output ===//
436//===----------------------------------------------------------------------===//
Reid Spencerad89bd62004-07-25 18:07:36 +0000437
Chris Lattnerda895d62005-02-27 06:18:25 +0000438// outputInstructionFormat0 - Output those weird instructions that have a large
Chris Lattnerdee199f2005-05-06 22:34:01 +0000439// number of operands or have large operands themselves.
Reid Spencerad89bd62004-07-25 18:07:36 +0000440//
441// Format: [opcode] [type] [numargs] [arg0] [arg1] ... [arg<numargs-1>]
442//
Chris Lattnerf9d71782004-10-14 01:46:07 +0000443void BytecodeWriter::outputInstructionFormat0(const Instruction *I,
444 unsigned Opcode,
445 const SlotCalculator &Table,
446 unsigned Type) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000447 // Opcode must have top two bits clear...
448 output_vbr(Opcode << 2); // Instruction Opcode ID
449 output_typeid(Type); // Result type
450
451 unsigned NumArgs = I->getNumOperands();
Reid Spencercae60532006-12-06 04:27:07 +0000452 output_vbr(NumArgs + (isa<CastInst>(I) || isa<InvokeInst>(I) ||
453 isa<CmpInst>(I) || isa<VAArgInst>(I) || Opcode == 58));
Reid Spencerad89bd62004-07-25 18:07:36 +0000454
455 if (!isa<GetElementPtrInst>(&I)) {
456 for (unsigned i = 0; i < NumArgs; ++i) {
457 int Slot = Table.getSlot(I->getOperand(i));
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000458 assert(Slot >= 0 && "No slot number for value!?!?");
Reid Spencerad89bd62004-07-25 18:07:36 +0000459 output_vbr((unsigned)Slot);
460 }
461
462 if (isa<CastInst>(I) || isa<VAArgInst>(I)) {
463 int Slot = Table.getSlot(I->getType());
464 assert(Slot != -1 && "Cast return type unknown?");
465 output_typeid((unsigned)Slot);
Reid Spencercae60532006-12-06 04:27:07 +0000466 } else if (isa<CmpInst>(I)) {
467 output_vbr(unsigned(cast<CmpInst>(I)->getPredicate()));
Reid Spencer3da59db2006-11-27 01:05:10 +0000468 } else if (isa<InvokeInst>(I)) {
Chris Lattnerdee199f2005-05-06 22:34:01 +0000469 output_vbr(cast<InvokeInst>(I)->getCallingConv());
470 } else if (Opcode == 58) { // Call escape sequence
471 output_vbr((cast<CallInst>(I)->getCallingConv() << 1) |
Jeff Cohen39cef602005-05-07 02:44:04 +0000472 unsigned(cast<CallInst>(I)->isTailCall()));
Reid Spencerad89bd62004-07-25 18:07:36 +0000473 }
Reid Spencerad89bd62004-07-25 18:07:36 +0000474 } else {
475 int Slot = Table.getSlot(I->getOperand(0));
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000476 assert(Slot >= 0 && "No slot number for value!?!?");
Reid Spencerad89bd62004-07-25 18:07:36 +0000477 output_vbr(unsigned(Slot));
478
479 // We need to encode the type of sequential type indices into their slot #
480 unsigned Idx = 1;
481 for (gep_type_iterator TI = gep_type_begin(I), E = gep_type_end(I);
482 Idx != NumArgs; ++TI, ++Idx) {
483 Slot = Table.getSlot(I->getOperand(Idx));
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000484 assert(Slot >= 0 && "No slot number for value!?!?");
485
Reid Spencerad89bd62004-07-25 18:07:36 +0000486 if (isa<SequentialType>(*TI)) {
487 unsigned IdxId;
488 switch (I->getOperand(Idx)->getType()->getTypeID()) {
489 default: assert(0 && "Unknown index type!");
490 case Type::UIntTyID: IdxId = 0; break;
491 case Type::IntTyID: IdxId = 1; break;
492 case Type::ULongTyID: IdxId = 2; break;
493 case Type::LongTyID: IdxId = 3; break;
494 }
495 Slot = (Slot << 2) | IdxId;
496 }
497 output_vbr(unsigned(Slot));
498 }
499 }
Reid Spencerad89bd62004-07-25 18:07:36 +0000500}
501
502
503// outputInstrVarArgsCall - Output the absurdly annoying varargs function calls.
504// This are more annoying than most because the signature of the call does not
505// tell us anything about the types of the arguments in the varargs portion.
506// Because of this, we encode (as type 0) all of the argument types explicitly
507// before the argument value. This really sucks, but you shouldn't be using
508// varargs functions in your code! *death to printf*!
509//
510// Format: [opcode] [type] [numargs] [arg0] [arg1] ... [arg<numargs-1>]
511//
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000512void BytecodeWriter::outputInstrVarArgsCall(const Instruction *I,
513 unsigned Opcode,
514 const SlotCalculator &Table,
515 unsigned Type) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000516 assert(isa<CallInst>(I) || isa<InvokeInst>(I));
517 // Opcode must have top two bits clear...
518 output_vbr(Opcode << 2); // Instruction Opcode ID
519 output_typeid(Type); // Result type (varargs type)
520
521 const PointerType *PTy = cast<PointerType>(I->getOperand(0)->getType());
522 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
523 unsigned NumParams = FTy->getNumParams();
524
525 unsigned NumFixedOperands;
526 if (isa<CallInst>(I)) {
527 // Output an operand for the callee and each fixed argument, then two for
528 // each variable argument.
529 NumFixedOperands = 1+NumParams;
530 } else {
531 assert(isa<InvokeInst>(I) && "Not call or invoke??");
532 // Output an operand for the callee and destinations, then two for each
533 // variable argument.
534 NumFixedOperands = 3+NumParams;
535 }
Reid Spencer3da59db2006-11-27 01:05:10 +0000536 output_vbr(2 * I->getNumOperands()-NumFixedOperands +
537 unsigned(Opcode == 58 || isa<InvokeInst>(I)));
Reid Spencerad89bd62004-07-25 18:07:36 +0000538
539 // The type for the function has already been emitted in the type field of the
540 // instruction. Just emit the slot # now.
541 for (unsigned i = 0; i != NumFixedOperands; ++i) {
542 int Slot = Table.getSlot(I->getOperand(i));
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000543 assert(Slot >= 0 && "No slot number for value!?!?");
Reid Spencerad89bd62004-07-25 18:07:36 +0000544 output_vbr((unsigned)Slot);
545 }
546
547 for (unsigned i = NumFixedOperands, e = I->getNumOperands(); i != e; ++i) {
548 // Output Arg Type ID
549 int Slot = Table.getSlot(I->getOperand(i)->getType());
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000550 assert(Slot >= 0 && "No slot number for value!?!?");
Reid Spencerad89bd62004-07-25 18:07:36 +0000551 output_typeid((unsigned)Slot);
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000552
Reid Spencerad89bd62004-07-25 18:07:36 +0000553 // Output arg ID itself
554 Slot = Table.getSlot(I->getOperand(i));
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000555 assert(Slot >= 0 && "No slot number for value!?!?");
Reid Spencerad89bd62004-07-25 18:07:36 +0000556 output_vbr((unsigned)Slot);
557 }
Chris Lattnera65371e2006-05-26 18:42:34 +0000558
Reid Spencer3da59db2006-11-27 01:05:10 +0000559 if (isa<InvokeInst>(I)) {
560 // Emit the tail call/calling conv for invoke instructions
561 output_vbr(cast<InvokeInst>(I)->getCallingConv());
562 } else if (Opcode == 58) {
Chris Lattnera65371e2006-05-26 18:42:34 +0000563 const CallInst *CI = cast<CallInst>(I);
564 output_vbr((CI->getCallingConv() << 1) | unsigned(CI->isTailCall()));
Chris Lattnera65371e2006-05-26 18:42:34 +0000565 }
Reid Spencerad89bd62004-07-25 18:07:36 +0000566}
567
568
569// outputInstructionFormat1 - Output one operand instructions, knowing that no
570// operand index is >= 2^12.
571//
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000572inline void BytecodeWriter::outputInstructionFormat1(const Instruction *I,
573 unsigned Opcode,
574 unsigned *Slots,
575 unsigned Type) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000576 // bits Instruction format:
577 // --------------------------
578 // 01-00: Opcode type, fixed to 1.
579 // 07-02: Opcode
580 // 19-08: Resulting type plane
581 // 31-20: Operand #1 (if set to (2^12-1), then zero operands)
582 //
Chris Lattnerf9d71782004-10-14 01:46:07 +0000583 output(1 | (Opcode << 2) | (Type << 8) | (Slots[0] << 20));
Reid Spencerad89bd62004-07-25 18:07:36 +0000584}
585
586
587// outputInstructionFormat2 - Output two operand instructions, knowing that no
588// operand index is >= 2^8.
589//
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000590inline void BytecodeWriter::outputInstructionFormat2(const Instruction *I,
591 unsigned Opcode,
592 unsigned *Slots,
593 unsigned Type) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000594 // bits Instruction format:
595 // --------------------------
596 // 01-00: Opcode type, fixed to 2.
597 // 07-02: Opcode
598 // 15-08: Resulting type plane
599 // 23-16: Operand #1
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000600 // 31-24: Operand #2
Reid Spencerad89bd62004-07-25 18:07:36 +0000601 //
Chris Lattnerf9d71782004-10-14 01:46:07 +0000602 output(2 | (Opcode << 2) | (Type << 8) | (Slots[0] << 16) | (Slots[1] << 24));
Reid Spencerad89bd62004-07-25 18:07:36 +0000603}
604
605
606// outputInstructionFormat3 - Output three operand instructions, knowing that no
607// operand index is >= 2^6.
608//
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000609inline void BytecodeWriter::outputInstructionFormat3(const Instruction *I,
Reid Spencerad89bd62004-07-25 18:07:36 +0000610 unsigned Opcode,
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000611 unsigned *Slots,
612 unsigned Type) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000613 // bits Instruction format:
614 // --------------------------
615 // 01-00: Opcode type, fixed to 3.
616 // 07-02: Opcode
617 // 13-08: Resulting type plane
618 // 19-14: Operand #1
619 // 25-20: Operand #2
620 // 31-26: Operand #3
621 //
Chris Lattnerf9d71782004-10-14 01:46:07 +0000622 output(3 | (Opcode << 2) | (Type << 8) |
Chris Lattner84d1ced2004-10-14 01:57:28 +0000623 (Slots[0] << 14) | (Slots[1] << 20) | (Slots[2] << 26));
Reid Spencerad89bd62004-07-25 18:07:36 +0000624}
625
626void BytecodeWriter::outputInstruction(const Instruction &I) {
Reid Spencer3da59db2006-11-27 01:05:10 +0000627 assert(I.getOpcode() < 57 && "Opcode too big???");
Reid Spencerad89bd62004-07-25 18:07:36 +0000628 unsigned Opcode = I.getOpcode();
629 unsigned NumOperands = I.getNumOperands();
630
Chris Lattner38287bd2005-05-06 06:13:34 +0000631 // Encode 'tail call' as 61, 'volatile load' as 62, and 'volatile store' as
632 // 63.
Chris Lattnerdee199f2005-05-06 22:34:01 +0000633 if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
634 if (CI->getCallingConv() == CallingConv::C) {
635 if (CI->isTailCall())
636 Opcode = 61; // CCC + Tail Call
637 else
638 ; // Opcode = Instruction::Call
639 } else if (CI->getCallingConv() == CallingConv::Fast) {
640 if (CI->isTailCall())
641 Opcode = 59; // FastCC + TailCall
642 else
643 Opcode = 60; // FastCC + Not Tail Call
644 } else {
645 Opcode = 58; // Call escape sequence.
646 }
Chris Lattnerdee199f2005-05-06 22:34:01 +0000647 } else if (isa<LoadInst>(I) && cast<LoadInst>(I).isVolatile()) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000648 Opcode = 62;
Chris Lattnerdee199f2005-05-06 22:34:01 +0000649 } else if (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile()) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000650 Opcode = 63;
Chris Lattnerdee199f2005-05-06 22:34:01 +0000651 }
Reid Spencerad89bd62004-07-25 18:07:36 +0000652
653 // Figure out which type to encode with the instruction. Typically we want
654 // the type of the first parameter, as opposed to the type of the instruction
655 // (for example, with setcc, we always know it returns bool, but the type of
656 // the first param is actually interesting). But if we have no arguments
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000657 // we take the type of the instruction itself.
Reid Spencerad89bd62004-07-25 18:07:36 +0000658 //
659 const Type *Ty;
660 switch (I.getOpcode()) {
661 case Instruction::Select:
662 case Instruction::Malloc:
663 case Instruction::Alloca:
664 Ty = I.getType(); // These ALWAYS want to encode the return type
665 break;
666 case Instruction::Store:
667 Ty = I.getOperand(1)->getType(); // Encode the pointer type...
668 assert(isa<PointerType>(Ty) && "Store to nonpointer type!?!?");
669 break;
670 default: // Otherwise use the default behavior...
671 Ty = NumOperands ? I.getOperand(0)->getType() : I.getType();
672 break;
673 }
674
675 unsigned Type;
676 int Slot = Table.getSlot(Ty);
677 assert(Slot != -1 && "Type not available!!?!");
678 Type = (unsigned)Slot;
679
680 // Varargs calls and invokes are encoded entirely different from any other
681 // instructions.
682 if (const CallInst *CI = dyn_cast<CallInst>(&I)){
683 const PointerType *Ty =cast<PointerType>(CI->getCalledValue()->getType());
684 if (cast<FunctionType>(Ty->getElementType())->isVarArg()) {
685 outputInstrVarArgsCall(CI, Opcode, Table, Type);
686 return;
687 }
688 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
689 const PointerType *Ty =cast<PointerType>(II->getCalledValue()->getType());
690 if (cast<FunctionType>(Ty->getElementType())->isVarArg()) {
691 outputInstrVarArgsCall(II, Opcode, Table, Type);
692 return;
693 }
694 }
695
696 if (NumOperands <= 3) {
697 // Make sure that we take the type number into consideration. We don't want
698 // to overflow the field size for the instruction format we select.
699 //
700 unsigned MaxOpSlot = Type;
701 unsigned Slots[3]; Slots[0] = (1 << 12)-1; // Marker to signify 0 operands
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000702
Reid Spencerad89bd62004-07-25 18:07:36 +0000703 for (unsigned i = 0; i != NumOperands; ++i) {
704 int slot = Table.getSlot(I.getOperand(i));
705 assert(slot != -1 && "Broken bytecode!");
706 if (unsigned(slot) > MaxOpSlot) MaxOpSlot = unsigned(slot);
707 Slots[i] = unsigned(slot);
708 }
709
710 // Handle the special cases for various instructions...
711 if (isa<CastInst>(I) || isa<VAArgInst>(I)) {
712 // Cast has to encode the destination type as the second argument in the
713 // packet, or else we won't know what type to cast to!
714 Slots[1] = Table.getSlot(I.getType());
715 assert(Slots[1] != ~0U && "Cast return type unknown?");
716 if (Slots[1] > MaxOpSlot) MaxOpSlot = Slots[1];
717 NumOperands++;
Chris Lattner42ba6b42005-11-05 22:08:14 +0000718 } else if (const AllocationInst *AI = dyn_cast<AllocationInst>(&I)) {
719 assert(NumOperands == 1 && "Bogus allocation!");
720 if (AI->getAlignment()) {
721 Slots[1] = Log2_32(AI->getAlignment())+1;
722 if (Slots[1] > MaxOpSlot) MaxOpSlot = Slots[1];
723 NumOperands = 2;
724 }
Reid Spencerc8dab492006-12-03 06:28:54 +0000725 } else if (isa<ICmpInst>(I) || isa<FCmpInst>(I)) {
726 // We need to encode the compare instruction's predicate as the third
727 // operand. Its not really a slot, but we don't want to break the
728 // instruction format for these instructions.
729 NumOperands++;
730 assert(NumOperands == 3 && "CmpInst with wrong number of operands?");
731 Slots[2] = unsigned(cast<CmpInst>(&I)->getPredicate());
732 if (Slots[2] > MaxOpSlot)
733 MaxOpSlot = Slots[2];
Reid Spencerad89bd62004-07-25 18:07:36 +0000734 } else if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&I)) {
735 // We need to encode the type of sequential type indices into their slot #
736 unsigned Idx = 1;
737 for (gep_type_iterator I = gep_type_begin(GEP), E = gep_type_end(GEP);
738 I != E; ++I, ++Idx)
739 if (isa<SequentialType>(*I)) {
740 unsigned IdxId;
741 switch (GEP->getOperand(Idx)->getType()->getTypeID()) {
742 default: assert(0 && "Unknown index type!");
743 case Type::UIntTyID: IdxId = 0; break;
744 case Type::IntTyID: IdxId = 1; break;
745 case Type::ULongTyID: IdxId = 2; break;
746 case Type::LongTyID: IdxId = 3; break;
747 }
748 Slots[Idx] = (Slots[Idx] << 2) | IdxId;
749 if (Slots[Idx] > MaxOpSlot) MaxOpSlot = Slots[Idx];
750 }
Chris Lattnerdee199f2005-05-06 22:34:01 +0000751 } else if (Opcode == 58) {
752 // If this is the escape sequence for call, emit the tailcall/cc info.
753 const CallInst &CI = cast<CallInst>(I);
754 ++NumOperands;
Chris Lattnerebf8e6c2006-05-19 21:57:37 +0000755 if (NumOperands <= 3) {
756 Slots[NumOperands-1] =
757 (CI.getCallingConv() << 1)|unsigned(CI.isTailCall());
Chris Lattnerdee199f2005-05-06 22:34:01 +0000758 if (Slots[NumOperands-1] > MaxOpSlot)
759 MaxOpSlot = Slots[NumOperands-1];
760 }
Reid Spencer3da59db2006-11-27 01:05:10 +0000761 } else if (isa<InvokeInst>(I)) {
Chris Lattnerdee199f2005-05-06 22:34:01 +0000762 // Invoke escape seq has at least 4 operands to encode.
763 ++NumOperands;
Reid Spencerad89bd62004-07-25 18:07:36 +0000764 }
765
766 // Decide which instruction encoding to use. This is determined primarily
767 // by the number of operands, and secondarily by whether or not the max
768 // operand will fit into the instruction encoding. More operands == fewer
769 // bits per operand.
770 //
771 switch (NumOperands) {
772 case 0:
773 case 1:
774 if (MaxOpSlot < (1 << 12)-1) { // -1 because we use 4095 to indicate 0 ops
775 outputInstructionFormat1(&I, Opcode, Slots, Type);
776 return;
777 }
778 break;
779
780 case 2:
781 if (MaxOpSlot < (1 << 8)) {
782 outputInstructionFormat2(&I, Opcode, Slots, Type);
783 return;
784 }
785 break;
786
787 case 3:
788 if (MaxOpSlot < (1 << 6)) {
789 outputInstructionFormat3(&I, Opcode, Slots, Type);
790 return;
791 }
792 break;
793 default:
794 break;
795 }
796 }
797
798 // If we weren't handled before here, we either have a large number of
799 // operands or a large operand index that we are referring to.
800 outputInstructionFormat0(&I, Opcode, Table, Type);
801}
802
803//===----------------------------------------------------------------------===//
804//=== Block Output ===//
805//===----------------------------------------------------------------------===//
806
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000807BytecodeWriter::BytecodeWriter(std::vector<unsigned char> &o, const Module *M)
Reid Spencer798ff642004-05-26 07:37:11 +0000808 : Out(o), Table(M) {
Chris Lattner00950542001-06-06 20:29:01 +0000809
Chris Lattner83bb3d22004-01-14 23:36:54 +0000810 // Emit the signature...
Chris Lattnerc847f7c2006-07-28 22:07:54 +0000811 static const unsigned char *Sig = (const unsigned char*)"llvm";
Reid Spencerad89bd62004-07-25 18:07:36 +0000812 output_data(Sig, Sig+4);
Chris Lattner00950542001-06-06 20:29:01 +0000813
814 // Emit the top level CLASS block.
Reid Spencerad89bd62004-07-25 18:07:36 +0000815 BytecodeBlock ModuleBlock(BytecodeFormat::ModuleBlockID, *this, false, true);
Chris Lattner00950542001-06-06 20:29:01 +0000816
Chris Lattnerd445c6b2003-08-24 13:47:36 +0000817 bool isBigEndian = M->getEndianness() == Module::BigEndian;
818 bool hasLongPointers = M->getPointerSize() == Module::Pointer64;
819 bool hasNoEndianness = M->getEndianness() == Module::AnyEndianness;
820 bool hasNoPointerSize = M->getPointerSize() == Module::AnyPointerSize;
Chris Lattner186a1f72003-03-19 20:56:46 +0000821
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000822 // Output the version identifier and other information.
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000823 unsigned Version = (BCVersionNum << 4) |
Reid Spencer38d54be2004-08-17 07:45:14 +0000824 (unsigned)isBigEndian | (hasLongPointers << 1) |
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000825 (hasNoEndianness << 2) |
Reid Spencer38d54be2004-08-17 07:45:14 +0000826 (hasNoPointerSize << 3);
Reid Spencerad89bd62004-07-25 18:07:36 +0000827 output_vbr(Version);
Chris Lattner00950542001-06-06 20:29:01 +0000828
Reid Spencercb3595c2004-07-04 11:45:47 +0000829 // The Global type plane comes first
Chris Lattner186a1f72003-03-19 20:56:46 +0000830 {
Chris Lattnerc847f7c2006-07-28 22:07:54 +0000831 BytecodeBlock CPool(BytecodeFormat::GlobalTypePlaneBlockID, *this);
832 outputTypes(Type::FirstDerivedTyID);
Chris Lattner186a1f72003-03-19 20:56:46 +0000833 }
Chris Lattner00950542001-06-06 20:29:01 +0000834
Chris Lattner186a1f72003-03-19 20:56:46 +0000835 // The ModuleInfoBlock follows directly after the type information
Chris Lattnere8fdde12001-09-07 16:39:41 +0000836 outputModuleInfoBlock(M);
837
Chris Lattner186a1f72003-03-19 20:56:46 +0000838 // Output module level constants, used for global variable initializers
839 outputConstants(false);
840
Chris Lattnerb5794002002-04-07 22:49:37 +0000841 // Do the whole module now! Process each function at a time...
Chris Lattner0b12b5f2002-06-25 16:13:21 +0000842 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
Chris Lattner186a1f72003-03-19 20:56:46 +0000843 outputFunction(I);
Chris Lattnere8fdde12001-09-07 16:39:41 +0000844
845 // If needed, output the symbol table for the module...
Chris Lattner6e6026b2002-11-20 18:36:02 +0000846 outputSymbolTable(M->getSymbolTable());
Chris Lattner00950542001-06-06 20:29:01 +0000847}
848
Chris Lattnerf9d71782004-10-14 01:46:07 +0000849void BytecodeWriter::outputTypes(unsigned TypeNum) {
Reid Spencercb3595c2004-07-04 11:45:47 +0000850 // Write the type plane for types first because earlier planes (e.g. for a
851 // primitive type like float) may have constants constructed using types
852 // coming later (e.g., via getelementptr from a pointer type). The type
853 // plane is needed before types can be fwd or bkwd referenced.
854 const std::vector<const Type*>& Types = Table.getTypes();
855 assert(!Types.empty() && "No types at all?");
856 assert(TypeNum <= Types.size() && "Invalid TypeNo index");
857
858 unsigned NumEntries = Types.size() - TypeNum;
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000859
Reid Spencercb3595c2004-07-04 11:45:47 +0000860 // Output type header: [num entries]
Reid Spencerad89bd62004-07-25 18:07:36 +0000861 output_vbr(NumEntries);
Reid Spencercb3595c2004-07-04 11:45:47 +0000862
863 for (unsigned i = TypeNum; i < TypeNum+NumEntries; ++i)
864 outputType(Types[i]);
865}
866
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000867// Helper function for outputConstants().
868// Writes out all the constants in the plane Plane starting at entry StartNo.
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000869//
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000870void BytecodeWriter::outputConstantsInPlane(const std::vector<const Value*>
871 &Plane, unsigned StartNo) {
872 unsigned ValNo = StartNo;
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000873
Chris Lattner83bb3d22004-01-14 23:36:54 +0000874 // Scan through and ignore function arguments, global values, and constant
875 // strings.
876 for (; ValNo < Plane.size() &&
877 (isa<Argument>(Plane[ValNo]) || isa<GlobalValue>(Plane[ValNo]) ||
878 (isa<ConstantArray>(Plane[ValNo]) &&
879 cast<ConstantArray>(Plane[ValNo])->isString())); ValNo++)
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000880 /*empty*/;
881
882 unsigned NC = ValNo; // Number of constants
Chris Lattner3bc5a602006-01-25 23:08:15 +0000883 for (; NC < Plane.size() && (isa<Constant>(Plane[NC]) ||
884 isa<InlineAsm>(Plane[NC])); NC++)
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000885 /*empty*/;
886 NC -= ValNo; // Convert from index into count
887 if (NC == 0) return; // Skip empty type planes...
888
Chris Lattnerd6942d72004-01-14 16:54:21 +0000889 // FIXME: Most slabs only have 1 or 2 entries! We should encode this much
890 // more compactly.
891
Reid Spencerb83eb642006-10-20 07:07:24 +0000892 // Put out type header: [num entries][type id number]
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000893 //
Reid Spencerad89bd62004-07-25 18:07:36 +0000894 output_vbr(NC);
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000895
Reid Spencerb83eb642006-10-20 07:07:24 +0000896 // Put out the Type ID Number...
Alkis Evlogimenos60596382003-10-17 02:02:40 +0000897 int Slot = Table.getSlot(Plane.front()->getType());
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000898 assert (Slot != -1 && "Type in constant pool but not in function!!");
Reid Spencerad89bd62004-07-25 18:07:36 +0000899 output_typeid((unsigned)Slot);
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000900
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000901 for (unsigned i = ValNo; i < ValNo+NC; ++i) {
902 const Value *V = Plane[i];
Chris Lattner3bc5a602006-01-25 23:08:15 +0000903 if (const Constant *C = dyn_cast<Constant>(V))
Reid Spencere0125b62004-07-18 00:16:21 +0000904 outputConstant(C);
Chris Lattner3bc5a602006-01-25 23:08:15 +0000905 else
906 outputInlineAsm(cast<InlineAsm>(V));
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000907 }
908}
909
Chris Lattner9e60d8d2005-05-05 22:21:19 +0000910static inline bool hasNullValue(const Type *Ty) {
911 return Ty != Type::LabelTy && Ty != Type::VoidTy && !isa<OpaqueType>(Ty);
Chris Lattner80b97342004-01-17 23:25:43 +0000912}
913
Chris Lattner79df7c02002-03-26 18:01:55 +0000914void BytecodeWriter::outputConstants(bool isFunction) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000915 BytecodeBlock CPool(BytecodeFormat::ConstantPoolBlockID, *this,
Chris Lattner0baa0af2004-01-15 21:06:57 +0000916 true /* Elide block if empty */);
Chris Lattner00950542001-06-06 20:29:01 +0000917
918 unsigned NumPlanes = Table.getNumPlanes();
Chris Lattnerf69315b2003-05-22 18:35:38 +0000919
Reid Spencere0125b62004-07-18 00:16:21 +0000920 if (isFunction)
921 // Output the type plane before any constants!
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000922 outputTypes(Table.getModuleTypeLevel());
Reid Spencere0125b62004-07-18 00:16:21 +0000923 else
Chris Lattnerf9d71782004-10-14 01:46:07 +0000924 // Output module-level string constants before any other constants.
Chris Lattner83bb3d22004-01-14 23:36:54 +0000925 outputConstantStrings();
926
Reid Spencercb3595c2004-07-04 11:45:47 +0000927 for (unsigned pno = 0; pno != NumPlanes; pno++) {
928 const std::vector<const Value*> &Plane = Table.getPlane(pno);
929 if (!Plane.empty()) { // Skip empty type planes...
930 unsigned ValNo = 0;
931 if (isFunction) // Don't re-emit module constants
Reid Spencer0852c802004-07-04 11:46:15 +0000932 ValNo += Table.getModuleLevel(pno);
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000933
Chris Lattner9e60d8d2005-05-05 22:21:19 +0000934 if (hasNullValue(Plane[0]->getType())) {
Reid Spencer0852c802004-07-04 11:46:15 +0000935 // Skip zero initializer
936 if (ValNo == 0)
937 ValNo = 1;
Chris Lattnerf69315b2003-05-22 18:35:38 +0000938 }
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000939
Reid Spencercb3595c2004-07-04 11:45:47 +0000940 // Write out constants in the plane
941 outputConstantsInPlane(Plane, ValNo);
Chris Lattnerf69315b2003-05-22 18:35:38 +0000942 }
Reid Spencercb3595c2004-07-04 11:45:47 +0000943 }
Chris Lattner00950542001-06-06 20:29:01 +0000944}
945
Chris Lattner6b252422003-10-16 18:28:50 +0000946static unsigned getEncodedLinkage(const GlobalValue *GV) {
947 switch (GV->getLinkage()) {
948 default: assert(0 && "Invalid linkage!");
Anton Korobeynikovb74ed072006-09-14 18:23:27 +0000949 case GlobalValue::ExternalLinkage: return 0;
950 case GlobalValue::WeakLinkage: return 1;
951 case GlobalValue::AppendingLinkage: return 2;
952 case GlobalValue::InternalLinkage: return 3;
953 case GlobalValue::LinkOnceLinkage: return 4;
954 case GlobalValue::DLLImportLinkage: return 5;
955 case GlobalValue::DLLExportLinkage: return 6;
956 case GlobalValue::ExternalWeakLinkage: return 7;
Chris Lattner6b252422003-10-16 18:28:50 +0000957 }
958}
959
Chris Lattner00950542001-06-06 20:29:01 +0000960void BytecodeWriter::outputModuleInfoBlock(const Module *M) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000961 BytecodeBlock ModuleInfoBlock(BytecodeFormat::ModuleGlobalInfoBlockID, *this);
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000962
Chris Lattner404cddf2005-11-12 01:33:40 +0000963 // Give numbers to sections as we encounter them.
964 unsigned SectionIDCounter = 0;
965 std::vector<std::string> SectionNames;
966 std::map<std::string, unsigned> SectionID;
967
Chris Lattner70cc3392001-09-10 07:58:01 +0000968 // Output the types for the global variables in the module...
Chris Lattner28caccf2005-05-06 20:27:03 +0000969 for (Module::const_global_iterator I = M->global_begin(),
Chris Lattner8eb52dd2005-11-06 07:11:04 +0000970 End = M->global_end(); I != End; ++I) {
Alkis Evlogimenos60596382003-10-17 02:02:40 +0000971 int Slot = Table.getSlot(I->getType());
Chris Lattner70cc3392001-09-10 07:58:01 +0000972 assert(Slot != -1 && "Module global vars is broken!");
Chris Lattnerd70684f2001-09-18 04:01:05 +0000973
Chris Lattner8eb52dd2005-11-06 07:11:04 +0000974 assert((I->hasInitializer() || !I->hasInternalLinkage()) &&
975 "Global must have an initializer or have external linkage!");
976
Chris Lattner22482a12003-10-18 06:30:21 +0000977 // Fields: bit0 = isConstant, bit1 = hasInitializer, bit2-4=Linkage,
Chris Lattner8eb52dd2005-11-06 07:11:04 +0000978 // bit5+ = Slot # for type.
Chris Lattner404cddf2005-11-12 01:33:40 +0000979 bool HasExtensionWord = (I->getAlignment() != 0) || I->hasSection();
Chris Lattner8eb52dd2005-11-06 07:11:04 +0000980
981 // If we need to use the extension byte, set linkage=3(internal) and
982 // initializer = 0 (impossible!).
983 if (!HasExtensionWord) {
984 unsigned oSlot = ((unsigned)Slot << 5) | (getEncodedLinkage(I) << 2) |
985 (I->hasInitializer() << 1) | (unsigned)I->isConstant();
986 output_vbr(oSlot);
Anton Korobeynikovb74ed072006-09-14 18:23:27 +0000987 } else {
Chris Lattner8eb52dd2005-11-06 07:11:04 +0000988 unsigned oSlot = ((unsigned)Slot << 5) | (3 << 2) |
989 (0 << 1) | (unsigned)I->isConstant();
990 output_vbr(oSlot);
991
992 // The extension word has this format: bit 0 = has initializer, bit 1-3 =
Chris Lattner404cddf2005-11-12 01:33:40 +0000993 // linkage, bit 4-8 = alignment (log2), bit 9 = has SectionID,
994 // bits 10+ = future use.
Jeff Cohenba0ffcc2005-11-12 01:01:50 +0000995 unsigned ExtWord = (unsigned)I->hasInitializer() |
996 (getEncodedLinkage(I) << 1) |
Chris Lattner404cddf2005-11-12 01:33:40 +0000997 ((Log2_32(I->getAlignment())+1) << 4) |
998 ((unsigned)I->hasSection() << 9);
Chris Lattner8eb52dd2005-11-06 07:11:04 +0000999 output_vbr(ExtWord);
Chris Lattner404cddf2005-11-12 01:33:40 +00001000 if (I->hasSection()) {
1001 // Give section names unique ID's.
1002 unsigned &Entry = SectionID[I->getSection()];
1003 if (Entry == 0) {
1004 Entry = ++SectionIDCounter;
1005 SectionNames.push_back(I->getSection());
1006 }
1007 output_vbr(Entry);
1008 }
Chris Lattner8eb52dd2005-11-06 07:11:04 +00001009 }
Chris Lattnerd70684f2001-09-18 04:01:05 +00001010
Chris Lattner1b98c5c2001-10-13 06:48:38 +00001011 // If we have an initializer, output it now.
Chris Lattner0b12b5f2002-06-25 16:13:21 +00001012 if (I->hasInitializer()) {
Alkis Evlogimenos60596382003-10-17 02:02:40 +00001013 Slot = Table.getSlot((Value*)I->getInitializer());
Chris Lattnerd70684f2001-09-18 04:01:05 +00001014 assert(Slot != -1 && "No slot for global var initializer!");
Reid Spencerad89bd62004-07-25 18:07:36 +00001015 output_vbr((unsigned)Slot);
Chris Lattnerd70684f2001-09-18 04:01:05 +00001016 }
Chris Lattner70cc3392001-09-10 07:58:01 +00001017 }
Reid Spencerad89bd62004-07-25 18:07:36 +00001018 output_typeid((unsigned)Table.getSlot(Type::VoidTy));
Chris Lattner70cc3392001-09-10 07:58:01 +00001019
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001020 // Output the types of the functions in this module.
Chris Lattner7fc9fe32001-06-27 23:41:11 +00001021 for (Module::const_iterator I = M->begin(), End = M->end(); I != End; ++I) {
Alkis Evlogimenos60596382003-10-17 02:02:40 +00001022 int Slot = Table.getSlot(I->getType());
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001023 assert(Slot != -1 && "Module slot calculator is broken!");
Chris Lattner00950542001-06-06 20:29:01 +00001024 assert(Slot >= Type::FirstDerivedTyID && "Derived type not in range!");
Chris Lattnere73bd452005-11-06 07:43:39 +00001025 assert(((Slot << 6) >> 6) == Slot && "Slot # too big!");
Chris Lattner54b369e2005-11-06 07:46:13 +00001026 unsigned CC = I->getCallingConv()+1;
1027 unsigned ID = (Slot << 5) | (CC & 15);
Chris Lattner479ffeb2005-05-06 20:42:57 +00001028
Chris Lattnerd6e431f2004-11-15 22:39:49 +00001029 if (I->isExternal()) // If external, we don't have an FunctionInfo block.
1030 ID |= 1 << 4;
Chris Lattnere73bd452005-11-06 07:43:39 +00001031
Anton Korobeynikovb74ed072006-09-14 18:23:27 +00001032 if (I->getAlignment() || I->hasSection() || (CC & ~15) != 0 ||
1033 (I->isExternal() && I->hasDLLImportLinkage()) ||
1034 (I->isExternal() && I->hasExternalWeakLinkage())
1035 )
Chris Lattnere73bd452005-11-06 07:43:39 +00001036 ID |= 1 << 31; // Do we need an extension word?
1037
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001038 output_vbr(ID);
Chris Lattnere73bd452005-11-06 07:43:39 +00001039
1040 if (ID & (1 << 31)) {
1041 // Extension byte: bits 0-4 = alignment, bits 5-9 = top nibble of calling
Anton Korobeynikovb74ed072006-09-14 18:23:27 +00001042 // convention, bit 10 = hasSectionID., bits 11-12 = external linkage type
1043 unsigned extLinkage = 0;
1044
1045 if (I->isExternal()) {
1046 if (I->hasDLLImportLinkage()) {
1047 extLinkage = 1;
1048 } else if (I->hasExternalWeakLinkage()) {
1049 extLinkage = 2;
1050 }
1051 }
1052
Chris Lattner404cddf2005-11-12 01:33:40 +00001053 ID = (Log2_32(I->getAlignment())+1) | ((CC >> 4) << 5) |
Anton Korobeynikovb74ed072006-09-14 18:23:27 +00001054 (I->hasSection() << 10) |
1055 ((extLinkage & 3) << 11);
Chris Lattnere73bd452005-11-06 07:43:39 +00001056 output_vbr(ID);
Chris Lattner404cddf2005-11-12 01:33:40 +00001057
1058 // Give section names unique ID's.
1059 if (I->hasSection()) {
1060 unsigned &Entry = SectionID[I->getSection()];
1061 if (Entry == 0) {
1062 Entry = ++SectionIDCounter;
1063 SectionNames.push_back(I->getSection());
1064 }
1065 output_vbr(Entry);
1066 }
Chris Lattnere73bd452005-11-06 07:43:39 +00001067 }
Chris Lattner00950542001-06-06 20:29:01 +00001068 }
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001069 output_vbr((unsigned)Table.getSlot(Type::VoidTy) << 5);
Reid Spencerad89bd62004-07-25 18:07:36 +00001070
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001071 // Emit the list of dependent libraries for the Module.
Reid Spencer5ac88122004-07-25 21:32:02 +00001072 Module::lib_iterator LI = M->lib_begin();
1073 Module::lib_iterator LE = M->lib_end();
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001074 output_vbr(unsigned(LE - LI)); // Emit the number of dependent libraries.
1075 for (; LI != LE; ++LI)
Reid Spencer38d54be2004-08-17 07:45:14 +00001076 output(*LI);
Reid Spencerad89bd62004-07-25 18:07:36 +00001077
1078 // Output the target triple from the module
Reid Spencer38d54be2004-08-17 07:45:14 +00001079 output(M->getTargetTriple());
Chris Lattner404cddf2005-11-12 01:33:40 +00001080
1081 // Emit the table of section names.
1082 output_vbr((unsigned)SectionNames.size());
1083 for (unsigned i = 0, e = SectionNames.size(); i != e; ++i)
1084 output(SectionNames[i]);
Chris Lattner7e6db762006-01-23 23:43:17 +00001085
1086 // Output the inline asm string.
Chris Lattner66316012006-01-24 04:14:29 +00001087 output(M->getModuleInlineAsm());
Chris Lattner00950542001-06-06 20:29:01 +00001088}
1089
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001090void BytecodeWriter::outputInstructions(const Function *F) {
Reid Spencerad89bd62004-07-25 18:07:36 +00001091 BytecodeBlock ILBlock(BytecodeFormat::InstructionListBlockID, *this);
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001092 for (Function::const_iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
1093 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I)
1094 outputInstruction(*I);
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001095}
1096
Chris Lattner186a1f72003-03-19 20:56:46 +00001097void BytecodeWriter::outputFunction(const Function *F) {
Chris Lattnerfd7f8fe2004-11-15 21:56:33 +00001098 // If this is an external function, there is nothing else to emit!
1099 if (F->isExternal()) return;
1100
Chris Lattnerd6e431f2004-11-15 22:39:49 +00001101 BytecodeBlock FunctionBlock(BytecodeFormat::FunctionBlockID, *this);
1102 output_vbr(getEncodedLinkage(F));
1103
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001104 // Get slot information about the function...
1105 Table.incorporateFunction(F);
1106
1107 if (Table.getCompactionTable().empty()) {
1108 // Output information about the constants in the function if the compaction
1109 // table is not being used.
Chris Lattnere8fdde12001-09-07 16:39:41 +00001110 outputConstants(true);
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001111 } else {
1112 // Otherwise, emit the compaction table.
1113 outputCompactionTable();
Chris Lattnere8fdde12001-09-07 16:39:41 +00001114 }
Misha Brukman23c6d2c2005-04-21 21:48:46 +00001115
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001116 // Output all of the instructions in the body of the function
1117 outputInstructions(F);
Misha Brukman23c6d2c2005-04-21 21:48:46 +00001118
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001119 // If needed, output the symbol table for the function...
1120 outputSymbolTable(F->getSymbolTable());
Misha Brukman23c6d2c2005-04-21 21:48:46 +00001121
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001122 Table.purgeFunction();
1123}
1124
1125void BytecodeWriter::outputCompactionTablePlane(unsigned PlaneNo,
1126 const std::vector<const Value*> &Plane,
1127 unsigned StartNo) {
1128 unsigned End = Table.getModuleLevel(PlaneNo);
Chris Lattner52f86d62004-01-20 00:54:06 +00001129 if (Plane.empty() || StartNo == End || End == 0) return; // Nothing to emit
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001130 assert(StartNo < End && "Cannot emit negative range!");
1131 assert(StartNo < Plane.size() && End <= Plane.size());
1132
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001133 // Do not emit the null initializer!
Reid Spencercb3595c2004-07-04 11:45:47 +00001134 ++StartNo;
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001135
Chris Lattner24102432004-01-18 22:35:34 +00001136 // Figure out which encoding to use. By far the most common case we have is
1137 // to emit 0-2 entries in a compaction table plane.
1138 switch (End-StartNo) {
1139 case 0: // Avoid emitting two vbr's if possible.
1140 case 1:
1141 case 2:
Reid Spencerad89bd62004-07-25 18:07:36 +00001142 output_vbr((PlaneNo << 2) | End-StartNo);
Chris Lattner24102432004-01-18 22:35:34 +00001143 break;
1144 default:
1145 // Output the number of things.
Reid Spencerad89bd62004-07-25 18:07:36 +00001146 output_vbr((unsigned(End-StartNo) << 2) | 3);
1147 output_typeid(PlaneNo); // Emit the type plane this is
Chris Lattner24102432004-01-18 22:35:34 +00001148 break;
1149 }
1150
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001151 for (unsigned i = StartNo; i != End; ++i)
Reid Spencerad89bd62004-07-25 18:07:36 +00001152 output_vbr(Table.getGlobalSlot(Plane[i]));
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001153}
1154
Reid Spencercb3595c2004-07-04 11:45:47 +00001155void BytecodeWriter::outputCompactionTypes(unsigned StartNo) {
1156 // Get the compaction type table from the slot calculator
1157 const std::vector<const Type*> &CTypes = Table.getCompactionTypes();
1158
1159 // The compaction types may have been uncompactified back to the
1160 // global types. If so, we just write an empty table
Chris Lattnerc847f7c2006-07-28 22:07:54 +00001161 if (CTypes.size() == 0) {
Reid Spencerad89bd62004-07-25 18:07:36 +00001162 output_vbr(0U);
Reid Spencercb3595c2004-07-04 11:45:47 +00001163 return;
1164 }
1165
1166 assert(CTypes.size() >= StartNo && "Invalid compaction types start index");
1167
1168 // Determine how many types to write
1169 unsigned NumTypes = CTypes.size() - StartNo;
1170
1171 // Output the number of types.
Reid Spencerad89bd62004-07-25 18:07:36 +00001172 output_vbr(NumTypes);
Reid Spencercb3595c2004-07-04 11:45:47 +00001173
1174 for (unsigned i = StartNo; i < StartNo+NumTypes; ++i)
Reid Spencerad89bd62004-07-25 18:07:36 +00001175 output_typeid(Table.getGlobalSlot(CTypes[i]));
Reid Spencercb3595c2004-07-04 11:45:47 +00001176}
1177
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001178void BytecodeWriter::outputCompactionTable() {
Reid Spencer0033c182004-08-27 00:38:44 +00001179 // Avoid writing the compaction table at all if there is no content.
1180 if (Table.getCompactionTypes().size() >= Type::FirstDerivedTyID ||
1181 (!Table.CompactionTableIsEmpty())) {
Misha Brukman23c6d2c2005-04-21 21:48:46 +00001182 BytecodeBlock CTB(BytecodeFormat::CompactionTableBlockID, *this,
Reid Spencer0033c182004-08-27 00:38:44 +00001183 true/*ElideIfEmpty*/);
Chris Lattnerf9d71782004-10-14 01:46:07 +00001184 const std::vector<std::vector<const Value*> > &CT =
1185 Table.getCompactionTable();
Misha Brukman23c6d2c2005-04-21 21:48:46 +00001186
Reid Spencer0033c182004-08-27 00:38:44 +00001187 // First things first, emit the type compaction table if there is one.
1188 outputCompactionTypes(Type::FirstDerivedTyID);
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001189
Reid Spencer0033c182004-08-27 00:38:44 +00001190 for (unsigned i = 0, e = CT.size(); i != e; ++i)
1191 outputCompactionTablePlane(i, CT[i], 0);
1192 }
Chris Lattner00950542001-06-06 20:29:01 +00001193}
1194
Chris Lattner00950542001-06-06 20:29:01 +00001195void BytecodeWriter::outputSymbolTable(const SymbolTable &MST) {
Chris Lattner737d3cd2004-01-10 19:56:59 +00001196 // Do not output the Bytecode block for an empty symbol table, it just wastes
1197 // space!
Chris Lattnerf9d71782004-10-14 01:46:07 +00001198 if (MST.isEmpty()) return;
Chris Lattner737d3cd2004-01-10 19:56:59 +00001199
Reid Spencerad89bd62004-07-25 18:07:36 +00001200 BytecodeBlock SymTabBlock(BytecodeFormat::SymbolTableBlockID, *this,
Chris Lattnerf9d71782004-10-14 01:46:07 +00001201 true/*ElideIfEmpty*/);
Chris Lattner00950542001-06-06 20:29:01 +00001202
Misha Brukman23c6d2c2005-04-21 21:48:46 +00001203 // Write the number of types
Reid Spencerad89bd62004-07-25 18:07:36 +00001204 output_vbr(MST.num_types());
Reid Spencer250c4182004-08-17 02:59:02 +00001205
1206 // Write each of the types
Reid Spencer94f2df22004-05-25 17:29:59 +00001207 for (SymbolTable::type_const_iterator TI = MST.type_begin(),
Chris Lattnerc847f7c2006-07-28 22:07:54 +00001208 TE = MST.type_end(); TI != TE; ++TI) {
Reid Spencer250c4182004-08-17 02:59:02 +00001209 // Symtab entry:[def slot #][name]
Reid Spencerad89bd62004-07-25 18:07:36 +00001210 output_typeid((unsigned)Table.getSlot(TI->second));
Misha Brukman23c6d2c2005-04-21 21:48:46 +00001211 output(TI->first);
Reid Spencer94f2df22004-05-25 17:29:59 +00001212 }
1213
1214 // Now do each of the type planes in order.
Misha Brukman23c6d2c2005-04-21 21:48:46 +00001215 for (SymbolTable::plane_const_iterator PI = MST.plane_begin(),
Reid Spencer94f2df22004-05-25 17:29:59 +00001216 PE = MST.plane_end(); PI != PE; ++PI) {
1217 SymbolTable::value_const_iterator I = MST.value_begin(PI->first);
1218 SymbolTable::value_const_iterator End = MST.value_end(PI->first);
Chris Lattner00950542001-06-06 20:29:01 +00001219 int Slot;
Misha Brukman23c6d2c2005-04-21 21:48:46 +00001220
Chris Lattner00950542001-06-06 20:29:01 +00001221 if (I == End) continue; // Don't mess with an absent type...
1222
Reid Spencer250c4182004-08-17 02:59:02 +00001223 // Write the number of values in this plane
Chris Lattner001d16a2005-03-07 02:59:36 +00001224 output_vbr((unsigned)PI->second.size());
Chris Lattner00950542001-06-06 20:29:01 +00001225
Reid Spencer250c4182004-08-17 02:59:02 +00001226 // Write the slot number of the type for this plane
Reid Spencer94f2df22004-05-25 17:29:59 +00001227 Slot = Table.getSlot(PI->first);
Chris Lattner00950542001-06-06 20:29:01 +00001228 assert(Slot != -1 && "Type in symtab, but not in table!");
Reid Spencerad89bd62004-07-25 18:07:36 +00001229 output_typeid((unsigned)Slot);
Chris Lattner00950542001-06-06 20:29:01 +00001230
Reid Spencer250c4182004-08-17 02:59:02 +00001231 // Write each of the values in this plane
Chris Lattner7fc9fe32001-06-27 23:41:11 +00001232 for (; I != End; ++I) {
Chris Lattner00950542001-06-06 20:29:01 +00001233 // Symtab entry: [def slot #][name]
Alkis Evlogimenos60596382003-10-17 02:02:40 +00001234 Slot = Table.getSlot(I->second);
Chris Lattnere8fdde12001-09-07 16:39:41 +00001235 assert(Slot != -1 && "Value in symtab but has no slot number!!");
Reid Spencerad89bd62004-07-25 18:07:36 +00001236 output_vbr((unsigned)Slot);
Reid Spencer38d54be2004-08-17 07:45:14 +00001237 output(I->first);
Chris Lattner00950542001-06-06 20:29:01 +00001238 }
1239 }
1240}
1241
Bill Wendlinge8156192006-12-07 01:30:32 +00001242void llvm::WriteBytecodeToFile(const Module *M, OStream &Out,
Chris Lattnerc847f7c2006-07-28 22:07:54 +00001243 bool compress) {
Reid Spencerad89bd62004-07-25 18:07:36 +00001244 assert(M && "You can't write a null module!!");
Chris Lattner00950542001-06-06 20:29:01 +00001245
Reid Spencer32f55532006-06-07 23:18:34 +00001246 // Make sure that std::cout is put into binary mode for systems
1247 // that care.
Bill Wendlinge8156192006-12-07 01:30:32 +00001248 if (Out == cout)
Reid Spencer32f55532006-06-07 23:18:34 +00001249 sys::Program::ChangeStdoutToBinary();
1250
Reid Spencer17f52c52004-11-06 23:17:23 +00001251 // Create a vector of unsigned char for the bytecode output. We
1252 // reserve 256KBytes of space in the vector so that we avoid doing
1253 // lots of little allocations. 256KBytes is sufficient for a large
1254 // proportion of the bytecode files we will encounter. Larger files
1255 // will be automatically doubled in size as needed (std::vector
1256 // behavior).
Reid Spencerad89bd62004-07-25 18:07:36 +00001257 std::vector<unsigned char> Buffer;
Reid Spencer17f52c52004-11-06 23:17:23 +00001258 Buffer.reserve(256 * 1024);
Chris Lattner00950542001-06-06 20:29:01 +00001259
Reid Spencer17f52c52004-11-06 23:17:23 +00001260 // The BytecodeWriter populates Buffer for us.
Reid Spencerad89bd62004-07-25 18:07:36 +00001261 BytecodeWriter BCW(Buffer, M);
Chris Lattner00950542001-06-06 20:29:01 +00001262
Reid Spencer17f52c52004-11-06 23:17:23 +00001263 // Keep track of how much we've written
Chris Lattnerce6ef112002-07-26 18:40:14 +00001264 BytesWritten += Buffer.size();
1265
Reid Spencer17f52c52004-11-06 23:17:23 +00001266 // Determine start and end points of the Buffer
Reid Spencer83296f52004-11-07 18:17:38 +00001267 const unsigned char *FirstByte = &Buffer.front();
Reid Spencer17f52c52004-11-06 23:17:23 +00001268
1269 // If we're supposed to compress this mess ...
1270 if (compress) {
1271
1272 // We signal compression by using an alternate magic number for the
Reid Spencer83296f52004-11-07 18:17:38 +00001273 // file. The compressed bytecode file's magic number is "llvc" instead
Misha Brukman23c6d2c2005-04-21 21:48:46 +00001274 // of "llvm".
Reid Spencer83296f52004-11-07 18:17:38 +00001275 char compressed_magic[4];
1276 compressed_magic[0] = 'l';
1277 compressed_magic[1] = 'l';
1278 compressed_magic[2] = 'v';
1279 compressed_magic[3] = 'c';
Reid Spencer17f52c52004-11-06 23:17:23 +00001280
Bill Wendling68fe61d2006-11-29 00:19:40 +00001281 Out.stream()->write(compressed_magic,4);
Reid Spencer17f52c52004-11-06 23:17:23 +00001282
Reid Spencera70d84d2004-11-14 22:01:41 +00001283 // Compress everything after the magic number (which we altered)
Reid Spencer3ed469c2006-11-02 20:25:50 +00001284 Compressor::compressToStream(
Reid Spencer17f52c52004-11-06 23:17:23 +00001285 (char*)(FirstByte+4), // Skip the magic number
1286 Buffer.size()-4, // Skip the magic number
Bill Wendling68fe61d2006-11-29 00:19:40 +00001287 *Out.stream() // Where to write compressed data
Reid Spencer17f52c52004-11-06 23:17:23 +00001288 );
1289
Reid Spencer17f52c52004-11-06 23:17:23 +00001290 } else {
1291
1292 // We're not compressing, so just write the entire block.
Bill Wendling68fe61d2006-11-29 00:19:40 +00001293 Out.stream()->write((char*)FirstByte, Buffer.size());
Chris Lattnere8fdde12001-09-07 16:39:41 +00001294 }
Reid Spencer17f52c52004-11-06 23:17:23 +00001295
1296 // make sure it hits disk now
Bill Wendling68fe61d2006-11-29 00:19:40 +00001297 Out.stream()->flush();
Chris Lattner00950542001-06-06 20:29:01 +00001298}