92b6a62cc6011cec7792e38fe4bc1dd6d85b9673
[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 char's, 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 <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   // Output the ID of first "derived" type:
47   output_vbr((unsigned)Type::FirstDerivedTyID, Out);
48   align32(Out);
49
50   // Output module level constants, including types used by the function protos
51   outputConstants(false);
52
53   // The ModuleInfoBlock follows directly after the Module constant pool
54   outputModuleInfoBlock(M);
55
56   // Do the whole module now! Process each function at a time...
57   for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
58     processMethod(I);
59
60   // If needed, output the symbol table for the module...
61   outputSymbolTable(M->getSymbolTable());
62 }
63
64 // Helper function for outputConstants().
65 // Writes out all the constants in the plane Plane starting at entry StartNo.
66 // 
67 void BytecodeWriter::outputConstantsInPlane(const std::vector<const Value*>
68                                             &Plane, unsigned StartNo) {
69   unsigned ValNo = StartNo;
70   
71   // Scan through and ignore function arguments...
72   for (; ValNo < Plane.size() && isa<Argument>(Plane[ValNo]); ValNo++)
73     /*empty*/;
74
75   unsigned NC = ValNo;              // Number of constants
76   for (; NC < Plane.size() && 
77          (isa<Constant>(Plane[NC]) || isa<Type>(Plane[NC])); NC++)
78     /*empty*/;
79   NC -= ValNo;                      // Convert from index into count
80   if (NC == 0) return;              // Skip empty type planes...
81
82   // Output type header: [num entries][type id number]
83   //
84   output_vbr(NC, Out);
85
86   // Output the Type ID Number...
87   int Slot = Table.getValSlot(Plane.front()->getType());
88   assert (Slot != -1 && "Type in constant pool but not in function!!");
89   output_vbr((unsigned)Slot, Out);
90
91   //cerr << "Emitting " << NC << " constants of type '" 
92   //     << Plane.front()->getType()->getName() << "' = Slot #" << Slot << "\n";
93
94   for (unsigned i = ValNo; i < ValNo+NC; ++i) {
95     const Value *V = Plane[i];
96     if (const Constant *CPV = dyn_cast<Constant>(V)) {
97       //cerr << "Serializing value: <" << V->getType() << ">: " << V << ":" 
98       //     << Out.size() << "\n";
99       outputConstant(CPV);
100     } else {
101       outputType(cast<const Type>(V));
102     }
103   }
104 }
105
106 void BytecodeWriter::outputConstants(bool isFunction) {
107   BytecodeBlock CPool(BytecodeFormat::ConstantPool, Out);
108
109   unsigned NumPlanes = Table.getNumPlanes();
110   
111   // Write the type plane for types first because earlier planes
112   // (e.g. for a primitive type like float) may have constants constructed
113   // using types coming later (e.g., via getelementptr from a pointer type).
114   // The type plane is needed before types can be fwd or bkwd referenced.
115   if (!isFunction) {
116     const std::vector<const Value*> &Plane = Table.getPlane(Type::TypeTyID);
117     assert(!Plane.empty() && "No types at all?");
118     unsigned ValNo = Type::FirstDerivedTyID; // Start at the derived types...
119     outputConstantsInPlane(Plane, ValNo);      // Write out the types
120   }
121   
122   for (unsigned pno = 0; pno != NumPlanes; pno++) {
123     const std::vector<const Value*> &Plane = Table.getPlane(pno);
124     if (!Plane.empty()) {             // Skip empty type planes...
125       unsigned ValNo = 0;
126       if (isFunction)                   // Don't reemit module constants
127         ValNo = Table.getModuleLevel(pno);
128       else if (pno == Type::TypeTyID) // If type plane wasn't written out above
129         continue;
130
131       outputConstantsInPlane(Plane, ValNo); // Write out constants in the plane
132     }
133   }
134 }
135
136 void BytecodeWriter::outputModuleInfoBlock(const Module *M) {
137   BytecodeBlock ModuleInfoBlock(BytecodeFormat::ModuleGlobalInfo, Out);
138   
139   // Output the types for the global variables in the module...
140   for (Module::const_giterator I = M->gbegin(), End = M->gend(); I != End;++I) {
141     int Slot = Table.getValSlot(I->getType());
142     assert(Slot != -1 && "Module global vars is broken!");
143
144     // Fields: bit0 = isConstant, bit1 = hasInitializer, bit2=InternalLinkage,
145     // bit3+ = slot#
146     unsigned oSlot = ((unsigned)Slot << 3) | (I->hasInternalLinkage() << 2) |
147                      (I->hasInitializer() << 1) | I->isConstant();
148     output_vbr(oSlot, Out);
149
150     // If we have an initializer, output it now.
151     if (I->hasInitializer()) {
152       Slot = Table.getValSlot((Value*)I->getInitializer());
153       assert(Slot != -1 && "No slot for global var initializer!");
154       output_vbr((unsigned)Slot, Out);
155     }
156   }
157   output_vbr((unsigned)Table.getValSlot(Type::VoidTy), Out);
158
159   // Output the types of the functions in this module...
160   for (Module::const_iterator I = M->begin(), End = M->end(); I != End; ++I) {
161     int Slot = Table.getValSlot(I->getType());
162     assert(Slot != -1 && "Module const pool is broken!");
163     assert(Slot >= Type::FirstDerivedTyID && "Derived type not in range!");
164     output_vbr((unsigned)Slot, Out);
165   }
166   output_vbr((unsigned)Table.getValSlot(Type::VoidTy), Out);
167
168
169   align32(Out);
170 }
171
172 void BytecodeWriter::processMethod(const Function *F) {
173   BytecodeBlock FunctionBlock(BytecodeFormat::Function, Out);
174   output_vbr((unsigned)F->hasInternalLinkage(), Out);
175   // Only output the constant pool and other goodies if needed...
176   if (!F->isExternal()) {
177
178     // Get slot information about the function...
179     Table.incorporateFunction(F);
180
181     // Output information about the constants in the function...
182     outputConstants(true);
183
184     // Output basic block nodes...
185     for (Function::const_iterator I = F->begin(), E = F->end(); I != E; ++I)
186       processBasicBlock(*I);
187     
188     // If needed, output the symbol table for the function...
189     outputSymbolTable(F->getSymbolTable());
190     
191     Table.purgeFunction();
192   }
193 }
194
195
196 void BytecodeWriter::processBasicBlock(const BasicBlock &BB) {
197   BytecodeBlock FunctionBlock(BytecodeFormat::BasicBlock, Out);
198   // Process all the instructions in the bb...
199   for(BasicBlock::const_iterator I = BB.begin(), E = BB.end(); I != E; ++I)
200     processInstruction(*I);
201 }
202
203 void BytecodeWriter::outputSymbolTable(const SymbolTable &MST) {
204   BytecodeBlock FunctionBlock(BytecodeFormat::SymbolTable, Out);
205
206   for (SymbolTable::const_iterator TI = MST.begin(); TI != MST.end(); ++TI) {
207     SymbolTable::type_const_iterator I = MST.type_begin(TI->first);
208     SymbolTable::type_const_iterator End = MST.type_end(TI->first);
209     int Slot;
210     
211     if (I == End) continue;  // Don't mess with an absent type...
212
213     // Symtab block header: [num entries][type id number]
214     output_vbr(MST.type_size(TI->first), Out);
215
216     Slot = Table.getValSlot(TI->first);
217     assert(Slot != -1 && "Type in symtab, but not in table!");
218     output_vbr((unsigned)Slot, Out);
219
220     for (; I != End; ++I) {
221       // Symtab entry: [def slot #][name]
222       Slot = Table.getValSlot(I->second);
223       assert(Slot != -1 && "Value in symtab but has no slot number!!");
224       output_vbr((unsigned)Slot, Out);
225       output(I->first, Out, false); // Don't force alignment...
226     }
227   }
228 }
229
230 void WriteBytecodeToFile(const Module *C, std::ostream &Out) {
231   assert(C && "You can't write a null module!!");
232
233   std::deque<unsigned char> Buffer;
234
235   // This object populates buffer for us...
236   BytecodeWriter BCW(Buffer, C);
237
238   // Keep track of how much we've written...
239   BytesWritten += Buffer.size();
240
241   // Okay, write the deque out to the ostream now... the deque is not
242   // sequential in memory, however, so write out as much as possible in big
243   // chunks, until we're done.
244   //
245   std::deque<unsigned char>::const_iterator I = Buffer.begin(),E = Buffer.end();
246   while (I != E) {                           // Loop until it's all written
247     // Scan to see how big this chunk is...
248     const unsigned char *ChunkPtr = &*I;
249     const unsigned char *LastPtr = ChunkPtr;
250     while (I != E) {
251       const unsigned char *ThisPtr = &*++I;
252       if (LastPtr+1 != ThisPtr) {   // Advanced by more than a byte of memory?
253         ++LastPtr;
254         break;
255       }
256       LastPtr = ThisPtr;
257     }
258     
259     // Write out the chunk...
260     Out.write((char*)ChunkPtr, LastPtr-ChunkPtr);
261   }
262
263   Out.flush();
264 }