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