Remove all of the annoying statistics now that I'm finished (for the near
[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/Constants.h"
28 #include "llvm/DerivedTypes.h"
29 #include "llvm/Module.h"
30 #include "llvm/SymbolTable.h"
31 #include "Support/STLExtras.h"
32 #include "Support/Statistic.h"
33 #include <cstring>
34 #include <algorithm>
35 using namespace llvm;
36
37 static RegisterPass<WriteBytecodePass> X("emitbytecode", "Bytecode Writer");
38
39 static Statistic<> 
40 BytesWritten("bytecodewriter", "Number of bytecode bytes written");
41
42 BytecodeWriter::BytecodeWriter(std::deque<unsigned char> &o, const Module *M) 
43   : Out(o), Table(M, true) {
44
45   // Emit the signature...
46   static const unsigned char *Sig =  (const unsigned char*)"llvm";
47   output_data(Sig, Sig+4, Out);
48
49   // Emit the top level CLASS block.
50   BytecodeBlock ModuleBlock(BytecodeFormat::Module, Out);
51
52   bool isBigEndian      = M->getEndianness() == Module::BigEndian;
53   bool hasLongPointers  = M->getPointerSize() == Module::Pointer64;
54   bool hasNoEndianness  = M->getEndianness() == Module::AnyEndianness;
55   bool hasNoPointerSize = M->getPointerSize() == Module::AnyPointerSize;
56
57   // Output the version identifier... we are currently on bytecode version #1,
58   // which corresponds to LLVM v1.2.
59   unsigned Version = (1 << 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, and constant
99   // strings.
100   for (; ValNo < Plane.size() &&
101          (isa<Argument>(Plane[ValNo]) || isa<GlobalValue>(Plane[ValNo]) ||
102           (isa<ConstantArray>(Plane[ValNo]) &&
103            cast<ConstantArray>(Plane[ValNo])->isString())); ValNo++)
104     /*empty*/;
105
106   unsigned NC = ValNo;              // Number of constants
107   for (; NC < Plane.size() && 
108          (isa<Constant>(Plane[NC]) || isa<Type>(Plane[NC])); NC++)
109     /*empty*/;
110   NC -= ValNo;                      // Convert from index into count
111   if (NC == 0) return;              // Skip empty type planes...
112
113   // FIXME: Most slabs only have 1 or 2 entries!  We should encode this much
114   // more compactly.
115
116   // Output type header: [num entries][type id number]
117   //
118   output_vbr(NC, Out);
119
120   // Output the Type ID Number...
121   int Slot = Table.getSlot(Plane.front()->getType());
122   assert (Slot != -1 && "Type in constant pool but not in function!!");
123   output_vbr((unsigned)Slot, Out);
124
125   //cerr << "Emitting " << NC << " constants of type '" 
126   //     << Plane.front()->getType()->getName() << "' = Slot #" << Slot << "\n";
127
128   for (unsigned i = ValNo; i < ValNo+NC; ++i) {
129     const Value *V = Plane[i];
130     if (const Constant *CPV = dyn_cast<Constant>(V)) {
131       //cerr << "Serializing value: <" << V->getType() << ">: " << V << ":" 
132       //     << Out.size() << "\n";
133       outputConstant(CPV);
134     } else {
135       outputType(cast<Type>(V));
136     }
137   }
138 }
139
140 static inline bool hasNullValue(unsigned TyID) {
141   return TyID != Type::LabelTyID && TyID != Type::TypeTyID &&
142          TyID != Type::VoidTyID;
143 }
144
145 void BytecodeWriter::outputConstants(bool isFunction) {
146   BytecodeBlock CPool(BytecodeFormat::ConstantPool, Out,
147                       true  /* Elide block if empty */);
148
149   unsigned NumPlanes = Table.getNumPlanes();
150
151   // Output the type plane before any constants!
152   if (isFunction && NumPlanes > Type::TypeTyID) {
153     const std::vector<const Value*> &Plane = Table.getPlane(Type::TypeTyID);
154     if (!Plane.empty()) {              // Skip empty type planes...
155       unsigned ValNo = Table.getModuleLevel(Type::TypeTyID);
156       outputConstantsInPlane(Plane, ValNo);
157     }
158   }
159   
160   // Output module-level string constants before any other constants.x
161   if (!isFunction)
162     outputConstantStrings();
163
164   for (unsigned pno = 0; pno != NumPlanes; pno++)
165     if (pno != Type::TypeTyID) {         // Type plane handled above.
166       const std::vector<const Value*> &Plane = Table.getPlane(pno);
167       if (!Plane.empty()) {              // Skip empty type planes...
168         unsigned ValNo = 0;
169         if (isFunction)                  // Don't re-emit module constants
170           ValNo += Table.getModuleLevel(pno);
171         
172         if (hasNullValue(pno)) {
173           // Skip zero initializer
174           if (ValNo == 0)
175             ValNo = 1;
176         }
177         
178         // Write out constants in the plane
179         outputConstantsInPlane(Plane, ValNo);
180       }
181     }
182 }
183
184 static unsigned getEncodedLinkage(const GlobalValue *GV) {
185   switch (GV->getLinkage()) {
186   default: assert(0 && "Invalid linkage!");
187   case GlobalValue::ExternalLinkage:  return 0;
188   case GlobalValue::WeakLinkage:      return 1;
189   case GlobalValue::AppendingLinkage: return 2;
190   case GlobalValue::InternalLinkage:  return 3;
191   case GlobalValue::LinkOnceLinkage:  return 4;
192   }
193 }
194
195 void BytecodeWriter::outputModuleInfoBlock(const Module *M) {
196   BytecodeBlock ModuleInfoBlock(BytecodeFormat::ModuleGlobalInfo, Out);
197   
198   // Output the types for the global variables in the module...
199   for (Module::const_giterator I = M->gbegin(), End = M->gend(); I != End;++I) {
200     int Slot = Table.getSlot(I->getType());
201     assert(Slot != -1 && "Module global vars is broken!");
202
203     // Fields: bit0 = isConstant, bit1 = hasInitializer, bit2-4=Linkage,
204     // bit5+ = Slot # for type
205     unsigned oSlot = ((unsigned)Slot << 5) | (getEncodedLinkage(I) << 2) |
206                      (I->hasInitializer() << 1) | I->isConstant();
207     output_vbr(oSlot, Out);
208
209     // If we have an initializer, output it now.
210     if (I->hasInitializer()) {
211       Slot = Table.getSlot((Value*)I->getInitializer());
212       assert(Slot != -1 && "No slot for global var initializer!");
213       output_vbr((unsigned)Slot, Out);
214     }
215   }
216   output_vbr((unsigned)Table.getSlot(Type::VoidTy), Out);
217
218   // Output the types of the functions in this module...
219   for (Module::const_iterator I = M->begin(), End = M->end(); I != End; ++I) {
220     int Slot = Table.getSlot(I->getType());
221     assert(Slot != -1 && "Module const pool is broken!");
222     assert(Slot >= Type::FirstDerivedTyID && "Derived type not in range!");
223     output_vbr((unsigned)Slot, Out);
224   }
225   output_vbr((unsigned)Table.getSlot(Type::VoidTy), Out);
226 }
227
228 void BytecodeWriter::outputInstructions(const Function *F) {
229   BytecodeBlock ILBlock(BytecodeFormat::InstructionList, Out);
230   for (Function::const_iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
231     for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I)
232       outputInstruction(*I);
233 }
234
235 void BytecodeWriter::outputFunction(const Function *F) {
236   BytecodeBlock FunctionBlock(BytecodeFormat::Function, Out);
237   output_vbr(getEncodedLinkage(F), Out);
238
239   // If this is an external function, there is nothing else to emit!
240   if (F->isExternal()) return;
241
242   // Get slot information about the function...
243   Table.incorporateFunction(F);
244
245   if (Table.getCompactionTable().empty()) {
246     // Output information about the constants in the function if the compaction
247     // table is not being used.
248     outputConstants(true);
249   } else {
250     // Otherwise, emit the compaction table.
251     outputCompactionTable();
252   }
253   
254   // Output all of the instructions in the body of the function
255   outputInstructions(F);
256   
257   // If needed, output the symbol table for the function...
258   outputSymbolTable(F->getSymbolTable());
259   
260   Table.purgeFunction();
261 }
262
263 void BytecodeWriter::outputCompactionTablePlane(unsigned PlaneNo,
264                                          const std::vector<const Value*> &Plane,
265                                                 unsigned StartNo) {
266   unsigned End = Table.getModuleLevel(PlaneNo);
267   if (Plane.empty() || StartNo == End || End == 0) return;   // Nothing to emit
268   assert(StartNo < End && "Cannot emit negative range!");
269   assert(StartNo < Plane.size() && End <= Plane.size());
270
271   // Do not emit the null initializer!
272   if (PlaneNo != Type::TypeTyID) ++StartNo;
273
274   // Figure out which encoding to use.  By far the most common case we have is
275   // to emit 0-2 entries in a compaction table plane.
276   switch (End-StartNo) {
277   case 0:         // Avoid emitting two vbr's if possible.
278   case 1:
279   case 2:
280     output_vbr((PlaneNo << 2) | End-StartNo, Out);
281     break;
282   default:
283     // Output the number of things.
284     output_vbr((unsigned(End-StartNo) << 2) | 3, Out);
285     output_vbr(PlaneNo, Out);                 // Emit the type plane this is
286     break;
287   }
288
289   for (unsigned i = StartNo; i != End; ++i)
290     output_vbr(Table.getGlobalSlot(Plane[i]), Out);
291 }
292
293 void BytecodeWriter::outputCompactionTable() {
294   BytecodeBlock CTB(BytecodeFormat::CompactionTable, Out, true/*ElideIfEmpty*/);
295   const std::vector<std::vector<const Value*> > &CT =Table.getCompactionTable();
296   
297   // First thing is first, emit the type compaction table if there is one.
298   if (CT.size() > Type::TypeTyID)
299     outputCompactionTablePlane(Type::TypeTyID, CT[Type::TypeTyID],
300                                Type::FirstDerivedTyID);
301
302   for (unsigned i = 0, e = CT.size(); i != e; ++i)
303     if (i != Type::TypeTyID)
304       outputCompactionTablePlane(i, CT[i], 0);
305 }
306
307 void BytecodeWriter::outputSymbolTable(const SymbolTable &MST) {
308   // Do not output the Bytecode block for an empty symbol table, it just wastes
309   // space!
310   if (MST.begin() == MST.end()) return;
311
312   BytecodeBlock SymTabBlock(BytecodeFormat::SymbolTable, Out,
313                             true/* ElideIfEmpty*/);
314
315   for (SymbolTable::const_iterator TI = MST.begin(); TI != MST.end(); ++TI) {
316     SymbolTable::type_const_iterator I = MST.type_begin(TI->first);
317     SymbolTable::type_const_iterator End = MST.type_end(TI->first);
318     int Slot;
319     
320     if (I == End) continue;  // Don't mess with an absent type...
321
322     // Symtab block header: [num entries][type id number]
323     output_vbr(MST.type_size(TI->first), Out);
324
325     Slot = Table.getSlot(TI->first);
326     assert(Slot != -1 && "Type in symtab, but not in table!");
327     output_vbr((unsigned)Slot, Out);
328
329     for (; I != End; ++I) {
330       // Symtab entry: [def slot #][name]
331       const Value *V = I->second;
332
333       Slot = Table.getSlot(I->second);
334       assert(Slot != -1 && "Value in symtab but has no slot number!!");
335       output_vbr((unsigned)Slot, Out);
336       output(I->first, Out, false); // Don't force alignment...
337     }
338   }
339 }
340
341 void llvm::WriteBytecodeToFile(const Module *C, std::ostream &Out) {
342   assert(C && "You can't write a null module!!");
343
344   std::deque<unsigned char> Buffer;
345
346   // This object populates buffer for us...
347   BytecodeWriter BCW(Buffer, C);
348
349   // Keep track of how much we've written...
350   BytesWritten += Buffer.size();
351
352   // Okay, write the deque out to the ostream now... the deque is not
353   // sequential in memory, however, so write out as much as possible in big
354   // chunks, until we're done.
355   //
356   std::deque<unsigned char>::const_iterator I = Buffer.begin(),E = Buffer.end();
357   while (I != E) {                           // Loop until it's all written
358     // Scan to see how big this chunk is...
359     const unsigned char *ChunkPtr = &*I;
360     const unsigned char *LastPtr = ChunkPtr;
361     while (I != E) {
362       const unsigned char *ThisPtr = &*++I;
363       if (LastPtr+1 != ThisPtr) {   // Advanced by more than a byte of memory?
364         ++LastPtr;
365         break;
366       }
367       LastPtr = ThisPtr;
368     }
369     
370     // Write out the chunk...
371     Out.write((char*)ChunkPtr, LastPtr-ChunkPtr);
372   }
373
374   Out.flush();
375 }