1 //===-- Writer.cpp - Library for writing VM bytecode files -------*- C++ -*--=//
3 // This library implements the functionality defined in llvm/Bytecode/Writer.h
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. :( :( :(
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.
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
20 //===----------------------------------------------------------------------===//
22 #include "WriterInternals.h"
23 #include "llvm/Bytecode/WriteBytecodePass.h"
24 #include "llvm/Module.h"
25 #include "llvm/SymbolTable.h"
26 #include "llvm/DerivedTypes.h"
27 #include "Support/STLExtras.h"
28 #include "Support/StatisticReporter.h"
32 static RegisterPass<WriteBytecodePass> X("emitbytecode", "Bytecode Writer");
35 BytesWritten("bytecodewriter\t- Number of bytecode bytes written");
38 BytecodeWriter::BytecodeWriter(std::deque<unsigned char> &o, const Module *M)
39 : Out(o), Table(M, false) {
43 // Emit the top level CLASS block.
44 BytecodeBlock ModuleBlock(BytecodeFormat::Module, Out);
46 // Output the ID of first "derived" type:
47 output_vbr((unsigned)Type::FirstDerivedTyID, Out);
50 // Output module level constants, including types used by the function protos
51 outputConstants(false);
53 // The ModuleInfoBlock follows directly after the Module constant pool
54 outputModuleInfoBlock(M);
56 // Do the whole module now! Process each function at a time...
57 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
60 // If needed, output the symbol table for the module...
61 if (M->hasSymbolTable())
62 outputSymbolTable(*M->getSymbolTable());
65 // Helper function for outputConstants().
66 // Writes out all the constants in the plane Plane starting at entry StartNo.
68 void BytecodeWriter::outputConstantsInPlane(const std::vector<const Value*>
69 &Plane, unsigned StartNo) {
70 unsigned ValNo = StartNo;
72 // Scan through and ignore function arguments...
73 for (; ValNo < Plane.size() && isa<Argument>(Plane[ValNo]); ValNo++)
76 unsigned NC = ValNo; // Number of constants
77 for (; NC < Plane.size() &&
78 (isa<Constant>(Plane[NC]) || isa<Type>(Plane[NC])); NC++)
80 NC -= ValNo; // Convert from index into count
81 if (NC == 0) return; // Skip empty type planes...
83 // Output type header: [num entries][type id number]
87 // Output the Type ID Number...
88 int Slot = Table.getValSlot(Plane.front()->getType());
89 assert (Slot != -1 && "Type in constant pool but not in function!!");
90 output_vbr((unsigned)Slot, Out);
92 //cerr << "Emitting " << NC << " constants of type '"
93 // << Plane.front()->getType()->getName() << "' = Slot #" << Slot << "\n";
95 for (unsigned i = ValNo; i < ValNo+NC; ++i) {
96 const Value *V = Plane[i];
97 if (const Constant *CPV = dyn_cast<Constant>(V)) {
98 //cerr << "Serializing value: <" << V->getType() << ">: " << V << ":"
99 // << Out.size() << "\n";
102 outputType(cast<const Type>(V));
107 void BytecodeWriter::outputConstants(bool isFunction) {
108 BytecodeBlock CPool(BytecodeFormat::ConstantPool, Out);
110 unsigned NumPlanes = Table.getNumPlanes();
112 // Write the type plane for types first because earlier planes
113 // (e.g. for a primitive type like float) may have constants constructed
114 // using types coming later (e.g., via getelementptr from a pointer type).
115 // The type plane is needed before types can be fwd or bkwd referenced.
117 const std::vector<const Value*> &Plane = Table.getPlane(Type::TypeTyID);
118 assert(!Plane.empty() && "No types at all?");
119 unsigned ValNo = Type::FirstDerivedTyID; // Start at the derived types...
120 outputConstantsInPlane(Plane, ValNo); // Write out the types
123 for (unsigned pno = 0; pno < NumPlanes; pno++) {
124 const std::vector<const Value*> &Plane = Table.getPlane(pno);
125 if (Plane.empty()) continue; // Skip empty type planes...
128 if (isFunction) // Don't reemit module constants
129 ValNo = Table.getModuleLevel(pno);
130 else if (pno == Type::TypeTyID)
131 continue; // Type plane was written out above
133 outputConstantsInPlane(Plane, ValNo); // Write out constants in the plane
137 void BytecodeWriter::outputModuleInfoBlock(const Module *M) {
138 BytecodeBlock ModuleInfoBlock(BytecodeFormat::ModuleGlobalInfo, Out);
140 // Output the types for the global variables in the module...
141 for (Module::const_giterator I = M->gbegin(), End = M->gend(); I != End;++I) {
142 int Slot = Table.getValSlot(I->getType());
143 assert(Slot != -1 && "Module global vars is broken!");
145 // Fields: bit0 = isConstant, bit1 = hasInitializer, bit2=InternalLinkage,
147 unsigned oSlot = ((unsigned)Slot << 3) | (I->hasInternalLinkage() << 2) |
148 (I->hasInitializer() << 1) | I->isConstant();
149 output_vbr(oSlot, Out);
151 // If we have an initializer, output it now.
152 if (I->hasInitializer()) {
153 Slot = Table.getValSlot((Value*)I->getInitializer());
154 assert(Slot != -1 && "No slot for global var initializer!");
155 output_vbr((unsigned)Slot, Out);
158 output_vbr((unsigned)Table.getValSlot(Type::VoidTy), Out);
160 // Output the types of the functions in this module...
161 for (Module::const_iterator I = M->begin(), End = M->end(); I != End; ++I) {
162 int Slot = Table.getValSlot(I->getType());
163 assert(Slot != -1 && "Module const pool is broken!");
164 assert(Slot >= Type::FirstDerivedTyID && "Derived type not in range!");
165 output_vbr((unsigned)Slot, Out);
167 output_vbr((unsigned)Table.getValSlot(Type::VoidTy), Out);
173 void BytecodeWriter::processMethod(const Function *F) {
174 BytecodeBlock FunctionBlock(BytecodeFormat::Function, Out);
175 output_vbr((unsigned)F->hasInternalLinkage(), Out);
176 // Only output the constant pool and other goodies if needed...
177 if (!F->isExternal()) {
179 // Get slot information about the function...
180 Table.incorporateFunction(F);
182 // Output information about the constants in the function...
183 outputConstants(true);
185 // Output basic block nodes...
186 for (Function::const_iterator I = F->begin(), E = F->end(); I != E; ++I)
187 processBasicBlock(*I);
189 // If needed, output the symbol table for the function...
190 if (F->hasSymbolTable())
191 outputSymbolTable(*F->getSymbolTable());
193 Table.purgeFunction();
198 void BytecodeWriter::processBasicBlock(const BasicBlock &BB) {
199 BytecodeBlock FunctionBlock(BytecodeFormat::BasicBlock, Out);
200 // Process all the instructions in the bb...
201 for(BasicBlock::const_iterator I = BB.begin(), E = BB.end(); I != E; ++I)
202 processInstruction(*I);
205 void BytecodeWriter::outputSymbolTable(const SymbolTable &MST) {
206 BytecodeBlock FunctionBlock(BytecodeFormat::SymbolTable, Out);
208 for (SymbolTable::const_iterator TI = MST.begin(); TI != MST.end(); ++TI) {
209 SymbolTable::type_const_iterator I = MST.type_begin(TI->first);
210 SymbolTable::type_const_iterator End = MST.type_end(TI->first);
213 if (I == End) continue; // Don't mess with an absent type...
215 // Symtab block header: [num entries][type id number]
216 output_vbr(MST.type_size(TI->first), Out);
218 Slot = Table.getValSlot(TI->first);
219 assert(Slot != -1 && "Type in symtab, but not in table!");
220 output_vbr((unsigned)Slot, Out);
222 for (; I != End; ++I) {
223 // Symtab entry: [def slot #][name]
224 Slot = Table.getValSlot(I->second);
225 assert(Slot != -1 && "Value in symtab but has no slot number!!");
226 output_vbr((unsigned)Slot, Out);
227 output(I->first, Out, false); // Don't force alignment...
232 void WriteBytecodeToFile(const Module *C, std::ostream &Out) {
233 assert(C && "You can't write a null module!!");
235 std::deque<unsigned char> Buffer;
237 // This object populates buffer for us...
238 BytecodeWriter BCW(Buffer, C);
240 // Keep track of how much we've written...
241 BytesWritten += Buffer.size();
243 // Okay, write the deque out to the ostream now... the deque is not
244 // sequential in memory, however, so write out as much as possible in big
245 // chunks, until we're done.
247 std::deque<unsigned char>::const_iterator I = Buffer.begin(),E = Buffer.end();
248 while (I != E) { // Loop until it's all written
249 // Scan to see how big this chunk is...
250 const unsigned char *ChunkPtr = &*I;
251 const unsigned char *LastPtr = ChunkPtr;
253 const unsigned char *ThisPtr = &*++I;
254 if (LastPtr+1 != ThisPtr) { // Advanced by more than a byte of memory?
261 // Write out the chunk...
262 Out.write((char*)ChunkPtr, LastPtr-ChunkPtr);