1 //===-- Writer.cpp - Library for writing VM bytecode files -------*- C++ -*--=//
3 // This library implements the functionality defined in llvm/Bytecode/Writer.h
5 // Note that this file uses an unusual technique of outputting all the bytecode
6 // to a deque of unsigned chare, then copies the deque to an ostream. The
7 // reason for this is that we must do "seeking" in the stream to do back-
8 // patching, and some very important ostreams that we want to support (like
9 // pipes) do not support seeking. :( :( :(
11 // The choice of the deque data structure is influenced by the extremely fast
12 // "append" speed, plus the free "seek"/replace in the middle of the stream. I
13 // didn't use a vector because the stream could end up very large and copying
14 // the whole thing to reallocate would be kinda silly.
16 // Note that the performance of this library is not terribly important, because
17 // it shouldn't be used by JIT type applications... so it is not a huge focus
20 //===----------------------------------------------------------------------===//
22 #include "WriterInternals.h"
23 #include "llvm/Bytecode/WriteBytecodePass.h"
24 #include "llvm/Module.h"
25 #include "llvm/SymbolTable.h"
26 #include "llvm/DerivedTypes.h"
27 #include "Support/STLExtras.h"
28 #include "Support/Statistic.h"
29 #include "Config/string.h"
32 static RegisterPass<WriteBytecodePass> X("emitbytecode", "Bytecode Writer");
35 BytesWritten("bytecodewriter", "Number of bytecode bytes written");
38 BytecodeWriter::BytecodeWriter(std::deque<unsigned char> &o, const Module *M)
39 : Out(o), Table(M, false) {
43 // Emit the top level CLASS block.
44 BytecodeBlock ModuleBlock(BytecodeFormat::Module, Out);
46 bool isBigEndian = M->getEndianness() == Module::BigEndian;
47 bool hasLongPointers = M->getPointerSize() == Module::Pointer64;
48 bool hasNoEndianness = M->getEndianness() == Module::AnyEndianness;
49 bool hasNoPointerSize = M->getPointerSize() == Module::AnyPointerSize;
51 // Output the version identifier... we are currently on bytecode version #2
52 unsigned Version = (2 << 4) | isBigEndian | (hasLongPointers << 1) |
53 (hasNoEndianness << 2) | (hasNoPointerSize << 3);
54 output_vbr(Version, Out);
58 BytecodeBlock CPool(BytecodeFormat::GlobalTypePlane, Out);
60 // Write the type plane for types first because earlier planes (e.g. for a
61 // primitive type like float) may have constants constructed using types
62 // coming later (e.g., via getelementptr from a pointer type). The type
63 // plane is needed before types can be fwd or bkwd referenced.
64 const std::vector<const Value*> &Plane = Table.getPlane(Type::TypeTyID);
65 assert(!Plane.empty() && "No types at all?");
66 unsigned ValNo = Type::FirstDerivedTyID; // Start at the derived types...
67 outputConstantsInPlane(Plane, ValNo); // Write out the types
70 // The ModuleInfoBlock follows directly after the type information
71 outputModuleInfoBlock(M);
73 // Output module level constants, used for global variable initializers
74 outputConstants(false);
76 // Do the whole module now! Process each function at a time...
77 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
80 // If needed, output the symbol table for the module...
81 outputSymbolTable(M->getSymbolTable());
84 // Helper function for outputConstants().
85 // Writes out all the constants in the plane Plane starting at entry StartNo.
87 void BytecodeWriter::outputConstantsInPlane(const std::vector<const Value*>
88 &Plane, unsigned StartNo) {
89 unsigned ValNo = StartNo;
91 // Scan through and ignore function arguments/global values...
92 for (; ValNo < Plane.size() && (isa<Argument>(Plane[ValNo]) ||
93 isa<GlobalValue>(Plane[ValNo])); ValNo++)
96 unsigned NC = ValNo; // Number of constants
97 for (; NC < Plane.size() &&
98 (isa<Constant>(Plane[NC]) || isa<Type>(Plane[NC])); NC++)
100 NC -= ValNo; // Convert from index into count
101 if (NC == 0) return; // Skip empty type planes...
103 // Output type header: [num entries][type id number]
107 // Output the Type ID Number...
108 int Slot = Table.getValSlot(Plane.front()->getType());
109 assert (Slot != -1 && "Type in constant pool but not in function!!");
110 output_vbr((unsigned)Slot, Out);
112 //cerr << "Emitting " << NC << " constants of type '"
113 // << Plane.front()->getType()->getName() << "' = Slot #" << Slot << "\n";
115 for (unsigned i = ValNo; i < ValNo+NC; ++i) {
116 const Value *V = Plane[i];
117 if (const Constant *CPV = dyn_cast<Constant>(V)) {
118 //cerr << "Serializing value: <" << V->getType() << ">: " << V << ":"
119 // << Out.size() << "\n";
122 outputType(cast<Type>(V));
127 void BytecodeWriter::outputConstants(bool isFunction) {
128 BytecodeBlock CPool(BytecodeFormat::ConstantPool, Out);
130 unsigned NumPlanes = Table.getNumPlanes();
132 // Output the type plane before any constants!
133 if (isFunction && NumPlanes > Type::TypeTyID) {
134 const std::vector<const Value*> &Plane = Table.getPlane(Type::TypeTyID);
135 if (!Plane.empty()) { // Skip empty type planes...
136 unsigned ValNo = Table.getModuleLevel(Type::TypeTyID);
137 outputConstantsInPlane(Plane, ValNo);
141 for (unsigned pno = 0; pno != NumPlanes; pno++)
142 if (pno != Type::TypeTyID) { // Type plane handled above.
143 const std::vector<const Value*> &Plane = Table.getPlane(pno);
144 if (!Plane.empty()) { // Skip empty type planes...
146 if (isFunction) // Don't re-emit module constants
147 ValNo += Table.getModuleLevel(pno);
149 if (pno >= Type::FirstDerivedTyID) {
150 // Skip zero initializer
155 // Write out constants in the plane
156 outputConstantsInPlane(Plane, ValNo);
161 void BytecodeWriter::outputModuleInfoBlock(const Module *M) {
162 BytecodeBlock ModuleInfoBlock(BytecodeFormat::ModuleGlobalInfo, Out);
164 // Output the types for the global variables in the module...
165 for (Module::const_giterator I = M->gbegin(), End = M->gend(); I != End;++I) {
166 int Slot = Table.getValSlot(I->getType());
167 assert(Slot != -1 && "Module global vars is broken!");
169 // Fields: bit0 = isConstant, bit1 = hasInitializer, bit2,3=Linkage,
170 // bit4+ = Slot # for type
171 unsigned oSlot = ((unsigned)Slot << 4) | ((unsigned)I->getLinkage() << 2) |
172 (I->hasInitializer() << 1) | I->isConstant();
173 output_vbr(oSlot, Out);
175 // If we have an initializer, output it now.
176 if (I->hasInitializer()) {
177 Slot = Table.getValSlot((Value*)I->getInitializer());
178 assert(Slot != -1 && "No slot for global var initializer!");
179 output_vbr((unsigned)Slot, Out);
182 output_vbr((unsigned)Table.getValSlot(Type::VoidTy), Out);
184 // Output the types of the functions in this module...
185 for (Module::const_iterator I = M->begin(), End = M->end(); I != End; ++I) {
186 int Slot = Table.getValSlot(I->getType());
187 assert(Slot != -1 && "Module const pool is broken!");
188 assert(Slot >= Type::FirstDerivedTyID && "Derived type not in range!");
189 output_vbr((unsigned)Slot, Out);
191 output_vbr((unsigned)Table.getValSlot(Type::VoidTy), Out);
196 void BytecodeWriter::outputFunction(const Function *F) {
197 BytecodeBlock FunctionBlock(BytecodeFormat::Function, Out);
198 output_vbr((unsigned)F->getLinkage(), Out);
199 // Only output the constant pool and other goodies if needed...
200 if (!F->isExternal()) {
202 // Get slot information about the function...
203 Table.incorporateFunction(F);
205 // Output information about the constants in the function...
206 outputConstants(true);
208 // Output basic block nodes...
209 for (Function::const_iterator I = F->begin(), E = F->end(); I != E; ++I)
210 processBasicBlock(*I);
212 // If needed, output the symbol table for the function...
213 outputSymbolTable(F->getSymbolTable());
215 Table.purgeFunction();
220 void BytecodeWriter::processBasicBlock(const BasicBlock &BB) {
221 BytecodeBlock FunctionBlock(BytecodeFormat::BasicBlock, Out);
222 // Process all the instructions in the bb...
223 for(BasicBlock::const_iterator I = BB.begin(), E = BB.end(); I != E; ++I)
224 processInstruction(*I);
227 void BytecodeWriter::outputSymbolTable(const SymbolTable &MST) {
228 BytecodeBlock FunctionBlock(BytecodeFormat::SymbolTable, Out);
230 for (SymbolTable::const_iterator TI = MST.begin(); TI != MST.end(); ++TI) {
231 SymbolTable::type_const_iterator I = MST.type_begin(TI->first);
232 SymbolTable::type_const_iterator End = MST.type_end(TI->first);
235 if (I == End) continue; // Don't mess with an absent type...
237 // Symtab block header: [num entries][type id number]
238 output_vbr(MST.type_size(TI->first), Out);
240 Slot = Table.getValSlot(TI->first);
241 assert(Slot != -1 && "Type in symtab, but not in table!");
242 output_vbr((unsigned)Slot, Out);
244 for (; I != End; ++I) {
245 // Symtab entry: [def slot #][name]
246 Slot = Table.getValSlot(I->second);
247 assert(Slot != -1 && "Value in symtab but has no slot number!!");
248 output_vbr((unsigned)Slot, Out);
249 output(I->first, Out, false); // Don't force alignment...
254 void WriteBytecodeToFile(const Module *C, std::ostream &Out) {
255 assert(C && "You can't write a null module!!");
257 std::deque<unsigned char> Buffer;
259 // This object populates buffer for us...
260 BytecodeWriter BCW(Buffer, C);
262 // Keep track of how much we've written...
263 BytesWritten += Buffer.size();
265 // Okay, write the deque out to the ostream now... the deque is not
266 // sequential in memory, however, so write out as much as possible in big
267 // chunks, until we're done.
269 std::deque<unsigned char>::const_iterator I = Buffer.begin(),E = Buffer.end();
270 while (I != E) { // Loop until it's all written
271 // Scan to see how big this chunk is...
272 const unsigned char *ChunkPtr = &*I;
273 const unsigned char *LastPtr = ChunkPtr;
275 const unsigned char *ThisPtr = &*++I;
276 if (LastPtr+1 != ThisPtr) { // Advanced by more than a byte of memory?
283 // Write out the chunk...
284 Out.write((char*)ChunkPtr, LastPtr-ChunkPtr);