5cc3eec8722c838dad62bfc663a1ba0188672742
[oota-llvm.git] / lib / Bytecode / Writer / Writer.cpp
1 //===-- Writer.cpp - Library for writing VM bytecode files ----------------===//
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, 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 #0
52   unsigned Version = (0 << 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.getSlot(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 static unsigned getEncodedLinkage(const GlobalValue *GV) {
162   switch (GV->getLinkage()) {
163   default: assert(0 && "Invalid linkage!");
164   case GlobalValue::ExternalLinkage:  return 0;
165   case GlobalValue::WeakLinkage:      return 1;
166   case GlobalValue::AppendingLinkage: return 2;
167   case GlobalValue::InternalLinkage:  return 3;
168   case GlobalValue::LinkOnceLinkage:  return 4;
169   }
170 }
171
172 void BytecodeWriter::outputModuleInfoBlock(const Module *M) {
173   BytecodeBlock ModuleInfoBlock(BytecodeFormat::ModuleGlobalInfo, Out);
174   
175   // Output the types for the global variables in the module...
176   for (Module::const_giterator I = M->gbegin(), End = M->gend(); I != End;++I) {
177     int Slot = Table.getSlot(I->getType());
178     assert(Slot != -1 && "Module global vars is broken!");
179
180     // Fields: bit0 = isConstant, bit1 = hasInitializer, bit2-4=Linkage,
181     // bit5+ = Slot # for type
182     unsigned oSlot = ((unsigned)Slot << 5) | (getEncodedLinkage(I) << 2) |
183                      (I->hasInitializer() << 1) | I->isConstant();
184     output_vbr(oSlot, Out);
185
186     // If we have an initializer, output it now.
187     if (I->hasInitializer()) {
188       Slot = Table.getSlot((Value*)I->getInitializer());
189       assert(Slot != -1 && "No slot for global var initializer!");
190       output_vbr((unsigned)Slot, Out);
191     }
192   }
193   output_vbr((unsigned)Table.getSlot(Type::VoidTy), Out);
194
195   // Output the types of the functions in this module...
196   for (Module::const_iterator I = M->begin(), End = M->end(); I != End; ++I) {
197     int Slot = Table.getSlot(I->getType());
198     assert(Slot != -1 && "Module const pool is broken!");
199     assert(Slot >= Type::FirstDerivedTyID && "Derived type not in range!");
200     output_vbr((unsigned)Slot, Out);
201   }
202   output_vbr((unsigned)Table.getSlot(Type::VoidTy), Out);
203
204   align32(Out);
205 }
206
207 void BytecodeWriter::outputFunction(const Function *F) {
208   BytecodeBlock FunctionBlock(BytecodeFormat::Function, Out);
209   output_vbr(getEncodedLinkage(F), Out);
210   // Only output the constant pool and other goodies if needed...
211   if (!F->isExternal()) {
212
213     // Get slot information about the function...
214     Table.incorporateFunction(F);
215
216     // Output information about the constants in the function...
217     outputConstants(true);
218
219     // Output basic block nodes...
220     for (Function::const_iterator I = F->begin(), E = F->end(); I != E; ++I)
221       processBasicBlock(*I);
222     
223     // If needed, output the symbol table for the function...
224     outputSymbolTable(F->getSymbolTable());
225     
226     Table.purgeFunction();
227   }
228 }
229
230
231 void BytecodeWriter::processBasicBlock(const BasicBlock &BB) {
232   BytecodeBlock FunctionBlock(BytecodeFormat::BasicBlock, Out);
233   // Process all the instructions in the bb...
234   for(BasicBlock::const_iterator I = BB.begin(), E = BB.end(); I != E; ++I)
235     processInstruction(*I);
236 }
237
238 void BytecodeWriter::outputSymbolTable(const SymbolTable &MST) {
239   BytecodeBlock FunctionBlock(BytecodeFormat::SymbolTable, Out);
240
241   for (SymbolTable::const_iterator TI = MST.begin(); TI != MST.end(); ++TI) {
242     SymbolTable::type_const_iterator I = MST.type_begin(TI->first);
243     SymbolTable::type_const_iterator End = MST.type_end(TI->first);
244     int Slot;
245     
246     if (I == End) continue;  // Don't mess with an absent type...
247
248     // Symtab block header: [num entries][type id number]
249     output_vbr(MST.type_size(TI->first), Out);
250
251     Slot = Table.getSlot(TI->first);
252     assert(Slot != -1 && "Type in symtab, but not in table!");
253     output_vbr((unsigned)Slot, Out);
254
255     for (; I != End; ++I) {
256       // Symtab entry: [def slot #][name]
257       Slot = Table.getSlot(I->second);
258       assert(Slot != -1 && "Value in symtab but has no slot number!!");
259       output_vbr((unsigned)Slot, Out);
260       output(I->first, Out, false); // Don't force alignment...
261     }
262   }
263 }
264
265 void WriteBytecodeToFile(const Module *C, std::ostream &Out) {
266   assert(C && "You can't write a null module!!");
267
268   std::deque<unsigned char> Buffer;
269
270   // This object populates buffer for us...
271   BytecodeWriter BCW(Buffer, C);
272
273   // Keep track of how much we've written...
274   BytesWritten += Buffer.size();
275
276   // Okay, write the deque out to the ostream now... the deque is not
277   // sequential in memory, however, so write out as much as possible in big
278   // chunks, until we're done.
279   //
280   std::deque<unsigned char>::const_iterator I = Buffer.begin(),E = Buffer.end();
281   while (I != E) {                           // Loop until it's all written
282     // Scan to see how big this chunk is...
283     const unsigned char *ChunkPtr = &*I;
284     const unsigned char *LastPtr = ChunkPtr;
285     while (I != E) {
286       const unsigned char *ThisPtr = &*++I;
287       if (LastPtr+1 != ThisPtr) {   // Advanced by more than a byte of memory?
288         ++LastPtr;
289         break;
290       }
291       LastPtr = ThisPtr;
292     }
293     
294     // Write out the chunk...
295     Out.write((char*)ChunkPtr, LastPtr-ChunkPtr);
296   }
297
298   Out.flush();
299 }