9c9e1abcdd82576bc6cba12e109d0d809d84056c
[oota-llvm.git] / lib / Bytecode / Writer / Writer.cpp
1 //===-- Writer.cpp - Library for writing VM bytecode files ----------------===//
2 // 
3 //                     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.
7 // 
8 //===----------------------------------------------------------------------===//
9 //
10 // This library implements the functionality defined in llvm/Bytecode/Writer.h
11 //
12 // Note that this file uses an unusual technique of outputting all the bytecode
13 // to a deque of unsigned char, then copies the deque to an ostream.  The
14 // 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 //
18 // The choice of the deque data structure is influenced by the extremely fast
19 // "append" speed, plus the free "seek"/replace in the middle of the stream. I
20 // didn't use a vector because the stream could end up very large and copying
21 // the whole thing to reallocate would be kinda silly.
22 //
23 // Note that the performance of this library is not terribly important, because
24 // it shouldn't be used by JIT type applications... so it is not a huge focus
25 // at least.  :)
26 //
27 //===----------------------------------------------------------------------===//
28
29 #include "WriterInternals.h"
30 #include "llvm/Bytecode/WriteBytecodePass.h"
31 #include "llvm/Module.h"
32 #include "llvm/SymbolTable.h"
33 #include "llvm/DerivedTypes.h"
34 #include "Support/STLExtras.h"
35 #include "Support/Statistic.h"
36 #include "Config/string.h"
37 #include <algorithm>
38
39 namespace llvm {
40
41 static RegisterPass<WriteBytecodePass> X("emitbytecode", "Bytecode Writer");
42
43 static Statistic<> 
44 BytesWritten("bytecodewriter", "Number of bytecode bytes written");
45
46
47 BytecodeWriter::BytecodeWriter(std::deque<unsigned char> &o, const Module *M) 
48   : Out(o), Table(M, false) {
49
50   outputSignature();
51
52   // Emit the top level CLASS block.
53   BytecodeBlock ModuleBlock(BytecodeFormat::Module, Out);
54
55   bool isBigEndian      = M->getEndianness() == Module::BigEndian;
56   bool hasLongPointers  = M->getPointerSize() == Module::Pointer64;
57   bool hasNoEndianness  = M->getEndianness() == Module::AnyEndianness;
58   bool hasNoPointerSize = M->getPointerSize() == Module::AnyPointerSize;
59
60   // Output the version identifier... we are currently on bytecode version #0
61   unsigned Version = (0 << 4) | isBigEndian | (hasLongPointers << 1) |
62                      (hasNoEndianness << 2) | (hasNoPointerSize << 3);
63   output_vbr(Version, Out);
64   align32(Out);
65
66   {
67     BytecodeBlock CPool(BytecodeFormat::GlobalTypePlane, Out);
68     
69     // Write the type plane for types first because earlier planes (e.g. for a
70     // primitive type like float) may have constants constructed using types
71     // coming later (e.g., via getelementptr from a pointer type).  The type
72     // plane is needed before types can be fwd or bkwd referenced.
73     const std::vector<const Value*> &Plane = Table.getPlane(Type::TypeTyID);
74     assert(!Plane.empty() && "No types at all?");
75     unsigned ValNo = Type::FirstDerivedTyID; // Start at the derived types...
76     outputConstantsInPlane(Plane, ValNo);      // Write out the types
77   }
78
79   // The ModuleInfoBlock follows directly after the type information
80   outputModuleInfoBlock(M);
81
82   // Output module level constants, used for global variable initializers
83   outputConstants(false);
84
85   // Do the whole module now! Process each function at a time...
86   for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
87     outputFunction(I);
88
89   // If needed, output the symbol table for the module...
90   outputSymbolTable(M->getSymbolTable());
91 }
92
93 // Helper function for outputConstants().
94 // Writes out all the constants in the plane Plane starting at entry StartNo.
95 // 
96 void BytecodeWriter::outputConstantsInPlane(const std::vector<const Value*>
97                                             &Plane, unsigned StartNo) {
98   unsigned ValNo = StartNo;
99   
100   // Scan through and ignore function arguments/global values...
101   for (; ValNo < Plane.size() && (isa<Argument>(Plane[ValNo]) ||
102                                   isa<GlobalValue>(Plane[ValNo])); ValNo++)
103     /*empty*/;
104
105   unsigned NC = ValNo;              // Number of constants
106   for (; NC < Plane.size() && 
107          (isa<Constant>(Plane[NC]) || isa<Type>(Plane[NC])); NC++)
108     /*empty*/;
109   NC -= ValNo;                      // Convert from index into count
110   if (NC == 0) return;              // Skip empty type planes...
111
112   // Output type header: [num entries][type id number]
113   //
114   output_vbr(NC, Out);
115
116   // Output the Type ID Number...
117   int Slot = Table.getSlot(Plane.front()->getType());
118   assert (Slot != -1 && "Type in constant pool but not in function!!");
119   output_vbr((unsigned)Slot, Out);
120
121   //cerr << "Emitting " << NC << " constants of type '" 
122   //     << Plane.front()->getType()->getName() << "' = Slot #" << Slot << "\n";
123
124   for (unsigned i = ValNo; i < ValNo+NC; ++i) {
125     const Value *V = Plane[i];
126     if (const Constant *CPV = dyn_cast<Constant>(V)) {
127       //cerr << "Serializing value: <" << V->getType() << ">: " << V << ":" 
128       //     << Out.size() << "\n";
129       outputConstant(CPV);
130     } else {
131       outputType(cast<Type>(V));
132     }
133   }
134 }
135
136 void BytecodeWriter::outputConstants(bool isFunction) {
137   BytecodeBlock CPool(BytecodeFormat::ConstantPool, Out);
138
139   unsigned NumPlanes = Table.getNumPlanes();
140
141   // Output the type plane before any constants!
142   if (isFunction && NumPlanes > Type::TypeTyID) {
143     const std::vector<const Value*> &Plane = Table.getPlane(Type::TypeTyID);
144     if (!Plane.empty()) {              // Skip empty type planes...
145       unsigned ValNo = Table.getModuleLevel(Type::TypeTyID);
146       outputConstantsInPlane(Plane, ValNo);
147     }
148   }
149   
150   for (unsigned pno = 0; pno != NumPlanes; pno++)
151     if (pno != Type::TypeTyID) {         // Type plane handled above.
152       const std::vector<const Value*> &Plane = Table.getPlane(pno);
153       if (!Plane.empty()) {              // Skip empty type planes...
154         unsigned ValNo = 0;
155         if (isFunction)                  // Don't re-emit module constants
156           ValNo += Table.getModuleLevel(pno);
157         
158         if (pno >= Type::FirstDerivedTyID) {
159           // Skip zero initializer
160           if (ValNo == 0)
161             ValNo = 1;
162         }
163         
164         // Write out constants in the plane
165         outputConstantsInPlane(Plane, ValNo);
166       }
167     }
168 }
169
170 static unsigned getEncodedLinkage(const GlobalValue *GV) {
171   switch (GV->getLinkage()) {
172   default: assert(0 && "Invalid linkage!");
173   case GlobalValue::ExternalLinkage:  return 0;
174   case GlobalValue::WeakLinkage:      return 1;
175   case GlobalValue::AppendingLinkage: return 2;
176   case GlobalValue::InternalLinkage:  return 3;
177   case GlobalValue::LinkOnceLinkage:  return 4;
178   }
179 }
180
181 void BytecodeWriter::outputModuleInfoBlock(const Module *M) {
182   BytecodeBlock ModuleInfoBlock(BytecodeFormat::ModuleGlobalInfo, Out);
183   
184   // Output the types for the global variables in the module...
185   for (Module::const_giterator I = M->gbegin(), End = M->gend(); I != End;++I) {
186     int Slot = Table.getSlot(I->getType());
187     assert(Slot != -1 && "Module global vars is broken!");
188
189     // Fields: bit0 = isConstant, bit1 = hasInitializer, bit2-4=Linkage,
190     // bit5+ = Slot # for type
191     unsigned oSlot = ((unsigned)Slot << 5) | (getEncodedLinkage(I) << 2) |
192                      (I->hasInitializer() << 1) | I->isConstant();
193     output_vbr(oSlot, Out);
194
195     // If we have an initializer, output it now.
196     if (I->hasInitializer()) {
197       Slot = Table.getSlot((Value*)I->getInitializer());
198       assert(Slot != -1 && "No slot for global var initializer!");
199       output_vbr((unsigned)Slot, Out);
200     }
201   }
202   output_vbr((unsigned)Table.getSlot(Type::VoidTy), Out);
203
204   // Output the types of the functions in this module...
205   for (Module::const_iterator I = M->begin(), End = M->end(); I != End; ++I) {
206     int Slot = Table.getSlot(I->getType());
207     assert(Slot != -1 && "Module const pool is broken!");
208     assert(Slot >= Type::FirstDerivedTyID && "Derived type not in range!");
209     output_vbr((unsigned)Slot, Out);
210   }
211   output_vbr((unsigned)Table.getSlot(Type::VoidTy), Out);
212
213   align32(Out);
214 }
215
216 void BytecodeWriter::outputFunction(const Function *F) {
217   BytecodeBlock FunctionBlock(BytecodeFormat::Function, Out);
218   output_vbr(getEncodedLinkage(F), Out);
219   // Only output the constant pool and other goodies if needed...
220   if (!F->isExternal()) {
221
222     // Get slot information about the function...
223     Table.incorporateFunction(F);
224
225     // Output information about the constants in the function...
226     outputConstants(true);
227
228     // Output basic block nodes...
229     for (Function::const_iterator I = F->begin(), E = F->end(); I != E; ++I)
230       processBasicBlock(*I);
231     
232     // If needed, output the symbol table for the function...
233     outputSymbolTable(F->getSymbolTable());
234     
235     Table.purgeFunction();
236   }
237 }
238
239
240 void BytecodeWriter::processBasicBlock(const BasicBlock &BB) {
241   BytecodeBlock FunctionBlock(BytecodeFormat::BasicBlock, Out);
242   // Process all the instructions in the bb...
243   for(BasicBlock::const_iterator I = BB.begin(), E = BB.end(); I != E; ++I)
244     processInstruction(*I);
245 }
246
247 void BytecodeWriter::outputSymbolTable(const SymbolTable &MST) {
248   BytecodeBlock FunctionBlock(BytecodeFormat::SymbolTable, Out);
249
250   for (SymbolTable::const_iterator TI = MST.begin(); TI != MST.end(); ++TI) {
251     SymbolTable::type_const_iterator I = MST.type_begin(TI->first);
252     SymbolTable::type_const_iterator End = MST.type_end(TI->first);
253     int Slot;
254     
255     if (I == End) continue;  // Don't mess with an absent type...
256
257     // Symtab block header: [num entries][type id number]
258     output_vbr(MST.type_size(TI->first), Out);
259
260     Slot = Table.getSlot(TI->first);
261     assert(Slot != -1 && "Type in symtab, but not in table!");
262     output_vbr((unsigned)Slot, Out);
263
264     for (; I != End; ++I) {
265       // Symtab entry: [def slot #][name]
266       Slot = Table.getSlot(I->second);
267       assert(Slot != -1 && "Value in symtab but has no slot number!!");
268       output_vbr((unsigned)Slot, Out);
269       output(I->first, Out, false); // Don't force alignment...
270     }
271   }
272 }
273
274 void WriteBytecodeToFile(const Module *C, std::ostream &Out) {
275   assert(C && "You can't write a null module!!");
276
277   std::deque<unsigned char> Buffer;
278
279   // This object populates buffer for us...
280   BytecodeWriter BCW(Buffer, C);
281
282   // Keep track of how much we've written...
283   BytesWritten += Buffer.size();
284
285   // Okay, write the deque out to the ostream now... the deque is not
286   // sequential in memory, however, so write out as much as possible in big
287   // chunks, until we're done.
288   //
289   std::deque<unsigned char>::const_iterator I = Buffer.begin(),E = Buffer.end();
290   while (I != E) {                           // Loop until it's all written
291     // Scan to see how big this chunk is...
292     const unsigned char *ChunkPtr = &*I;
293     const unsigned char *LastPtr = ChunkPtr;
294     while (I != E) {
295       const unsigned char *ThisPtr = &*++I;
296       if (LastPtr+1 != ThisPtr) {   // Advanced by more than a byte of memory?
297         ++LastPtr;
298         break;
299       }
300       LastPtr = ThisPtr;
301     }
302     
303     // Write out the chunk...
304     Out.write((char*)ChunkPtr, LastPtr-ChunkPtr);
305   }
306
307   Out.flush();
308 }
309
310 } // End llvm namespace