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