blob: 1c420443a6bbfec4a7134314841a85230e5f6ead [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"
Reid Spencer78d033e2007-01-06 07:24:44 +000029#include "llvm/TypeSymbolTable.h"
Reid Spenceref9b9a72007-02-05 20:47:22 +000030#include "llvm/ValueSymbolTable.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
Reid Spencer7d003412007-02-09 18:03:35 +000073inline void BytecodeWriter::output(int32_t i) {
74 output((uint32_t)i);
Reid Spencerad89bd62004-07-25 18:07:36 +000075}
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
Reid Spencer7d003412007-02-09 18:03:35 +000096inline void BytecodeWriter::output_vbr(uint32_t i) {
Reid Spencerad89bd62004-07-25 18:07:36 +000097 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())
Reid Spencera54b7cb2007-01-12 07:05:14 +0000203 output_vbr((unsigned)Type::PackedStructTyID);
Andrew Lenharth38ecbf12006-12-08 18:06:16 +0000204 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...
Reid Spencera54b7cb2007-01-12 07:05:14 +0000208 if (T->isPrimitiveType())
Reid Spencerad89bd62004-07-25 18:07:36 +0000209 return; // We might do this if we alias a prim type: %x = type int
Reid Spencerad89bd62004-07-25 18:07:36 +0000210
211 switch (T->getTypeID()) { // Handle derived types now.
Reid Spencera54b7cb2007-01-12 07:05:14 +0000212 case Type::IntegerTyID:
213 output_vbr(cast<IntegerType>(T)->getBitWidth());
214 break;
Reid Spencerad89bd62004-07-25 18:07:36 +0000215 case Type::FunctionTyID: {
216 const FunctionType *MT = cast<FunctionType>(T);
Chris Lattner972b4dc2007-02-10 05:17:48 +0000217 output_typeid(Table.getTypeSlot(MT->getReturnType()));
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) {
Chris Lattner972b4dc2007-02-10 05:17:48 +0000227 output_typeid(Table.getTypeSlot(*I));
Reid Spencer88cfda22006-12-31 05:44:24 +0000228 output_vbr(unsigned(MT->getParamAttrs(Idx)));
229 Idx++;
Reid Spencerad89bd62004-07-25 18:07:36 +0000230 }
231
232 // Terminate list with VoidTy if we are a varargs function...
233 if (MT->isVarArg())
234 output_typeid((unsigned)Type::VoidTyID);
235 break;
236 }
237
238 case Type::ArrayTyID: {
239 const ArrayType *AT = cast<ArrayType>(T);
Chris Lattner972b4dc2007-02-10 05:17:48 +0000240 output_typeid(Table.getTypeSlot(AT->getElementType()));
Reid Spencerad89bd62004-07-25 18:07:36 +0000241 output_vbr(AT->getNumElements());
242 break;
243 }
244
Brian Gaeke715c90b2004-08-20 06:00:58 +0000245 case Type::PackedTyID: {
246 const PackedType *PT = cast<PackedType>(T);
Chris Lattner972b4dc2007-02-10 05:17:48 +0000247 output_typeid(Table.getTypeSlot(PT->getElementType()));
Brian Gaeke715c90b2004-08-20 06:00:58 +0000248 output_vbr(PT->getNumElements());
249 break;
250 }
251
Reid Spencerad89bd62004-07-25 18:07:36 +0000252 case Type::StructTyID: {
253 const StructType *ST = cast<StructType>(T);
Reid Spencerad89bd62004-07-25 18:07:36 +0000254 // Output all of the element types...
255 for (StructType::element_iterator I = ST->element_begin(),
256 E = ST->element_end(); I != E; ++I) {
Chris Lattner972b4dc2007-02-10 05:17:48 +0000257 output_typeid(Table.getTypeSlot(*I));
Reid Spencerad89bd62004-07-25 18:07:36 +0000258 }
259
260 // Terminate list with VoidTy
261 output_typeid((unsigned)Type::VoidTyID);
262 break;
263 }
264
Chris Lattner972b4dc2007-02-10 05:17:48 +0000265 case Type::PointerTyID:
266 output_typeid(Table.getTypeSlot(cast<PointerType>(T)->getElementType()));
Reid Spencerad89bd62004-07-25 18:07:36 +0000267 break;
Reid Spencerad89bd62004-07-25 18:07:36 +0000268
Chris Lattnerb0bf6642004-10-14 01:35:17 +0000269 case Type::OpaqueTyID:
Reid Spencerad89bd62004-07-25 18:07:36 +0000270 // No need to emit anything, just the count of opaque types is enough.
271 break;
Reid Spencerad89bd62004-07-25 18:07:36 +0000272
Reid Spencerad89bd62004-07-25 18:07:36 +0000273 default:
Bill Wendlinge8156192006-12-07 01:30:32 +0000274 cerr << __FILE__ << ":" << __LINE__ << ": Don't know how to serialize"
275 << " Type '" << T->getDescription() << "'\n";
Reid Spencerad89bd62004-07-25 18:07:36 +0000276 break;
277 }
278}
279
280void BytecodeWriter::outputConstant(const Constant *CPV) {
Chris Lattner42a75512007-01-15 02:27:26 +0000281 assert(((CPV->getType()->isPrimitiveType() || CPV->getType()->isInteger()) ||
Reid Spencera54b7cb2007-01-12 07:05:14 +0000282 !CPV->isNullValue()) && "Shouldn't output null constants!");
Reid Spencerad89bd62004-07-25 18:07:36 +0000283
284 // We must check for a ConstantExpr before switching by type because
285 // a ConstantExpr can be of any type, and has no explicit value.
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000286 //
Reid Spencerad89bd62004-07-25 18:07:36 +0000287 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
288 // FIXME: Encoding of constant exprs could be much more compact!
289 assert(CE->getNumOperands() > 0 && "ConstantExpr with 0 operands");
Reid Spencer3da59db2006-11-27 01:05:10 +0000290 assert(CE->getNumOperands() != 1 || CE->isCast());
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000291 output_vbr(1+CE->getNumOperands()); // flags as an expr
Reid Spencerb83eb642006-10-20 07:07:24 +0000292 output_vbr(CE->getOpcode()); // Put out the CE op code
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000293
Reid Spencerad89bd62004-07-25 18:07:36 +0000294 for (User::const_op_iterator OI = CE->op_begin(); OI != CE->op_end(); ++OI){
Chris Lattner972b4dc2007-02-10 05:17:48 +0000295 output_vbr(Table.getSlot(*OI));
296 output_typeid(Table.getTypeSlot((*OI)->getType()));
Reid Spencerad89bd62004-07-25 18:07:36 +0000297 }
Reid Spencer595b4772006-12-04 05:23:49 +0000298 if (CE->isCompare())
299 output_vbr((unsigned)CE->getPredicate());
Reid Spencerad89bd62004-07-25 18:07:36 +0000300 return;
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000301 } else if (isa<UndefValue>(CPV)) {
302 output_vbr(1U); // 1 -> UndefValue constant.
303 return;
Reid Spencerad89bd62004-07-25 18:07:36 +0000304 } else {
Reid Spencerb83eb642006-10-20 07:07:24 +0000305 output_vbr(0U); // flag as not a ConstantExpr (i.e. 0 operands)
Reid Spencerad89bd62004-07-25 18:07:36 +0000306 }
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000307
Reid Spencerad89bd62004-07-25 18:07:36 +0000308 switch (CPV->getType()->getTypeID()) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000309 case Type::IntegerTyID: { // Integer types...
310 unsigned NumBits = cast<IntegerType>(CPV->getType())->getBitWidth();
Chris Lattnerfb939312007-01-12 23:26:17 +0000311 if (NumBits <= 32)
Reid Spencera54b7cb2007-01-12 07:05:14 +0000312 output_vbr(uint32_t(cast<ConstantInt>(CPV)->getZExtValue()));
313 else if (NumBits <= 64)
314 output_vbr(uint64_t(cast<ConstantInt>(CPV)->getZExtValue()));
315 else
316 assert("Integer types > 64 bits not supported.");
Reid Spencerad89bd62004-07-25 18:07:36 +0000317 break;
Reid Spencera54b7cb2007-01-12 07:05:14 +0000318 }
Reid Spencerad89bd62004-07-25 18:07:36 +0000319
Reid Spencerad89bd62004-07-25 18:07:36 +0000320 case Type::ArrayTyID: {
321 const ConstantArray *CPA = cast<ConstantArray>(CPV);
322 assert(!CPA->isString() && "Constant strings should be handled specially!");
323
Chris Lattnera2bdad42007-02-10 05:13:03 +0000324 for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
325 output_vbr(Table.getSlot(CPA->getOperand(i)));
Reid Spencerad89bd62004-07-25 18:07:36 +0000326 break;
327 }
328
Brian Gaeke715c90b2004-08-20 06:00:58 +0000329 case Type::PackedTyID: {
330 const ConstantPacked *CP = cast<ConstantPacked>(CPV);
Chris Lattnera2bdad42007-02-10 05:13:03 +0000331 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
332 output_vbr(Table.getSlot(CP->getOperand(i)));
Brian Gaeke715c90b2004-08-20 06:00:58 +0000333 break;
334 }
335
Reid Spencerad89bd62004-07-25 18:07:36 +0000336 case Type::StructTyID: {
337 const ConstantStruct *CPS = cast<ConstantStruct>(CPV);
Reid Spencerad89bd62004-07-25 18:07:36 +0000338
Chris Lattnera2bdad42007-02-10 05:13:03 +0000339 for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
340 output_vbr(Table.getSlot(CPS->getOperand(i)));
Reid Spencerad89bd62004-07-25 18:07:36 +0000341 break;
342 }
343
344 case Type::PointerTyID:
345 assert(0 && "No non-null, non-constant-expr constants allowed!");
346 abort();
347
348 case Type::FloatTyID: { // Floating point types...
349 float Tmp = (float)cast<ConstantFP>(CPV)->getValue();
350 output_float(Tmp);
351 break;
352 }
353 case Type::DoubleTyID: {
354 double Tmp = cast<ConstantFP>(CPV)->getValue();
355 output_double(Tmp);
356 break;
357 }
358
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000359 case Type::VoidTyID:
Reid Spencerad89bd62004-07-25 18:07:36 +0000360 case Type::LabelTyID:
361 default:
Bill Wendlinge8156192006-12-07 01:30:32 +0000362 cerr << __FILE__ << ":" << __LINE__ << ": Don't know how to serialize"
363 << " type '" << *CPV->getType() << "'\n";
Reid Spencerad89bd62004-07-25 18:07:36 +0000364 break;
365 }
366 return;
367}
368
Chris Lattner3bc5a602006-01-25 23:08:15 +0000369/// outputInlineAsm - InlineAsm's get emitted to the constant pool, so they can
370/// be shared by multiple uses.
371void BytecodeWriter::outputInlineAsm(const InlineAsm *IA) {
372 // Output a marker, so we know when we have one one parsing the constant pool.
373 // Note that this encoding is 5 bytes: not very efficient for a marker. Since
374 // unique inline asms are rare, this should hardly matter.
375 output_vbr(~0U);
376
377 output(IA->getAsmString());
378 output(IA->getConstraintString());
379 output_vbr(unsigned(IA->hasSideEffects()));
380}
381
Reid Spencerad89bd62004-07-25 18:07:36 +0000382void BytecodeWriter::outputConstantStrings() {
383 SlotCalculator::string_iterator I = Table.string_begin();
384 SlotCalculator::string_iterator E = Table.string_end();
385 if (I == E) return; // No strings to emit
386
387 // If we have != 0 strings to emit, output them now. Strings are emitted into
388 // the 'void' type plane.
389 output_vbr(unsigned(E-I));
390 output_typeid(Type::VoidTyID);
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000391
Reid Spencerad89bd62004-07-25 18:07:36 +0000392 // Emit all of the strings.
393 for (I = Table.string_begin(); I != E; ++I) {
394 const ConstantArray *Str = *I;
Chris Lattner972b4dc2007-02-10 05:17:48 +0000395 output_typeid(Table.getTypeSlot(Str->getType()));
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000396
Reid Spencerad89bd62004-07-25 18:07:36 +0000397 // Now that we emitted the type (which indicates the size of the string),
398 // emit all of the characters.
399 std::string Val = Str->getAsString();
400 output_data(Val.c_str(), Val.c_str()+Val.size());
401 }
402}
403
404//===----------------------------------------------------------------------===//
405//=== Instruction Output ===//
406//===----------------------------------------------------------------------===//
Reid Spencerad89bd62004-07-25 18:07:36 +0000407
Chris Lattnerda895d62005-02-27 06:18:25 +0000408// outputInstructionFormat0 - Output those weird instructions that have a large
Chris Lattnerdee199f2005-05-06 22:34:01 +0000409// number of operands or have large operands themselves.
Reid Spencerad89bd62004-07-25 18:07:36 +0000410//
411// Format: [opcode] [type] [numargs] [arg0] [arg1] ... [arg<numargs-1>]
412//
Chris Lattnerf9d71782004-10-14 01:46:07 +0000413void BytecodeWriter::outputInstructionFormat0(const Instruction *I,
414 unsigned Opcode,
415 const SlotCalculator &Table,
416 unsigned Type) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000417 // Opcode must have top two bits clear...
418 output_vbr(Opcode << 2); // Instruction Opcode ID
419 output_typeid(Type); // Result type
420
421 unsigned NumArgs = I->getNumOperands();
Reid Spencercae60532006-12-06 04:27:07 +0000422 output_vbr(NumArgs + (isa<CastInst>(I) || isa<InvokeInst>(I) ||
423 isa<CmpInst>(I) || isa<VAArgInst>(I) || Opcode == 58));
Reid Spencerad89bd62004-07-25 18:07:36 +0000424
425 if (!isa<GetElementPtrInst>(&I)) {
Chris Lattnera2bdad42007-02-10 05:13:03 +0000426 for (unsigned i = 0; i < NumArgs; ++i)
427 output_vbr(Table.getSlot(I->getOperand(i)));
Reid Spencerad89bd62004-07-25 18:07:36 +0000428
429 if (isa<CastInst>(I) || isa<VAArgInst>(I)) {
Chris Lattner972b4dc2007-02-10 05:17:48 +0000430 output_typeid(Table.getTypeSlot(I->getType()));
Reid Spencercae60532006-12-06 04:27:07 +0000431 } else if (isa<CmpInst>(I)) {
432 output_vbr(unsigned(cast<CmpInst>(I)->getPredicate()));
Reid Spencer3da59db2006-11-27 01:05:10 +0000433 } else if (isa<InvokeInst>(I)) {
Chris Lattnerdee199f2005-05-06 22:34:01 +0000434 output_vbr(cast<InvokeInst>(I)->getCallingConv());
435 } else if (Opcode == 58) { // Call escape sequence
436 output_vbr((cast<CallInst>(I)->getCallingConv() << 1) |
Jeff Cohen39cef602005-05-07 02:44:04 +0000437 unsigned(cast<CallInst>(I)->isTailCall()));
Reid Spencerad89bd62004-07-25 18:07:36 +0000438 }
Reid Spencerad89bd62004-07-25 18:07:36 +0000439 } else {
Chris Lattnera2bdad42007-02-10 05:13:03 +0000440 output_vbr(Table.getSlot(I->getOperand(0)));
Reid Spencerad89bd62004-07-25 18:07:36 +0000441
442 // We need to encode the type of sequential type indices into their slot #
443 unsigned Idx = 1;
444 for (gep_type_iterator TI = gep_type_begin(I), E = gep_type_end(I);
445 Idx != NumArgs; ++TI, ++Idx) {
Chris Lattnera2bdad42007-02-10 05:13:03 +0000446 unsigned Slot = Table.getSlot(I->getOperand(Idx));
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000447
Reid Spencerad89bd62004-07-25 18:07:36 +0000448 if (isa<SequentialType>(*TI)) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000449 // These should be either 32-bits or 64-bits, however, with bit
450 // accurate types we just distinguish between less than or equal to
451 // 32-bits or greater than 32-bits.
Reid Spencer790366b2007-01-13 00:10:02 +0000452 unsigned BitWidth =
453 cast<IntegerType>(I->getOperand(Idx)->getType())->getBitWidth();
454 assert(BitWidth == 32 || BitWidth == 64 &&
455 "Invalid bitwidth for GEP index");
456 unsigned IdxId = BitWidth == 32 ? 0 : 1;
Reid Spencer88cfda22006-12-31 05:44:24 +0000457 Slot = (Slot << 1) | IdxId;
Reid Spencerad89bd62004-07-25 18:07:36 +0000458 }
Chris Lattnera2bdad42007-02-10 05:13:03 +0000459 output_vbr(Slot);
Reid Spencerad89bd62004-07-25 18:07:36 +0000460 }
461 }
Reid Spencerad89bd62004-07-25 18:07:36 +0000462}
463
464
465// outputInstrVarArgsCall - Output the absurdly annoying varargs function calls.
466// This are more annoying than most because the signature of the call does not
467// tell us anything about the types of the arguments in the varargs portion.
468// Because of this, we encode (as type 0) all of the argument types explicitly
469// before the argument value. This really sucks, but you shouldn't be using
470// varargs functions in your code! *death to printf*!
471//
472// Format: [opcode] [type] [numargs] [arg0] [arg1] ... [arg<numargs-1>]
473//
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000474void BytecodeWriter::outputInstrVarArgsCall(const Instruction *I,
475 unsigned Opcode,
476 const SlotCalculator &Table,
477 unsigned Type) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000478 assert(isa<CallInst>(I) || isa<InvokeInst>(I));
479 // Opcode must have top two bits clear...
480 output_vbr(Opcode << 2); // Instruction Opcode ID
481 output_typeid(Type); // Result type (varargs type)
482
483 const PointerType *PTy = cast<PointerType>(I->getOperand(0)->getType());
484 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
485 unsigned NumParams = FTy->getNumParams();
486
487 unsigned NumFixedOperands;
488 if (isa<CallInst>(I)) {
489 // Output an operand for the callee and each fixed argument, then two for
490 // each variable argument.
491 NumFixedOperands = 1+NumParams;
492 } else {
493 assert(isa<InvokeInst>(I) && "Not call or invoke??");
494 // Output an operand for the callee and destinations, then two for each
495 // variable argument.
496 NumFixedOperands = 3+NumParams;
497 }
Reid Spencer3da59db2006-11-27 01:05:10 +0000498 output_vbr(2 * I->getNumOperands()-NumFixedOperands +
499 unsigned(Opcode == 58 || isa<InvokeInst>(I)));
Reid Spencerad89bd62004-07-25 18:07:36 +0000500
501 // The type for the function has already been emitted in the type field of the
502 // instruction. Just emit the slot # now.
Chris Lattnera2bdad42007-02-10 05:13:03 +0000503 for (unsigned i = 0; i != NumFixedOperands; ++i)
504 output_vbr(Table.getSlot(I->getOperand(i)));
Reid Spencerad89bd62004-07-25 18:07:36 +0000505
506 for (unsigned i = NumFixedOperands, e = I->getNumOperands(); i != e; ++i) {
507 // Output Arg Type ID
Chris Lattner972b4dc2007-02-10 05:17:48 +0000508 output_typeid(Table.getTypeSlot(I->getOperand(i)->getType()));
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000509
Reid Spencerad89bd62004-07-25 18:07:36 +0000510 // Output arg ID itself
Chris Lattnera2bdad42007-02-10 05:13:03 +0000511 output_vbr(Table.getSlot(I->getOperand(i)));
Reid Spencerad89bd62004-07-25 18:07:36 +0000512 }
Chris Lattnera65371e2006-05-26 18:42:34 +0000513
Reid Spencer3da59db2006-11-27 01:05:10 +0000514 if (isa<InvokeInst>(I)) {
515 // Emit the tail call/calling conv for invoke instructions
516 output_vbr(cast<InvokeInst>(I)->getCallingConv());
517 } else if (Opcode == 58) {
Chris Lattnera65371e2006-05-26 18:42:34 +0000518 const CallInst *CI = cast<CallInst>(I);
519 output_vbr((CI->getCallingConv() << 1) | unsigned(CI->isTailCall()));
Chris Lattnera65371e2006-05-26 18:42:34 +0000520 }
Reid Spencerad89bd62004-07-25 18:07:36 +0000521}
522
523
524// outputInstructionFormat1 - Output one operand instructions, knowing that no
525// operand index is >= 2^12.
526//
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000527inline void BytecodeWriter::outputInstructionFormat1(const Instruction *I,
528 unsigned Opcode,
529 unsigned *Slots,
530 unsigned Type) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000531 // bits Instruction format:
532 // --------------------------
533 // 01-00: Opcode type, fixed to 1.
534 // 07-02: Opcode
535 // 19-08: Resulting type plane
536 // 31-20: Operand #1 (if set to (2^12-1), then zero operands)
537 //
Chris Lattnerf9d71782004-10-14 01:46:07 +0000538 output(1 | (Opcode << 2) | (Type << 8) | (Slots[0] << 20));
Reid Spencerad89bd62004-07-25 18:07:36 +0000539}
540
541
542// outputInstructionFormat2 - Output two operand instructions, knowing that no
543// operand index is >= 2^8.
544//
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000545inline void BytecodeWriter::outputInstructionFormat2(const Instruction *I,
546 unsigned Opcode,
547 unsigned *Slots,
548 unsigned Type) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000549 // bits Instruction format:
550 // --------------------------
551 // 01-00: Opcode type, fixed to 2.
552 // 07-02: Opcode
553 // 15-08: Resulting type plane
554 // 23-16: Operand #1
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000555 // 31-24: Operand #2
Reid Spencerad89bd62004-07-25 18:07:36 +0000556 //
Chris Lattnerf9d71782004-10-14 01:46:07 +0000557 output(2 | (Opcode << 2) | (Type << 8) | (Slots[0] << 16) | (Slots[1] << 24));
Reid Spencerad89bd62004-07-25 18:07:36 +0000558}
559
560
561// outputInstructionFormat3 - Output three operand instructions, knowing that no
562// operand index is >= 2^6.
563//
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000564inline void BytecodeWriter::outputInstructionFormat3(const Instruction *I,
Reid Spencerad89bd62004-07-25 18:07:36 +0000565 unsigned Opcode,
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000566 unsigned *Slots,
567 unsigned Type) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000568 // bits Instruction format:
569 // --------------------------
570 // 01-00: Opcode type, fixed to 3.
571 // 07-02: Opcode
572 // 13-08: Resulting type plane
573 // 19-14: Operand #1
574 // 25-20: Operand #2
575 // 31-26: Operand #3
576 //
Chris Lattnerf9d71782004-10-14 01:46:07 +0000577 output(3 | (Opcode << 2) | (Type << 8) |
Chris Lattner84d1ced2004-10-14 01:57:28 +0000578 (Slots[0] << 14) | (Slots[1] << 20) | (Slots[2] << 26));
Reid Spencerad89bd62004-07-25 18:07:36 +0000579}
580
581void BytecodeWriter::outputInstruction(const Instruction &I) {
Reid Spencer3da59db2006-11-27 01:05:10 +0000582 assert(I.getOpcode() < 57 && "Opcode too big???");
Reid Spencerad89bd62004-07-25 18:07:36 +0000583 unsigned Opcode = I.getOpcode();
584 unsigned NumOperands = I.getNumOperands();
585
Chris Lattner38287bd2005-05-06 06:13:34 +0000586 // Encode 'tail call' as 61, 'volatile load' as 62, and 'volatile store' as
587 // 63.
Chris Lattnerdee199f2005-05-06 22:34:01 +0000588 if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
589 if (CI->getCallingConv() == CallingConv::C) {
590 if (CI->isTailCall())
591 Opcode = 61; // CCC + Tail Call
592 else
593 ; // Opcode = Instruction::Call
594 } else if (CI->getCallingConv() == CallingConv::Fast) {
595 if (CI->isTailCall())
596 Opcode = 59; // FastCC + TailCall
597 else
598 Opcode = 60; // FastCC + Not Tail Call
599 } else {
600 Opcode = 58; // Call escape sequence.
601 }
Chris Lattnerdee199f2005-05-06 22:34:01 +0000602 } else if (isa<LoadInst>(I) && cast<LoadInst>(I).isVolatile()) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000603 Opcode = 62;
Chris Lattnerdee199f2005-05-06 22:34:01 +0000604 } else if (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile()) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000605 Opcode = 63;
Chris Lattnerdee199f2005-05-06 22:34:01 +0000606 }
Reid Spencerad89bd62004-07-25 18:07:36 +0000607
608 // Figure out which type to encode with the instruction. Typically we want
609 // the type of the first parameter, as opposed to the type of the instruction
610 // (for example, with setcc, we always know it returns bool, but the type of
611 // the first param is actually interesting). But if we have no arguments
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000612 // we take the type of the instruction itself.
Reid Spencerad89bd62004-07-25 18:07:36 +0000613 //
614 const Type *Ty;
615 switch (I.getOpcode()) {
616 case Instruction::Select:
617 case Instruction::Malloc:
618 case Instruction::Alloca:
619 Ty = I.getType(); // These ALWAYS want to encode the return type
620 break;
621 case Instruction::Store:
622 Ty = I.getOperand(1)->getType(); // Encode the pointer type...
623 assert(isa<PointerType>(Ty) && "Store to nonpointer type!?!?");
624 break;
625 default: // Otherwise use the default behavior...
626 Ty = NumOperands ? I.getOperand(0)->getType() : I.getType();
627 break;
628 }
629
Chris Lattner972b4dc2007-02-10 05:17:48 +0000630 unsigned Type = Table.getTypeSlot(Ty);
Reid Spencerad89bd62004-07-25 18:07:36 +0000631
632 // Varargs calls and invokes are encoded entirely different from any other
633 // instructions.
634 if (const CallInst *CI = dyn_cast<CallInst>(&I)){
635 const PointerType *Ty =cast<PointerType>(CI->getCalledValue()->getType());
636 if (cast<FunctionType>(Ty->getElementType())->isVarArg()) {
637 outputInstrVarArgsCall(CI, Opcode, Table, Type);
638 return;
639 }
640 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
641 const PointerType *Ty =cast<PointerType>(II->getCalledValue()->getType());
642 if (cast<FunctionType>(Ty->getElementType())->isVarArg()) {
643 outputInstrVarArgsCall(II, Opcode, Table, Type);
644 return;
645 }
646 }
647
648 if (NumOperands <= 3) {
649 // Make sure that we take the type number into consideration. We don't want
650 // to overflow the field size for the instruction format we select.
651 //
652 unsigned MaxOpSlot = Type;
653 unsigned Slots[3]; Slots[0] = (1 << 12)-1; // Marker to signify 0 operands
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000654
Reid Spencerad89bd62004-07-25 18:07:36 +0000655 for (unsigned i = 0; i != NumOperands; ++i) {
Chris Lattnera2bdad42007-02-10 05:13:03 +0000656 unsigned Slot = Table.getSlot(I.getOperand(i));
657 if (Slot > MaxOpSlot) MaxOpSlot = Slot;
658 Slots[i] = Slot;
Reid Spencerad89bd62004-07-25 18:07:36 +0000659 }
660
661 // Handle the special cases for various instructions...
662 if (isa<CastInst>(I) || isa<VAArgInst>(I)) {
663 // Cast has to encode the destination type as the second argument in the
664 // packet, or else we won't know what type to cast to!
Chris Lattnercb43fdc2007-02-10 04:15:40 +0000665 Slots[1] = Table.getTypeSlot(I.getType());
Reid Spencerad89bd62004-07-25 18:07:36 +0000666 if (Slots[1] > MaxOpSlot) MaxOpSlot = Slots[1];
667 NumOperands++;
Chris Lattner42ba6b42005-11-05 22:08:14 +0000668 } else if (const AllocationInst *AI = dyn_cast<AllocationInst>(&I)) {
669 assert(NumOperands == 1 && "Bogus allocation!");
670 if (AI->getAlignment()) {
671 Slots[1] = Log2_32(AI->getAlignment())+1;
672 if (Slots[1] > MaxOpSlot) MaxOpSlot = Slots[1];
673 NumOperands = 2;
674 }
Reid Spencerc8dab492006-12-03 06:28:54 +0000675 } else if (isa<ICmpInst>(I) || isa<FCmpInst>(I)) {
676 // We need to encode the compare instruction's predicate as the third
677 // operand. Its not really a slot, but we don't want to break the
678 // instruction format for these instructions.
679 NumOperands++;
680 assert(NumOperands == 3 && "CmpInst with wrong number of operands?");
681 Slots[2] = unsigned(cast<CmpInst>(&I)->getPredicate());
682 if (Slots[2] > MaxOpSlot)
683 MaxOpSlot = Slots[2];
Reid Spencerad89bd62004-07-25 18:07:36 +0000684 } else if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&I)) {
685 // We need to encode the type of sequential type indices into their slot #
686 unsigned Idx = 1;
687 for (gep_type_iterator I = gep_type_begin(GEP), E = gep_type_end(GEP);
688 I != E; ++I, ++Idx)
689 if (isa<SequentialType>(*I)) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000690 // These should be either 32-bits or 64-bits, however, with bit
691 // accurate types we just distinguish between less than or equal to
692 // 32-bits or greater than 32-bits.
Reid Spencer790366b2007-01-13 00:10:02 +0000693 unsigned BitWidth =
694 cast<IntegerType>(GEP->getOperand(Idx)->getType())->getBitWidth();
695 assert(BitWidth == 32 || BitWidth == 64 &&
696 "Invalid bitwidth for GEP index");
697 unsigned IdxId = BitWidth == 32 ? 0 : 1;
Reid Spencer88cfda22006-12-31 05:44:24 +0000698 Slots[Idx] = (Slots[Idx] << 1) | IdxId;
Reid Spencerad89bd62004-07-25 18:07:36 +0000699 if (Slots[Idx] > MaxOpSlot) MaxOpSlot = Slots[Idx];
700 }
Chris Lattnerdee199f2005-05-06 22:34:01 +0000701 } else if (Opcode == 58) {
702 // If this is the escape sequence for call, emit the tailcall/cc info.
703 const CallInst &CI = cast<CallInst>(I);
704 ++NumOperands;
Chris Lattnerebf8e6c2006-05-19 21:57:37 +0000705 if (NumOperands <= 3) {
706 Slots[NumOperands-1] =
707 (CI.getCallingConv() << 1)|unsigned(CI.isTailCall());
Chris Lattnerdee199f2005-05-06 22:34:01 +0000708 if (Slots[NumOperands-1] > MaxOpSlot)
709 MaxOpSlot = Slots[NumOperands-1];
710 }
Reid Spencer3da59db2006-11-27 01:05:10 +0000711 } else if (isa<InvokeInst>(I)) {
Chris Lattnerdee199f2005-05-06 22:34:01 +0000712 // Invoke escape seq has at least 4 operands to encode.
713 ++NumOperands;
Reid Spencerad89bd62004-07-25 18:07:36 +0000714 }
715
716 // Decide which instruction encoding to use. This is determined primarily
717 // by the number of operands, and secondarily by whether or not the max
718 // operand will fit into the instruction encoding. More operands == fewer
719 // bits per operand.
720 //
721 switch (NumOperands) {
722 case 0:
723 case 1:
724 if (MaxOpSlot < (1 << 12)-1) { // -1 because we use 4095 to indicate 0 ops
725 outputInstructionFormat1(&I, Opcode, Slots, Type);
726 return;
727 }
728 break;
729
730 case 2:
731 if (MaxOpSlot < (1 << 8)) {
732 outputInstructionFormat2(&I, Opcode, Slots, Type);
733 return;
734 }
735 break;
736
737 case 3:
738 if (MaxOpSlot < (1 << 6)) {
739 outputInstructionFormat3(&I, Opcode, Slots, Type);
740 return;
741 }
742 break;
743 default:
744 break;
745 }
746 }
747
748 // If we weren't handled before here, we either have a large number of
749 // operands or a large operand index that we are referring to.
750 outputInstructionFormat0(&I, Opcode, Table, Type);
751}
752
753//===----------------------------------------------------------------------===//
754//=== Block Output ===//
755//===----------------------------------------------------------------------===//
756
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000757BytecodeWriter::BytecodeWriter(std::vector<unsigned char> &o, const Module *M)
Reid Spencer798ff642004-05-26 07:37:11 +0000758 : Out(o), Table(M) {
Chris Lattner00950542001-06-06 20:29:01 +0000759
Chris Lattner83bb3d22004-01-14 23:36:54 +0000760 // Emit the signature...
Chris Lattnerc847f7c2006-07-28 22:07:54 +0000761 static const unsigned char *Sig = (const unsigned char*)"llvm";
Reid Spencerad89bd62004-07-25 18:07:36 +0000762 output_data(Sig, Sig+4);
Chris Lattner00950542001-06-06 20:29:01 +0000763
764 // Emit the top level CLASS block.
Reid Spencerad89bd62004-07-25 18:07:36 +0000765 BytecodeBlock ModuleBlock(BytecodeFormat::ModuleBlockID, *this, false, true);
Chris Lattner00950542001-06-06 20:29:01 +0000766
Reid Spenceraacc35a2007-01-26 08:10:24 +0000767 // Output the version identifier
768 output_vbr(BCVersionNum);
Chris Lattner00950542001-06-06 20:29:01 +0000769
Reid Spencercb3595c2004-07-04 11:45:47 +0000770 // The Global type plane comes first
Chris Lattner186a1f72003-03-19 20:56:46 +0000771 {
Chris Lattnerc847f7c2006-07-28 22:07:54 +0000772 BytecodeBlock CPool(BytecodeFormat::GlobalTypePlaneBlockID, *this);
773 outputTypes(Type::FirstDerivedTyID);
Chris Lattner186a1f72003-03-19 20:56:46 +0000774 }
Chris Lattner00950542001-06-06 20:29:01 +0000775
Chris Lattner186a1f72003-03-19 20:56:46 +0000776 // The ModuleInfoBlock follows directly after the type information
Chris Lattnere8fdde12001-09-07 16:39:41 +0000777 outputModuleInfoBlock(M);
778
Chris Lattner186a1f72003-03-19 20:56:46 +0000779 // Output module level constants, used for global variable initializers
Chris Lattner8dcd81c2007-02-09 07:53:20 +0000780 outputConstants();
Chris Lattner186a1f72003-03-19 20:56:46 +0000781
Chris Lattnerb5794002002-04-07 22:49:37 +0000782 // Do the whole module now! Process each function at a time...
Chris Lattner0b12b5f2002-06-25 16:13:21 +0000783 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
Chris Lattner186a1f72003-03-19 20:56:46 +0000784 outputFunction(I);
Chris Lattnere8fdde12001-09-07 16:39:41 +0000785
Reid Spencer78d033e2007-01-06 07:24:44 +0000786 // Output the symbole table for types
787 outputTypeSymbolTable(M->getTypeSymbolTable());
788
789 // Output the symbol table for values
790 outputValueSymbolTable(M->getValueSymbolTable());
Chris Lattner00950542001-06-06 20:29:01 +0000791}
792
Chris Lattnerf9d71782004-10-14 01:46:07 +0000793void BytecodeWriter::outputTypes(unsigned TypeNum) {
Reid Spencercb3595c2004-07-04 11:45:47 +0000794 // Write the type plane for types first because earlier planes (e.g. for a
795 // primitive type like float) may have constants constructed using types
796 // coming later (e.g., via getelementptr from a pointer type). The type
797 // plane is needed before types can be fwd or bkwd referenced.
798 const std::vector<const Type*>& Types = Table.getTypes();
799 assert(!Types.empty() && "No types at all?");
800 assert(TypeNum <= Types.size() && "Invalid TypeNo index");
801
802 unsigned NumEntries = Types.size() - TypeNum;
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000803
Reid Spencercb3595c2004-07-04 11:45:47 +0000804 // Output type header: [num entries]
Reid Spencerad89bd62004-07-25 18:07:36 +0000805 output_vbr(NumEntries);
Reid Spencercb3595c2004-07-04 11:45:47 +0000806
807 for (unsigned i = TypeNum; i < TypeNum+NumEntries; ++i)
808 outputType(Types[i]);
809}
810
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000811// Helper function for outputConstants().
812// Writes out all the constants in the plane Plane starting at entry StartNo.
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000813//
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000814void BytecodeWriter::outputConstantsInPlane(const std::vector<const Value*>
815 &Plane, unsigned StartNo) {
816 unsigned ValNo = StartNo;
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000817
Chris Lattner83bb3d22004-01-14 23:36:54 +0000818 // Scan through and ignore function arguments, global values, and constant
819 // strings.
820 for (; ValNo < Plane.size() &&
821 (isa<Argument>(Plane[ValNo]) || isa<GlobalValue>(Plane[ValNo]) ||
822 (isa<ConstantArray>(Plane[ValNo]) &&
823 cast<ConstantArray>(Plane[ValNo])->isString())); ValNo++)
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000824 /*empty*/;
825
826 unsigned NC = ValNo; // Number of constants
Chris Lattner3bc5a602006-01-25 23:08:15 +0000827 for (; NC < Plane.size() && (isa<Constant>(Plane[NC]) ||
828 isa<InlineAsm>(Plane[NC])); NC++)
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000829 /*empty*/;
830 NC -= ValNo; // Convert from index into count
831 if (NC == 0) return; // Skip empty type planes...
832
Chris Lattnerd6942d72004-01-14 16:54:21 +0000833 // FIXME: Most slabs only have 1 or 2 entries! We should encode this much
834 // more compactly.
835
Reid Spencerb83eb642006-10-20 07:07:24 +0000836 // Put out type header: [num entries][type id number]
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000837 //
Reid Spencerad89bd62004-07-25 18:07:36 +0000838 output_vbr(NC);
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000839
Chris Lattner972b4dc2007-02-10 05:17:48 +0000840 // Put out the Type ID Number.
841 output_typeid(Table.getTypeSlot(Plane.front()->getType()));
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000842
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000843 for (unsigned i = ValNo; i < ValNo+NC; ++i) {
844 const Value *V = Plane[i];
Chris Lattner3bc5a602006-01-25 23:08:15 +0000845 if (const Constant *C = dyn_cast<Constant>(V))
Reid Spencere0125b62004-07-18 00:16:21 +0000846 outputConstant(C);
Chris Lattner3bc5a602006-01-25 23:08:15 +0000847 else
848 outputInlineAsm(cast<InlineAsm>(V));
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000849 }
850}
851
Chris Lattner9e60d8d2005-05-05 22:21:19 +0000852static inline bool hasNullValue(const Type *Ty) {
853 return Ty != Type::LabelTy && Ty != Type::VoidTy && !isa<OpaqueType>(Ty);
Chris Lattner80b97342004-01-17 23:25:43 +0000854}
855
Chris Lattner8dcd81c2007-02-09 07:53:20 +0000856void BytecodeWriter::outputConstants() {
Reid Spencerad89bd62004-07-25 18:07:36 +0000857 BytecodeBlock CPool(BytecodeFormat::ConstantPoolBlockID, *this,
Chris Lattner0baa0af2004-01-15 21:06:57 +0000858 true /* Elide block if empty */);
Chris Lattner00950542001-06-06 20:29:01 +0000859
860 unsigned NumPlanes = Table.getNumPlanes();
Chris Lattnerf69315b2003-05-22 18:35:38 +0000861
Chris Lattner8dcd81c2007-02-09 07:53:20 +0000862 // Output module-level string constants before any other constants.
863 outputConstantStrings();
Chris Lattner83bb3d22004-01-14 23:36:54 +0000864
Reid Spencercb3595c2004-07-04 11:45:47 +0000865 for (unsigned pno = 0; pno != NumPlanes; pno++) {
866 const std::vector<const Value*> &Plane = Table.getPlane(pno);
867 if (!Plane.empty()) { // Skip empty type planes...
868 unsigned ValNo = 0;
Chris Lattner9e60d8d2005-05-05 22:21:19 +0000869 if (hasNullValue(Plane[0]->getType())) {
Reid Spencer0852c802004-07-04 11:46:15 +0000870 // Skip zero initializer
Chris Lattner8dcd81c2007-02-09 07:53:20 +0000871 ValNo = 1;
Chris Lattnerf69315b2003-05-22 18:35:38 +0000872 }
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000873
Reid Spencercb3595c2004-07-04 11:45:47 +0000874 // Write out constants in the plane
875 outputConstantsInPlane(Plane, ValNo);
Chris Lattnerf69315b2003-05-22 18:35:38 +0000876 }
Reid Spencercb3595c2004-07-04 11:45:47 +0000877 }
Chris Lattner00950542001-06-06 20:29:01 +0000878}
879
Chris Lattner6b252422003-10-16 18:28:50 +0000880static unsigned getEncodedLinkage(const GlobalValue *GV) {
881 switch (GV->getLinkage()) {
882 default: assert(0 && "Invalid linkage!");
Anton Korobeynikovb74ed072006-09-14 18:23:27 +0000883 case GlobalValue::ExternalLinkage: return 0;
884 case GlobalValue::WeakLinkage: return 1;
885 case GlobalValue::AppendingLinkage: return 2;
886 case GlobalValue::InternalLinkage: return 3;
887 case GlobalValue::LinkOnceLinkage: return 4;
888 case GlobalValue::DLLImportLinkage: return 5;
889 case GlobalValue::DLLExportLinkage: return 6;
890 case GlobalValue::ExternalWeakLinkage: return 7;
Chris Lattner6b252422003-10-16 18:28:50 +0000891 }
892}
893
Anton Korobeynikov7f705592007-01-12 19:20:47 +0000894static unsigned getEncodedVisibility(const GlobalValue *GV) {
895 switch (GV->getVisibility()) {
896 default: assert(0 && "Invalid visibility!");
897 case GlobalValue::DefaultVisibility: return 0;
898 case GlobalValue::HiddenVisibility: return 1;
899 }
900}
901
Chris Lattner00950542001-06-06 20:29:01 +0000902void BytecodeWriter::outputModuleInfoBlock(const Module *M) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000903 BytecodeBlock ModuleInfoBlock(BytecodeFormat::ModuleGlobalInfoBlockID, *this);
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000904
Chris Lattner404cddf2005-11-12 01:33:40 +0000905 // Give numbers to sections as we encounter them.
906 unsigned SectionIDCounter = 0;
907 std::vector<std::string> SectionNames;
908 std::map<std::string, unsigned> SectionID;
909
Chris Lattner70cc3392001-09-10 07:58:01 +0000910 // Output the types for the global variables in the module...
Chris Lattner28caccf2005-05-06 20:27:03 +0000911 for (Module::const_global_iterator I = M->global_begin(),
Chris Lattner8eb52dd2005-11-06 07:11:04 +0000912 End = M->global_end(); I != End; ++I) {
Chris Lattner972b4dc2007-02-10 05:17:48 +0000913 unsigned Slot = Table.getTypeSlot(I->getType());
Chris Lattnerd70684f2001-09-18 04:01:05 +0000914
Chris Lattner8eb52dd2005-11-06 07:11:04 +0000915 assert((I->hasInitializer() || !I->hasInternalLinkage()) &&
916 "Global must have an initializer or have external linkage!");
917
Chris Lattner22482a12003-10-18 06:30:21 +0000918 // Fields: bit0 = isConstant, bit1 = hasInitializer, bit2-4=Linkage,
Chris Lattner8eb52dd2005-11-06 07:11:04 +0000919 // bit5+ = Slot # for type.
Anton Korobeynikov7f705592007-01-12 19:20:47 +0000920 bool HasExtensionWord = (I->getAlignment() != 0) ||
921 I->hasSection() ||
922 (I->getVisibility() != GlobalValue::DefaultVisibility);
Chris Lattner8eb52dd2005-11-06 07:11:04 +0000923
924 // If we need to use the extension byte, set linkage=3(internal) and
925 // initializer = 0 (impossible!).
926 if (!HasExtensionWord) {
Chris Lattner972b4dc2007-02-10 05:17:48 +0000927 unsigned oSlot = (Slot << 5) | (getEncodedLinkage(I) << 2) |
Chris Lattner8eb52dd2005-11-06 07:11:04 +0000928 (I->hasInitializer() << 1) | (unsigned)I->isConstant();
929 output_vbr(oSlot);
Anton Korobeynikovb74ed072006-09-14 18:23:27 +0000930 } else {
Chris Lattner972b4dc2007-02-10 05:17:48 +0000931 unsigned oSlot = (Slot << 5) | (3 << 2) |
Chris Lattner8eb52dd2005-11-06 07:11:04 +0000932 (0 << 1) | (unsigned)I->isConstant();
933 output_vbr(oSlot);
934
935 // The extension word has this format: bit 0 = has initializer, bit 1-3 =
Anton Korobeynikov7f705592007-01-12 19:20:47 +0000936 // linkage, bit 4-8 = alignment (log2), bit 9 = has SectionID,
937 // bits 10-12 = visibility, bits 13+ = future use.
Jeff Cohenba0ffcc2005-11-12 01:01:50 +0000938 unsigned ExtWord = (unsigned)I->hasInitializer() |
939 (getEncodedLinkage(I) << 1) |
Chris Lattner404cddf2005-11-12 01:33:40 +0000940 ((Log2_32(I->getAlignment())+1) << 4) |
Anton Korobeynikov7f705592007-01-12 19:20:47 +0000941 ((unsigned)I->hasSection() << 9) |
942 (getEncodedVisibility(I) << 10);
Chris Lattner8eb52dd2005-11-06 07:11:04 +0000943 output_vbr(ExtWord);
Chris Lattner404cddf2005-11-12 01:33:40 +0000944 if (I->hasSection()) {
945 // Give section names unique ID's.
946 unsigned &Entry = SectionID[I->getSection()];
947 if (Entry == 0) {
948 Entry = ++SectionIDCounter;
949 SectionNames.push_back(I->getSection());
950 }
951 output_vbr(Entry);
952 }
Chris Lattner8eb52dd2005-11-06 07:11:04 +0000953 }
Chris Lattnerd70684f2001-09-18 04:01:05 +0000954
Chris Lattner1b98c5c2001-10-13 06:48:38 +0000955 // If we have an initializer, output it now.
Chris Lattnera2bdad42007-02-10 05:13:03 +0000956 if (I->hasInitializer())
957 output_vbr(Table.getSlot((Value*)I->getInitializer()));
Chris Lattner70cc3392001-09-10 07:58:01 +0000958 }
Chris Lattner972b4dc2007-02-10 05:17:48 +0000959 output_typeid(Table.getTypeSlot(Type::VoidTy));
Chris Lattner70cc3392001-09-10 07:58:01 +0000960
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000961 // Output the types of the functions in this module.
Chris Lattner7fc9fe32001-06-27 23:41:11 +0000962 for (Module::const_iterator I = M->begin(), End = M->end(); I != End; ++I) {
Chris Lattner972b4dc2007-02-10 05:17:48 +0000963 unsigned Slot = Table.getTypeSlot(I->getType());
Chris Lattnere73bd452005-11-06 07:43:39 +0000964 assert(((Slot << 6) >> 6) == Slot && "Slot # too big!");
Chris Lattner54b369e2005-11-06 07:46:13 +0000965 unsigned CC = I->getCallingConv()+1;
966 unsigned ID = (Slot << 5) | (CC & 15);
Chris Lattner479ffeb2005-05-06 20:42:57 +0000967
Reid Spencer5cbf9852007-01-30 20:08:39 +0000968 if (I->isDeclaration()) // If external, we don't have an FunctionInfo block.
Chris Lattnerd6e431f2004-11-15 22:39:49 +0000969 ID |= 1 << 4;
Chris Lattnere73bd452005-11-06 07:43:39 +0000970
Anton Korobeynikovb74ed072006-09-14 18:23:27 +0000971 if (I->getAlignment() || I->hasSection() || (CC & ~15) != 0 ||
Reid Spencer5cbf9852007-01-30 20:08:39 +0000972 (I->isDeclaration() && I->hasDLLImportLinkage()) ||
973 (I->isDeclaration() && I->hasExternalWeakLinkage())
Anton Korobeynikovb74ed072006-09-14 18:23:27 +0000974 )
Chris Lattnere73bd452005-11-06 07:43:39 +0000975 ID |= 1 << 31; // Do we need an extension word?
976
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000977 output_vbr(ID);
Chris Lattnere73bd452005-11-06 07:43:39 +0000978
979 if (ID & (1 << 31)) {
980 // Extension byte: bits 0-4 = alignment, bits 5-9 = top nibble of calling
Anton Korobeynikovb74ed072006-09-14 18:23:27 +0000981 // convention, bit 10 = hasSectionID., bits 11-12 = external linkage type
982 unsigned extLinkage = 0;
983
Reid Spencer5cbf9852007-01-30 20:08:39 +0000984 if (I->isDeclaration()) {
Anton Korobeynikovb74ed072006-09-14 18:23:27 +0000985 if (I->hasDLLImportLinkage()) {
986 extLinkage = 1;
987 } else if (I->hasExternalWeakLinkage()) {
988 extLinkage = 2;
989 }
990 }
991
Chris Lattner404cddf2005-11-12 01:33:40 +0000992 ID = (Log2_32(I->getAlignment())+1) | ((CC >> 4) << 5) |
Anton Korobeynikovb74ed072006-09-14 18:23:27 +0000993 (I->hasSection() << 10) |
994 ((extLinkage & 3) << 11);
Chris Lattnere73bd452005-11-06 07:43:39 +0000995 output_vbr(ID);
Chris Lattner404cddf2005-11-12 01:33:40 +0000996
997 // Give section names unique ID's.
998 if (I->hasSection()) {
999 unsigned &Entry = SectionID[I->getSection()];
1000 if (Entry == 0) {
1001 Entry = ++SectionIDCounter;
1002 SectionNames.push_back(I->getSection());
1003 }
1004 output_vbr(Entry);
1005 }
Chris Lattnere73bd452005-11-06 07:43:39 +00001006 }
Chris Lattner00950542001-06-06 20:29:01 +00001007 }
Chris Lattner972b4dc2007-02-10 05:17:48 +00001008 output_vbr(Table.getTypeSlot(Type::VoidTy) << 5);
Reid Spencerad89bd62004-07-25 18:07:36 +00001009
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001010 // Emit the list of dependent libraries for the Module.
Reid Spencer5ac88122004-07-25 21:32:02 +00001011 Module::lib_iterator LI = M->lib_begin();
1012 Module::lib_iterator LE = M->lib_end();
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001013 output_vbr(unsigned(LE - LI)); // Emit the number of dependent libraries.
1014 for (; LI != LE; ++LI)
Reid Spencer38d54be2004-08-17 07:45:14 +00001015 output(*LI);
Reid Spencerad89bd62004-07-25 18:07:36 +00001016
1017 // Output the target triple from the module
Reid Spencer38d54be2004-08-17 07:45:14 +00001018 output(M->getTargetTriple());
Reid Spenceraacc35a2007-01-26 08:10:24 +00001019
1020 // Output the data layout from the module
1021 output(M->getDataLayout());
Chris Lattner404cddf2005-11-12 01:33:40 +00001022
1023 // Emit the table of section names.
1024 output_vbr((unsigned)SectionNames.size());
1025 for (unsigned i = 0, e = SectionNames.size(); i != e; ++i)
1026 output(SectionNames[i]);
Chris Lattner7e6db762006-01-23 23:43:17 +00001027
1028 // Output the inline asm string.
Chris Lattner66316012006-01-24 04:14:29 +00001029 output(M->getModuleInlineAsm());
Chris Lattner00950542001-06-06 20:29:01 +00001030}
1031
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001032void BytecodeWriter::outputInstructions(const Function *F) {
Reid Spencerad89bd62004-07-25 18:07:36 +00001033 BytecodeBlock ILBlock(BytecodeFormat::InstructionListBlockID, *this);
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001034 for (Function::const_iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
1035 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I)
1036 outputInstruction(*I);
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001037}
1038
Chris Lattner186a1f72003-03-19 20:56:46 +00001039void BytecodeWriter::outputFunction(const Function *F) {
Chris Lattnerfd7f8fe2004-11-15 21:56:33 +00001040 // If this is an external function, there is nothing else to emit!
Reid Spencer5cbf9852007-01-30 20:08:39 +00001041 if (F->isDeclaration()) return;
Chris Lattnerfd7f8fe2004-11-15 21:56:33 +00001042
Chris Lattnerd6e431f2004-11-15 22:39:49 +00001043 BytecodeBlock FunctionBlock(BytecodeFormat::FunctionBlockID, *this);
Anton Korobeynikov7f705592007-01-12 19:20:47 +00001044 unsigned rWord = (getEncodedVisibility(F) << 16) | getEncodedLinkage(F);
1045 output_vbr(rWord);
Chris Lattnerd6e431f2004-11-15 22:39:49 +00001046
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001047 // Get slot information about the function...
1048 Table.incorporateFunction(F);
1049
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001050 // Output all of the instructions in the body of the function
1051 outputInstructions(F);
Misha Brukman23c6d2c2005-04-21 21:48:46 +00001052
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001053 // If needed, output the symbol table for the function...
Reid Spencer78d033e2007-01-06 07:24:44 +00001054 outputValueSymbolTable(F->getValueSymbolTable());
Misha Brukman23c6d2c2005-04-21 21:48:46 +00001055
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001056 Table.purgeFunction();
1057}
1058
Chris Lattner00950542001-06-06 20:29:01 +00001059
Reid Spencer78d033e2007-01-06 07:24:44 +00001060void BytecodeWriter::outputTypeSymbolTable(const TypeSymbolTable &TST) {
1061 // Do not output the block for an empty symbol table, it just wastes
Chris Lattner737d3cd2004-01-10 19:56:59 +00001062 // space!
Reid Spencer78d033e2007-01-06 07:24:44 +00001063 if (TST.empty()) return;
Chris Lattner737d3cd2004-01-10 19:56:59 +00001064
Reid Spencer78d033e2007-01-06 07:24:44 +00001065 // Create a header for the symbol table
1066 BytecodeBlock SymTabBlock(BytecodeFormat::TypeSymbolTableBlockID, *this,
Chris Lattnerf9d71782004-10-14 01:46:07 +00001067 true/*ElideIfEmpty*/);
Misha Brukman23c6d2c2005-04-21 21:48:46 +00001068 // Write the number of types
Reid Spencer78d033e2007-01-06 07:24:44 +00001069 output_vbr(TST.size());
Reid Spencer250c4182004-08-17 02:59:02 +00001070
1071 // Write each of the types
Reid Spencer78d033e2007-01-06 07:24:44 +00001072 for (TypeSymbolTable::const_iterator TI = TST.begin(), TE = TST.end();
1073 TI != TE; ++TI) {
Reid Spencer250c4182004-08-17 02:59:02 +00001074 // Symtab entry:[def slot #][name]
Chris Lattner972b4dc2007-02-10 05:17:48 +00001075 output_typeid(Table.getTypeSlot(TI->second));
Misha Brukman23c6d2c2005-04-21 21:48:46 +00001076 output(TI->first);
Reid Spencer94f2df22004-05-25 17:29:59 +00001077 }
Reid Spencer78d033e2007-01-06 07:24:44 +00001078}
1079
Reid Spenceref9b9a72007-02-05 20:47:22 +00001080void BytecodeWriter::outputValueSymbolTable(const ValueSymbolTable &VST) {
Reid Spencer78d033e2007-01-06 07:24:44 +00001081 // Do not output the Bytecode block for an empty symbol table, it just wastes
1082 // space!
Reid Spenceref9b9a72007-02-05 20:47:22 +00001083 if (VST.empty()) return;
Reid Spencer78d033e2007-01-06 07:24:44 +00001084
1085 BytecodeBlock SymTabBlock(BytecodeFormat::ValueSymbolTableBlockID, *this,
1086 true/*ElideIfEmpty*/);
Reid Spencer94f2df22004-05-25 17:29:59 +00001087
Reid Spenceref9b9a72007-02-05 20:47:22 +00001088 // Organize the symbol table by type
1089 typedef std::pair<std::string, const Value*> PlaneMapEntry;
1090 typedef std::vector<PlaneMapEntry> PlaneMapVector;
1091 typedef std::map<const Type*, PlaneMapVector > PlaneMap;
1092 PlaneMap Planes;
1093 for (ValueSymbolTable::const_iterator SI = VST.begin(), SE = VST.end();
1094 SI != SE; ++SI)
1095 Planes[SI->second->getType()].push_back(
1096 std::make_pair(SI->first,SI->second));
1097
1098 for (PlaneMap::const_iterator PI = Planes.begin(), PE = Planes.end();
1099 PI != PE; ++PI) {
Reid Spenceref9b9a72007-02-05 20:47:22 +00001100 PlaneMapVector::const_iterator I = PI->second.begin();
1101 PlaneMapVector::const_iterator End = PI->second.end();
1102
Chris Lattner00950542001-06-06 20:29:01 +00001103 if (I == End) continue; // Don't mess with an absent type...
1104
Reid Spencer250c4182004-08-17 02:59:02 +00001105 // Write the number of values in this plane
Chris Lattner001d16a2005-03-07 02:59:36 +00001106 output_vbr((unsigned)PI->second.size());
Chris Lattner00950542001-06-06 20:29:01 +00001107
Reid Spencer250c4182004-08-17 02:59:02 +00001108 // Write the slot number of the type for this plane
Chris Lattner972b4dc2007-02-10 05:17:48 +00001109 output_typeid(Table.getTypeSlot(PI->first));
Chris Lattner00950542001-06-06 20:29:01 +00001110
Reid Spencer250c4182004-08-17 02:59:02 +00001111 // Write each of the values in this plane
Chris Lattner7fc9fe32001-06-27 23:41:11 +00001112 for (; I != End; ++I) {
Chris Lattner00950542001-06-06 20:29:01 +00001113 // Symtab entry: [def slot #][name]
Chris Lattnera2bdad42007-02-10 05:13:03 +00001114 output_vbr(Table.getSlot(I->second));
Reid Spencer38d54be2004-08-17 07:45:14 +00001115 output(I->first);
Chris Lattner00950542001-06-06 20:29:01 +00001116 }
1117 }
1118}
1119
Bill Wendlinge8156192006-12-07 01:30:32 +00001120void llvm::WriteBytecodeToFile(const Module *M, OStream &Out,
Chris Lattnerc847f7c2006-07-28 22:07:54 +00001121 bool compress) {
Reid Spencerad89bd62004-07-25 18:07:36 +00001122 assert(M && "You can't write a null module!!");
Chris Lattner00950542001-06-06 20:29:01 +00001123
Reid Spencer32f55532006-06-07 23:18:34 +00001124 // Make sure that std::cout is put into binary mode for systems
1125 // that care.
Bill Wendlinge8156192006-12-07 01:30:32 +00001126 if (Out == cout)
Reid Spencer32f55532006-06-07 23:18:34 +00001127 sys::Program::ChangeStdoutToBinary();
1128
Reid Spencer17f52c52004-11-06 23:17:23 +00001129 // Create a vector of unsigned char for the bytecode output. We
1130 // reserve 256KBytes of space in the vector so that we avoid doing
1131 // lots of little allocations. 256KBytes is sufficient for a large
1132 // proportion of the bytecode files we will encounter. Larger files
1133 // will be automatically doubled in size as needed (std::vector
1134 // behavior).
Reid Spencerad89bd62004-07-25 18:07:36 +00001135 std::vector<unsigned char> Buffer;
Reid Spencer17f52c52004-11-06 23:17:23 +00001136 Buffer.reserve(256 * 1024);
Chris Lattner00950542001-06-06 20:29:01 +00001137
Reid Spencer17f52c52004-11-06 23:17:23 +00001138 // The BytecodeWriter populates Buffer for us.
Reid Spencerad89bd62004-07-25 18:07:36 +00001139 BytecodeWriter BCW(Buffer, M);
Chris Lattner00950542001-06-06 20:29:01 +00001140
Reid Spencer17f52c52004-11-06 23:17:23 +00001141 // Keep track of how much we've written
Chris Lattnerce6ef112002-07-26 18:40:14 +00001142 BytesWritten += Buffer.size();
1143
Reid Spencer17f52c52004-11-06 23:17:23 +00001144 // Determine start and end points of the Buffer
Reid Spencer83296f52004-11-07 18:17:38 +00001145 const unsigned char *FirstByte = &Buffer.front();
Reid Spencer17f52c52004-11-06 23:17:23 +00001146
1147 // If we're supposed to compress this mess ...
1148 if (compress) {
1149
1150 // We signal compression by using an alternate magic number for the
Reid Spencer83296f52004-11-07 18:17:38 +00001151 // file. The compressed bytecode file's magic number is "llvc" instead
Misha Brukman23c6d2c2005-04-21 21:48:46 +00001152 // of "llvm".
Reid Spencer83296f52004-11-07 18:17:38 +00001153 char compressed_magic[4];
1154 compressed_magic[0] = 'l';
1155 compressed_magic[1] = 'l';
1156 compressed_magic[2] = 'v';
1157 compressed_magic[3] = 'c';
Reid Spencer17f52c52004-11-06 23:17:23 +00001158
Bill Wendling68fe61d2006-11-29 00:19:40 +00001159 Out.stream()->write(compressed_magic,4);
Reid Spencer17f52c52004-11-06 23:17:23 +00001160
Reid Spencera70d84d2004-11-14 22:01:41 +00001161 // Compress everything after the magic number (which we altered)
Reid Spencer3ed469c2006-11-02 20:25:50 +00001162 Compressor::compressToStream(
Reid Spencer17f52c52004-11-06 23:17:23 +00001163 (char*)(FirstByte+4), // Skip the magic number
1164 Buffer.size()-4, // Skip the magic number
Bill Wendling68fe61d2006-11-29 00:19:40 +00001165 *Out.stream() // Where to write compressed data
Reid Spencer17f52c52004-11-06 23:17:23 +00001166 );
1167
Reid Spencer17f52c52004-11-06 23:17:23 +00001168 } else {
1169
1170 // We're not compressing, so just write the entire block.
Bill Wendling68fe61d2006-11-29 00:19:40 +00001171 Out.stream()->write((char*)FirstByte, Buffer.size());
Chris Lattnere8fdde12001-09-07 16:39:41 +00001172 }
Reid Spencer17f52c52004-11-06 23:17:23 +00001173
1174 // make sure it hits disk now
Bill Wendling68fe61d2006-11-29 00:19:40 +00001175 Out.stream()->flush();
Chris Lattner00950542001-06-06 20:29:01 +00001176}