* Support writing GlobalVariables with info comments by them
[oota-llvm.git] / lib / VMCore / AsmWriter.cpp
1 //===-- Writer.cpp - Library for Printing VM assembly files ------*- C++ -*--=//
2 //
3 // This library implements the functionality defined in llvm/Assembly/Writer.h
4 //
5 // This library uses the Analysis library to figure out offsets for
6 // variables in the method tables...
7 //
8 // TODO: print out the type name instead of the full type if a particular type
9 //       is in the symbol table...
10 //
11 //===----------------------------------------------------------------------===//
12
13 #include "llvm/Assembly/Writer.h"
14 #include "llvm/Analysis/SlotCalculator.h"
15 #include "llvm/Module.h"
16 #include "llvm/Method.h"
17 #include "llvm/GlobalVariable.h"
18 #include "llvm/BasicBlock.h"
19 #include "llvm/ConstPoolVals.h"
20 #include "llvm/iOther.h"
21 #include "llvm/iMemory.h"
22 #include "llvm/iTerminators.h"
23 #include "llvm/Support/STLExtras.h"
24 #include "llvm/SymbolTable.h"
25 #include <algorithm>
26
27 // WriteAsOperand - Write the name of the specified value out to the specified
28 // ostream.  This can be useful when you just want to print int %reg126, not the
29 // whole instruction that generated it.
30 //
31 ostream &WriteAsOperand(ostream &Out, const Value *V, bool PrintType, 
32                         bool PrintName, SlotCalculator *Table) {
33   if (PrintType)
34     Out << " " << V->getType();
35   
36   if (PrintName && V->hasName()) {
37     Out << " %" << V->getName();
38   } else {
39     if (const ConstPoolVal *CPV = dyn_cast<const ConstPoolVal>(V)) {
40       Out << " " << CPV->getStrValue();
41     } else {
42       int Slot;
43       if (Table) {
44         Slot = Table->getValSlot(V);
45       } else {
46         if (const Type *Ty = dyn_cast<const Type>(V)) {
47           return Out << " " << Ty;
48         } else if (const MethodArgument *MA =dyn_cast<const MethodArgument>(V)){
49           Table = new SlotCalculator(MA->getParent(), true);
50         } else if (const Instruction *I = dyn_cast<const Instruction>(V)) {
51           Table = new SlotCalculator(I->getParent()->getParent(), true);
52         } else if (const BasicBlock *BB = dyn_cast<const BasicBlock>(V)) {
53           Table = new SlotCalculator(BB->getParent(), true);
54         } else if (const GlobalVariable *GV =dyn_cast<const GlobalVariable>(V)){
55           Table = new SlotCalculator(GV->getParent(), true);
56         } else if (const Method *Meth = dyn_cast<const Method>(V)) {
57           Table = new SlotCalculator(Meth, true);
58         } else if (const Module *Mod  = dyn_cast<const Module>(V)) {
59           Table = new SlotCalculator(Mod, true);
60         } else {
61           return Out << "BAD VALUE TYPE!";
62         }
63         Slot = Table->getValSlot(V);
64         delete Table;
65       }
66       if (Slot >= 0)  Out << " %" << Slot;
67       else if (PrintName)
68         Out << "<badref>";     // Not embeded into a location?
69     }
70   }
71   return Out;
72 }
73
74
75
76 class AssemblyWriter {
77   ostream &Out;
78   SlotCalculator &Table;
79 public:
80   inline AssemblyWriter(ostream &o, SlotCalculator &Tab) : Out(o), Table(Tab) {
81   }
82
83   inline void write(const Module *M)         { processModule(M);      }
84   inline void write(const GlobalVariable *G) { processGlobal(G);      }
85   inline void write(const Method *M)         { processMethod(M);      }
86   inline void write(const BasicBlock *BB)    { processBasicBlock(BB); }
87   inline void write(const Instruction *I)    { processInstruction(I); }
88   inline void write(const ConstPoolVal *CPV) { processConstant(CPV);  }
89
90 private :
91   void processModule(const Module *M);
92   void processSymbolTable(const SymbolTable &ST);
93   void processConstant(const ConstPoolVal *CPV);
94   void processGlobal(const GlobalVariable *GV);
95   void processMethod(const Method *M);
96   void processMethodArgument(const MethodArgument *MA);
97   void processBasicBlock(const BasicBlock *BB);
98   void processInstruction(const Instruction *I);
99   
100   void writeOperand(const Value *Op, bool PrintType, bool PrintName = true);
101
102   // printInfoComment - Print a little comment after the instruction indicating
103   // which slot it occupies.
104   void printInfoComment(const Value *V);
105
106 };
107
108
109 void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType, 
110                                   bool PrintName) {
111   WriteAsOperand(Out, Operand, PrintType, PrintName, &Table);
112 }
113
114
115 void AssemblyWriter::processModule(const Module *M) {
116   // Loop over the symbol table, emitting all named constants...
117   if (M->hasSymbolTable())
118     processSymbolTable(*M->getSymbolTable());
119   
120   for_each(M->gbegin(), M->gend(), 
121            bind_obj(this, &AssemblyWriter::processGlobal));
122
123   Out << "implementation\n";
124   
125   // Output all of the methods...
126   for_each(M->begin(), M->end(), bind_obj(this,&AssemblyWriter::processMethod));
127 }
128
129 void AssemblyWriter::processGlobal(const GlobalVariable *GV) {
130   if (GV->hasName()) Out << "%" << GV->getName() << " = ";
131
132   if (!GV->hasInitializer()) Out << "uninitialized ";
133
134   Out << (GV->isConstant() ? "constant " : "global ") 
135       << GV->getType()->getValueType()->getDescription();
136
137   if (GV->hasInitializer())
138     writeOperand(GV->getInitializer(), false, false);
139
140   printInfoComment(GV);
141   Out << endl;
142 }
143
144
145 // processSymbolTable - Run through symbol table looking for named constants
146 // if a named constant is found, emit it's declaration...
147 //
148 void AssemblyWriter::processSymbolTable(const SymbolTable &ST) {
149   for (SymbolTable::const_iterator TI = ST.begin(); TI != ST.end(); ++TI) {
150     SymbolTable::type_const_iterator I = ST.type_begin(TI->first);
151     SymbolTable::type_const_iterator End = ST.type_end(TI->first);
152     
153     for (; I != End; ++I) {
154       const Value *V = I->second;
155       if (const ConstPoolVal *CPV = dyn_cast<const ConstPoolVal>(V)) {
156         processConstant(CPV);
157       } else if (const Type *Ty = dyn_cast<const Type>(V)) {
158         Out << "\t%" << I->first << " = type " << Ty->getDescription() << endl;
159       }
160     }
161   }
162 }
163
164
165 // processConstant - Print out a constant pool entry...
166 //
167 void AssemblyWriter::processConstant(const ConstPoolVal *CPV) {
168   // Don't print out unnamed constants, they will be inlined
169   if (!CPV->hasName()) return;
170
171   // Print out name...
172   Out << "\t%" << CPV->getName() << " = ";
173
174   // Print out the constant type...
175   Out << CPV->getType();
176
177   // Write the value out now...
178   writeOperand(CPV, false, false);
179
180   if (!CPV->hasName() && CPV->getType() != Type::VoidTy) {
181     int Slot = Table.getValSlot(CPV); // Print out the def slot taken...
182     Out << "\t\t; <" << CPV->getType() << ">:";
183     if (Slot >= 0) Out << Slot;
184     else Out << "<badref>";
185   } 
186
187   Out << endl;
188 }
189
190 // processMethod - Process all aspects of a method.
191 //
192 void AssemblyWriter::processMethod(const Method *M) {
193   // Print out the return type and name...
194   Out << "\n" << (M->isExternal() ? "declare " : "") 
195       << M->getReturnType() << " \"" << M->getName() << "\"(";
196   Table.incorporateMethod(M);
197
198   // Loop over the arguments, processing them...
199   const MethodType *MT = cast<const MethodType>(M->getMethodType());
200
201   if (!M->isExternal()) {
202     for_each(M->getArgumentList().begin(), M->getArgumentList().end(),
203              bind_obj(this, &AssemblyWriter::processMethodArgument));
204   } else {
205     // Loop over the arguments, processing them...
206     const MethodType *MT = cast<const MethodType>(M->getMethodType());
207     for (MethodType::ParamTypes::const_iterator I = MT->getParamTypes().begin(),
208            E = MT->getParamTypes().end(); I != E; ++I) {
209       if (I != MT->getParamTypes().begin()) Out << ", ";
210       Out << *I;
211     }
212   }
213
214   // Finish printing arguments...
215   if (MT->isVarArg()) {
216     if (MT->getParamTypes().size()) Out << ", ";
217     Out << "...";  // Output varargs portion of signature!
218   }
219   Out << ")\n";
220
221   if (!M->isExternal()) {
222     // Loop over the symbol table, emitting all named constants...
223     if (M->hasSymbolTable())
224       processSymbolTable(*M->getSymbolTable());
225
226     Out << "begin";
227   
228     // Output all of its basic blocks... for the method
229     for_each(M->begin(), M->end(),
230              bind_obj(this, &AssemblyWriter::processBasicBlock));
231
232     Out << "end\n";
233   }
234
235   Table.purgeMethod();
236 }
237
238 // processMethodArgument - This member is called for every argument that 
239 // is passed into the method.  Simply print it out
240 //
241 void AssemblyWriter::processMethodArgument(const MethodArgument *Arg) {
242   // Insert commas as we go... the first arg doesn't get a comma
243   if (Arg != Arg->getParent()->getArgumentList().front()) Out << ", ";
244
245   // Output type...
246   Out << Arg->getType();
247   
248   // Output name, if available...
249   if (Arg->hasName())
250     Out << " %" << Arg->getName();
251   else if (Table.getValSlot(Arg) < 0)
252     Out << "<badref>";
253 }
254
255 // processBasicBlock - This member is called for each basic block in a methd.
256 //
257 void AssemblyWriter::processBasicBlock(const BasicBlock *BB) {
258   if (BB->hasName()) {              // Print out the label if it exists...
259     Out << "\n" << BB->getName() << ":";
260   } else {
261     int Slot = Table.getValSlot(BB);
262     Out << "\n; <label>:";
263     if (Slot >= 0) 
264       Out << Slot;         // Extra newline seperates out label's
265     else 
266       Out << "<badref>"; 
267   }
268   Out << "\t\t\t\t\t;[#uses=" << BB->use_size() << "]\n";  // Output # uses
269
270   // Output all of the instructions in the basic block...
271   for_each(BB->begin(), BB->end(),
272            bind_obj(this, &AssemblyWriter::processInstruction));
273 }
274
275
276 // printInfoComment - Print a little comment after the instruction indicating
277 // which slot it occupies.
278 //
279 void AssemblyWriter::printInfoComment(const Value *V) {
280   if (V->getType() != Type::VoidTy) {
281     Out << "\t\t; <" << V->getType() << ">";
282
283     if (!V->hasName()) {
284       int Slot = Table.getValSlot(V); // Print out the def slot taken...
285       if (Slot >= 0) Out << ":" << Slot;
286       else Out << ":<badref>";
287     }
288     Out << "\t[#uses=" << V->use_size() << "]";  // Output # uses
289   }
290 }
291
292 // processInstruction - This member is called for each Instruction in a methd.
293 //
294 void AssemblyWriter::processInstruction(const Instruction *I) {
295   Out << "\t";
296
297   // Print out name if it exists...
298   if (I && I->hasName())
299     Out << "%" << I->getName() << " = ";
300
301   // Print out the opcode...
302   Out << I->getOpcodeName();
303
304   // Print out the type of the operands...
305   const Value *Operand = I->getNumOperands() ? I->getOperand(0) : 0;
306
307   // Special case conditional branches to swizzle the condition out to the front
308   if (I->getOpcode() == Instruction::Br && I->getNumOperands() > 1) {
309     writeOperand(I->getOperand(2), true);
310     Out << ",";
311     writeOperand(Operand, true);
312     Out << ",";
313     writeOperand(I->getOperand(1), true);
314
315   } else if (I->getOpcode() == Instruction::Switch) {
316     // Special case switch statement to get formatting nice and correct...
317     writeOperand(Operand         , true); Out << ",";
318     writeOperand(I->getOperand(1), true); Out << " [";
319
320     for (unsigned op = 2, Eop = I->getNumOperands(); op < Eop; op += 2) {
321       Out << "\n\t\t";
322       writeOperand(I->getOperand(op  ), true); Out << ",";
323       writeOperand(I->getOperand(op+1), true);
324     }
325     Out << "\n\t]";
326   } else if (isa<PHINode>(I)) {
327     Out << " " << Operand->getType();
328
329     Out << " [";  writeOperand(Operand, false); Out << ",";
330     writeOperand(I->getOperand(1), false); Out << " ]";
331     for (unsigned op = 2, Eop = I->getNumOperands(); op < Eop; op += 2) {
332       Out << ", [";  
333       writeOperand(I->getOperand(op  ), false); Out << ",";
334       writeOperand(I->getOperand(op+1), false); Out << " ]";
335     }
336   } else if (isa<ReturnInst>(I) && !Operand) {
337     Out << " void";
338   } else if (isa<CallInst>(I)) {
339     // TODO: Should try to print out short form of the Call instruction
340     writeOperand(Operand, true);
341     Out << "(";
342     if (I->getNumOperands() > 1) writeOperand(I->getOperand(1), true);
343     for (unsigned op = 2, Eop = I->getNumOperands(); op < Eop; ++op) {
344       Out << ",";
345       writeOperand(I->getOperand(op), true);
346     }
347
348     Out << " )";
349   } else if (const InvokeInst *II = dyn_cast<InvokeInst>(I)) {
350     // TODO: Should try to print out short form of the Invoke instruction
351     writeOperand(Operand, true);
352     Out << "(";
353     if (I->getNumOperands() > 3) writeOperand(I->getOperand(3), true);
354     for (unsigned op = 4, Eop = I->getNumOperands(); op < Eop; ++op) {
355       Out << ",";
356       writeOperand(I->getOperand(op), true);
357     }
358
359     Out << " )\n\t\t\tto";
360     writeOperand(II->getNormalDest(), true);
361     Out << " except";
362     writeOperand(II->getExceptionalDest(), true);
363
364   } else if (I->getOpcode() == Instruction::Malloc || 
365              I->getOpcode() == Instruction::Alloca) {
366     Out << " " << cast<const PointerType>(I->getType())->getValueType();
367     if (I->getNumOperands()) {
368       Out << ",";
369       writeOperand(I->getOperand(0), true);
370     }
371   } else if (isa<CastInst>(I)) {
372     writeOperand(Operand, true);
373     Out << " to " << I->getType();
374   } else if (Operand) {   // Print the normal way...
375
376     // PrintAllTypes - Instructions who have operands of all the same type 
377     // omit the type from all but the first operand.  If the instruction has
378     // different type operands (for example br), then they are all printed.
379     bool PrintAllTypes = false;
380     const Type *TheType = Operand->getType();
381
382     for (unsigned i = 1, E = I->getNumOperands(); i != E; ++i) {
383       Operand = I->getOperand(i);
384       if (Operand->getType() != TheType) {
385         PrintAllTypes = true;       // We have differing types!  Print them all!
386         break;
387       }
388     }
389
390     if (!PrintAllTypes)
391       Out << " " << I->getOperand(0)->getType();
392
393     for (unsigned i = 0, E = I->getNumOperands(); i != E; ++i) {
394       if (i) Out << ",";
395       writeOperand(I->getOperand(i), PrintAllTypes);
396     }
397   }
398
399   printInfoComment(I);
400   Out << endl;
401 }
402
403
404 //===----------------------------------------------------------------------===//
405 //                       External Interface declarations
406 //===----------------------------------------------------------------------===//
407
408
409
410 void WriteToAssembly(const Module *M, ostream &o) {
411   if (M == 0) { o << "<null> module\n"; return; }
412   SlotCalculator SlotTable(M, true);
413   AssemblyWriter W(o, SlotTable);
414
415   W.write(M);
416 }
417
418 void WriteToAssembly(const GlobalVariable *G, ostream &o) {
419   if (G == 0) { o << "<null> global variable\n"; return; }
420   SlotCalculator SlotTable(G->getParent(), true);
421   AssemblyWriter W(o, SlotTable);
422   W.write(G);
423 }
424
425 void WriteToAssembly(const Method *M, ostream &o) {
426   if (M == 0) { o << "<null> method\n"; return; }
427   SlotCalculator SlotTable(M->getParent(), true);
428   AssemblyWriter W(o, SlotTable);
429
430   W.write(M);
431 }
432
433
434 void WriteToAssembly(const BasicBlock *BB, ostream &o) {
435   if (BB == 0) { o << "<null> basic block\n"; return; }
436
437   SlotCalculator SlotTable(BB->getParent(), true);
438   AssemblyWriter W(o, SlotTable);
439
440   W.write(BB);
441 }
442
443 void WriteToAssembly(const ConstPoolVal *CPV, ostream &o) {
444   if (CPV == 0) { o << "<null> constant pool value\n"; return; }
445   WriteAsOperand(o, CPV, true, true, 0);
446 }
447
448 void WriteToAssembly(const Instruction *I, ostream &o) {
449   if (I == 0) { o << "<null> instruction\n"; return; }
450
451   SlotCalculator SlotTable(I->getParent() ? I->getParent()->getParent() : 0, 
452                            true);
453   AssemblyWriter W(o, SlotTable);
454
455   W.write(I);
456 }