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