Fixed spelling and grammar.
[oota-llvm.git] / lib / Bytecode / Writer / Writer.cpp
1 //===-- Writer.cpp - Library for writing VM bytecode files -------*- C++ -*--=//
2 //
3 // This library implements the functionality defined in llvm/Bytecode/Writer.h
4 //
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.  :( :( :(
10 //
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.
15 //
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
18 // at least.  :)
19 //
20 //===----------------------------------------------------------------------===//
21
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"
30 #include <algorithm>
31
32 static RegisterPass<WriteBytecodePass> X("emitbytecode", "Bytecode Writer");
33
34 static Statistic<> 
35 BytesWritten("bytecodewriter", "Number of bytecode bytes written");
36
37
38 BytecodeWriter::BytecodeWriter(std::deque<unsigned char> &o, const Module *M) 
39   : Out(o), Table(M, false) {
40
41   outputSignature();
42
43   // Emit the top level CLASS block.
44   BytecodeBlock ModuleBlock(BytecodeFormat::Module, Out);
45
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;
50
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);
55   align32(Out);
56
57   {
58     BytecodeBlock CPool(BytecodeFormat::GlobalTypePlane, Out);
59     
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
68   }
69
70   // The ModuleInfoBlock follows directly after the type information
71   outputModuleInfoBlock(M);
72
73   // Output module level constants, used for global variable initializers
74   outputConstants(false);
75
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)
78     outputFunction(I);
79
80   // If needed, output the symbol table for the module...
81   outputSymbolTable(M->getSymbolTable());
82 }
83
84 // Helper function for outputConstants().
85 // Writes out all the constants in the plane Plane starting at entry StartNo.
86 // 
87 void BytecodeWriter::outputConstantsInPlane(const std::vector<const Value*>
88                                             &Plane, unsigned StartNo) {
89   unsigned ValNo = StartNo;
90   
91   // Scan through and ignore function arguments/global values...
92   for (; ValNo < Plane.size() && (isa<Argument>(Plane[ValNo]) ||
93                                   isa<GlobalValue>(Plane[ValNo])); ValNo++)
94     /*empty*/;
95
96   unsigned NC = ValNo;              // Number of constants
97   for (; NC < Plane.size() && 
98          (isa<Constant>(Plane[NC]) || isa<Type>(Plane[NC])); NC++)
99     /*empty*/;
100   NC -= ValNo;                      // Convert from index into count
101   if (NC == 0) return;              // Skip empty type planes...
102
103   // Output type header: [num entries][type id number]
104   //
105   output_vbr(NC, Out);
106
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);
111
112   //cerr << "Emitting " << NC << " constants of type '" 
113   //     << Plane.front()->getType()->getName() << "' = Slot #" << Slot << "\n";
114
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";
120       outputConstant(CPV);
121     } else {
122       outputType(cast<Type>(V));
123     }
124   }
125 }
126
127 void BytecodeWriter::outputConstants(bool isFunction) {
128   BytecodeBlock CPool(BytecodeFormat::ConstantPool, Out);
129
130   unsigned NumPlanes = Table.getNumPlanes();
131
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);
138     }
139   }
140   
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...
145         unsigned ValNo = 0;
146         if (isFunction)                  // Don't re-emit module constants
147           ValNo += Table.getModuleLevel(pno);
148         
149         if (pno >= Type::FirstDerivedTyID) {
150           // Skip zero initializer
151           if (ValNo == 0)
152             ValNo = 1;
153         }
154         
155         // Write out constants in the plane
156         outputConstantsInPlane(Plane, ValNo);
157       }
158     }
159 }
160
161 void BytecodeWriter::outputModuleInfoBlock(const Module *M) {
162   BytecodeBlock ModuleInfoBlock(BytecodeFormat::ModuleGlobalInfo, Out);
163   
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!");
168
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);
174
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);
180     }
181   }
182   output_vbr((unsigned)Table.getValSlot(Type::VoidTy), Out);
183
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);
190   }
191   output_vbr((unsigned)Table.getValSlot(Type::VoidTy), Out);
192
193   align32(Out);
194 }
195
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()) {
201
202     // Get slot information about the function...
203     Table.incorporateFunction(F);
204
205     // Output information about the constants in the function...
206     outputConstants(true);
207
208     // Output basic block nodes...
209     for (Function::const_iterator I = F->begin(), E = F->end(); I != E; ++I)
210       processBasicBlock(*I);
211     
212     // If needed, output the symbol table for the function...
213     outputSymbolTable(F->getSymbolTable());
214     
215     Table.purgeFunction();
216   }
217 }
218
219
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);
225 }
226
227 void BytecodeWriter::outputSymbolTable(const SymbolTable &MST) {
228   BytecodeBlock FunctionBlock(BytecodeFormat::SymbolTable, Out);
229
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);
233     int Slot;
234     
235     if (I == End) continue;  // Don't mess with an absent type...
236
237     // Symtab block header: [num entries][type id number]
238     output_vbr(MST.type_size(TI->first), Out);
239
240     Slot = Table.getValSlot(TI->first);
241     assert(Slot != -1 && "Type in symtab, but not in table!");
242     output_vbr((unsigned)Slot, Out);
243
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...
250     }
251   }
252 }
253
254 void WriteBytecodeToFile(const Module *C, std::ostream &Out) {
255   assert(C && "You can't write a null module!!");
256
257   std::deque<unsigned char> Buffer;
258
259   // This object populates buffer for us...
260   BytecodeWriter BCW(Buffer, C);
261
262   // Keep track of how much we've written...
263   BytesWritten += Buffer.size();
264
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.
268   //
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;
274     while (I != E) {
275       const unsigned char *ThisPtr = &*++I;
276       if (LastPtr+1 != ThisPtr) {   // Advanced by more than a byte of memory?
277         ++LastPtr;
278         break;
279       }
280       LastPtr = ThisPtr;
281     }
282     
283     // Write out the chunk...
284     Out.write((char*)ChunkPtr, LastPtr-ChunkPtr);
285   }
286
287   Out.flush();
288 }