blob: 1dd0dc923a5ab1471a4650245463cd4e5c64d68d [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
Reid Spencer91ac04a2007-04-09 06:14:31 +000020#define DEBUG_TYPE "bcwriter"
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"
Reid Spencer91ac04a2007-04-09 06:14:31 +000026#include "llvm/ParameterAttributes.h"
Chris Lattner3bc5a602006-01-25 23:08:15 +000027#include "llvm/InlineAsm.h"
Reid Spencerad89bd62004-07-25 18:07:36 +000028#include "llvm/Instructions.h"
Chris Lattner00950542001-06-06 20:29:01 +000029#include "llvm/Module.h"
Reid Spencer78d033e2007-01-06 07:24:44 +000030#include "llvm/TypeSymbolTable.h"
Reid Spenceref9b9a72007-02-05 20:47:22 +000031#include "llvm/ValueSymbolTable.h"
Reid Spencerad89bd62004-07-25 18:07:36 +000032#include "llvm/Support/GetElementPtrTypeIterator.h"
Reid Spencer17f52c52004-11-06 23:17:23 +000033#include "llvm/Support/Compressor.h"
Jim Laskeycb6682f2005-08-17 19:34:49 +000034#include "llvm/Support/MathExtras.h"
Bill Wendling68fe61d2006-11-29 00:19:40 +000035#include "llvm/Support/Streams.h"
Reid Spencer32f55532006-06-07 23:18:34 +000036#include "llvm/System/Program.h"
Chris Lattnerae052aa2007-02-10 07:31:44 +000037#include "llvm/ADT/SmallVector.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000038#include "llvm/ADT/STLExtras.h"
39#include "llvm/ADT/Statistic.h"
Chris Lattner32abce62004-01-10 19:10:01 +000040#include <cstring>
Chris Lattner00950542001-06-06 20:29:01 +000041#include <algorithm>
Chris Lattner44f549b2004-01-10 18:49:43 +000042using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000043
Reid Spencer38d54be2004-08-17 07:45:14 +000044/// This value needs to be incremented every time the bytecode format changes
45/// so that the reader can distinguish which format of the bytecode file has
46/// been written.
47/// @brief The bytecode version number
Reid Spencer6996feb2006-11-08 21:27:54 +000048const unsigned BCVersionNum = 7;
Reid Spencer38d54be2004-08-17 07:45:14 +000049
Chris Lattner635cd932002-07-23 19:56:44 +000050static RegisterPass<WriteBytecodePass> X("emitbytecode", "Bytecode Writer");
51
Chris Lattner1c560ad2006-12-19 23:16:47 +000052STATISTIC(BytesWritten, "Number of bytecode bytes written");
Chris Lattner635cd932002-07-23 19:56:44 +000053
Reid Spencerad89bd62004-07-25 18:07:36 +000054//===----------------------------------------------------------------------===//
55//=== Output Primitives ===//
56//===----------------------------------------------------------------------===//
57
58// output - If a position is specified, it must be in the valid portion of the
Misha Brukman23c6d2c2005-04-21 21:48:46 +000059// string... note that this should be inlined always so only the relevant IF
Reid Spencerad89bd62004-07-25 18:07:36 +000060// body should be included.
61inline void BytecodeWriter::output(unsigned i, int pos) {
62 if (pos == -1) { // Be endian clean, little endian is our friend
Misha Brukman23c6d2c2005-04-21 21:48:46 +000063 Out.push_back((unsigned char)i);
Reid Spencerad89bd62004-07-25 18:07:36 +000064 Out.push_back((unsigned char)(i >> 8));
65 Out.push_back((unsigned char)(i >> 16));
66 Out.push_back((unsigned char)(i >> 24));
67 } else {
68 Out[pos ] = (unsigned char)i;
69 Out[pos+1] = (unsigned char)(i >> 8);
70 Out[pos+2] = (unsigned char)(i >> 16);
71 Out[pos+3] = (unsigned char)(i >> 24);
72 }
73}
74
Reid Spencer7d003412007-02-09 18:03:35 +000075inline void BytecodeWriter::output(int32_t i) {
76 output((uint32_t)i);
Reid Spencerad89bd62004-07-25 18:07:36 +000077}
78
79/// output_vbr - Output an unsigned value, by using the least number of bytes
80/// possible. This is useful because many of our "infinite" values are really
81/// very small most of the time; but can be large a few times.
Misha Brukman23c6d2c2005-04-21 21:48:46 +000082/// Data format used: If you read a byte with the high bit set, use the low
83/// seven bits as data and then read another byte.
Reid Spencerad89bd62004-07-25 18:07:36 +000084inline void BytecodeWriter::output_vbr(uint64_t i) {
85 while (1) {
86 if (i < 0x80) { // done?
87 Out.push_back((unsigned char)i); // We know the high bit is clear...
88 return;
89 }
Misha Brukman23c6d2c2005-04-21 21:48:46 +000090
Reid Spencerad89bd62004-07-25 18:07:36 +000091 // Nope, we are bigger than a character, output the next 7 bits and set the
92 // high bit to say that there is more coming...
93 Out.push_back(0x80 | ((unsigned char)i & 0x7F));
94 i >>= 7; // Shift out 7 bits now...
95 }
96}
97
Reid Spencer7d003412007-02-09 18:03:35 +000098inline void BytecodeWriter::output_vbr(uint32_t i) {
Reid Spencerad89bd62004-07-25 18:07:36 +000099 while (1) {
100 if (i < 0x80) { // done?
101 Out.push_back((unsigned char)i); // We know the high bit is clear...
102 return;
103 }
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000104
Reid Spencerad89bd62004-07-25 18:07:36 +0000105 // Nope, we are bigger than a character, output the next 7 bits and set the
106 // high bit to say that there is more coming...
107 Out.push_back(0x80 | ((unsigned char)i & 0x7F));
108 i >>= 7; // Shift out 7 bits now...
109 }
110}
111
112inline void BytecodeWriter::output_typeid(unsigned i) {
113 if (i <= 0x00FFFFFF)
114 this->output_vbr(i);
115 else {
116 this->output_vbr(0x00FFFFFF);
117 this->output_vbr(i);
118 }
119}
120
121inline void BytecodeWriter::output_vbr(int64_t i) {
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000122 if (i < 0)
Reid Spencerad89bd62004-07-25 18:07:36 +0000123 output_vbr(((uint64_t)(-i) << 1) | 1); // Set low order sign bit...
124 else
125 output_vbr((uint64_t)i << 1); // Low order bit is clear.
126}
127
128
129inline void BytecodeWriter::output_vbr(int i) {
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000130 if (i < 0)
Reid Spencerad89bd62004-07-25 18:07:36 +0000131 output_vbr(((unsigned)(-i) << 1) | 1); // Set low order sign bit...
132 else
133 output_vbr((unsigned)i << 1); // Low order bit is clear.
134}
135
Chris Lattnerdec628e2007-02-12 05:18:08 +0000136inline void BytecodeWriter::output_str(const char *Str, unsigned Len) {
Chris Lattnerc847f7c2006-07-28 22:07:54 +0000137 output_vbr(Len); // Strings may have an arbitrary length.
Chris Lattnerdec628e2007-02-12 05:18:08 +0000138 Out.insert(Out.end(), Str, Str+Len);
Reid Spencerad89bd62004-07-25 18:07:36 +0000139}
140
141inline void BytecodeWriter::output_data(const void *Ptr, const void *End) {
142 Out.insert(Out.end(), (const unsigned char*)Ptr, (const unsigned char*)End);
143}
144
145inline void BytecodeWriter::output_float(float& FloatVal) {
146 /// FIXME: This isn't optimal, it has size problems on some platforms
147 /// where FP is not IEEE.
Jim Laskeycb6682f2005-08-17 19:34:49 +0000148 uint32_t i = FloatToBits(FloatVal);
Chris Lattnerc847f7c2006-07-28 22:07:54 +0000149 Out.push_back( static_cast<unsigned char>( (i ) & 0xFF));
150 Out.push_back( static_cast<unsigned char>( (i >> 8 ) & 0xFF));
Jim Laskeycb6682f2005-08-17 19:34:49 +0000151 Out.push_back( static_cast<unsigned char>( (i >> 16) & 0xFF));
152 Out.push_back( static_cast<unsigned char>( (i >> 24) & 0xFF));
Reid Spencerad89bd62004-07-25 18:07:36 +0000153}
154
155inline void BytecodeWriter::output_double(double& DoubleVal) {
156 /// FIXME: This isn't optimal, it has size problems on some platforms
157 /// where FP is not IEEE.
Jim Laskeycb6682f2005-08-17 19:34:49 +0000158 uint64_t i = DoubleToBits(DoubleVal);
Chris Lattnerc847f7c2006-07-28 22:07:54 +0000159 Out.push_back( static_cast<unsigned char>( (i ) & 0xFF));
160 Out.push_back( static_cast<unsigned char>( (i >> 8 ) & 0xFF));
Jim Laskeycb6682f2005-08-17 19:34:49 +0000161 Out.push_back( static_cast<unsigned char>( (i >> 16) & 0xFF));
162 Out.push_back( static_cast<unsigned char>( (i >> 24) & 0xFF));
163 Out.push_back( static_cast<unsigned char>( (i >> 32) & 0xFF));
164 Out.push_back( static_cast<unsigned char>( (i >> 40) & 0xFF));
165 Out.push_back( static_cast<unsigned char>( (i >> 48) & 0xFF));
166 Out.push_back( static_cast<unsigned char>( (i >> 56) & 0xFF));
Reid Spencerad89bd62004-07-25 18:07:36 +0000167}
168
Chris Lattnerc76ea432005-11-12 18:34:09 +0000169inline BytecodeBlock::BytecodeBlock(unsigned ID, BytecodeWriter &w,
170 bool elideIfEmpty, bool hasLongFormat)
Reid Spencerad89bd62004-07-25 18:07:36 +0000171 : Id(ID), Writer(w), ElideIfEmpty(elideIfEmpty), HasLongFormat(hasLongFormat){
172
173 if (HasLongFormat) {
174 w.output(ID);
175 w.output(0U); // For length in long format
176 } else {
177 w.output(0U); /// Place holder for ID and length for this block
178 }
179 Loc = w.size();
180}
181
Chris Lattnerb0bf6642004-10-14 01:35:17 +0000182inline BytecodeBlock::~BytecodeBlock() { // Do backpatch when block goes out
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000183 // of scope...
Reid Spencerad89bd62004-07-25 18:07:36 +0000184 if (Loc == Writer.size() && ElideIfEmpty) {
185 // If the block is empty, and we are allowed to, do not emit the block at
186 // all!
187 Writer.resize(Writer.size()-(HasLongFormat?8:4));
188 return;
189 }
190
Reid Spencerad89bd62004-07-25 18:07:36 +0000191 if (HasLongFormat)
192 Writer.output(unsigned(Writer.size()-Loc), int(Loc-4));
193 else
194 Writer.output(unsigned(Writer.size()-Loc) << 5 | (Id & 0x1F), int(Loc-4));
Reid Spencerad89bd62004-07-25 18:07:36 +0000195}
196
197//===----------------------------------------------------------------------===//
198//=== Constant Output ===//
199//===----------------------------------------------------------------------===//
200
Reid Spencer91ac04a2007-04-09 06:14:31 +0000201void BytecodeWriter::outputParamAttrsList(const ParamAttrsList *Attrs) {
202 if (!Attrs) {
203 output_vbr(unsigned(0));
204 return;
205 }
206 unsigned numAttrs = Attrs->size();
207 output_vbr(numAttrs);
208 for (unsigned i = 0; i < numAttrs; ++i) {
209 uint16_t index = Attrs->getParamIndex(i);
210 uint16_t attrs = Attrs->getParamAttrs(index);
211 output_vbr(uint32_t(index));
212 output_vbr(uint32_t(attrs));
213 }
214}
215
Reid Spencerad89bd62004-07-25 18:07:36 +0000216void BytecodeWriter::outputType(const Type *T) {
Andrew Lenharth38ecbf12006-12-08 18:06:16 +0000217 const StructType* STy = dyn_cast<StructType>(T);
218 if(STy && STy->isPacked())
Reid Spencera54b7cb2007-01-12 07:05:14 +0000219 output_vbr((unsigned)Type::PackedStructTyID);
Andrew Lenharth38ecbf12006-12-08 18:06:16 +0000220 else
221 output_vbr((unsigned)T->getTypeID());
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000222
Reid Spencerad89bd62004-07-25 18:07:36 +0000223 // That's all there is to handling primitive types...
Reid Spencera54b7cb2007-01-12 07:05:14 +0000224 if (T->isPrimitiveType())
Reid Spencerad89bd62004-07-25 18:07:36 +0000225 return; // We might do this if we alias a prim type: %x = type int
Reid Spencerad89bd62004-07-25 18:07:36 +0000226
227 switch (T->getTypeID()) { // Handle derived types now.
Reid Spencera54b7cb2007-01-12 07:05:14 +0000228 case Type::IntegerTyID:
229 output_vbr(cast<IntegerType>(T)->getBitWidth());
230 break;
Reid Spencerad89bd62004-07-25 18:07:36 +0000231 case Type::FunctionTyID: {
Reid Spencer91ac04a2007-04-09 06:14:31 +0000232 const FunctionType *FT = cast<FunctionType>(T);
233 output_typeid(Table.getTypeSlot(FT->getReturnType()));
Reid Spencerad89bd62004-07-25 18:07:36 +0000234
235 // Output the number of arguments to function (+1 if varargs):
Reid Spencer91ac04a2007-04-09 06:14:31 +0000236 output_vbr((unsigned)FT->getNumParams()+FT->isVarArg());
Reid Spencerad89bd62004-07-25 18:07:36 +0000237
238 // Output all of the arguments...
Reid Spencer91ac04a2007-04-09 06:14:31 +0000239 FunctionType::param_iterator I = FT->param_begin();
240 for (; I != FT->param_end(); ++I)
Chris Lattner972b4dc2007-02-10 05:17:48 +0000241 output_typeid(Table.getTypeSlot(*I));
Reid Spencerad89bd62004-07-25 18:07:36 +0000242
243 // Terminate list with VoidTy if we are a varargs function...
Reid Spencer91ac04a2007-04-09 06:14:31 +0000244 if (FT->isVarArg())
Reid Spencerad89bd62004-07-25 18:07:36 +0000245 output_typeid((unsigned)Type::VoidTyID);
Reid Spencer91ac04a2007-04-09 06:14:31 +0000246
247 // Put out all the parameter attributes
248 outputParamAttrsList(FT->getParamAttrs());
Reid Spencerad89bd62004-07-25 18:07:36 +0000249 break;
250 }
251
252 case Type::ArrayTyID: {
253 const ArrayType *AT = cast<ArrayType>(T);
Chris Lattner972b4dc2007-02-10 05:17:48 +0000254 output_typeid(Table.getTypeSlot(AT->getElementType()));
Reid Spencerad89bd62004-07-25 18:07:36 +0000255 output_vbr(AT->getNumElements());
256 break;
257 }
258
Reid Spencer9d6565a2007-02-15 02:26:10 +0000259 case Type::VectorTyID: {
260 const VectorType *PT = cast<VectorType>(T);
Chris Lattner972b4dc2007-02-10 05:17:48 +0000261 output_typeid(Table.getTypeSlot(PT->getElementType()));
Brian Gaeke715c90b2004-08-20 06:00:58 +0000262 output_vbr(PT->getNumElements());
263 break;
264 }
265
Reid Spencerad89bd62004-07-25 18:07:36 +0000266 case Type::StructTyID: {
267 const StructType *ST = cast<StructType>(T);
Reid Spencerad89bd62004-07-25 18:07:36 +0000268 // Output all of the element types...
269 for (StructType::element_iterator I = ST->element_begin(),
270 E = ST->element_end(); I != E; ++I) {
Chris Lattner972b4dc2007-02-10 05:17:48 +0000271 output_typeid(Table.getTypeSlot(*I));
Reid Spencerad89bd62004-07-25 18:07:36 +0000272 }
273
274 // Terminate list with VoidTy
275 output_typeid((unsigned)Type::VoidTyID);
276 break;
277 }
278
Chris Lattner972b4dc2007-02-10 05:17:48 +0000279 case Type::PointerTyID:
280 output_typeid(Table.getTypeSlot(cast<PointerType>(T)->getElementType()));
Reid Spencerad89bd62004-07-25 18:07:36 +0000281 break;
Reid Spencerad89bd62004-07-25 18:07:36 +0000282
Chris Lattnerb0bf6642004-10-14 01:35:17 +0000283 case Type::OpaqueTyID:
Reid Spencerad89bd62004-07-25 18:07:36 +0000284 // No need to emit anything, just the count of opaque types is enough.
285 break;
Reid Spencerad89bd62004-07-25 18:07:36 +0000286
Reid Spencerad89bd62004-07-25 18:07:36 +0000287 default:
Bill Wendlinge8156192006-12-07 01:30:32 +0000288 cerr << __FILE__ << ":" << __LINE__ << ": Don't know how to serialize"
289 << " Type '" << T->getDescription() << "'\n";
Reid Spencerad89bd62004-07-25 18:07:36 +0000290 break;
291 }
292}
293
294void BytecodeWriter::outputConstant(const Constant *CPV) {
Chris Lattner42a75512007-01-15 02:27:26 +0000295 assert(((CPV->getType()->isPrimitiveType() || CPV->getType()->isInteger()) ||
Reid Spencera54b7cb2007-01-12 07:05:14 +0000296 !CPV->isNullValue()) && "Shouldn't output null constants!");
Reid Spencerad89bd62004-07-25 18:07:36 +0000297
298 // We must check for a ConstantExpr before switching by type because
299 // a ConstantExpr can be of any type, and has no explicit value.
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000300 //
Reid Spencerad89bd62004-07-25 18:07:36 +0000301 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
302 // FIXME: Encoding of constant exprs could be much more compact!
303 assert(CE->getNumOperands() > 0 && "ConstantExpr with 0 operands");
Reid Spencer3da59db2006-11-27 01:05:10 +0000304 assert(CE->getNumOperands() != 1 || CE->isCast());
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000305 output_vbr(1+CE->getNumOperands()); // flags as an expr
Reid Spencerb83eb642006-10-20 07:07:24 +0000306 output_vbr(CE->getOpcode()); // Put out the CE op code
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000307
Reid Spencerad89bd62004-07-25 18:07:36 +0000308 for (User::const_op_iterator OI = CE->op_begin(); OI != CE->op_end(); ++OI){
Chris Lattner972b4dc2007-02-10 05:17:48 +0000309 output_vbr(Table.getSlot(*OI));
310 output_typeid(Table.getTypeSlot((*OI)->getType()));
Reid Spencerad89bd62004-07-25 18:07:36 +0000311 }
Reid Spencer595b4772006-12-04 05:23:49 +0000312 if (CE->isCompare())
313 output_vbr((unsigned)CE->getPredicate());
Reid Spencerad89bd62004-07-25 18:07:36 +0000314 return;
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000315 } else if (isa<UndefValue>(CPV)) {
316 output_vbr(1U); // 1 -> UndefValue constant.
317 return;
Reid Spencerad89bd62004-07-25 18:07:36 +0000318 } else {
Reid Spencerb83eb642006-10-20 07:07:24 +0000319 output_vbr(0U); // flag as not a ConstantExpr (i.e. 0 operands)
Reid Spencerad89bd62004-07-25 18:07:36 +0000320 }
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000321
Reid Spencerad89bd62004-07-25 18:07:36 +0000322 switch (CPV->getType()->getTypeID()) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000323 case Type::IntegerTyID: { // Integer types...
Reid Spencer9abd1382007-02-28 02:25:20 +0000324 const ConstantInt *CI = cast<ConstantInt>(CPV);
Reid Spencera54b7cb2007-01-12 07:05:14 +0000325 unsigned NumBits = cast<IntegerType>(CPV->getType())->getBitWidth();
Chris Lattnerfb939312007-01-12 23:26:17 +0000326 if (NumBits <= 32)
Reid Spencer9abd1382007-02-28 02:25:20 +0000327 output_vbr(uint32_t(CI->getZExtValue()));
Reid Spencera54b7cb2007-01-12 07:05:14 +0000328 else if (NumBits <= 64)
Reid Spencer9abd1382007-02-28 02:25:20 +0000329 output_vbr(uint64_t(CI->getZExtValue()));
330 else {
331 // We have an arbitrary precision integer value to write whose
332 // bit width is > 64. However, in canonical unsigned integer
333 // format it is likely that the high bits are going to be zero.
334 // So, we only write the number of active words.
335 uint32_t activeWords = CI->getValue().getActiveWords();
336 const uint64_t *rawData = CI->getValue().getRawData();
337 output_vbr(activeWords);
338 for (uint32_t i = 0; i < activeWords; ++i)
339 output_vbr(rawData[i]);
340 }
Reid Spencerad89bd62004-07-25 18:07:36 +0000341 break;
Reid Spencera54b7cb2007-01-12 07:05:14 +0000342 }
Reid Spencerad89bd62004-07-25 18:07:36 +0000343
Reid Spencerad89bd62004-07-25 18:07:36 +0000344 case Type::ArrayTyID: {
345 const ConstantArray *CPA = cast<ConstantArray>(CPV);
346 assert(!CPA->isString() && "Constant strings should be handled specially!");
347
Chris Lattnera2bdad42007-02-10 05:13:03 +0000348 for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
349 output_vbr(Table.getSlot(CPA->getOperand(i)));
Reid Spencerad89bd62004-07-25 18:07:36 +0000350 break;
351 }
352
Reid Spencer9d6565a2007-02-15 02:26:10 +0000353 case Type::VectorTyID: {
354 const ConstantVector *CP = cast<ConstantVector>(CPV);
Chris Lattnera2bdad42007-02-10 05:13:03 +0000355 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
356 output_vbr(Table.getSlot(CP->getOperand(i)));
Brian Gaeke715c90b2004-08-20 06:00:58 +0000357 break;
358 }
359
Reid Spencerad89bd62004-07-25 18:07:36 +0000360 case Type::StructTyID: {
361 const ConstantStruct *CPS = cast<ConstantStruct>(CPV);
Reid Spencerad89bd62004-07-25 18:07:36 +0000362
Chris Lattnera2bdad42007-02-10 05:13:03 +0000363 for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
364 output_vbr(Table.getSlot(CPS->getOperand(i)));
Reid Spencerad89bd62004-07-25 18:07:36 +0000365 break;
366 }
367
368 case Type::PointerTyID:
369 assert(0 && "No non-null, non-constant-expr constants allowed!");
370 abort();
371
372 case Type::FloatTyID: { // Floating point types...
373 float Tmp = (float)cast<ConstantFP>(CPV)->getValue();
374 output_float(Tmp);
375 break;
376 }
377 case Type::DoubleTyID: {
378 double Tmp = cast<ConstantFP>(CPV)->getValue();
379 output_double(Tmp);
380 break;
381 }
382
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000383 case Type::VoidTyID:
Reid Spencerad89bd62004-07-25 18:07:36 +0000384 case Type::LabelTyID:
385 default:
Bill Wendlinge8156192006-12-07 01:30:32 +0000386 cerr << __FILE__ << ":" << __LINE__ << ": Don't know how to serialize"
387 << " type '" << *CPV->getType() << "'\n";
Reid Spencerad89bd62004-07-25 18:07:36 +0000388 break;
389 }
390 return;
391}
392
Chris Lattner3bc5a602006-01-25 23:08:15 +0000393/// outputInlineAsm - InlineAsm's get emitted to the constant pool, so they can
394/// be shared by multiple uses.
395void BytecodeWriter::outputInlineAsm(const InlineAsm *IA) {
396 // Output a marker, so we know when we have one one parsing the constant pool.
397 // Note that this encoding is 5 bytes: not very efficient for a marker. Since
398 // unique inline asms are rare, this should hardly matter.
399 output_vbr(~0U);
400
401 output(IA->getAsmString());
402 output(IA->getConstraintString());
403 output_vbr(unsigned(IA->hasSideEffects()));
404}
405
Reid Spencerad89bd62004-07-25 18:07:36 +0000406void BytecodeWriter::outputConstantStrings() {
407 SlotCalculator::string_iterator I = Table.string_begin();
408 SlotCalculator::string_iterator E = Table.string_end();
409 if (I == E) return; // No strings to emit
410
411 // If we have != 0 strings to emit, output them now. Strings are emitted into
412 // the 'void' type plane.
413 output_vbr(unsigned(E-I));
414 output_typeid(Type::VoidTyID);
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000415
Reid Spencerad89bd62004-07-25 18:07:36 +0000416 // Emit all of the strings.
417 for (I = Table.string_begin(); I != E; ++I) {
418 const ConstantArray *Str = *I;
Chris Lattner972b4dc2007-02-10 05:17:48 +0000419 output_typeid(Table.getTypeSlot(Str->getType()));
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000420
Reid Spencerad89bd62004-07-25 18:07:36 +0000421 // Now that we emitted the type (which indicates the size of the string),
422 // emit all of the characters.
423 std::string Val = Str->getAsString();
424 output_data(Val.c_str(), Val.c_str()+Val.size());
425 }
426}
427
428//===----------------------------------------------------------------------===//
429//=== Instruction Output ===//
430//===----------------------------------------------------------------------===//
Reid Spencerad89bd62004-07-25 18:07:36 +0000431
Chris Lattnerda895d62005-02-27 06:18:25 +0000432// outputInstructionFormat0 - Output those weird instructions that have a large
Chris Lattnerdee199f2005-05-06 22:34:01 +0000433// number of operands or have large operands themselves.
Reid Spencerad89bd62004-07-25 18:07:36 +0000434//
435// Format: [opcode] [type] [numargs] [arg0] [arg1] ... [arg<numargs-1>]
436//
Chris Lattnerf9d71782004-10-14 01:46:07 +0000437void BytecodeWriter::outputInstructionFormat0(const Instruction *I,
438 unsigned Opcode,
439 const SlotCalculator &Table,
440 unsigned Type) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000441 // Opcode must have top two bits clear...
442 output_vbr(Opcode << 2); // Instruction Opcode ID
443 output_typeid(Type); // Result type
444
445 unsigned NumArgs = I->getNumOperands();
Chris Lattner39a6a362007-04-09 03:37:36 +0000446 bool HasExtraArg = false;
447 if (isa<CastInst>(I) || isa<InvokeInst>(I) ||
448 isa<CmpInst>(I) || isa<VAArgInst>(I) || Opcode == 58)
449 HasExtraArg = true;
450 if (const AllocationInst *AI = dyn_cast<AllocationInst>(I))
451 HasExtraArg = AI->getAlignment() != 0;
452
453 output_vbr(NumArgs + HasExtraArg);
Reid Spencerad89bd62004-07-25 18:07:36 +0000454
455 if (!isa<GetElementPtrInst>(&I)) {
Chris Lattnera2bdad42007-02-10 05:13:03 +0000456 for (unsigned i = 0; i < NumArgs; ++i)
457 output_vbr(Table.getSlot(I->getOperand(i)));
Reid Spencerad89bd62004-07-25 18:07:36 +0000458
459 if (isa<CastInst>(I) || isa<VAArgInst>(I)) {
Chris Lattner972b4dc2007-02-10 05:17:48 +0000460 output_typeid(Table.getTypeSlot(I->getType()));
Reid Spencercae60532006-12-06 04:27:07 +0000461 } else if (isa<CmpInst>(I)) {
462 output_vbr(unsigned(cast<CmpInst>(I)->getPredicate()));
Reid Spencer3da59db2006-11-27 01:05:10 +0000463 } else if (isa<InvokeInst>(I)) {
Chris Lattnerdee199f2005-05-06 22:34:01 +0000464 output_vbr(cast<InvokeInst>(I)->getCallingConv());
465 } else if (Opcode == 58) { // Call escape sequence
466 output_vbr((cast<CallInst>(I)->getCallingConv() << 1) |
Jeff Cohen39cef602005-05-07 02:44:04 +0000467 unsigned(cast<CallInst>(I)->isTailCall()));
Chris Lattner39a6a362007-04-09 03:37:36 +0000468 } else if (const AllocationInst *AI = dyn_cast<AllocationInst>(I)) {
469 if (AI->getAlignment())
470 output_vbr((unsigned)Log2_32(AI->getAlignment())+1);
Reid Spencerad89bd62004-07-25 18:07:36 +0000471 }
Reid Spencerad89bd62004-07-25 18:07:36 +0000472 } else {
Chris Lattnera2bdad42007-02-10 05:13:03 +0000473 output_vbr(Table.getSlot(I->getOperand(0)));
Reid Spencerad89bd62004-07-25 18:07:36 +0000474
475 // We need to encode the type of sequential type indices into their slot #
476 unsigned Idx = 1;
477 for (gep_type_iterator TI = gep_type_begin(I), E = gep_type_end(I);
478 Idx != NumArgs; ++TI, ++Idx) {
Chris Lattnera2bdad42007-02-10 05:13:03 +0000479 unsigned Slot = Table.getSlot(I->getOperand(Idx));
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000480
Reid Spencerad89bd62004-07-25 18:07:36 +0000481 if (isa<SequentialType>(*TI)) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000482 // These should be either 32-bits or 64-bits, however, with bit
483 // accurate types we just distinguish between less than or equal to
484 // 32-bits or greater than 32-bits.
Reid Spencer790366b2007-01-13 00:10:02 +0000485 unsigned BitWidth =
486 cast<IntegerType>(I->getOperand(Idx)->getType())->getBitWidth();
487 assert(BitWidth == 32 || BitWidth == 64 &&
488 "Invalid bitwidth for GEP index");
489 unsigned IdxId = BitWidth == 32 ? 0 : 1;
Reid Spencer88cfda22006-12-31 05:44:24 +0000490 Slot = (Slot << 1) | IdxId;
Reid Spencerad89bd62004-07-25 18:07:36 +0000491 }
Chris Lattnera2bdad42007-02-10 05:13:03 +0000492 output_vbr(Slot);
Reid Spencerad89bd62004-07-25 18:07:36 +0000493 }
494 }
Reid Spencerad89bd62004-07-25 18:07:36 +0000495}
496
497
498// outputInstrVarArgsCall - Output the absurdly annoying varargs function calls.
499// This are more annoying than most because the signature of the call does not
500// tell us anything about the types of the arguments in the varargs portion.
501// Because of this, we encode (as type 0) all of the argument types explicitly
502// before the argument value. This really sucks, but you shouldn't be using
503// varargs functions in your code! *death to printf*!
504//
505// Format: [opcode] [type] [numargs] [arg0] [arg1] ... [arg<numargs-1>]
506//
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000507void BytecodeWriter::outputInstrVarArgsCall(const Instruction *I,
508 unsigned Opcode,
509 const SlotCalculator &Table,
510 unsigned Type) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000511 assert(isa<CallInst>(I) || isa<InvokeInst>(I));
512 // Opcode must have top two bits clear...
513 output_vbr(Opcode << 2); // Instruction Opcode ID
514 output_typeid(Type); // Result type (varargs type)
515
516 const PointerType *PTy = cast<PointerType>(I->getOperand(0)->getType());
517 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
518 unsigned NumParams = FTy->getNumParams();
519
520 unsigned NumFixedOperands;
521 if (isa<CallInst>(I)) {
522 // Output an operand for the callee and each fixed argument, then two for
523 // each variable argument.
524 NumFixedOperands = 1+NumParams;
525 } else {
526 assert(isa<InvokeInst>(I) && "Not call or invoke??");
527 // Output an operand for the callee and destinations, then two for each
528 // variable argument.
529 NumFixedOperands = 3+NumParams;
530 }
Reid Spencer3da59db2006-11-27 01:05:10 +0000531 output_vbr(2 * I->getNumOperands()-NumFixedOperands +
532 unsigned(Opcode == 58 || isa<InvokeInst>(I)));
Reid Spencerad89bd62004-07-25 18:07:36 +0000533
534 // The type for the function has already been emitted in the type field of the
535 // instruction. Just emit the slot # now.
Chris Lattnera2bdad42007-02-10 05:13:03 +0000536 for (unsigned i = 0; i != NumFixedOperands; ++i)
537 output_vbr(Table.getSlot(I->getOperand(i)));
Reid Spencerad89bd62004-07-25 18:07:36 +0000538
539 for (unsigned i = NumFixedOperands, e = I->getNumOperands(); i != e; ++i) {
540 // Output Arg Type ID
Chris Lattner972b4dc2007-02-10 05:17:48 +0000541 output_typeid(Table.getTypeSlot(I->getOperand(i)->getType()));
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000542
Reid Spencerad89bd62004-07-25 18:07:36 +0000543 // Output arg ID itself
Chris Lattnera2bdad42007-02-10 05:13:03 +0000544 output_vbr(Table.getSlot(I->getOperand(i)));
Reid Spencerad89bd62004-07-25 18:07:36 +0000545 }
Chris Lattnera65371e2006-05-26 18:42:34 +0000546
Reid Spencer3da59db2006-11-27 01:05:10 +0000547 if (isa<InvokeInst>(I)) {
548 // Emit the tail call/calling conv for invoke instructions
549 output_vbr(cast<InvokeInst>(I)->getCallingConv());
550 } else if (Opcode == 58) {
Chris Lattnera65371e2006-05-26 18:42:34 +0000551 const CallInst *CI = cast<CallInst>(I);
552 output_vbr((CI->getCallingConv() << 1) | unsigned(CI->isTailCall()));
Chris Lattnera65371e2006-05-26 18:42:34 +0000553 }
Reid Spencerad89bd62004-07-25 18:07:36 +0000554}
555
556
557// outputInstructionFormat1 - Output one operand instructions, knowing that no
558// operand index is >= 2^12.
559//
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000560inline void BytecodeWriter::outputInstructionFormat1(const Instruction *I,
561 unsigned Opcode,
562 unsigned *Slots,
563 unsigned Type) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000564 // bits Instruction format:
565 // --------------------------
566 // 01-00: Opcode type, fixed to 1.
567 // 07-02: Opcode
568 // 19-08: Resulting type plane
569 // 31-20: Operand #1 (if set to (2^12-1), then zero operands)
570 //
Chris Lattnerf9d71782004-10-14 01:46:07 +0000571 output(1 | (Opcode << 2) | (Type << 8) | (Slots[0] << 20));
Reid Spencerad89bd62004-07-25 18:07:36 +0000572}
573
574
575// outputInstructionFormat2 - Output two operand instructions, knowing that no
576// operand index is >= 2^8.
577//
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000578inline void BytecodeWriter::outputInstructionFormat2(const Instruction *I,
579 unsigned Opcode,
580 unsigned *Slots,
581 unsigned Type) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000582 // bits Instruction format:
583 // --------------------------
584 // 01-00: Opcode type, fixed to 2.
585 // 07-02: Opcode
586 // 15-08: Resulting type plane
587 // 23-16: Operand #1
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000588 // 31-24: Operand #2
Reid Spencerad89bd62004-07-25 18:07:36 +0000589 //
Chris Lattnerf9d71782004-10-14 01:46:07 +0000590 output(2 | (Opcode << 2) | (Type << 8) | (Slots[0] << 16) | (Slots[1] << 24));
Reid Spencerad89bd62004-07-25 18:07:36 +0000591}
592
593
594// outputInstructionFormat3 - Output three operand instructions, knowing that no
595// operand index is >= 2^6.
596//
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000597inline void BytecodeWriter::outputInstructionFormat3(const Instruction *I,
Reid Spencerad89bd62004-07-25 18:07:36 +0000598 unsigned Opcode,
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000599 unsigned *Slots,
600 unsigned Type) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000601 // bits Instruction format:
602 // --------------------------
603 // 01-00: Opcode type, fixed to 3.
604 // 07-02: Opcode
605 // 13-08: Resulting type plane
606 // 19-14: Operand #1
607 // 25-20: Operand #2
608 // 31-26: Operand #3
609 //
Chris Lattnerf9d71782004-10-14 01:46:07 +0000610 output(3 | (Opcode << 2) | (Type << 8) |
Chris Lattner84d1ced2004-10-14 01:57:28 +0000611 (Slots[0] << 14) | (Slots[1] << 20) | (Slots[2] << 26));
Reid Spencerad89bd62004-07-25 18:07:36 +0000612}
613
614void BytecodeWriter::outputInstruction(const Instruction &I) {
Reid Spencer3da59db2006-11-27 01:05:10 +0000615 assert(I.getOpcode() < 57 && "Opcode too big???");
Reid Spencerad89bd62004-07-25 18:07:36 +0000616 unsigned Opcode = I.getOpcode();
617 unsigned NumOperands = I.getNumOperands();
618
Christopher Lamb2330e4d2007-04-21 08:16:25 +0000619 // Encode 'tail call' as 61
Chris Lattner38287bd2005-05-06 06:13:34 +0000620 // 63.
Chris Lattnerdee199f2005-05-06 22:34:01 +0000621 if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
622 if (CI->getCallingConv() == CallingConv::C) {
623 if (CI->isTailCall())
624 Opcode = 61; // CCC + Tail Call
625 else
626 ; // Opcode = Instruction::Call
627 } else if (CI->getCallingConv() == CallingConv::Fast) {
628 if (CI->isTailCall())
629 Opcode = 59; // FastCC + TailCall
630 else
631 Opcode = 60; // FastCC + Not Tail Call
632 } else {
633 Opcode = 58; // Call escape sequence.
634 }
Chris Lattnerdee199f2005-05-06 22:34:01 +0000635 }
Reid Spencerad89bd62004-07-25 18:07:36 +0000636
637 // Figure out which type to encode with the instruction. Typically we want
638 // the type of the first parameter, as opposed to the type of the instruction
639 // (for example, with setcc, we always know it returns bool, but the type of
640 // the first param is actually interesting). But if we have no arguments
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000641 // we take the type of the instruction itself.
Reid Spencerad89bd62004-07-25 18:07:36 +0000642 //
643 const Type *Ty;
644 switch (I.getOpcode()) {
645 case Instruction::Select:
646 case Instruction::Malloc:
647 case Instruction::Alloca:
648 Ty = I.getType(); // These ALWAYS want to encode the return type
649 break;
650 case Instruction::Store:
651 Ty = I.getOperand(1)->getType(); // Encode the pointer type...
652 assert(isa<PointerType>(Ty) && "Store to nonpointer type!?!?");
653 break;
654 default: // Otherwise use the default behavior...
655 Ty = NumOperands ? I.getOperand(0)->getType() : I.getType();
656 break;
657 }
658
Chris Lattner972b4dc2007-02-10 05:17:48 +0000659 unsigned Type = Table.getTypeSlot(Ty);
Reid Spencerad89bd62004-07-25 18:07:36 +0000660
661 // Varargs calls and invokes are encoded entirely different from any other
662 // instructions.
663 if (const CallInst *CI = dyn_cast<CallInst>(&I)){
664 const PointerType *Ty =cast<PointerType>(CI->getCalledValue()->getType());
665 if (cast<FunctionType>(Ty->getElementType())->isVarArg()) {
666 outputInstrVarArgsCall(CI, Opcode, Table, Type);
667 return;
668 }
669 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
670 const PointerType *Ty =cast<PointerType>(II->getCalledValue()->getType());
671 if (cast<FunctionType>(Ty->getElementType())->isVarArg()) {
672 outputInstrVarArgsCall(II, Opcode, Table, Type);
673 return;
674 }
675 }
676
677 if (NumOperands <= 3) {
678 // Make sure that we take the type number into consideration. We don't want
679 // to overflow the field size for the instruction format we select.
680 //
681 unsigned MaxOpSlot = Type;
682 unsigned Slots[3]; Slots[0] = (1 << 12)-1; // Marker to signify 0 operands
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000683
Reid Spencerad89bd62004-07-25 18:07:36 +0000684 for (unsigned i = 0; i != NumOperands; ++i) {
Chris Lattnera2bdad42007-02-10 05:13:03 +0000685 unsigned Slot = Table.getSlot(I.getOperand(i));
686 if (Slot > MaxOpSlot) MaxOpSlot = Slot;
687 Slots[i] = Slot;
Reid Spencerad89bd62004-07-25 18:07:36 +0000688 }
689
690 // Handle the special cases for various instructions...
691 if (isa<CastInst>(I) || isa<VAArgInst>(I)) {
692 // Cast has to encode the destination type as the second argument in the
693 // packet, or else we won't know what type to cast to!
Chris Lattnercb43fdc2007-02-10 04:15:40 +0000694 Slots[1] = Table.getTypeSlot(I.getType());
Reid Spencerad89bd62004-07-25 18:07:36 +0000695 if (Slots[1] > MaxOpSlot) MaxOpSlot = Slots[1];
696 NumOperands++;
Chris Lattner42ba6b42005-11-05 22:08:14 +0000697 } else if (const AllocationInst *AI = dyn_cast<AllocationInst>(&I)) {
698 assert(NumOperands == 1 && "Bogus allocation!");
699 if (AI->getAlignment()) {
700 Slots[1] = Log2_32(AI->getAlignment())+1;
701 if (Slots[1] > MaxOpSlot) MaxOpSlot = Slots[1];
702 NumOperands = 2;
703 }
Reid Spencerc8dab492006-12-03 06:28:54 +0000704 } else if (isa<ICmpInst>(I) || isa<FCmpInst>(I)) {
705 // We need to encode the compare instruction's predicate as the third
706 // operand. Its not really a slot, but we don't want to break the
707 // instruction format for these instructions.
708 NumOperands++;
709 assert(NumOperands == 3 && "CmpInst with wrong number of operands?");
710 Slots[2] = unsigned(cast<CmpInst>(&I)->getPredicate());
711 if (Slots[2] > MaxOpSlot)
712 MaxOpSlot = Slots[2];
Reid Spencerad89bd62004-07-25 18:07:36 +0000713 } else if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&I)) {
714 // We need to encode the type of sequential type indices into their slot #
715 unsigned Idx = 1;
716 for (gep_type_iterator I = gep_type_begin(GEP), E = gep_type_end(GEP);
717 I != E; ++I, ++Idx)
718 if (isa<SequentialType>(*I)) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000719 // These should be either 32-bits or 64-bits, however, with bit
720 // accurate types we just distinguish between less than or equal to
721 // 32-bits or greater than 32-bits.
Reid Spencer790366b2007-01-13 00:10:02 +0000722 unsigned BitWidth =
723 cast<IntegerType>(GEP->getOperand(Idx)->getType())->getBitWidth();
724 assert(BitWidth == 32 || BitWidth == 64 &&
725 "Invalid bitwidth for GEP index");
726 unsigned IdxId = BitWidth == 32 ? 0 : 1;
Reid Spencer88cfda22006-12-31 05:44:24 +0000727 Slots[Idx] = (Slots[Idx] << 1) | IdxId;
Reid Spencerad89bd62004-07-25 18:07:36 +0000728 if (Slots[Idx] > MaxOpSlot) MaxOpSlot = Slots[Idx];
729 }
Chris Lattnerdee199f2005-05-06 22:34:01 +0000730 } else if (Opcode == 58) {
731 // If this is the escape sequence for call, emit the tailcall/cc info.
732 const CallInst &CI = cast<CallInst>(I);
733 ++NumOperands;
Chris Lattnerebf8e6c2006-05-19 21:57:37 +0000734 if (NumOperands <= 3) {
735 Slots[NumOperands-1] =
736 (CI.getCallingConv() << 1)|unsigned(CI.isTailCall());
Chris Lattnerdee199f2005-05-06 22:34:01 +0000737 if (Slots[NumOperands-1] > MaxOpSlot)
738 MaxOpSlot = Slots[NumOperands-1];
739 }
Reid Spencer3da59db2006-11-27 01:05:10 +0000740 } else if (isa<InvokeInst>(I)) {
Chris Lattnerdee199f2005-05-06 22:34:01 +0000741 // Invoke escape seq has at least 4 operands to encode.
742 ++NumOperands;
Christopher Lamb2330e4d2007-04-21 08:16:25 +0000743 } else if (const LoadInst *LI = dyn_cast<LoadInst>(&I)) {
744 // Encode attributed load as opcode 62
745 // We need to encode the attributes of the load instruction as the second
746 // operand. Its not really a slot, but we don't want to break the
747 // instruction format for these instructions.
748 if (LI->getAlignment() || LI->isVolatile()) {
749 NumOperands = 2;
750 Slots[1] = ((Log2_32(LI->getAlignment())+1)<<1) +
751 (LI->isVolatile() ? 1 : 0);
752 if (Slots[1] > MaxOpSlot)
753 MaxOpSlot = Slots[1];
754 Opcode = 62;
755 }
756 } else if (const StoreInst *SI = dyn_cast<StoreInst>(&I)) {
757 // Encode attributed store as opcode 63
758 // We need to encode the attributes of the store instruction as the third
759 // operand. Its not really a slot, but we don't want to break the
760 // instruction format for these instructions.
761 if (SI->getAlignment() || SI->isVolatile()) {
762 NumOperands = 3;
763 Slots[2] = ((Log2_32(SI->getAlignment())+1)<<1) +
764 (SI->isVolatile() ? 1 : 0);
765 if (Slots[2] > MaxOpSlot)
766 MaxOpSlot = Slots[2];
767 Opcode = 63;
768 }
Reid Spencerad89bd62004-07-25 18:07:36 +0000769 }
770
771 // Decide which instruction encoding to use. This is determined primarily
772 // by the number of operands, and secondarily by whether or not the max
773 // operand will fit into the instruction encoding. More operands == fewer
774 // bits per operand.
775 //
776 switch (NumOperands) {
777 case 0:
778 case 1:
779 if (MaxOpSlot < (1 << 12)-1) { // -1 because we use 4095 to indicate 0 ops
780 outputInstructionFormat1(&I, Opcode, Slots, Type);
781 return;
782 }
783 break;
784
785 case 2:
786 if (MaxOpSlot < (1 << 8)) {
787 outputInstructionFormat2(&I, Opcode, Slots, Type);
788 return;
789 }
790 break;
791
792 case 3:
793 if (MaxOpSlot < (1 << 6)) {
794 outputInstructionFormat3(&I, Opcode, Slots, Type);
795 return;
796 }
797 break;
798 default:
799 break;
800 }
801 }
802
803 // If we weren't handled before here, we either have a large number of
804 // operands or a large operand index that we are referring to.
805 outputInstructionFormat0(&I, Opcode, Table, Type);
806}
807
808//===----------------------------------------------------------------------===//
809//=== Block Output ===//
810//===----------------------------------------------------------------------===//
811
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000812BytecodeWriter::BytecodeWriter(std::vector<unsigned char> &o, const Module *M)
Reid Spencer798ff642004-05-26 07:37:11 +0000813 : Out(o), Table(M) {
Chris Lattner00950542001-06-06 20:29:01 +0000814
Chris Lattner83bb3d22004-01-14 23:36:54 +0000815 // Emit the signature...
Chris Lattnerc847f7c2006-07-28 22:07:54 +0000816 static const unsigned char *Sig = (const unsigned char*)"llvm";
Reid Spencerad89bd62004-07-25 18:07:36 +0000817 output_data(Sig, Sig+4);
Chris Lattner00950542001-06-06 20:29:01 +0000818
819 // Emit the top level CLASS block.
Reid Spencerad89bd62004-07-25 18:07:36 +0000820 BytecodeBlock ModuleBlock(BytecodeFormat::ModuleBlockID, *this, false, true);
Chris Lattner00950542001-06-06 20:29:01 +0000821
Reid Spenceraacc35a2007-01-26 08:10:24 +0000822 // Output the version identifier
823 output_vbr(BCVersionNum);
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
Chris Lattner8dcd81c2007-02-09 07:53:20 +0000835 outputConstants();
Chris Lattner186a1f72003-03-19 20:56:46 +0000836
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//
Chris Lattner863da4c2007-02-10 07:42:59 +0000869void BytecodeWriter::outputConstantsInPlane(const Value *const *Plane,
870 unsigned PlaneSize,
871 unsigned StartNo) {
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000872 unsigned ValNo = StartNo;
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000873
Chris Lattner83bb3d22004-01-14 23:36:54 +0000874 // Scan through and ignore function arguments, global values, and constant
875 // strings.
Chris Lattner863da4c2007-02-10 07:42:59 +0000876 for (; ValNo < PlaneSize &&
Chris Lattner83bb3d22004-01-14 23:36:54 +0000877 (isa<Argument>(Plane[ValNo]) || isa<GlobalValue>(Plane[ValNo]) ||
878 (isa<ConstantArray>(Plane[ValNo]) &&
879 cast<ConstantArray>(Plane[ValNo])->isString())); ValNo++)
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000880 /*empty*/;
881
882 unsigned NC = ValNo; // Number of constants
Chris Lattner863da4c2007-02-10 07:42:59 +0000883 for (; NC < PlaneSize && (isa<Constant>(Plane[NC]) ||
884 isa<InlineAsm>(Plane[NC])); NC++)
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000885 /*empty*/;
886 NC -= ValNo; // Convert from index into count
887 if (NC == 0) return; // Skip empty type planes...
888
Chris Lattnerd6942d72004-01-14 16:54:21 +0000889 // FIXME: Most slabs only have 1 or 2 entries! We should encode this much
890 // more compactly.
891
Reid Spencerb83eb642006-10-20 07:07:24 +0000892 // Put out type header: [num entries][type id number]
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000893 //
Reid Spencerad89bd62004-07-25 18:07:36 +0000894 output_vbr(NC);
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000895
Chris Lattner972b4dc2007-02-10 05:17:48 +0000896 // Put out the Type ID Number.
Chris Lattner863da4c2007-02-10 07:42:59 +0000897 output_typeid(Table.getTypeSlot(Plane[0]->getType()));
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000898
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000899 for (unsigned i = ValNo; i < ValNo+NC; ++i) {
900 const Value *V = Plane[i];
Chris Lattner3bc5a602006-01-25 23:08:15 +0000901 if (const Constant *C = dyn_cast<Constant>(V))
Reid Spencere0125b62004-07-18 00:16:21 +0000902 outputConstant(C);
Chris Lattner3bc5a602006-01-25 23:08:15 +0000903 else
904 outputInlineAsm(cast<InlineAsm>(V));
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000905 }
906}
907
Chris Lattner9e60d8d2005-05-05 22:21:19 +0000908static inline bool hasNullValue(const Type *Ty) {
909 return Ty != Type::LabelTy && Ty != Type::VoidTy && !isa<OpaqueType>(Ty);
Chris Lattner80b97342004-01-17 23:25:43 +0000910}
911
Chris Lattner8dcd81c2007-02-09 07:53:20 +0000912void BytecodeWriter::outputConstants() {
Reid Spencerad89bd62004-07-25 18:07:36 +0000913 BytecodeBlock CPool(BytecodeFormat::ConstantPoolBlockID, *this,
Chris Lattner0baa0af2004-01-15 21:06:57 +0000914 true /* Elide block if empty */);
Chris Lattner00950542001-06-06 20:29:01 +0000915
916 unsigned NumPlanes = Table.getNumPlanes();
Chris Lattnerf69315b2003-05-22 18:35:38 +0000917
Chris Lattner8dcd81c2007-02-09 07:53:20 +0000918 // Output module-level string constants before any other constants.
919 outputConstantStrings();
Chris Lattner83bb3d22004-01-14 23:36:54 +0000920
Reid Spencercb3595c2004-07-04 11:45:47 +0000921 for (unsigned pno = 0; pno != NumPlanes; pno++) {
Chris Lattner863da4c2007-02-10 07:42:59 +0000922 const SlotCalculator::TypePlane &Plane = Table.getPlane(pno);
Reid Spencercb3595c2004-07-04 11:45:47 +0000923 if (!Plane.empty()) { // Skip empty type planes...
924 unsigned ValNo = 0;
Chris Lattner9e60d8d2005-05-05 22:21:19 +0000925 if (hasNullValue(Plane[0]->getType())) {
Reid Spencer0852c802004-07-04 11:46:15 +0000926 // Skip zero initializer
Chris Lattner8dcd81c2007-02-09 07:53:20 +0000927 ValNo = 1;
Chris Lattnerf69315b2003-05-22 18:35:38 +0000928 }
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000929
Reid Spencercb3595c2004-07-04 11:45:47 +0000930 // Write out constants in the plane
Chris Lattner863da4c2007-02-10 07:42:59 +0000931 outputConstantsInPlane(&Plane[0], Plane.size(), ValNo);
Chris Lattnerf69315b2003-05-22 18:35:38 +0000932 }
Reid Spencercb3595c2004-07-04 11:45:47 +0000933 }
Chris Lattner00950542001-06-06 20:29:01 +0000934}
935
Chris Lattner6b252422003-10-16 18:28:50 +0000936static unsigned getEncodedLinkage(const GlobalValue *GV) {
937 switch (GV->getLinkage()) {
938 default: assert(0 && "Invalid linkage!");
Anton Korobeynikovb74ed072006-09-14 18:23:27 +0000939 case GlobalValue::ExternalLinkage: return 0;
940 case GlobalValue::WeakLinkage: return 1;
941 case GlobalValue::AppendingLinkage: return 2;
942 case GlobalValue::InternalLinkage: return 3;
943 case GlobalValue::LinkOnceLinkage: return 4;
944 case GlobalValue::DLLImportLinkage: return 5;
945 case GlobalValue::DLLExportLinkage: return 6;
946 case GlobalValue::ExternalWeakLinkage: return 7;
Chris Lattner6b252422003-10-16 18:28:50 +0000947 }
948}
949
Anton Korobeynikov7f705592007-01-12 19:20:47 +0000950static unsigned getEncodedVisibility(const GlobalValue *GV) {
951 switch (GV->getVisibility()) {
952 default: assert(0 && "Invalid visibility!");
953 case GlobalValue::DefaultVisibility: return 0;
954 case GlobalValue::HiddenVisibility: return 1;
955 }
956}
957
Chris Lattner00950542001-06-06 20:29:01 +0000958void BytecodeWriter::outputModuleInfoBlock(const Module *M) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000959 BytecodeBlock ModuleInfoBlock(BytecodeFormat::ModuleGlobalInfoBlockID, *this);
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000960
Chris Lattner404cddf2005-11-12 01:33:40 +0000961 // Give numbers to sections as we encounter them.
962 unsigned SectionIDCounter = 0;
963 std::vector<std::string> SectionNames;
964 std::map<std::string, unsigned> SectionID;
965
Chris Lattner70cc3392001-09-10 07:58:01 +0000966 // Output the types for the global variables in the module...
Chris Lattner28caccf2005-05-06 20:27:03 +0000967 for (Module::const_global_iterator I = M->global_begin(),
Chris Lattner8eb52dd2005-11-06 07:11:04 +0000968 End = M->global_end(); I != End; ++I) {
Chris Lattner972b4dc2007-02-10 05:17:48 +0000969 unsigned Slot = Table.getTypeSlot(I->getType());
Chris Lattnerd70684f2001-09-18 04:01:05 +0000970
Chris Lattner8eb52dd2005-11-06 07:11:04 +0000971 assert((I->hasInitializer() || !I->hasInternalLinkage()) &&
972 "Global must have an initializer or have external linkage!");
973
Chris Lattner22482a12003-10-18 06:30:21 +0000974 // Fields: bit0 = isConstant, bit1 = hasInitializer, bit2-4=Linkage,
Lauro Ramos Venancioc7635522007-04-12 18:32:50 +0000975 // bit5 = isThreadLocal, bit6+ = Slot # for type.
Anton Korobeynikov7f705592007-01-12 19:20:47 +0000976 bool HasExtensionWord = (I->getAlignment() != 0) ||
977 I->hasSection() ||
978 (I->getVisibility() != GlobalValue::DefaultVisibility);
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) {
Lauro Ramos Venancioc7635522007-04-12 18:32:50 +0000983 unsigned oSlot = (Slot << 6)| (((unsigned)I->isThreadLocal()) << 5) |
984 (getEncodedLinkage(I) << 2) | (I->hasInitializer() << 1)
985 | (unsigned)I->isConstant();
Chris Lattner8eb52dd2005-11-06 07:11:04 +0000986 output_vbr(oSlot);
Anton Korobeynikovb74ed072006-09-14 18:23:27 +0000987 } else {
Lauro Ramos Venancioc7635522007-04-12 18:32:50 +0000988 unsigned oSlot = (Slot << 6) | (((unsigned)I->isThreadLocal()) << 5) |
989 (3 << 2) | (0 << 1) | (unsigned)I->isConstant();
Chris Lattner8eb52dd2005-11-06 07:11:04 +0000990 output_vbr(oSlot);
991
992 // The extension word has this format: bit 0 = has initializer, bit 1-3 =
Anton Korobeynikov7f705592007-01-12 19:20:47 +0000993 // linkage, bit 4-8 = alignment (log2), bit 9 = has SectionID,
994 // bits 10-12 = visibility, bits 13+ = future use.
Jeff Cohenba0ffcc2005-11-12 01:01:50 +0000995 unsigned ExtWord = (unsigned)I->hasInitializer() |
996 (getEncodedLinkage(I) << 1) |
Chris Lattner404cddf2005-11-12 01:33:40 +0000997 ((Log2_32(I->getAlignment())+1) << 4) |
Anton Korobeynikov7f705592007-01-12 19:20:47 +0000998 ((unsigned)I->hasSection() << 9) |
999 (getEncodedVisibility(I) << 10);
Chris Lattner8eb52dd2005-11-06 07:11:04 +00001000 output_vbr(ExtWord);
Chris Lattner404cddf2005-11-12 01:33:40 +00001001 if (I->hasSection()) {
1002 // Give section names unique ID's.
1003 unsigned &Entry = SectionID[I->getSection()];
1004 if (Entry == 0) {
1005 Entry = ++SectionIDCounter;
1006 SectionNames.push_back(I->getSection());
1007 }
1008 output_vbr(Entry);
1009 }
Chris Lattner8eb52dd2005-11-06 07:11:04 +00001010 }
Chris Lattnerd70684f2001-09-18 04:01:05 +00001011
Chris Lattner1b98c5c2001-10-13 06:48:38 +00001012 // If we have an initializer, output it now.
Chris Lattnera2bdad42007-02-10 05:13:03 +00001013 if (I->hasInitializer())
1014 output_vbr(Table.getSlot((Value*)I->getInitializer()));
Chris Lattner70cc3392001-09-10 07:58:01 +00001015 }
Chris Lattner972b4dc2007-02-10 05:17:48 +00001016 output_typeid(Table.getTypeSlot(Type::VoidTy));
Chris Lattner70cc3392001-09-10 07:58:01 +00001017
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001018 // Output the types of the functions in this module.
Chris Lattner7fc9fe32001-06-27 23:41:11 +00001019 for (Module::const_iterator I = M->begin(), End = M->end(); I != End; ++I) {
Chris Lattner972b4dc2007-02-10 05:17:48 +00001020 unsigned Slot = Table.getTypeSlot(I->getType());
Chris Lattnere73bd452005-11-06 07:43:39 +00001021 assert(((Slot << 6) >> 6) == Slot && "Slot # too big!");
Chris Lattner54b369e2005-11-06 07:46:13 +00001022 unsigned CC = I->getCallingConv()+1;
1023 unsigned ID = (Slot << 5) | (CC & 15);
Chris Lattner479ffeb2005-05-06 20:42:57 +00001024
Reid Spencere8501ab2007-04-16 23:32:28 +00001025 if (I->isDeclaration()) // If external, we don't have an FunctionInfo block.
Chris Lattnerd6e431f2004-11-15 22:39:49 +00001026 ID |= 1 << 4;
Chris Lattnere73bd452005-11-06 07:43:39 +00001027
Anton Korobeynikovb74ed072006-09-14 18:23:27 +00001028 if (I->getAlignment() || I->hasSection() || (CC & ~15) != 0 ||
Reid Spencer5cbf9852007-01-30 20:08:39 +00001029 (I->isDeclaration() && I->hasDLLImportLinkage()) ||
1030 (I->isDeclaration() && I->hasExternalWeakLinkage())
Anton Korobeynikovb74ed072006-09-14 18:23:27 +00001031 )
Chris Lattnere73bd452005-11-06 07:43:39 +00001032 ID |= 1 << 31; // Do we need an extension word?
1033
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001034 output_vbr(ID);
Chris Lattnere73bd452005-11-06 07:43:39 +00001035
1036 if (ID & (1 << 31)) {
1037 // Extension byte: bits 0-4 = alignment, bits 5-9 = top nibble of calling
Anton Korobeynikovb74ed072006-09-14 18:23:27 +00001038 // convention, bit 10 = hasSectionID., bits 11-12 = external linkage type
1039 unsigned extLinkage = 0;
1040
Reid Spencer5cbf9852007-01-30 20:08:39 +00001041 if (I->isDeclaration()) {
Anton Korobeynikovb74ed072006-09-14 18:23:27 +00001042 if (I->hasDLLImportLinkage()) {
1043 extLinkage = 1;
1044 } else if (I->hasExternalWeakLinkage()) {
1045 extLinkage = 2;
1046 }
1047 }
1048
Chris Lattner404cddf2005-11-12 01:33:40 +00001049 ID = (Log2_32(I->getAlignment())+1) | ((CC >> 4) << 5) |
Anton Korobeynikovb74ed072006-09-14 18:23:27 +00001050 (I->hasSection() << 10) |
1051 ((extLinkage & 3) << 11);
Chris Lattnere73bd452005-11-06 07:43:39 +00001052 output_vbr(ID);
Chris Lattner404cddf2005-11-12 01:33:40 +00001053
1054 // Give section names unique ID's.
1055 if (I->hasSection()) {
1056 unsigned &Entry = SectionID[I->getSection()];
1057 if (Entry == 0) {
1058 Entry = ++SectionIDCounter;
1059 SectionNames.push_back(I->getSection());
1060 }
1061 output_vbr(Entry);
1062 }
Chris Lattnere73bd452005-11-06 07:43:39 +00001063 }
Chris Lattner00950542001-06-06 20:29:01 +00001064 }
Chris Lattner972b4dc2007-02-10 05:17:48 +00001065 output_vbr(Table.getTypeSlot(Type::VoidTy) << 5);
Reid Spencerad89bd62004-07-25 18:07:36 +00001066
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001067 // Emit the list of dependent libraries for the Module.
Reid Spencer5ac88122004-07-25 21:32:02 +00001068 Module::lib_iterator LI = M->lib_begin();
1069 Module::lib_iterator LE = M->lib_end();
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001070 output_vbr(unsigned(LE - LI)); // Emit the number of dependent libraries.
1071 for (; LI != LE; ++LI)
Reid Spencer38d54be2004-08-17 07:45:14 +00001072 output(*LI);
Reid Spencerad89bd62004-07-25 18:07:36 +00001073
1074 // Output the target triple from the module
Reid Spencer38d54be2004-08-17 07:45:14 +00001075 output(M->getTargetTriple());
Reid Spenceraacc35a2007-01-26 08:10:24 +00001076
1077 // Output the data layout from the module
1078 output(M->getDataLayout());
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!
Reid Spencer5cbf9852007-01-30 20:08:39 +00001098 if (F->isDeclaration()) return;
Chris Lattnerfd7f8fe2004-11-15 21:56:33 +00001099
Chris Lattnerd6e431f2004-11-15 22:39:49 +00001100 BytecodeBlock FunctionBlock(BytecodeFormat::FunctionBlockID, *this);
Anton Korobeynikov7f705592007-01-12 19:20:47 +00001101 unsigned rWord = (getEncodedVisibility(F) << 16) | getEncodedLinkage(F);
1102 output_vbr(rWord);
Chris Lattnerd6e431f2004-11-15 22:39:49 +00001103
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001104 // Get slot information about the function...
1105 Table.incorporateFunction(F);
1106
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001107 // Output all of the instructions in the body of the function
1108 outputInstructions(F);
Misha Brukman23c6d2c2005-04-21 21:48:46 +00001109
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001110 // If needed, output the symbol table for the function...
Reid Spencer78d033e2007-01-06 07:24:44 +00001111 outputValueSymbolTable(F->getValueSymbolTable());
Misha Brukman23c6d2c2005-04-21 21:48:46 +00001112
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001113 Table.purgeFunction();
1114}
1115
Chris Lattner00950542001-06-06 20:29:01 +00001116
Reid Spencer78d033e2007-01-06 07:24:44 +00001117void BytecodeWriter::outputTypeSymbolTable(const TypeSymbolTable &TST) {
1118 // Do not output the block for an empty symbol table, it just wastes
Chris Lattner737d3cd2004-01-10 19:56:59 +00001119 // space!
Reid Spencer78d033e2007-01-06 07:24:44 +00001120 if (TST.empty()) return;
Chris Lattner737d3cd2004-01-10 19:56:59 +00001121
Reid Spencer78d033e2007-01-06 07:24:44 +00001122 // Create a header for the symbol table
1123 BytecodeBlock SymTabBlock(BytecodeFormat::TypeSymbolTableBlockID, *this,
Chris Lattnerf9d71782004-10-14 01:46:07 +00001124 true/*ElideIfEmpty*/);
Misha Brukman23c6d2c2005-04-21 21:48:46 +00001125 // Write the number of types
Reid Spencer78d033e2007-01-06 07:24:44 +00001126 output_vbr(TST.size());
Reid Spencer250c4182004-08-17 02:59:02 +00001127
1128 // Write each of the types
Reid Spencer78d033e2007-01-06 07:24:44 +00001129 for (TypeSymbolTable::const_iterator TI = TST.begin(), TE = TST.end();
1130 TI != TE; ++TI) {
Reid Spencer250c4182004-08-17 02:59:02 +00001131 // Symtab entry:[def slot #][name]
Chris Lattner972b4dc2007-02-10 05:17:48 +00001132 output_typeid(Table.getTypeSlot(TI->second));
Misha Brukman23c6d2c2005-04-21 21:48:46 +00001133 output(TI->first);
Reid Spencer94f2df22004-05-25 17:29:59 +00001134 }
Reid Spencer78d033e2007-01-06 07:24:44 +00001135}
1136
Reid Spenceref9b9a72007-02-05 20:47:22 +00001137void BytecodeWriter::outputValueSymbolTable(const ValueSymbolTable &VST) {
Reid Spencer78d033e2007-01-06 07:24:44 +00001138 // Do not output the Bytecode block for an empty symbol table, it just wastes
1139 // space!
Reid Spenceref9b9a72007-02-05 20:47:22 +00001140 if (VST.empty()) return;
Reid Spencer78d033e2007-01-06 07:24:44 +00001141
1142 BytecodeBlock SymTabBlock(BytecodeFormat::ValueSymbolTableBlockID, *this,
1143 true/*ElideIfEmpty*/);
Reid Spencer94f2df22004-05-25 17:29:59 +00001144
Reid Spenceref9b9a72007-02-05 20:47:22 +00001145 // Organize the symbol table by type
Chris Lattnerdec628e2007-02-12 05:18:08 +00001146 typedef SmallVector<const ValueName*, 8> PlaneMapVector;
Reid Spencer91ac04a2007-04-09 06:14:31 +00001147 typedef DenseMap<const Type*, PlaneMapVector> PlaneMap;
Reid Spenceref9b9a72007-02-05 20:47:22 +00001148 PlaneMap Planes;
1149 for (ValueSymbolTable::const_iterator SI = VST.begin(), SE = VST.end();
1150 SI != SE; ++SI)
Chris Lattnerdec628e2007-02-12 05:18:08 +00001151 Planes[SI->getValue()->getType()].push_back(&*SI);
Reid Spenceref9b9a72007-02-05 20:47:22 +00001152
Chris Lattnerae052aa2007-02-10 07:31:44 +00001153 for (PlaneMap::iterator PI = Planes.begin(), PE = Planes.end();
Reid Spenceref9b9a72007-02-05 20:47:22 +00001154 PI != PE; ++PI) {
Reid Spenceref9b9a72007-02-05 20:47:22 +00001155 PlaneMapVector::const_iterator I = PI->second.begin();
1156 PlaneMapVector::const_iterator End = PI->second.end();
1157
Chris Lattner00950542001-06-06 20:29:01 +00001158 if (I == End) continue; // Don't mess with an absent type...
1159
Reid Spencer250c4182004-08-17 02:59:02 +00001160 // Write the number of values in this plane
Chris Lattner001d16a2005-03-07 02:59:36 +00001161 output_vbr((unsigned)PI->second.size());
Chris Lattner00950542001-06-06 20:29:01 +00001162
Reid Spencer250c4182004-08-17 02:59:02 +00001163 // Write the slot number of the type for this plane
Chris Lattner972b4dc2007-02-10 05:17:48 +00001164 output_typeid(Table.getTypeSlot(PI->first));
Chris Lattner00950542001-06-06 20:29:01 +00001165
Reid Spencer250c4182004-08-17 02:59:02 +00001166 // Write each of the values in this plane
Chris Lattner7fc9fe32001-06-27 23:41:11 +00001167 for (; I != End; ++I) {
Chris Lattner00950542001-06-06 20:29:01 +00001168 // Symtab entry: [def slot #][name]
Chris Lattnerdec628e2007-02-12 05:18:08 +00001169 output_vbr(Table.getSlot((*I)->getValue()));
1170 output_str((*I)->getKeyData(), (*I)->getKeyLength());
Chris Lattner00950542001-06-06 20:29:01 +00001171 }
1172 }
1173}
1174
Bill Wendlinge8156192006-12-07 01:30:32 +00001175void llvm::WriteBytecodeToFile(const Module *M, OStream &Out,
Chris Lattnerc847f7c2006-07-28 22:07:54 +00001176 bool compress) {
Reid Spencerad89bd62004-07-25 18:07:36 +00001177 assert(M && "You can't write a null module!!");
Chris Lattner00950542001-06-06 20:29:01 +00001178
Reid Spencer32f55532006-06-07 23:18:34 +00001179 // Make sure that std::cout is put into binary mode for systems
1180 // that care.
Bill Wendlinge8156192006-12-07 01:30:32 +00001181 if (Out == cout)
Reid Spencer32f55532006-06-07 23:18:34 +00001182 sys::Program::ChangeStdoutToBinary();
1183
Reid Spencer17f52c52004-11-06 23:17:23 +00001184 // Create a vector of unsigned char for the bytecode output. We
1185 // reserve 256KBytes of space in the vector so that we avoid doing
1186 // lots of little allocations. 256KBytes is sufficient for a large
1187 // proportion of the bytecode files we will encounter. Larger files
1188 // will be automatically doubled in size as needed (std::vector
1189 // behavior).
Reid Spencerad89bd62004-07-25 18:07:36 +00001190 std::vector<unsigned char> Buffer;
Reid Spencer17f52c52004-11-06 23:17:23 +00001191 Buffer.reserve(256 * 1024);
Chris Lattner00950542001-06-06 20:29:01 +00001192
Reid Spencer17f52c52004-11-06 23:17:23 +00001193 // The BytecodeWriter populates Buffer for us.
Reid Spencerad89bd62004-07-25 18:07:36 +00001194 BytecodeWriter BCW(Buffer, M);
Chris Lattner00950542001-06-06 20:29:01 +00001195
Reid Spencer17f52c52004-11-06 23:17:23 +00001196 // Keep track of how much we've written
Chris Lattnerce6ef112002-07-26 18:40:14 +00001197 BytesWritten += Buffer.size();
1198
Reid Spencer17f52c52004-11-06 23:17:23 +00001199 // Determine start and end points of the Buffer
Reid Spencer83296f52004-11-07 18:17:38 +00001200 const unsigned char *FirstByte = &Buffer.front();
Reid Spencer17f52c52004-11-06 23:17:23 +00001201
1202 // If we're supposed to compress this mess ...
1203 if (compress) {
1204
1205 // We signal compression by using an alternate magic number for the
Reid Spencer83296f52004-11-07 18:17:38 +00001206 // file. The compressed bytecode file's magic number is "llvc" instead
Misha Brukman23c6d2c2005-04-21 21:48:46 +00001207 // of "llvm".
Reid Spencer83296f52004-11-07 18:17:38 +00001208 char compressed_magic[4];
1209 compressed_magic[0] = 'l';
1210 compressed_magic[1] = 'l';
1211 compressed_magic[2] = 'v';
1212 compressed_magic[3] = 'c';
Reid Spencer17f52c52004-11-06 23:17:23 +00001213
Bill Wendling68fe61d2006-11-29 00:19:40 +00001214 Out.stream()->write(compressed_magic,4);
Reid Spencer17f52c52004-11-06 23:17:23 +00001215
Reid Spencera70d84d2004-11-14 22:01:41 +00001216 // Compress everything after the magic number (which we altered)
Reid Spencer3ed469c2006-11-02 20:25:50 +00001217 Compressor::compressToStream(
Reid Spencer17f52c52004-11-06 23:17:23 +00001218 (char*)(FirstByte+4), // Skip the magic number
1219 Buffer.size()-4, // Skip the magic number
Bill Wendling68fe61d2006-11-29 00:19:40 +00001220 *Out.stream() // Where to write compressed data
Reid Spencer17f52c52004-11-06 23:17:23 +00001221 );
1222
Reid Spencer17f52c52004-11-06 23:17:23 +00001223 } else {
1224
1225 // We're not compressing, so just write the entire block.
Bill Wendling68fe61d2006-11-29 00:19:40 +00001226 Out.stream()->write((char*)FirstByte, Buffer.size());
Chris Lattnere8fdde12001-09-07 16:39:41 +00001227 }
Reid Spencer17f52c52004-11-06 23:17:23 +00001228
1229 // make sure it hits disk now
Bill Wendling68fe61d2006-11-29 00:19:40 +00001230 Out.stream()->flush();
Chris Lattner00950542001-06-06 20:29:01 +00001231}