Move FunctionArgument out of iOther.h into Argument.h and rename class to
[oota-llvm.git] / lib / Bytecode / Writer / Writer.cpp
1 //===-- Writer.cpp - Library for writing VM bytecode files -------*- C++ -*--=//
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's, 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/Module.h"
24 #include "llvm/GlobalVariable.h"
25 #include "llvm/Function.h"
26 #include "llvm/BasicBlock.h"
27 #include "llvm/ConstantVals.h"
28 #include "llvm/SymbolTable.h"
29 #include "llvm/DerivedTypes.h"
30 #include "Support/STLExtras.h"
31 #include <string.h>
32 #include <algorithm>
33
34 BytecodeWriter::BytecodeWriter(std::deque<unsigned char> &o, const Module *M) 
35   : Out(o), Table(M, false) {
36
37   outputSignature();
38
39   // Emit the top level CLASS block.
40   BytecodeBlock ModuleBlock(BytecodeFormat::Module, Out);
41
42   // Output the ID of first "derived" type:
43   output_vbr((unsigned)Type::FirstDerivedTyID, Out);
44   align32(Out);
45
46   // Output module level constants, including types used by the function protos
47   outputConstants(false);
48
49   // The ModuleInfoBlock follows directly after the Module constant pool
50   outputModuleInfoBlock(M);
51
52   // Do the whole module now! Process each function at a time...
53   for_each(M->begin(), M->end(),
54            bind_obj(this, &BytecodeWriter::processMethod));
55
56   // If needed, output the symbol table for the module...
57   if (M->hasSymbolTable())
58     outputSymbolTable(*M->getSymbolTable());
59 }
60
61 void BytecodeWriter::outputConstants(bool isFunction) {
62   BytecodeBlock CPool(BytecodeFormat::ConstantPool, Out);
63
64   unsigned NumPlanes = Table.getNumPlanes();
65   for (unsigned pno = 0; pno < NumPlanes; pno++) {
66     const std::vector<const Value*> &Plane = Table.getPlane(pno);
67     if (Plane.empty()) continue;      // Skip empty type planes...
68
69     unsigned ValNo = 0;
70     if (isFunction)                   // Don't reemit module constants
71       ValNo = Table.getModuleLevel(pno);
72     else if (pno == Type::TypeTyID)
73       ValNo = Type::FirstDerivedTyID; // Start emitting at the derived types...
74     
75     // Scan through and ignore function arguments...
76     for (; ValNo < Plane.size() && isa<Argument>(Plane[ValNo]); ValNo++)
77       /*empty*/;
78
79     unsigned NC = ValNo;              // Number of constants
80     for (; NC < Plane.size() && 
81            (isa<Constant>(Plane[NC]) || 
82             isa<Type>(Plane[NC])); NC++) /*empty*/;
83     NC -= ValNo;                      // Convert from index into count
84     if (NC == 0) continue;            // Skip empty type planes...
85
86     // Output type header: [num entries][type id number]
87     //
88     output_vbr(NC, Out);
89
90     // Output the Type ID Number...
91     int Slot = Table.getValSlot(Plane.front()->getType());
92     assert (Slot != -1 && "Type in constant pool but not in function!!");
93     output_vbr((unsigned)Slot, Out);
94
95     //cerr << "Emitting " << NC << " constants of type '" 
96     //   << Plane.front()->getType()->getName() << "' = Slot #" << Slot << "\n";
97
98     for (unsigned i = ValNo; i < ValNo+NC; ++i) {
99       const Value *V = Plane[i];
100       if (const Constant *CPV = dyn_cast<Constant>(V)) {
101         //cerr << "Serializing value: <" << V->getType() << ">: " 
102         //     << ((const Constant*)V)->getStrValue() << ":" 
103         //     << Out.size() << "\n";
104         outputConstant(CPV);
105       } else {
106         outputType(cast<const Type>(V));
107       }
108     }
109   }
110 }
111
112 void BytecodeWriter::outputModuleInfoBlock(const Module *M) {
113   BytecodeBlock ModuleInfoBlock(BytecodeFormat::ModuleGlobalInfo, Out);
114   
115   // Output the types for the global variables in the module...
116   for (Module::const_giterator I = M->gbegin(), End = M->gend(); I != End;++I) {
117     const GlobalVariable *GV = *I;
118     int Slot = Table.getValSlot(GV->getType());
119     assert(Slot != -1 && "Module global vars is broken!");
120
121     // Fields: bit0 = isConstant, bit1 = hasInitializer, bit2=InternalLinkage,
122     // bit3+ = slot#
123     unsigned oSlot = ((unsigned)Slot << 3) | (GV->hasInternalLinkage() << 2) |
124                      (GV->hasInitializer() << 1) | GV->isConstant();
125     output_vbr(oSlot, Out);
126
127     // If we have an initializer, output it now.
128     if (GV->hasInitializer()) {
129       Slot = Table.getValSlot(GV->getInitializer());
130       assert(Slot != -1 && "No slot for global var initializer!");
131       output_vbr((unsigned)Slot, Out);
132     }
133   }
134   output_vbr((unsigned)Table.getValSlot(Type::VoidTy), Out);
135
136   // Output the types of the functions in this module...
137   for (Module::const_iterator I = M->begin(), End = M->end(); I != End; ++I) {
138     int Slot = Table.getValSlot((*I)->getType());
139     assert(Slot != -1 && "Module const pool is broken!");
140     assert(Slot >= Type::FirstDerivedTyID && "Derived type not in range!");
141     output_vbr((unsigned)Slot, Out);
142   }
143   output_vbr((unsigned)Table.getValSlot(Type::VoidTy), Out);
144
145
146   align32(Out);
147 }
148
149 void BytecodeWriter::processMethod(const Function *M) {
150   BytecodeBlock FunctionBlock(BytecodeFormat::Function, Out);
151   output_vbr((unsigned)M->hasInternalLinkage(), Out);
152   // Only output the constant pool and other goodies if needed...
153   if (!M->isExternal()) {
154
155     // Get slot information about the function...
156     Table.incorporateFunction(M);
157
158     // Output information about the constants in the function...
159     outputConstants(true);
160
161     // Output basic block nodes...
162     for_each(M->begin(), M->end(),
163              bind_obj(this, &BytecodeWriter::processBasicBlock));
164     
165     // If needed, output the symbol table for the function...
166     if (M->hasSymbolTable())
167       outputSymbolTable(*M->getSymbolTable());
168     
169     Table.purgeFunction();
170   }
171 }
172
173
174 void BytecodeWriter::processBasicBlock(const BasicBlock *BB) {
175   BytecodeBlock FunctionBlock(BytecodeFormat::BasicBlock, Out);
176   // Process all the instructions in the bb...
177   for_each(BB->begin(), BB->end(),
178            bind_obj(this, &BytecodeWriter::processInstruction));
179 }
180
181 void BytecodeWriter::outputSymbolTable(const SymbolTable &MST) {
182   BytecodeBlock FunctionBlock(BytecodeFormat::SymbolTable, Out);
183
184   for (SymbolTable::const_iterator TI = MST.begin(); TI != MST.end(); ++TI) {
185     SymbolTable::type_const_iterator I = MST.type_begin(TI->first);
186     SymbolTable::type_const_iterator End = MST.type_end(TI->first);
187     int Slot;
188     
189     if (I == End) continue;  // Don't mess with an absent type...
190
191     // Symtab block header: [num entries][type id number]
192     output_vbr(MST.type_size(TI->first), Out);
193
194     Slot = Table.getValSlot(TI->first);
195     assert(Slot != -1 && "Type in symtab, but not in table!");
196     output_vbr((unsigned)Slot, Out);
197
198     for (; I != End; ++I) {
199       // Symtab entry: [def slot #][name]
200       Slot = Table.getValSlot(I->second);
201       assert(Slot != -1 && "Value in symtab but has no slot number!!");
202       output_vbr((unsigned)Slot, Out);
203       output(I->first, Out, false); // Don't force alignment...
204     }
205   }
206 }
207
208 void WriteBytecodeToFile(const Module *C, ostream &Out) {
209   assert(C && "You can't write a null module!!");
210
211   std::deque<unsigned char> Buffer;
212
213   // This object populates buffer for us...
214   BytecodeWriter BCW(Buffer, C);
215
216   // Okay, write the deque out to the ostream now... the deque is not
217   // sequential in memory, however, so write out as much as possible in big
218   // chunks, until we're done.
219   //
220   std::deque<unsigned char>::const_iterator I = Buffer.begin(),E = Buffer.end();
221   while (I != E) {                           // Loop until it's all written
222     // Scan to see how big this chunk is...
223     const unsigned char *ChunkPtr = &*I;
224     const unsigned char *LastPtr = ChunkPtr;
225     while (I != E) {
226       const unsigned char *ThisPtr = &*++I;
227       if (LastPtr+1 != ThisPtr) {   // Advanced by more than a byte of memory?
228         ++LastPtr;
229         break;
230       }
231       LastPtr = ThisPtr;
232     }
233     
234     // Write out the chunk...
235     Out.write((char*)ChunkPtr, LastPtr-ChunkPtr);
236   }
237
238   Out.flush();
239 }