blob: 7acd2094c5da5b4a2ce29646c840a58ce8229de6 [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
Chris Lattner1c560ad2006-12-19 23:16:47 +000020#define DEBUG_TYPE "bytecodewriter"
Chris Lattner00950542001-06-06 20:29:01 +000021#include "WriterInternals.h"
Chris Lattner635cd932002-07-23 19:56:44 +000022#include "llvm/Bytecode/WriteBytecodePass.h"
Chris Lattnerdee199f2005-05-06 22:34:01 +000023#include "llvm/CallingConv.h"
Chris Lattner83bb3d22004-01-14 23:36:54 +000024#include "llvm/Constants.h"
25#include "llvm/DerivedTypes.h"
Chris Lattner3bc5a602006-01-25 23:08:15 +000026#include "llvm/InlineAsm.h"
Reid Spencerad89bd62004-07-25 18:07:36 +000027#include "llvm/Instructions.h"
Chris Lattner00950542001-06-06 20:29:01 +000028#include "llvm/Module.h"
Chris Lattner00950542001-06-06 20:29:01 +000029#include "llvm/SymbolTable.h"
Reid Spencer78d033e2007-01-06 07:24:44 +000030#include "llvm/TypeSymbolTable.h"
Reid Spencerad89bd62004-07-25 18:07:36 +000031#include "llvm/Support/GetElementPtrTypeIterator.h"
Reid Spencer17f52c52004-11-06 23:17:23 +000032#include "llvm/Support/Compressor.h"
Jim Laskeycb6682f2005-08-17 19:34:49 +000033#include "llvm/Support/MathExtras.h"
Bill Wendling68fe61d2006-11-29 00:19:40 +000034#include "llvm/Support/Streams.h"
Reid Spencer32f55532006-06-07 23:18:34 +000035#include "llvm/System/Program.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000036#include "llvm/ADT/STLExtras.h"
37#include "llvm/ADT/Statistic.h"
Chris Lattner32abce62004-01-10 19:10:01 +000038#include <cstring>
Chris Lattner00950542001-06-06 20:29:01 +000039#include <algorithm>
Chris Lattner44f549b2004-01-10 18:49:43 +000040using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000041
Reid Spencer38d54be2004-08-17 07:45:14 +000042/// This value needs to be incremented every time the bytecode format changes
43/// so that the reader can distinguish which format of the bytecode file has
44/// been written.
45/// @brief The bytecode version number
Reid Spencer6996feb2006-11-08 21:27:54 +000046const unsigned BCVersionNum = 7;
Reid Spencer38d54be2004-08-17 07:45:14 +000047
Chris Lattner635cd932002-07-23 19:56:44 +000048static RegisterPass<WriteBytecodePass> X("emitbytecode", "Bytecode Writer");
49
Chris Lattner1c560ad2006-12-19 23:16:47 +000050STATISTIC(BytesWritten, "Number of bytecode bytes written");
Chris Lattner635cd932002-07-23 19:56:44 +000051
Reid Spencerad89bd62004-07-25 18:07:36 +000052//===----------------------------------------------------------------------===//
53//=== Output Primitives ===//
54//===----------------------------------------------------------------------===//
55
56// output - If a position is specified, it must be in the valid portion of the
Misha Brukman23c6d2c2005-04-21 21:48:46 +000057// string... note that this should be inlined always so only the relevant IF
Reid Spencerad89bd62004-07-25 18:07:36 +000058// body should be included.
59inline void BytecodeWriter::output(unsigned i, int pos) {
60 if (pos == -1) { // Be endian clean, little endian is our friend
Misha Brukman23c6d2c2005-04-21 21:48:46 +000061 Out.push_back((unsigned char)i);
Reid Spencerad89bd62004-07-25 18:07:36 +000062 Out.push_back((unsigned char)(i >> 8));
63 Out.push_back((unsigned char)(i >> 16));
64 Out.push_back((unsigned char)(i >> 24));
65 } else {
66 Out[pos ] = (unsigned char)i;
67 Out[pos+1] = (unsigned char)(i >> 8);
68 Out[pos+2] = (unsigned char)(i >> 16);
69 Out[pos+3] = (unsigned char)(i >> 24);
70 }
71}
72
73inline void BytecodeWriter::output(int i) {
74 output((unsigned)i);
75}
76
77/// output_vbr - Output an unsigned value, by using the least number of bytes
78/// possible. This is useful because many of our "infinite" values are really
79/// very small most of the time; but can be large a few times.
Misha Brukman23c6d2c2005-04-21 21:48:46 +000080/// Data format used: If you read a byte with the high bit set, use the low
81/// seven bits as data and then read another byte.
Reid Spencerad89bd62004-07-25 18:07:36 +000082inline void BytecodeWriter::output_vbr(uint64_t i) {
83 while (1) {
84 if (i < 0x80) { // done?
85 Out.push_back((unsigned char)i); // We know the high bit is clear...
86 return;
87 }
Misha Brukman23c6d2c2005-04-21 21:48:46 +000088
Reid Spencerad89bd62004-07-25 18:07:36 +000089 // Nope, we are bigger than a character, output the next 7 bits and set the
90 // high bit to say that there is more coming...
91 Out.push_back(0x80 | ((unsigned char)i & 0x7F));
92 i >>= 7; // Shift out 7 bits now...
93 }
94}
95
96inline void BytecodeWriter::output_vbr(unsigned i) {
97 while (1) {
98 if (i < 0x80) { // done?
99 Out.push_back((unsigned char)i); // We know the high bit is clear...
100 return;
101 }
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000102
Reid Spencerad89bd62004-07-25 18:07:36 +0000103 // Nope, we are bigger than a character, output the next 7 bits and set the
104 // high bit to say that there is more coming...
105 Out.push_back(0x80 | ((unsigned char)i & 0x7F));
106 i >>= 7; // Shift out 7 bits now...
107 }
108}
109
110inline void BytecodeWriter::output_typeid(unsigned i) {
111 if (i <= 0x00FFFFFF)
112 this->output_vbr(i);
113 else {
114 this->output_vbr(0x00FFFFFF);
115 this->output_vbr(i);
116 }
117}
118
119inline void BytecodeWriter::output_vbr(int64_t i) {
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000120 if (i < 0)
Reid Spencerad89bd62004-07-25 18:07:36 +0000121 output_vbr(((uint64_t)(-i) << 1) | 1); // Set low order sign bit...
122 else
123 output_vbr((uint64_t)i << 1); // Low order bit is clear.
124}
125
126
127inline void BytecodeWriter::output_vbr(int i) {
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000128 if (i < 0)
Reid Spencerad89bd62004-07-25 18:07:36 +0000129 output_vbr(((unsigned)(-i) << 1) | 1); // Set low order sign bit...
130 else
131 output_vbr((unsigned)i << 1); // Low order bit is clear.
132}
133
Reid Spencer38d54be2004-08-17 07:45:14 +0000134inline void BytecodeWriter::output(const std::string &s) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000135 unsigned Len = s.length();
Chris Lattnerc847f7c2006-07-28 22:07:54 +0000136 output_vbr(Len); // Strings may have an arbitrary length.
Reid Spencerad89bd62004-07-25 18:07:36 +0000137 Out.insert(Out.end(), s.begin(), s.end());
Reid Spencerad89bd62004-07-25 18:07:36 +0000138}
139
140inline void BytecodeWriter::output_data(const void *Ptr, const void *End) {
141 Out.insert(Out.end(), (const unsigned char*)Ptr, (const unsigned char*)End);
142}
143
144inline void BytecodeWriter::output_float(float& FloatVal) {
145 /// FIXME: This isn't optimal, it has size problems on some platforms
146 /// where FP is not IEEE.
Jim Laskeycb6682f2005-08-17 19:34:49 +0000147 uint32_t i = FloatToBits(FloatVal);
Chris Lattnerc847f7c2006-07-28 22:07:54 +0000148 Out.push_back( static_cast<unsigned char>( (i ) & 0xFF));
149 Out.push_back( static_cast<unsigned char>( (i >> 8 ) & 0xFF));
Jim Laskeycb6682f2005-08-17 19:34:49 +0000150 Out.push_back( static_cast<unsigned char>( (i >> 16) & 0xFF));
151 Out.push_back( static_cast<unsigned char>( (i >> 24) & 0xFF));
Reid Spencerad89bd62004-07-25 18:07:36 +0000152}
153
154inline void BytecodeWriter::output_double(double& DoubleVal) {
155 /// FIXME: This isn't optimal, it has size problems on some platforms
156 /// where FP is not IEEE.
Jim Laskeycb6682f2005-08-17 19:34:49 +0000157 uint64_t i = DoubleToBits(DoubleVal);
Chris Lattnerc847f7c2006-07-28 22:07:54 +0000158 Out.push_back( static_cast<unsigned char>( (i ) & 0xFF));
159 Out.push_back( static_cast<unsigned char>( (i >> 8 ) & 0xFF));
Jim Laskeycb6682f2005-08-17 19:34:49 +0000160 Out.push_back( static_cast<unsigned char>( (i >> 16) & 0xFF));
161 Out.push_back( static_cast<unsigned char>( (i >> 24) & 0xFF));
162 Out.push_back( static_cast<unsigned char>( (i >> 32) & 0xFF));
163 Out.push_back( static_cast<unsigned char>( (i >> 40) & 0xFF));
164 Out.push_back( static_cast<unsigned char>( (i >> 48) & 0xFF));
165 Out.push_back( static_cast<unsigned char>( (i >> 56) & 0xFF));
Reid Spencerad89bd62004-07-25 18:07:36 +0000166}
167
Chris Lattnerc76ea432005-11-12 18:34:09 +0000168inline BytecodeBlock::BytecodeBlock(unsigned ID, BytecodeWriter &w,
169 bool elideIfEmpty, bool hasLongFormat)
Reid Spencerad89bd62004-07-25 18:07:36 +0000170 : Id(ID), Writer(w), ElideIfEmpty(elideIfEmpty), HasLongFormat(hasLongFormat){
171
172 if (HasLongFormat) {
173 w.output(ID);
174 w.output(0U); // For length in long format
175 } else {
176 w.output(0U); /// Place holder for ID and length for this block
177 }
178 Loc = w.size();
179}
180
Chris Lattnerb0bf6642004-10-14 01:35:17 +0000181inline BytecodeBlock::~BytecodeBlock() { // Do backpatch when block goes out
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000182 // of scope...
Reid Spencerad89bd62004-07-25 18:07:36 +0000183 if (Loc == Writer.size() && ElideIfEmpty) {
184 // If the block is empty, and we are allowed to, do not emit the block at
185 // all!
186 Writer.resize(Writer.size()-(HasLongFormat?8:4));
187 return;
188 }
189
Reid Spencerad89bd62004-07-25 18:07:36 +0000190 if (HasLongFormat)
191 Writer.output(unsigned(Writer.size()-Loc), int(Loc-4));
192 else
193 Writer.output(unsigned(Writer.size()-Loc) << 5 | (Id & 0x1F), int(Loc-4));
Reid Spencerad89bd62004-07-25 18:07:36 +0000194}
195
196//===----------------------------------------------------------------------===//
197//=== Constant Output ===//
198//===----------------------------------------------------------------------===//
199
200void BytecodeWriter::outputType(const Type *T) {
Andrew Lenharth38ecbf12006-12-08 18:06:16 +0000201 const StructType* STy = dyn_cast<StructType>(T);
202 if(STy && STy->isPacked())
203 output_vbr((unsigned)Type::BC_ONLY_PackedStructTyID);
204 else
205 output_vbr((unsigned)T->getTypeID());
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000206
Reid Spencerad89bd62004-07-25 18:07:36 +0000207 // That's all there is to handling primitive types...
208 if (T->isPrimitiveType()) {
209 return; // We might do this if we alias a prim type: %x = type int
210 }
211
212 switch (T->getTypeID()) { // Handle derived types now.
213 case Type::FunctionTyID: {
214 const FunctionType *MT = cast<FunctionType>(T);
215 int Slot = Table.getSlot(MT->getReturnType());
216 assert(Slot != -1 && "Type used but not available!!");
217 output_typeid((unsigned)Slot);
Reid Spencer88cfda22006-12-31 05:44:24 +0000218 output_vbr(unsigned(MT->getParamAttrs(0)));
Reid Spencerad89bd62004-07-25 18:07:36 +0000219
220 // Output the number of arguments to function (+1 if varargs):
221 output_vbr((unsigned)MT->getNumParams()+MT->isVarArg());
222
223 // Output all of the arguments...
224 FunctionType::param_iterator I = MT->param_begin();
Reid Spencer88cfda22006-12-31 05:44:24 +0000225 unsigned Idx = 1;
Reid Spencerad89bd62004-07-25 18:07:36 +0000226 for (; I != MT->param_end(); ++I) {
227 Slot = Table.getSlot(*I);
228 assert(Slot != -1 && "Type used but not available!!");
229 output_typeid((unsigned)Slot);
Reid Spencer88cfda22006-12-31 05:44:24 +0000230 output_vbr(unsigned(MT->getParamAttrs(Idx)));
231 Idx++;
Reid Spencerad89bd62004-07-25 18:07:36 +0000232 }
233
234 // Terminate list with VoidTy if we are a varargs function...
235 if (MT->isVarArg())
236 output_typeid((unsigned)Type::VoidTyID);
237 break;
238 }
239
240 case Type::ArrayTyID: {
241 const ArrayType *AT = cast<ArrayType>(T);
242 int Slot = Table.getSlot(AT->getElementType());
243 assert(Slot != -1 && "Type used but not available!!");
244 output_typeid((unsigned)Slot);
Reid Spencerad89bd62004-07-25 18:07:36 +0000245 output_vbr(AT->getNumElements());
246 break;
247 }
248
Brian Gaeke715c90b2004-08-20 06:00:58 +0000249 case Type::PackedTyID: {
250 const PackedType *PT = cast<PackedType>(T);
251 int Slot = Table.getSlot(PT->getElementType());
252 assert(Slot != -1 && "Type used but not available!!");
253 output_typeid((unsigned)Slot);
254 output_vbr(PT->getNumElements());
255 break;
256 }
257
Reid Spencerad89bd62004-07-25 18:07:36 +0000258 case Type::StructTyID: {
259 const StructType *ST = cast<StructType>(T);
Reid Spencerad89bd62004-07-25 18:07:36 +0000260 // Output all of the element types...
261 for (StructType::element_iterator I = ST->element_begin(),
262 E = ST->element_end(); I != E; ++I) {
263 int Slot = Table.getSlot(*I);
264 assert(Slot != -1 && "Type used but not available!!");
265 output_typeid((unsigned)Slot);
266 }
267
268 // Terminate list with VoidTy
269 output_typeid((unsigned)Type::VoidTyID);
270 break;
271 }
272
273 case Type::PointerTyID: {
274 const PointerType *PT = cast<PointerType>(T);
275 int Slot = Table.getSlot(PT->getElementType());
276 assert(Slot != -1 && "Type used but not available!!");
277 output_typeid((unsigned)Slot);
278 break;
279 }
280
Chris Lattnerb0bf6642004-10-14 01:35:17 +0000281 case Type::OpaqueTyID:
Reid Spencerad89bd62004-07-25 18:07:36 +0000282 // No need to emit anything, just the count of opaque types is enough.
283 break;
Reid Spencerad89bd62004-07-25 18:07:36 +0000284
Reid Spencerad89bd62004-07-25 18:07:36 +0000285 default:
Bill Wendlinge8156192006-12-07 01:30:32 +0000286 cerr << __FILE__ << ":" << __LINE__ << ": Don't know how to serialize"
287 << " Type '" << T->getDescription() << "'\n";
Reid Spencerad89bd62004-07-25 18:07:36 +0000288 break;
289 }
290}
291
292void BytecodeWriter::outputConstant(const Constant *CPV) {
293 assert((CPV->getType()->isPrimitiveType() || !CPV->isNullValue()) &&
294 "Shouldn't output null constants!");
295
296 // We must check for a ConstantExpr before switching by type because
297 // a ConstantExpr can be of any type, and has no explicit value.
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000298 //
Reid Spencerad89bd62004-07-25 18:07:36 +0000299 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
300 // FIXME: Encoding of constant exprs could be much more compact!
301 assert(CE->getNumOperands() > 0 && "ConstantExpr with 0 operands");
Reid Spencer3da59db2006-11-27 01:05:10 +0000302 assert(CE->getNumOperands() != 1 || CE->isCast());
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000303 output_vbr(1+CE->getNumOperands()); // flags as an expr
Reid Spencerb83eb642006-10-20 07:07:24 +0000304 output_vbr(CE->getOpcode()); // Put out the CE op code
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000305
Reid Spencerad89bd62004-07-25 18:07:36 +0000306 for (User::const_op_iterator OI = CE->op_begin(); OI != CE->op_end(); ++OI){
307 int Slot = Table.getSlot(*OI);
308 assert(Slot != -1 && "Unknown constant used in ConstantExpr!!");
309 output_vbr((unsigned)Slot);
310 Slot = Table.getSlot((*OI)->getType());
311 output_typeid((unsigned)Slot);
312 }
Reid Spencer595b4772006-12-04 05:23:49 +0000313 if (CE->isCompare())
314 output_vbr((unsigned)CE->getPredicate());
Reid Spencerad89bd62004-07-25 18:07:36 +0000315 return;
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000316 } else if (isa<UndefValue>(CPV)) {
317 output_vbr(1U); // 1 -> UndefValue constant.
318 return;
Reid Spencerad89bd62004-07-25 18:07:36 +0000319 } else {
Reid Spencerb83eb642006-10-20 07:07:24 +0000320 output_vbr(0U); // flag as not a ConstantExpr (i.e. 0 operands)
Reid Spencerad89bd62004-07-25 18:07:36 +0000321 }
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000322
Reid Spencerad89bd62004-07-25 18:07:36 +0000323 switch (CPV->getType()->getTypeID()) {
Reid Spencer4fe16d62007-01-11 18:21:29 +0000324 case Type::Int1TyID: // Boolean Types
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000325 if (cast<ConstantInt>(CPV)->getBoolValue())
Reid Spencerad89bd62004-07-25 18:07:36 +0000326 output_vbr(1U);
327 else
328 output_vbr(0U);
329 break;
330
Reid Spencer88cfda22006-12-31 05:44:24 +0000331 case Type::Int8TyID: // Unsigned integer types...
332 case Type::Int16TyID:
333 case Type::Int32TyID:
334 case Type::Int64TyID:
Reid Spencerb83eb642006-10-20 07:07:24 +0000335 output_vbr(cast<ConstantInt>(CPV)->getZExtValue());
Reid Spencerad89bd62004-07-25 18:07:36 +0000336 break;
337
Reid Spencerad89bd62004-07-25 18:07:36 +0000338 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!");
Reid Spencer88cfda22006-12-31 05:44:24 +0000490 case Type::Int32TyID: IdxId = 0; break;
491 case Type::Int64TyID: IdxId = 1; break;
Reid Spencerad89bd62004-07-25 18:07:36 +0000492 }
Reid Spencer88cfda22006-12-31 05:44:24 +0000493 Slot = (Slot << 1) | IdxId;
Reid Spencerad89bd62004-07-25 18:07:36 +0000494 }
495 output_vbr(unsigned(Slot));
496 }
497 }
Reid Spencerad89bd62004-07-25 18:07:36 +0000498}
499
500
501// outputInstrVarArgsCall - Output the absurdly annoying varargs function calls.
502// This are more annoying than most because the signature of the call does not
503// tell us anything about the types of the arguments in the varargs portion.
504// Because of this, we encode (as type 0) all of the argument types explicitly
505// before the argument value. This really sucks, but you shouldn't be using
506// varargs functions in your code! *death to printf*!
507//
508// Format: [opcode] [type] [numargs] [arg0] [arg1] ... [arg<numargs-1>]
509//
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000510void BytecodeWriter::outputInstrVarArgsCall(const Instruction *I,
511 unsigned Opcode,
512 const SlotCalculator &Table,
513 unsigned Type) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000514 assert(isa<CallInst>(I) || isa<InvokeInst>(I));
515 // Opcode must have top two bits clear...
516 output_vbr(Opcode << 2); // Instruction Opcode ID
517 output_typeid(Type); // Result type (varargs type)
518
519 const PointerType *PTy = cast<PointerType>(I->getOperand(0)->getType());
520 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
521 unsigned NumParams = FTy->getNumParams();
522
523 unsigned NumFixedOperands;
524 if (isa<CallInst>(I)) {
525 // Output an operand for the callee and each fixed argument, then two for
526 // each variable argument.
527 NumFixedOperands = 1+NumParams;
528 } else {
529 assert(isa<InvokeInst>(I) && "Not call or invoke??");
530 // Output an operand for the callee and destinations, then two for each
531 // variable argument.
532 NumFixedOperands = 3+NumParams;
533 }
Reid Spencer3da59db2006-11-27 01:05:10 +0000534 output_vbr(2 * I->getNumOperands()-NumFixedOperands +
535 unsigned(Opcode == 58 || isa<InvokeInst>(I)));
Reid Spencerad89bd62004-07-25 18:07:36 +0000536
537 // The type for the function has already been emitted in the type field of the
538 // instruction. Just emit the slot # now.
539 for (unsigned i = 0; i != NumFixedOperands; ++i) {
540 int Slot = Table.getSlot(I->getOperand(i));
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000541 assert(Slot >= 0 && "No slot number for value!?!?");
Reid Spencerad89bd62004-07-25 18:07:36 +0000542 output_vbr((unsigned)Slot);
543 }
544
545 for (unsigned i = NumFixedOperands, e = I->getNumOperands(); i != e; ++i) {
546 // Output Arg Type ID
547 int Slot = Table.getSlot(I->getOperand(i)->getType());
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000548 assert(Slot >= 0 && "No slot number for value!?!?");
Reid Spencerad89bd62004-07-25 18:07:36 +0000549 output_typeid((unsigned)Slot);
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000550
Reid Spencerad89bd62004-07-25 18:07:36 +0000551 // Output arg ID itself
552 Slot = Table.getSlot(I->getOperand(i));
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000553 assert(Slot >= 0 && "No slot number for value!?!?");
Reid Spencerad89bd62004-07-25 18:07:36 +0000554 output_vbr((unsigned)Slot);
555 }
Chris Lattnera65371e2006-05-26 18:42:34 +0000556
Reid Spencer3da59db2006-11-27 01:05:10 +0000557 if (isa<InvokeInst>(I)) {
558 // Emit the tail call/calling conv for invoke instructions
559 output_vbr(cast<InvokeInst>(I)->getCallingConv());
560 } else if (Opcode == 58) {
Chris Lattnera65371e2006-05-26 18:42:34 +0000561 const CallInst *CI = cast<CallInst>(I);
562 output_vbr((CI->getCallingConv() << 1) | unsigned(CI->isTailCall()));
Chris Lattnera65371e2006-05-26 18:42:34 +0000563 }
Reid Spencerad89bd62004-07-25 18:07:36 +0000564}
565
566
567// outputInstructionFormat1 - Output one operand instructions, knowing that no
568// operand index is >= 2^12.
569//
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000570inline void BytecodeWriter::outputInstructionFormat1(const Instruction *I,
571 unsigned Opcode,
572 unsigned *Slots,
573 unsigned Type) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000574 // bits Instruction format:
575 // --------------------------
576 // 01-00: Opcode type, fixed to 1.
577 // 07-02: Opcode
578 // 19-08: Resulting type plane
579 // 31-20: Operand #1 (if set to (2^12-1), then zero operands)
580 //
Chris Lattnerf9d71782004-10-14 01:46:07 +0000581 output(1 | (Opcode << 2) | (Type << 8) | (Slots[0] << 20));
Reid Spencerad89bd62004-07-25 18:07:36 +0000582}
583
584
585// outputInstructionFormat2 - Output two operand instructions, knowing that no
586// operand index is >= 2^8.
587//
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000588inline void BytecodeWriter::outputInstructionFormat2(const Instruction *I,
589 unsigned Opcode,
590 unsigned *Slots,
591 unsigned Type) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000592 // bits Instruction format:
593 // --------------------------
594 // 01-00: Opcode type, fixed to 2.
595 // 07-02: Opcode
596 // 15-08: Resulting type plane
597 // 23-16: Operand #1
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000598 // 31-24: Operand #2
Reid Spencerad89bd62004-07-25 18:07:36 +0000599 //
Chris Lattnerf9d71782004-10-14 01:46:07 +0000600 output(2 | (Opcode << 2) | (Type << 8) | (Slots[0] << 16) | (Slots[1] << 24));
Reid Spencerad89bd62004-07-25 18:07:36 +0000601}
602
603
604// outputInstructionFormat3 - Output three operand instructions, knowing that no
605// operand index is >= 2^6.
606//
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000607inline void BytecodeWriter::outputInstructionFormat3(const Instruction *I,
Reid Spencerad89bd62004-07-25 18:07:36 +0000608 unsigned Opcode,
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000609 unsigned *Slots,
610 unsigned Type) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000611 // bits Instruction format:
612 // --------------------------
613 // 01-00: Opcode type, fixed to 3.
614 // 07-02: Opcode
615 // 13-08: Resulting type plane
616 // 19-14: Operand #1
617 // 25-20: Operand #2
618 // 31-26: Operand #3
619 //
Chris Lattnerf9d71782004-10-14 01:46:07 +0000620 output(3 | (Opcode << 2) | (Type << 8) |
Chris Lattner84d1ced2004-10-14 01:57:28 +0000621 (Slots[0] << 14) | (Slots[1] << 20) | (Slots[2] << 26));
Reid Spencerad89bd62004-07-25 18:07:36 +0000622}
623
624void BytecodeWriter::outputInstruction(const Instruction &I) {
Reid Spencer3da59db2006-11-27 01:05:10 +0000625 assert(I.getOpcode() < 57 && "Opcode too big???");
Reid Spencerad89bd62004-07-25 18:07:36 +0000626 unsigned Opcode = I.getOpcode();
627 unsigned NumOperands = I.getNumOperands();
628
Chris Lattner38287bd2005-05-06 06:13:34 +0000629 // Encode 'tail call' as 61, 'volatile load' as 62, and 'volatile store' as
630 // 63.
Chris Lattnerdee199f2005-05-06 22:34:01 +0000631 if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
632 if (CI->getCallingConv() == CallingConv::C) {
633 if (CI->isTailCall())
634 Opcode = 61; // CCC + Tail Call
635 else
636 ; // Opcode = Instruction::Call
637 } else if (CI->getCallingConv() == CallingConv::Fast) {
638 if (CI->isTailCall())
639 Opcode = 59; // FastCC + TailCall
640 else
641 Opcode = 60; // FastCC + Not Tail Call
642 } else {
643 Opcode = 58; // Call escape sequence.
644 }
Chris Lattnerdee199f2005-05-06 22:34:01 +0000645 } else if (isa<LoadInst>(I) && cast<LoadInst>(I).isVolatile()) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000646 Opcode = 62;
Chris Lattnerdee199f2005-05-06 22:34:01 +0000647 } else if (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile()) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000648 Opcode = 63;
Chris Lattnerdee199f2005-05-06 22:34:01 +0000649 }
Reid Spencerad89bd62004-07-25 18:07:36 +0000650
651 // Figure out which type to encode with the instruction. Typically we want
652 // the type of the first parameter, as opposed to the type of the instruction
653 // (for example, with setcc, we always know it returns bool, but the type of
654 // the first param is actually interesting). But if we have no arguments
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000655 // we take the type of the instruction itself.
Reid Spencerad89bd62004-07-25 18:07:36 +0000656 //
657 const Type *Ty;
658 switch (I.getOpcode()) {
659 case Instruction::Select:
660 case Instruction::Malloc:
661 case Instruction::Alloca:
662 Ty = I.getType(); // These ALWAYS want to encode the return type
663 break;
664 case Instruction::Store:
665 Ty = I.getOperand(1)->getType(); // Encode the pointer type...
666 assert(isa<PointerType>(Ty) && "Store to nonpointer type!?!?");
667 break;
668 default: // Otherwise use the default behavior...
669 Ty = NumOperands ? I.getOperand(0)->getType() : I.getType();
670 break;
671 }
672
673 unsigned Type;
674 int Slot = Table.getSlot(Ty);
675 assert(Slot != -1 && "Type not available!!?!");
676 Type = (unsigned)Slot;
677
678 // Varargs calls and invokes are encoded entirely different from any other
679 // instructions.
680 if (const CallInst *CI = dyn_cast<CallInst>(&I)){
681 const PointerType *Ty =cast<PointerType>(CI->getCalledValue()->getType());
682 if (cast<FunctionType>(Ty->getElementType())->isVarArg()) {
683 outputInstrVarArgsCall(CI, Opcode, Table, Type);
684 return;
685 }
686 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
687 const PointerType *Ty =cast<PointerType>(II->getCalledValue()->getType());
688 if (cast<FunctionType>(Ty->getElementType())->isVarArg()) {
689 outputInstrVarArgsCall(II, Opcode, Table, Type);
690 return;
691 }
692 }
693
694 if (NumOperands <= 3) {
695 // Make sure that we take the type number into consideration. We don't want
696 // to overflow the field size for the instruction format we select.
697 //
698 unsigned MaxOpSlot = Type;
699 unsigned Slots[3]; Slots[0] = (1 << 12)-1; // Marker to signify 0 operands
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000700
Reid Spencerad89bd62004-07-25 18:07:36 +0000701 for (unsigned i = 0; i != NumOperands; ++i) {
702 int slot = Table.getSlot(I.getOperand(i));
703 assert(slot != -1 && "Broken bytecode!");
704 if (unsigned(slot) > MaxOpSlot) MaxOpSlot = unsigned(slot);
705 Slots[i] = unsigned(slot);
706 }
707
708 // Handle the special cases for various instructions...
709 if (isa<CastInst>(I) || isa<VAArgInst>(I)) {
710 // Cast has to encode the destination type as the second argument in the
711 // packet, or else we won't know what type to cast to!
712 Slots[1] = Table.getSlot(I.getType());
713 assert(Slots[1] != ~0U && "Cast return type unknown?");
714 if (Slots[1] > MaxOpSlot) MaxOpSlot = Slots[1];
715 NumOperands++;
Chris Lattner42ba6b42005-11-05 22:08:14 +0000716 } else if (const AllocationInst *AI = dyn_cast<AllocationInst>(&I)) {
717 assert(NumOperands == 1 && "Bogus allocation!");
718 if (AI->getAlignment()) {
719 Slots[1] = Log2_32(AI->getAlignment())+1;
720 if (Slots[1] > MaxOpSlot) MaxOpSlot = Slots[1];
721 NumOperands = 2;
722 }
Reid Spencerc8dab492006-12-03 06:28:54 +0000723 } else if (isa<ICmpInst>(I) || isa<FCmpInst>(I)) {
724 // We need to encode the compare instruction's predicate as the third
725 // operand. Its not really a slot, but we don't want to break the
726 // instruction format for these instructions.
727 NumOperands++;
728 assert(NumOperands == 3 && "CmpInst with wrong number of operands?");
729 Slots[2] = unsigned(cast<CmpInst>(&I)->getPredicate());
730 if (Slots[2] > MaxOpSlot)
731 MaxOpSlot = Slots[2];
Reid Spencerad89bd62004-07-25 18:07:36 +0000732 } else if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&I)) {
733 // We need to encode the type of sequential type indices into their slot #
734 unsigned Idx = 1;
735 for (gep_type_iterator I = gep_type_begin(GEP), E = gep_type_end(GEP);
736 I != E; ++I, ++Idx)
737 if (isa<SequentialType>(*I)) {
738 unsigned IdxId;
739 switch (GEP->getOperand(Idx)->getType()->getTypeID()) {
740 default: assert(0 && "Unknown index type!");
Reid Spencer88cfda22006-12-31 05:44:24 +0000741 case Type::Int32TyID: IdxId = 0; break;
742 case Type::Int64TyID: IdxId = 1; break;
Reid Spencerad89bd62004-07-25 18:07:36 +0000743 }
Reid Spencer88cfda22006-12-31 05:44:24 +0000744 Slots[Idx] = (Slots[Idx] << 1) | IdxId;
Reid Spencerad89bd62004-07-25 18:07:36 +0000745 if (Slots[Idx] > MaxOpSlot) MaxOpSlot = Slots[Idx];
746 }
Chris Lattnerdee199f2005-05-06 22:34:01 +0000747 } else if (Opcode == 58) {
748 // If this is the escape sequence for call, emit the tailcall/cc info.
749 const CallInst &CI = cast<CallInst>(I);
750 ++NumOperands;
Chris Lattnerebf8e6c2006-05-19 21:57:37 +0000751 if (NumOperands <= 3) {
752 Slots[NumOperands-1] =
753 (CI.getCallingConv() << 1)|unsigned(CI.isTailCall());
Chris Lattnerdee199f2005-05-06 22:34:01 +0000754 if (Slots[NumOperands-1] > MaxOpSlot)
755 MaxOpSlot = Slots[NumOperands-1];
756 }
Reid Spencer3da59db2006-11-27 01:05:10 +0000757 } else if (isa<InvokeInst>(I)) {
Chris Lattnerdee199f2005-05-06 22:34:01 +0000758 // Invoke escape seq has at least 4 operands to encode.
759 ++NumOperands;
Reid Spencerad89bd62004-07-25 18:07:36 +0000760 }
761
762 // Decide which instruction encoding to use. This is determined primarily
763 // by the number of operands, and secondarily by whether or not the max
764 // operand will fit into the instruction encoding. More operands == fewer
765 // bits per operand.
766 //
767 switch (NumOperands) {
768 case 0:
769 case 1:
770 if (MaxOpSlot < (1 << 12)-1) { // -1 because we use 4095 to indicate 0 ops
771 outputInstructionFormat1(&I, Opcode, Slots, Type);
772 return;
773 }
774 break;
775
776 case 2:
777 if (MaxOpSlot < (1 << 8)) {
778 outputInstructionFormat2(&I, Opcode, Slots, Type);
779 return;
780 }
781 break;
782
783 case 3:
784 if (MaxOpSlot < (1 << 6)) {
785 outputInstructionFormat3(&I, Opcode, Slots, Type);
786 return;
787 }
788 break;
789 default:
790 break;
791 }
792 }
793
794 // If we weren't handled before here, we either have a large number of
795 // operands or a large operand index that we are referring to.
796 outputInstructionFormat0(&I, Opcode, Table, Type);
797}
798
799//===----------------------------------------------------------------------===//
800//=== Block Output ===//
801//===----------------------------------------------------------------------===//
802
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000803BytecodeWriter::BytecodeWriter(std::vector<unsigned char> &o, const Module *M)
Reid Spencer798ff642004-05-26 07:37:11 +0000804 : Out(o), Table(M) {
Chris Lattner00950542001-06-06 20:29:01 +0000805
Chris Lattner83bb3d22004-01-14 23:36:54 +0000806 // Emit the signature...
Chris Lattnerc847f7c2006-07-28 22:07:54 +0000807 static const unsigned char *Sig = (const unsigned char*)"llvm";
Reid Spencerad89bd62004-07-25 18:07:36 +0000808 output_data(Sig, Sig+4);
Chris Lattner00950542001-06-06 20:29:01 +0000809
810 // Emit the top level CLASS block.
Reid Spencerad89bd62004-07-25 18:07:36 +0000811 BytecodeBlock ModuleBlock(BytecodeFormat::ModuleBlockID, *this, false, true);
Chris Lattner00950542001-06-06 20:29:01 +0000812
Chris Lattnerd445c6b2003-08-24 13:47:36 +0000813 bool isBigEndian = M->getEndianness() == Module::BigEndian;
814 bool hasLongPointers = M->getPointerSize() == Module::Pointer64;
815 bool hasNoEndianness = M->getEndianness() == Module::AnyEndianness;
816 bool hasNoPointerSize = M->getPointerSize() == Module::AnyPointerSize;
Chris Lattner186a1f72003-03-19 20:56:46 +0000817
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000818 // Output the version identifier and other information.
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000819 unsigned Version = (BCVersionNum << 4) |
Reid Spencer38d54be2004-08-17 07:45:14 +0000820 (unsigned)isBigEndian | (hasLongPointers << 1) |
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000821 (hasNoEndianness << 2) |
Reid Spencer38d54be2004-08-17 07:45:14 +0000822 (hasNoPointerSize << 3);
Reid Spencerad89bd62004-07-25 18:07:36 +0000823 output_vbr(Version);
Chris Lattner00950542001-06-06 20:29:01 +0000824
Reid Spencercb3595c2004-07-04 11:45:47 +0000825 // The Global type plane comes first
Chris Lattner186a1f72003-03-19 20:56:46 +0000826 {
Chris Lattnerc847f7c2006-07-28 22:07:54 +0000827 BytecodeBlock CPool(BytecodeFormat::GlobalTypePlaneBlockID, *this);
828 outputTypes(Type::FirstDerivedTyID);
Chris Lattner186a1f72003-03-19 20:56:46 +0000829 }
Chris Lattner00950542001-06-06 20:29:01 +0000830
Chris Lattner186a1f72003-03-19 20:56:46 +0000831 // The ModuleInfoBlock follows directly after the type information
Chris Lattnere8fdde12001-09-07 16:39:41 +0000832 outputModuleInfoBlock(M);
833
Chris Lattner186a1f72003-03-19 20:56:46 +0000834 // Output module level constants, used for global variable initializers
835 outputConstants(false);
836
Chris Lattnerb5794002002-04-07 22:49:37 +0000837 // Do the whole module now! Process each function at a time...
Chris Lattner0b12b5f2002-06-25 16:13:21 +0000838 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
Chris Lattner186a1f72003-03-19 20:56:46 +0000839 outputFunction(I);
Chris Lattnere8fdde12001-09-07 16:39:41 +0000840
Reid Spencer78d033e2007-01-06 07:24:44 +0000841 // Output the symbole table for types
842 outputTypeSymbolTable(M->getTypeSymbolTable());
843
844 // Output the symbol table for values
845 outputValueSymbolTable(M->getValueSymbolTable());
Chris Lattner00950542001-06-06 20:29:01 +0000846}
847
Chris Lattnerf9d71782004-10-14 01:46:07 +0000848void BytecodeWriter::outputTypes(unsigned TypeNum) {
Reid Spencercb3595c2004-07-04 11:45:47 +0000849 // Write the type plane for types first because earlier planes (e.g. for a
850 // primitive type like float) may have constants constructed using types
851 // coming later (e.g., via getelementptr from a pointer type). The type
852 // plane is needed before types can be fwd or bkwd referenced.
853 const std::vector<const Type*>& Types = Table.getTypes();
854 assert(!Types.empty() && "No types at all?");
855 assert(TypeNum <= Types.size() && "Invalid TypeNo index");
856
857 unsigned NumEntries = Types.size() - TypeNum;
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000858
Reid Spencercb3595c2004-07-04 11:45:47 +0000859 // Output type header: [num entries]
Reid Spencerad89bd62004-07-25 18:07:36 +0000860 output_vbr(NumEntries);
Reid Spencercb3595c2004-07-04 11:45:47 +0000861
862 for (unsigned i = TypeNum; i < TypeNum+NumEntries; ++i)
863 outputType(Types[i]);
864}
865
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000866// Helper function for outputConstants().
867// Writes out all the constants in the plane Plane starting at entry StartNo.
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000868//
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000869void BytecodeWriter::outputConstantsInPlane(const std::vector<const Value*>
870 &Plane, unsigned StartNo) {
871 unsigned ValNo = StartNo;
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000872
Chris Lattner83bb3d22004-01-14 23:36:54 +0000873 // Scan through and ignore function arguments, global values, and constant
874 // strings.
875 for (; ValNo < Plane.size() &&
876 (isa<Argument>(Plane[ValNo]) || isa<GlobalValue>(Plane[ValNo]) ||
877 (isa<ConstantArray>(Plane[ValNo]) &&
878 cast<ConstantArray>(Plane[ValNo])->isString())); ValNo++)
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000879 /*empty*/;
880
881 unsigned NC = ValNo; // Number of constants
Chris Lattner3bc5a602006-01-25 23:08:15 +0000882 for (; NC < Plane.size() && (isa<Constant>(Plane[NC]) ||
883 isa<InlineAsm>(Plane[NC])); NC++)
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000884 /*empty*/;
885 NC -= ValNo; // Convert from index into count
886 if (NC == 0) return; // Skip empty type planes...
887
Chris Lattnerd6942d72004-01-14 16:54:21 +0000888 // FIXME: Most slabs only have 1 or 2 entries! We should encode this much
889 // more compactly.
890
Reid Spencerb83eb642006-10-20 07:07:24 +0000891 // Put out type header: [num entries][type id number]
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000892 //
Reid Spencerad89bd62004-07-25 18:07:36 +0000893 output_vbr(NC);
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000894
Reid Spencerb83eb642006-10-20 07:07:24 +0000895 // Put out the Type ID Number...
Alkis Evlogimenos60596382003-10-17 02:02:40 +0000896 int Slot = Table.getSlot(Plane.front()->getType());
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000897 assert (Slot != -1 && "Type in constant pool but not in function!!");
Reid Spencerad89bd62004-07-25 18:07:36 +0000898 output_typeid((unsigned)Slot);
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000899
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000900 for (unsigned i = ValNo; i < ValNo+NC; ++i) {
901 const Value *V = Plane[i];
Chris Lattner3bc5a602006-01-25 23:08:15 +0000902 if (const Constant *C = dyn_cast<Constant>(V))
Reid Spencere0125b62004-07-18 00:16:21 +0000903 outputConstant(C);
Chris Lattner3bc5a602006-01-25 23:08:15 +0000904 else
905 outputInlineAsm(cast<InlineAsm>(V));
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000906 }
907}
908
Chris Lattner9e60d8d2005-05-05 22:21:19 +0000909static inline bool hasNullValue(const Type *Ty) {
910 return Ty != Type::LabelTy && Ty != Type::VoidTy && !isa<OpaqueType>(Ty);
Chris Lattner80b97342004-01-17 23:25:43 +0000911}
912
Chris Lattner79df7c02002-03-26 18:01:55 +0000913void BytecodeWriter::outputConstants(bool isFunction) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000914 BytecodeBlock CPool(BytecodeFormat::ConstantPoolBlockID, *this,
Chris Lattner0baa0af2004-01-15 21:06:57 +0000915 true /* Elide block if empty */);
Chris Lattner00950542001-06-06 20:29:01 +0000916
917 unsigned NumPlanes = Table.getNumPlanes();
Chris Lattnerf69315b2003-05-22 18:35:38 +0000918
Reid Spencere0125b62004-07-18 00:16:21 +0000919 if (isFunction)
920 // Output the type plane before any constants!
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000921 outputTypes(Table.getModuleTypeLevel());
Reid Spencere0125b62004-07-18 00:16:21 +0000922 else
Chris Lattnerf9d71782004-10-14 01:46:07 +0000923 // Output module-level string constants before any other constants.
Chris Lattner83bb3d22004-01-14 23:36:54 +0000924 outputConstantStrings();
925
Reid Spencercb3595c2004-07-04 11:45:47 +0000926 for (unsigned pno = 0; pno != NumPlanes; pno++) {
927 const std::vector<const Value*> &Plane = Table.getPlane(pno);
928 if (!Plane.empty()) { // Skip empty type planes...
929 unsigned ValNo = 0;
930 if (isFunction) // Don't re-emit module constants
Reid Spencer0852c802004-07-04 11:46:15 +0000931 ValNo += Table.getModuleLevel(pno);
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000932
Chris Lattner9e60d8d2005-05-05 22:21:19 +0000933 if (hasNullValue(Plane[0]->getType())) {
Reid Spencer0852c802004-07-04 11:46:15 +0000934 // Skip zero initializer
935 if (ValNo == 0)
936 ValNo = 1;
Chris Lattnerf69315b2003-05-22 18:35:38 +0000937 }
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000938
Reid Spencercb3595c2004-07-04 11:45:47 +0000939 // Write out constants in the plane
940 outputConstantsInPlane(Plane, ValNo);
Chris Lattnerf69315b2003-05-22 18:35:38 +0000941 }
Reid Spencercb3595c2004-07-04 11:45:47 +0000942 }
Chris Lattner00950542001-06-06 20:29:01 +0000943}
944
Chris Lattner6b252422003-10-16 18:28:50 +0000945static unsigned getEncodedLinkage(const GlobalValue *GV) {
946 switch (GV->getLinkage()) {
947 default: assert(0 && "Invalid linkage!");
Anton Korobeynikovb74ed072006-09-14 18:23:27 +0000948 case GlobalValue::ExternalLinkage: return 0;
949 case GlobalValue::WeakLinkage: return 1;
950 case GlobalValue::AppendingLinkage: return 2;
951 case GlobalValue::InternalLinkage: return 3;
952 case GlobalValue::LinkOnceLinkage: return 4;
953 case GlobalValue::DLLImportLinkage: return 5;
954 case GlobalValue::DLLExportLinkage: return 6;
955 case GlobalValue::ExternalWeakLinkage: return 7;
Chris Lattner6b252422003-10-16 18:28:50 +0000956 }
957}
958
Chris Lattner00950542001-06-06 20:29:01 +0000959void BytecodeWriter::outputModuleInfoBlock(const Module *M) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000960 BytecodeBlock ModuleInfoBlock(BytecodeFormat::ModuleGlobalInfoBlockID, *this);
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000961
Chris Lattner404cddf2005-11-12 01:33:40 +0000962 // Give numbers to sections as we encounter them.
963 unsigned SectionIDCounter = 0;
964 std::vector<std::string> SectionNames;
965 std::map<std::string, unsigned> SectionID;
966
Chris Lattner70cc3392001-09-10 07:58:01 +0000967 // Output the types for the global variables in the module...
Chris Lattner28caccf2005-05-06 20:27:03 +0000968 for (Module::const_global_iterator I = M->global_begin(),
Chris Lattner8eb52dd2005-11-06 07:11:04 +0000969 End = M->global_end(); I != End; ++I) {
Alkis Evlogimenos60596382003-10-17 02:02:40 +0000970 int Slot = Table.getSlot(I->getType());
Chris Lattner70cc3392001-09-10 07:58:01 +0000971 assert(Slot != -1 && "Module global vars is broken!");
Chris Lattnerd70684f2001-09-18 04:01:05 +0000972
Chris Lattner8eb52dd2005-11-06 07:11:04 +0000973 assert((I->hasInitializer() || !I->hasInternalLinkage()) &&
974 "Global must have an initializer or have external linkage!");
975
Chris Lattner22482a12003-10-18 06:30:21 +0000976 // Fields: bit0 = isConstant, bit1 = hasInitializer, bit2-4=Linkage,
Chris Lattner8eb52dd2005-11-06 07:11:04 +0000977 // bit5+ = Slot # for type.
Chris Lattner404cddf2005-11-12 01:33:40 +0000978 bool HasExtensionWord = (I->getAlignment() != 0) || I->hasSection();
Chris Lattner8eb52dd2005-11-06 07:11:04 +0000979
980 // If we need to use the extension byte, set linkage=3(internal) and
981 // initializer = 0 (impossible!).
982 if (!HasExtensionWord) {
983 unsigned oSlot = ((unsigned)Slot << 5) | (getEncodedLinkage(I) << 2) |
984 (I->hasInitializer() << 1) | (unsigned)I->isConstant();
985 output_vbr(oSlot);
Anton Korobeynikovb74ed072006-09-14 18:23:27 +0000986 } else {
Chris Lattner8eb52dd2005-11-06 07:11:04 +0000987 unsigned oSlot = ((unsigned)Slot << 5) | (3 << 2) |
988 (0 << 1) | (unsigned)I->isConstant();
989 output_vbr(oSlot);
990
991 // The extension word has this format: bit 0 = has initializer, bit 1-3 =
Chris Lattner404cddf2005-11-12 01:33:40 +0000992 // linkage, bit 4-8 = alignment (log2), bit 9 = has SectionID,
993 // bits 10+ = future use.
Jeff Cohenba0ffcc2005-11-12 01:01:50 +0000994 unsigned ExtWord = (unsigned)I->hasInitializer() |
995 (getEncodedLinkage(I) << 1) |
Chris Lattner404cddf2005-11-12 01:33:40 +0000996 ((Log2_32(I->getAlignment())+1) << 4) |
997 ((unsigned)I->hasSection() << 9);
Chris Lattner8eb52dd2005-11-06 07:11:04 +0000998 output_vbr(ExtWord);
Chris Lattner404cddf2005-11-12 01:33:40 +0000999 if (I->hasSection()) {
1000 // Give section names unique ID's.
1001 unsigned &Entry = SectionID[I->getSection()];
1002 if (Entry == 0) {
1003 Entry = ++SectionIDCounter;
1004 SectionNames.push_back(I->getSection());
1005 }
1006 output_vbr(Entry);
1007 }
Chris Lattner8eb52dd2005-11-06 07:11:04 +00001008 }
Chris Lattnerd70684f2001-09-18 04:01:05 +00001009
Chris Lattner1b98c5c2001-10-13 06:48:38 +00001010 // If we have an initializer, output it now.
Chris Lattner0b12b5f2002-06-25 16:13:21 +00001011 if (I->hasInitializer()) {
Alkis Evlogimenos60596382003-10-17 02:02:40 +00001012 Slot = Table.getSlot((Value*)I->getInitializer());
Chris Lattnerd70684f2001-09-18 04:01:05 +00001013 assert(Slot != -1 && "No slot for global var initializer!");
Reid Spencerad89bd62004-07-25 18:07:36 +00001014 output_vbr((unsigned)Slot);
Chris Lattnerd70684f2001-09-18 04:01:05 +00001015 }
Chris Lattner70cc3392001-09-10 07:58:01 +00001016 }
Reid Spencerad89bd62004-07-25 18:07:36 +00001017 output_typeid((unsigned)Table.getSlot(Type::VoidTy));
Chris Lattner70cc3392001-09-10 07:58:01 +00001018
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001019 // Output the types of the functions in this module.
Chris Lattner7fc9fe32001-06-27 23:41:11 +00001020 for (Module::const_iterator I = M->begin(), End = M->end(); I != End; ++I) {
Alkis Evlogimenos60596382003-10-17 02:02:40 +00001021 int Slot = Table.getSlot(I->getType());
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001022 assert(Slot != -1 && "Module slot calculator is broken!");
Chris Lattner00950542001-06-06 20:29:01 +00001023 assert(Slot >= Type::FirstDerivedTyID && "Derived type not in range!");
Chris Lattnere73bd452005-11-06 07:43:39 +00001024 assert(((Slot << 6) >> 6) == Slot && "Slot # too big!");
Chris Lattner54b369e2005-11-06 07:46:13 +00001025 unsigned CC = I->getCallingConv()+1;
1026 unsigned ID = (Slot << 5) | (CC & 15);
Chris Lattner479ffeb2005-05-06 20:42:57 +00001027
Chris Lattnerd6e431f2004-11-15 22:39:49 +00001028 if (I->isExternal()) // If external, we don't have an FunctionInfo block.
1029 ID |= 1 << 4;
Chris Lattnere73bd452005-11-06 07:43:39 +00001030
Anton Korobeynikovb74ed072006-09-14 18:23:27 +00001031 if (I->getAlignment() || I->hasSection() || (CC & ~15) != 0 ||
1032 (I->isExternal() && I->hasDLLImportLinkage()) ||
1033 (I->isExternal() && I->hasExternalWeakLinkage())
1034 )
Chris Lattnere73bd452005-11-06 07:43:39 +00001035 ID |= 1 << 31; // Do we need an extension word?
1036
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001037 output_vbr(ID);
Chris Lattnere73bd452005-11-06 07:43:39 +00001038
1039 if (ID & (1 << 31)) {
1040 // Extension byte: bits 0-4 = alignment, bits 5-9 = top nibble of calling
Anton Korobeynikovb74ed072006-09-14 18:23:27 +00001041 // convention, bit 10 = hasSectionID., bits 11-12 = external linkage type
1042 unsigned extLinkage = 0;
1043
1044 if (I->isExternal()) {
1045 if (I->hasDLLImportLinkage()) {
1046 extLinkage = 1;
1047 } else if (I->hasExternalWeakLinkage()) {
1048 extLinkage = 2;
1049 }
1050 }
1051
Chris Lattner404cddf2005-11-12 01:33:40 +00001052 ID = (Log2_32(I->getAlignment())+1) | ((CC >> 4) << 5) |
Anton Korobeynikovb74ed072006-09-14 18:23:27 +00001053 (I->hasSection() << 10) |
1054 ((extLinkage & 3) << 11);
Chris Lattnere73bd452005-11-06 07:43:39 +00001055 output_vbr(ID);
Chris Lattner404cddf2005-11-12 01:33:40 +00001056
1057 // Give section names unique ID's.
1058 if (I->hasSection()) {
1059 unsigned &Entry = SectionID[I->getSection()];
1060 if (Entry == 0) {
1061 Entry = ++SectionIDCounter;
1062 SectionNames.push_back(I->getSection());
1063 }
1064 output_vbr(Entry);
1065 }
Chris Lattnere73bd452005-11-06 07:43:39 +00001066 }
Chris Lattner00950542001-06-06 20:29:01 +00001067 }
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001068 output_vbr((unsigned)Table.getSlot(Type::VoidTy) << 5);
Reid Spencerad89bd62004-07-25 18:07:36 +00001069
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001070 // Emit the list of dependent libraries for the Module.
Reid Spencer5ac88122004-07-25 21:32:02 +00001071 Module::lib_iterator LI = M->lib_begin();
1072 Module::lib_iterator LE = M->lib_end();
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001073 output_vbr(unsigned(LE - LI)); // Emit the number of dependent libraries.
1074 for (; LI != LE; ++LI)
Reid Spencer38d54be2004-08-17 07:45:14 +00001075 output(*LI);
Reid Spencerad89bd62004-07-25 18:07:36 +00001076
1077 // Output the target triple from the module
Reid Spencer38d54be2004-08-17 07:45:14 +00001078 output(M->getTargetTriple());
Chris Lattner404cddf2005-11-12 01:33:40 +00001079
1080 // Emit the table of section names.
1081 output_vbr((unsigned)SectionNames.size());
1082 for (unsigned i = 0, e = SectionNames.size(); i != e; ++i)
1083 output(SectionNames[i]);
Chris Lattner7e6db762006-01-23 23:43:17 +00001084
1085 // Output the inline asm string.
Chris Lattner66316012006-01-24 04:14:29 +00001086 output(M->getModuleInlineAsm());
Chris Lattner00950542001-06-06 20:29:01 +00001087}
1088
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001089void BytecodeWriter::outputInstructions(const Function *F) {
Reid Spencerad89bd62004-07-25 18:07:36 +00001090 BytecodeBlock ILBlock(BytecodeFormat::InstructionListBlockID, *this);
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001091 for (Function::const_iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
1092 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I)
1093 outputInstruction(*I);
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001094}
1095
Chris Lattner186a1f72003-03-19 20:56:46 +00001096void BytecodeWriter::outputFunction(const Function *F) {
Chris Lattnerfd7f8fe2004-11-15 21:56:33 +00001097 // If this is an external function, there is nothing else to emit!
1098 if (F->isExternal()) return;
1099
Chris Lattnerd6e431f2004-11-15 22:39:49 +00001100 BytecodeBlock FunctionBlock(BytecodeFormat::FunctionBlockID, *this);
1101 output_vbr(getEncodedLinkage(F));
1102
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001103 // Get slot information about the function...
1104 Table.incorporateFunction(F);
1105
1106 if (Table.getCompactionTable().empty()) {
1107 // Output information about the constants in the function if the compaction
1108 // table is not being used.
Chris Lattnere8fdde12001-09-07 16:39:41 +00001109 outputConstants(true);
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001110 } else {
1111 // Otherwise, emit the compaction table.
1112 outputCompactionTable();
Chris Lattnere8fdde12001-09-07 16:39:41 +00001113 }
Misha Brukman23c6d2c2005-04-21 21:48:46 +00001114
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001115 // Output all of the instructions in the body of the function
1116 outputInstructions(F);
Misha Brukman23c6d2c2005-04-21 21:48:46 +00001117
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001118 // If needed, output the symbol table for the function...
Reid Spencer78d033e2007-01-06 07:24:44 +00001119 outputValueSymbolTable(F->getValueSymbolTable());
Misha Brukman23c6d2c2005-04-21 21:48:46 +00001120
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001121 Table.purgeFunction();
1122}
1123
1124void BytecodeWriter::outputCompactionTablePlane(unsigned PlaneNo,
1125 const std::vector<const Value*> &Plane,
1126 unsigned StartNo) {
1127 unsigned End = Table.getModuleLevel(PlaneNo);
Chris Lattner52f86d62004-01-20 00:54:06 +00001128 if (Plane.empty() || StartNo == End || End == 0) return; // Nothing to emit
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001129 assert(StartNo < End && "Cannot emit negative range!");
1130 assert(StartNo < Plane.size() && End <= Plane.size());
1131
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001132 // Do not emit the null initializer!
Reid Spencercb3595c2004-07-04 11:45:47 +00001133 ++StartNo;
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001134
Chris Lattner24102432004-01-18 22:35:34 +00001135 // Figure out which encoding to use. By far the most common case we have is
1136 // to emit 0-2 entries in a compaction table plane.
1137 switch (End-StartNo) {
1138 case 0: // Avoid emitting two vbr's if possible.
1139 case 1:
1140 case 2:
Reid Spencerad89bd62004-07-25 18:07:36 +00001141 output_vbr((PlaneNo << 2) | End-StartNo);
Chris Lattner24102432004-01-18 22:35:34 +00001142 break;
1143 default:
1144 // Output the number of things.
Reid Spencerad89bd62004-07-25 18:07:36 +00001145 output_vbr((unsigned(End-StartNo) << 2) | 3);
1146 output_typeid(PlaneNo); // Emit the type plane this is
Chris Lattner24102432004-01-18 22:35:34 +00001147 break;
1148 }
1149
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001150 for (unsigned i = StartNo; i != End; ++i)
Reid Spencerad89bd62004-07-25 18:07:36 +00001151 output_vbr(Table.getGlobalSlot(Plane[i]));
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001152}
1153
Reid Spencercb3595c2004-07-04 11:45:47 +00001154void BytecodeWriter::outputCompactionTypes(unsigned StartNo) {
1155 // Get the compaction type table from the slot calculator
1156 const std::vector<const Type*> &CTypes = Table.getCompactionTypes();
1157
1158 // The compaction types may have been uncompactified back to the
1159 // global types. If so, we just write an empty table
Chris Lattnerc847f7c2006-07-28 22:07:54 +00001160 if (CTypes.size() == 0) {
Reid Spencerad89bd62004-07-25 18:07:36 +00001161 output_vbr(0U);
Reid Spencercb3595c2004-07-04 11:45:47 +00001162 return;
1163 }
1164
1165 assert(CTypes.size() >= StartNo && "Invalid compaction types start index");
1166
1167 // Determine how many types to write
1168 unsigned NumTypes = CTypes.size() - StartNo;
1169
1170 // Output the number of types.
Reid Spencerad89bd62004-07-25 18:07:36 +00001171 output_vbr(NumTypes);
Reid Spencercb3595c2004-07-04 11:45:47 +00001172
1173 for (unsigned i = StartNo; i < StartNo+NumTypes; ++i)
Reid Spencerad89bd62004-07-25 18:07:36 +00001174 output_typeid(Table.getGlobalSlot(CTypes[i]));
Reid Spencercb3595c2004-07-04 11:45:47 +00001175}
1176
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001177void BytecodeWriter::outputCompactionTable() {
Reid Spencer0033c182004-08-27 00:38:44 +00001178 // Avoid writing the compaction table at all if there is no content.
1179 if (Table.getCompactionTypes().size() >= Type::FirstDerivedTyID ||
1180 (!Table.CompactionTableIsEmpty())) {
Misha Brukman23c6d2c2005-04-21 21:48:46 +00001181 BytecodeBlock CTB(BytecodeFormat::CompactionTableBlockID, *this,
Reid Spencer0033c182004-08-27 00:38:44 +00001182 true/*ElideIfEmpty*/);
Chris Lattnerf9d71782004-10-14 01:46:07 +00001183 const std::vector<std::vector<const Value*> > &CT =
1184 Table.getCompactionTable();
Misha Brukman23c6d2c2005-04-21 21:48:46 +00001185
Reid Spencer0033c182004-08-27 00:38:44 +00001186 // First things first, emit the type compaction table if there is one.
1187 outputCompactionTypes(Type::FirstDerivedTyID);
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001188
Reid Spencer0033c182004-08-27 00:38:44 +00001189 for (unsigned i = 0, e = CT.size(); i != e; ++i)
1190 outputCompactionTablePlane(i, CT[i], 0);
1191 }
Chris Lattner00950542001-06-06 20:29:01 +00001192}
1193
Reid Spencer78d033e2007-01-06 07:24:44 +00001194void BytecodeWriter::outputTypeSymbolTable(const TypeSymbolTable &TST) {
1195 // Do not output the block for an empty symbol table, it just wastes
Chris Lattner737d3cd2004-01-10 19:56:59 +00001196 // space!
Reid Spencer78d033e2007-01-06 07:24:44 +00001197 if (TST.empty()) return;
Chris Lattner737d3cd2004-01-10 19:56:59 +00001198
Reid Spencer78d033e2007-01-06 07:24:44 +00001199 // Create a header for the symbol table
1200 BytecodeBlock SymTabBlock(BytecodeFormat::TypeSymbolTableBlockID, *this,
Chris Lattnerf9d71782004-10-14 01:46:07 +00001201 true/*ElideIfEmpty*/);
Misha Brukman23c6d2c2005-04-21 21:48:46 +00001202 // Write the number of types
Reid Spencer78d033e2007-01-06 07:24:44 +00001203 output_vbr(TST.size());
Reid Spencer250c4182004-08-17 02:59:02 +00001204
1205 // Write each of the types
Reid Spencer78d033e2007-01-06 07:24:44 +00001206 for (TypeSymbolTable::const_iterator TI = TST.begin(), TE = TST.end();
1207 TI != TE; ++TI) {
Reid Spencer250c4182004-08-17 02:59:02 +00001208 // Symtab entry:[def slot #][name]
Reid Spencerad89bd62004-07-25 18:07:36 +00001209 output_typeid((unsigned)Table.getSlot(TI->second));
Misha Brukman23c6d2c2005-04-21 21:48:46 +00001210 output(TI->first);
Reid Spencer94f2df22004-05-25 17:29:59 +00001211 }
Reid Spencer78d033e2007-01-06 07:24:44 +00001212}
1213
1214void BytecodeWriter::outputValueSymbolTable(const SymbolTable &MST) {
1215 // Do not output the Bytecode block for an empty symbol table, it just wastes
1216 // space!
1217 if (MST.isEmpty()) return;
1218
1219 BytecodeBlock SymTabBlock(BytecodeFormat::ValueSymbolTableBlockID, *this,
1220 true/*ElideIfEmpty*/);
Reid Spencer94f2df22004-05-25 17:29:59 +00001221
1222 // Now do each of the type planes in order.
Misha Brukman23c6d2c2005-04-21 21:48:46 +00001223 for (SymbolTable::plane_const_iterator PI = MST.plane_begin(),
Reid Spencer94f2df22004-05-25 17:29:59 +00001224 PE = MST.plane_end(); PI != PE; ++PI) {
1225 SymbolTable::value_const_iterator I = MST.value_begin(PI->first);
1226 SymbolTable::value_const_iterator End = MST.value_end(PI->first);
Chris Lattner00950542001-06-06 20:29:01 +00001227 int Slot;
Misha Brukman23c6d2c2005-04-21 21:48:46 +00001228
Chris Lattner00950542001-06-06 20:29:01 +00001229 if (I == End) continue; // Don't mess with an absent type...
1230
Reid Spencer250c4182004-08-17 02:59:02 +00001231 // Write the number of values in this plane
Chris Lattner001d16a2005-03-07 02:59:36 +00001232 output_vbr((unsigned)PI->second.size());
Chris Lattner00950542001-06-06 20:29:01 +00001233
Reid Spencer250c4182004-08-17 02:59:02 +00001234 // Write the slot number of the type for this plane
Reid Spencer94f2df22004-05-25 17:29:59 +00001235 Slot = Table.getSlot(PI->first);
Chris Lattner00950542001-06-06 20:29:01 +00001236 assert(Slot != -1 && "Type in symtab, but not in table!");
Reid Spencerad89bd62004-07-25 18:07:36 +00001237 output_typeid((unsigned)Slot);
Chris Lattner00950542001-06-06 20:29:01 +00001238
Reid Spencer250c4182004-08-17 02:59:02 +00001239 // Write each of the values in this plane
Chris Lattner7fc9fe32001-06-27 23:41:11 +00001240 for (; I != End; ++I) {
Chris Lattner00950542001-06-06 20:29:01 +00001241 // Symtab entry: [def slot #][name]
Alkis Evlogimenos60596382003-10-17 02:02:40 +00001242 Slot = Table.getSlot(I->second);
Chris Lattnere8fdde12001-09-07 16:39:41 +00001243 assert(Slot != -1 && "Value in symtab but has no slot number!!");
Reid Spencerad89bd62004-07-25 18:07:36 +00001244 output_vbr((unsigned)Slot);
Reid Spencer38d54be2004-08-17 07:45:14 +00001245 output(I->first);
Chris Lattner00950542001-06-06 20:29:01 +00001246 }
1247 }
1248}
1249
Bill Wendlinge8156192006-12-07 01:30:32 +00001250void llvm::WriteBytecodeToFile(const Module *M, OStream &Out,
Chris Lattnerc847f7c2006-07-28 22:07:54 +00001251 bool compress) {
Reid Spencerad89bd62004-07-25 18:07:36 +00001252 assert(M && "You can't write a null module!!");
Chris Lattner00950542001-06-06 20:29:01 +00001253
Reid Spencer32f55532006-06-07 23:18:34 +00001254 // Make sure that std::cout is put into binary mode for systems
1255 // that care.
Bill Wendlinge8156192006-12-07 01:30:32 +00001256 if (Out == cout)
Reid Spencer32f55532006-06-07 23:18:34 +00001257 sys::Program::ChangeStdoutToBinary();
1258
Reid Spencer17f52c52004-11-06 23:17:23 +00001259 // Create a vector of unsigned char for the bytecode output. We
1260 // reserve 256KBytes of space in the vector so that we avoid doing
1261 // lots of little allocations. 256KBytes is sufficient for a large
1262 // proportion of the bytecode files we will encounter. Larger files
1263 // will be automatically doubled in size as needed (std::vector
1264 // behavior).
Reid Spencerad89bd62004-07-25 18:07:36 +00001265 std::vector<unsigned char> Buffer;
Reid Spencer17f52c52004-11-06 23:17:23 +00001266 Buffer.reserve(256 * 1024);
Chris Lattner00950542001-06-06 20:29:01 +00001267
Reid Spencer17f52c52004-11-06 23:17:23 +00001268 // The BytecodeWriter populates Buffer for us.
Reid Spencerad89bd62004-07-25 18:07:36 +00001269 BytecodeWriter BCW(Buffer, M);
Chris Lattner00950542001-06-06 20:29:01 +00001270
Reid Spencer17f52c52004-11-06 23:17:23 +00001271 // Keep track of how much we've written
Chris Lattnerce6ef112002-07-26 18:40:14 +00001272 BytesWritten += Buffer.size();
1273
Reid Spencer17f52c52004-11-06 23:17:23 +00001274 // Determine start and end points of the Buffer
Reid Spencer83296f52004-11-07 18:17:38 +00001275 const unsigned char *FirstByte = &Buffer.front();
Reid Spencer17f52c52004-11-06 23:17:23 +00001276
1277 // If we're supposed to compress this mess ...
1278 if (compress) {
1279
1280 // We signal compression by using an alternate magic number for the
Reid Spencer83296f52004-11-07 18:17:38 +00001281 // file. The compressed bytecode file's magic number is "llvc" instead
Misha Brukman23c6d2c2005-04-21 21:48:46 +00001282 // of "llvm".
Reid Spencer83296f52004-11-07 18:17:38 +00001283 char compressed_magic[4];
1284 compressed_magic[0] = 'l';
1285 compressed_magic[1] = 'l';
1286 compressed_magic[2] = 'v';
1287 compressed_magic[3] = 'c';
Reid Spencer17f52c52004-11-06 23:17:23 +00001288
Bill Wendling68fe61d2006-11-29 00:19:40 +00001289 Out.stream()->write(compressed_magic,4);
Reid Spencer17f52c52004-11-06 23:17:23 +00001290
Reid Spencera70d84d2004-11-14 22:01:41 +00001291 // Compress everything after the magic number (which we altered)
Reid Spencer3ed469c2006-11-02 20:25:50 +00001292 Compressor::compressToStream(
Reid Spencer17f52c52004-11-06 23:17:23 +00001293 (char*)(FirstByte+4), // Skip the magic number
1294 Buffer.size()-4, // Skip the magic number
Bill Wendling68fe61d2006-11-29 00:19:40 +00001295 *Out.stream() // Where to write compressed data
Reid Spencer17f52c52004-11-06 23:17:23 +00001296 );
1297
Reid Spencer17f52c52004-11-06 23:17:23 +00001298 } else {
1299
1300 // We're not compressing, so just write the entire block.
Bill Wendling68fe61d2006-11-29 00:19:40 +00001301 Out.stream()->write((char*)FirstByte, Buffer.size());
Chris Lattnere8fdde12001-09-07 16:39:41 +00001302 }
Reid Spencer17f52c52004-11-06 23:17:23 +00001303
1304 // make sure it hits disk now
Bill Wendling68fe61d2006-11-29 00:19:40 +00001305 Out.stream()->flush();
Chris Lattner00950542001-06-06 20:29:01 +00001306}