1 //===-- Writer.cpp - Library for writing LLVM bytecode files --------------===//
3 // The LLVM Compiler Infrastructure
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.
8 //===----------------------------------------------------------------------===//
10 // This library implements the functionality defined in llvm/Bytecode/Writer.h
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. :( :( :(
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.
23 //===----------------------------------------------------------------------===//
25 #include "WriterInternals.h"
26 #include "llvm/Bytecode/WriteBytecodePass.h"
27 #include "llvm/Module.h"
28 #include "llvm/SymbolTable.h"
29 #include "llvm/DerivedTypes.h"
30 #include "Support/STLExtras.h"
31 #include "Support/Statistic.h"
36 static RegisterPass<WriteBytecodePass> X("emitbytecode", "Bytecode Writer");
39 BytesWritten("bytecodewriter", "Number of bytecode bytes written");
42 BytecodeWriter::BytecodeWriter(std::deque<unsigned char> &o, const Module *M)
43 : Out(o), Table(M, false) {
47 // Emit the top level CLASS block.
48 BytecodeBlock ModuleBlock(BytecodeFormat::Module, Out);
50 bool isBigEndian = M->getEndianness() == Module::BigEndian;
51 bool hasLongPointers = M->getPointerSize() == Module::Pointer64;
52 bool hasNoEndianness = M->getEndianness() == Module::AnyEndianness;
53 bool hasNoPointerSize = M->getPointerSize() == Module::AnyPointerSize;
55 // Output the version identifier... we are currently on bytecode version #0
56 unsigned Version = (0 << 4) | isBigEndian | (hasLongPointers << 1) |
57 (hasNoEndianness << 2) | (hasNoPointerSize << 3);
58 output_vbr(Version, Out);
62 BytecodeBlock CPool(BytecodeFormat::GlobalTypePlane, Out);
64 // Write the type plane for types first because earlier planes (e.g. for a
65 // primitive type like float) may have constants constructed using types
66 // coming later (e.g., via getelementptr from a pointer type). The type
67 // plane is needed before types can be fwd or bkwd referenced.
68 const std::vector<const Value*> &Plane = Table.getPlane(Type::TypeTyID);
69 assert(!Plane.empty() && "No types at all?");
70 unsigned ValNo = Type::FirstDerivedTyID; // Start at the derived types...
71 outputConstantsInPlane(Plane, ValNo); // Write out the types
74 // The ModuleInfoBlock follows directly after the type information
75 outputModuleInfoBlock(M);
77 // Output module level constants, used for global variable initializers
78 outputConstants(false);
80 // Do the whole module now! Process each function at a time...
81 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
84 // If needed, output the symbol table for the module...
85 outputSymbolTable(M->getSymbolTable());
88 // Helper function for outputConstants().
89 // Writes out all the constants in the plane Plane starting at entry StartNo.
91 void BytecodeWriter::outputConstantsInPlane(const std::vector<const Value*>
92 &Plane, unsigned StartNo) {
93 unsigned ValNo = StartNo;
95 // Scan through and ignore function arguments/global values...
96 for (; ValNo < Plane.size() && (isa<Argument>(Plane[ValNo]) ||
97 isa<GlobalValue>(Plane[ValNo])); ValNo++)
100 unsigned NC = ValNo; // Number of constants
101 for (; NC < Plane.size() &&
102 (isa<Constant>(Plane[NC]) || isa<Type>(Plane[NC])); NC++)
104 NC -= ValNo; // Convert from index into count
105 if (NC == 0) return; // Skip empty type planes...
107 // Output type header: [num entries][type id number]
111 // Output the Type ID Number...
112 int Slot = Table.getSlot(Plane.front()->getType());
113 assert (Slot != -1 && "Type in constant pool but not in function!!");
114 output_vbr((unsigned)Slot, Out);
116 //cerr << "Emitting " << NC << " constants of type '"
117 // << Plane.front()->getType()->getName() << "' = Slot #" << Slot << "\n";
119 for (unsigned i = ValNo; i < ValNo+NC; ++i) {
120 const Value *V = Plane[i];
121 if (const Constant *CPV = dyn_cast<Constant>(V)) {
122 //cerr << "Serializing value: <" << V->getType() << ">: " << V << ":"
123 // << Out.size() << "\n";
126 outputType(cast<Type>(V));
131 void BytecodeWriter::outputConstants(bool isFunction) {
132 BytecodeBlock CPool(BytecodeFormat::ConstantPool, Out);
134 unsigned NumPlanes = Table.getNumPlanes();
136 // Output the type plane before any constants!
137 if (isFunction && NumPlanes > Type::TypeTyID) {
138 const std::vector<const Value*> &Plane = Table.getPlane(Type::TypeTyID);
139 if (!Plane.empty()) { // Skip empty type planes...
140 unsigned ValNo = Table.getModuleLevel(Type::TypeTyID);
141 outputConstantsInPlane(Plane, ValNo);
145 for (unsigned pno = 0; pno != NumPlanes; pno++)
146 if (pno != Type::TypeTyID) { // Type plane handled above.
147 const std::vector<const Value*> &Plane = Table.getPlane(pno);
148 if (!Plane.empty()) { // Skip empty type planes...
150 if (isFunction) // Don't re-emit module constants
151 ValNo += Table.getModuleLevel(pno);
153 if (pno >= Type::FirstDerivedTyID) {
154 // Skip zero initializer
159 // Write out constants in the plane
160 outputConstantsInPlane(Plane, ValNo);
165 static unsigned getEncodedLinkage(const GlobalValue *GV) {
166 switch (GV->getLinkage()) {
167 default: assert(0 && "Invalid linkage!");
168 case GlobalValue::ExternalLinkage: return 0;
169 case GlobalValue::WeakLinkage: return 1;
170 case GlobalValue::AppendingLinkage: return 2;
171 case GlobalValue::InternalLinkage: return 3;
172 case GlobalValue::LinkOnceLinkage: return 4;
176 void BytecodeWriter::outputModuleInfoBlock(const Module *M) {
177 BytecodeBlock ModuleInfoBlock(BytecodeFormat::ModuleGlobalInfo, Out);
179 // Output the types for the global variables in the module...
180 for (Module::const_giterator I = M->gbegin(), End = M->gend(); I != End;++I) {
181 int Slot = Table.getSlot(I->getType());
182 assert(Slot != -1 && "Module global vars is broken!");
184 // Fields: bit0 = isConstant, bit1 = hasInitializer, bit2-4=Linkage,
185 // bit5+ = Slot # for type
186 unsigned oSlot = ((unsigned)Slot << 5) | (getEncodedLinkage(I) << 2) |
187 (I->hasInitializer() << 1) | I->isConstant();
188 output_vbr(oSlot, Out);
190 // If we have an initializer, output it now.
191 if (I->hasInitializer()) {
192 Slot = Table.getSlot((Value*)I->getInitializer());
193 assert(Slot != -1 && "No slot for global var initializer!");
194 output_vbr((unsigned)Slot, Out);
197 output_vbr((unsigned)Table.getSlot(Type::VoidTy), Out);
199 // Output the types of the functions in this module...
200 for (Module::const_iterator I = M->begin(), End = M->end(); I != End; ++I) {
201 int Slot = Table.getSlot(I->getType());
202 assert(Slot != -1 && "Module const pool is broken!");
203 assert(Slot >= Type::FirstDerivedTyID && "Derived type not in range!");
204 output_vbr((unsigned)Slot, Out);
206 output_vbr((unsigned)Table.getSlot(Type::VoidTy), Out);
211 void BytecodeWriter::outputFunction(const Function *F) {
212 BytecodeBlock FunctionBlock(BytecodeFormat::Function, Out);
213 output_vbr(getEncodedLinkage(F), Out);
214 // Only output the constant pool and other goodies if needed...
215 if (!F->isExternal()) {
217 // Get slot information about the function...
218 Table.incorporateFunction(F);
220 // Output information about the constants in the function...
221 outputConstants(true);
223 { // Output all of the instructions in the body of the function
224 BytecodeBlock ILBlock(BytecodeFormat::InstructionList, Out);
226 for (Function::const_iterator BB = F->begin(), E = F->end(); BB != E;++BB)
227 for(BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;++I)
228 processInstruction(*I);
231 // If needed, output the symbol table for the function...
232 outputSymbolTable(F->getSymbolTable());
234 Table.purgeFunction();
238 void BytecodeWriter::outputSymbolTable(const SymbolTable &MST) {
239 BytecodeBlock FunctionBlock(BytecodeFormat::SymbolTable, Out);
241 for (SymbolTable::const_iterator TI = MST.begin(); TI != MST.end(); ++TI) {
242 SymbolTable::type_const_iterator I = MST.type_begin(TI->first);
243 SymbolTable::type_const_iterator End = MST.type_end(TI->first);
246 if (I == End) continue; // Don't mess with an absent type...
248 // Symtab block header: [num entries][type id number]
249 output_vbr(MST.type_size(TI->first), Out);
251 Slot = Table.getSlot(TI->first);
252 assert(Slot != -1 && "Type in symtab, but not in table!");
253 output_vbr((unsigned)Slot, Out);
255 for (; I != End; ++I) {
256 // Symtab entry: [def slot #][name]
257 Slot = Table.getSlot(I->second);
258 assert(Slot != -1 && "Value in symtab but has no slot number!!");
259 output_vbr((unsigned)Slot, Out);
260 output(I->first, Out, false); // Don't force alignment...
265 void llvm::WriteBytecodeToFile(const Module *C, std::ostream &Out) {
266 assert(C && "You can't write a null module!!");
268 std::deque<unsigned char> Buffer;
270 // This object populates buffer for us...
271 BytecodeWriter BCW(Buffer, C);
273 // Keep track of how much we've written...
274 BytesWritten += Buffer.size();
276 // Okay, write the deque out to the ostream now... the deque is not
277 // sequential in memory, however, so write out as much as possible in big
278 // chunks, until we're done.
280 std::deque<unsigned char>::const_iterator I = Buffer.begin(),E = Buffer.end();
281 while (I != E) { // Loop until it's all written
282 // Scan to see how big this chunk is...
283 const unsigned char *ChunkPtr = &*I;
284 const unsigned char *LastPtr = ChunkPtr;
286 const unsigned char *ThisPtr = &*++I;
287 if (LastPtr+1 != ThisPtr) { // Advanced by more than a byte of memory?
294 // Write out the chunk...
295 Out.write((char*)ChunkPtr, LastPtr-ChunkPtr);