Err, we don't need Config/*.h files for things that are standard C++
[oota-llvm.git] / lib / Bytecode / Writer / Writer.cpp
1 //===-- Writer.cpp - Library for writing LLVM 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 //===----------------------------------------------------------------------===//
24
25 #include "WriterInternals.h"
26 #include "llvm/Bytecode/WriteBytecodePass.h"
27 #include "llvm/Module.h"
28 #include "llvm/SymbolTable.h"
29 #include "llvm/DerivedTypes.h"
30 #include "Support/STLExtras.h"
31 #include "Support/Statistic.h"
32 #include <cstring>
33 #include <algorithm>
34 using namespace llvm;
35
36 static RegisterPass<WriteBytecodePass> X("emitbytecode", "Bytecode Writer");
37
38 static Statistic<> 
39 BytesWritten("bytecodewriter", "Number of bytecode bytes written");
40
41
42 BytecodeWriter::BytecodeWriter(std::deque<unsigned char> &o, const Module *M) 
43   : Out(o), Table(M, false) {
44
45   outputSignature();
46
47   // Emit the top level CLASS block.
48   BytecodeBlock ModuleBlock(BytecodeFormat::Module, Out);
49
50   bool isBigEndian      = M->getEndianness() == Module::BigEndian;
51   bool hasLongPointers  = M->getPointerSize() == Module::Pointer64;
52   bool hasNoEndianness  = M->getEndianness() == Module::AnyEndianness;
53   bool hasNoPointerSize = M->getPointerSize() == Module::AnyPointerSize;
54
55   // Output the version identifier... we are currently on bytecode version #0
56   unsigned Version = (0 << 4) | isBigEndian | (hasLongPointers << 1) |
57                      (hasNoEndianness << 2) | (hasNoPointerSize << 3);
58   output_vbr(Version, Out);
59   align32(Out);
60
61   {
62     BytecodeBlock CPool(BytecodeFormat::GlobalTypePlane, Out);
63     
64     // Write the type plane for types first because earlier planes (e.g. for a
65     // primitive type like float) may have constants constructed using types
66     // coming later (e.g., via getelementptr from a pointer type).  The type
67     // plane is needed before types can be fwd or bkwd referenced.
68     const std::vector<const Value*> &Plane = Table.getPlane(Type::TypeTyID);
69     assert(!Plane.empty() && "No types at all?");
70     unsigned ValNo = Type::FirstDerivedTyID; // Start at the derived types...
71     outputConstantsInPlane(Plane, ValNo);      // Write out the types
72   }
73
74   // The ModuleInfoBlock follows directly after the type information
75   outputModuleInfoBlock(M);
76
77   // Output module level constants, used for global variable initializers
78   outputConstants(false);
79
80   // Do the whole module now! Process each function at a time...
81   for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
82     outputFunction(I);
83
84   // If needed, output the symbol table for the module...
85   outputSymbolTable(M->getSymbolTable());
86 }
87
88 // Helper function for outputConstants().
89 // Writes out all the constants in the plane Plane starting at entry StartNo.
90 // 
91 void BytecodeWriter::outputConstantsInPlane(const std::vector<const Value*>
92                                             &Plane, unsigned StartNo) {
93   unsigned ValNo = StartNo;
94   
95   // Scan through and ignore function arguments/global values...
96   for (; ValNo < Plane.size() && (isa<Argument>(Plane[ValNo]) ||
97                                   isa<GlobalValue>(Plane[ValNo])); ValNo++)
98     /*empty*/;
99
100   unsigned NC = ValNo;              // Number of constants
101   for (; NC < Plane.size() && 
102          (isa<Constant>(Plane[NC]) || isa<Type>(Plane[NC])); NC++)
103     /*empty*/;
104   NC -= ValNo;                      // Convert from index into count
105   if (NC == 0) return;              // Skip empty type planes...
106
107   // Output type header: [num entries][type id number]
108   //
109   output_vbr(NC, Out);
110
111   // Output the Type ID Number...
112   int Slot = Table.getSlot(Plane.front()->getType());
113   assert (Slot != -1 && "Type in constant pool but not in function!!");
114   output_vbr((unsigned)Slot, Out);
115
116   //cerr << "Emitting " << NC << " constants of type '" 
117   //     << Plane.front()->getType()->getName() << "' = Slot #" << Slot << "\n";
118
119   for (unsigned i = ValNo; i < ValNo+NC; ++i) {
120     const Value *V = Plane[i];
121     if (const Constant *CPV = dyn_cast<Constant>(V)) {
122       //cerr << "Serializing value: <" << V->getType() << ">: " << V << ":" 
123       //     << Out.size() << "\n";
124       outputConstant(CPV);
125     } else {
126       outputType(cast<Type>(V));
127     }
128   }
129 }
130
131 void BytecodeWriter::outputConstants(bool isFunction) {
132   BytecodeBlock CPool(BytecodeFormat::ConstantPool, Out);
133
134   unsigned NumPlanes = Table.getNumPlanes();
135
136   // Output the type plane before any constants!
137   if (isFunction && NumPlanes > Type::TypeTyID) {
138     const std::vector<const Value*> &Plane = Table.getPlane(Type::TypeTyID);
139     if (!Plane.empty()) {              // Skip empty type planes...
140       unsigned ValNo = Table.getModuleLevel(Type::TypeTyID);
141       outputConstantsInPlane(Plane, ValNo);
142     }
143   }
144   
145   for (unsigned pno = 0; pno != NumPlanes; pno++)
146     if (pno != Type::TypeTyID) {         // Type plane handled above.
147       const std::vector<const Value*> &Plane = Table.getPlane(pno);
148       if (!Plane.empty()) {              // Skip empty type planes...
149         unsigned ValNo = 0;
150         if (isFunction)                  // Don't re-emit module constants
151           ValNo += Table.getModuleLevel(pno);
152         
153         if (pno >= Type::FirstDerivedTyID) {
154           // Skip zero initializer
155           if (ValNo == 0)
156             ValNo = 1;
157         }
158         
159         // Write out constants in the plane
160         outputConstantsInPlane(Plane, ValNo);
161       }
162     }
163 }
164
165 static unsigned getEncodedLinkage(const GlobalValue *GV) {
166   switch (GV->getLinkage()) {
167   default: assert(0 && "Invalid linkage!");
168   case GlobalValue::ExternalLinkage:  return 0;
169   case GlobalValue::WeakLinkage:      return 1;
170   case GlobalValue::AppendingLinkage: return 2;
171   case GlobalValue::InternalLinkage:  return 3;
172   case GlobalValue::LinkOnceLinkage:  return 4;
173   }
174 }
175
176 void BytecodeWriter::outputModuleInfoBlock(const Module *M) {
177   BytecodeBlock ModuleInfoBlock(BytecodeFormat::ModuleGlobalInfo, Out);
178   
179   // Output the types for the global variables in the module...
180   for (Module::const_giterator I = M->gbegin(), End = M->gend(); I != End;++I) {
181     int Slot = Table.getSlot(I->getType());
182     assert(Slot != -1 && "Module global vars is broken!");
183
184     // Fields: bit0 = isConstant, bit1 = hasInitializer, bit2-4=Linkage,
185     // bit5+ = Slot # for type
186     unsigned oSlot = ((unsigned)Slot << 5) | (getEncodedLinkage(I) << 2) |
187                      (I->hasInitializer() << 1) | I->isConstant();
188     output_vbr(oSlot, Out);
189
190     // If we have an initializer, output it now.
191     if (I->hasInitializer()) {
192       Slot = Table.getSlot((Value*)I->getInitializer());
193       assert(Slot != -1 && "No slot for global var initializer!");
194       output_vbr((unsigned)Slot, Out);
195     }
196   }
197   output_vbr((unsigned)Table.getSlot(Type::VoidTy), Out);
198
199   // Output the types of the functions in this module...
200   for (Module::const_iterator I = M->begin(), End = M->end(); I != End; ++I) {
201     int Slot = Table.getSlot(I->getType());
202     assert(Slot != -1 && "Module const pool is broken!");
203     assert(Slot >= Type::FirstDerivedTyID && "Derived type not in range!");
204     output_vbr((unsigned)Slot, Out);
205   }
206   output_vbr((unsigned)Table.getSlot(Type::VoidTy), Out);
207
208   align32(Out);
209 }
210
211 void BytecodeWriter::outputFunction(const Function *F) {
212   BytecodeBlock FunctionBlock(BytecodeFormat::Function, Out);
213   output_vbr(getEncodedLinkage(F), Out);
214   // Only output the constant pool and other goodies if needed...
215   if (!F->isExternal()) {
216
217     // Get slot information about the function...
218     Table.incorporateFunction(F);
219
220     // Output information about the constants in the function...
221     outputConstants(true);
222
223     {  // Output all of the instructions in the body of the function
224       BytecodeBlock ILBlock(BytecodeFormat::InstructionList, Out);
225
226       for (Function::const_iterator BB = F->begin(), E = F->end(); BB != E;++BB)
227         for(BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;++I)
228           processInstruction(*I);
229     }
230     
231     // If needed, output the symbol table for the function...
232     outputSymbolTable(F->getSymbolTable());
233     
234     Table.purgeFunction();
235   }
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 llvm::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 }