1 //===-- Writer.cpp - Library for Printing VM assembly files ------*- C++ -*--=//
3 // This library implements the functionality defined in llvm/Assembly/Writer.h
5 // This library uses the Analysis library to figure out offsets for
6 // variables in the method tables...
8 // TODO: print out the type name instead of the full type if a particular type
9 // is in the symbol table...
11 //===----------------------------------------------------------------------===//
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/SymbolTable.h"
24 #include "llvm/Support/STLExtras.h"
25 #include "llvm/Support/StringExtras.h"
29 static const Module *getModuleFromVal(const Value *V) {
30 if (const MethodArgument *MA =dyn_cast<const MethodArgument>(V))
31 return MA->getParent() ? MA->getParent()->getParent() : 0;
32 else if (const BasicBlock *BB = dyn_cast<const BasicBlock>(V))
33 return BB->getParent() ? BB->getParent()->getParent() : 0;
34 else if (const Instruction *I = dyn_cast<const Instruction>(V)) {
35 const Method *M = I->getParent() ? I->getParent()->getParent() : 0;
36 return M ? M->getParent() : 0;
37 } else if (const GlobalValue *GV =dyn_cast<const GlobalValue>(V))
38 return GV->getParent();
39 else if (const Module *Mod = dyn_cast<const Module>(V))
44 static SlotCalculator *createSlotCalculator(const Value *V) {
45 assert(!isa<Type>(V) && "Can't create an SC for a type!");
46 if (const MethodArgument *MA =dyn_cast<const MethodArgument>(V)){
47 return new SlotCalculator(MA->getParent(), true);
48 } else if (const Instruction *I = dyn_cast<const Instruction>(V)) {
49 return new SlotCalculator(I->getParent()->getParent(), true);
50 } else if (const BasicBlock *BB = dyn_cast<const BasicBlock>(V)) {
51 return new SlotCalculator(BB->getParent(), true);
52 } else if (const GlobalVariable *GV =dyn_cast<const GlobalVariable>(V)){
53 return new SlotCalculator(GV->getParent(), true);
54 } else if (const Method *Meth = dyn_cast<const Method>(V)) {
55 return new SlotCalculator(Meth, true);
56 } else if (const Module *Mod = dyn_cast<const Module>(V)) {
57 return new SlotCalculator(Mod, true);
62 // WriteAsOperand - Write the name of the specified value out to the specified
63 // ostream. This can be useful when you just want to print int %reg126, not the
64 // whole instruction that generated it.
66 static void WriteAsOperandInternal(ostream &Out, const Value *V, bool PrintName,
67 SlotCalculator *Table) {
68 if (PrintName && V->hasName()) {
69 Out << " %" << V->getName();
71 if (const ConstPoolVal *CPV = dyn_cast<const ConstPoolVal>(V)) {
72 Out << " " << CPV->getStrValue();
76 Slot = Table->getValSlot(V);
78 if (const Type *Ty = dyn_cast<const Type>(V)) {
79 Out << " " << Ty->getDescription();
83 Table = createSlotCalculator(V);
84 if (Table == 0) { Out << "BAD VALUE TYPE!"; return; }
86 Slot = Table->getValSlot(V);
89 if (Slot >= 0) Out << " %" << Slot;
91 Out << "<badref>"; // Not embeded into a location?
97 // If the module has a symbol table, take all global types and stuff their
98 // names into the TypeNames map.
100 static void fillTypeNameTable(const Module *M,
101 map<const Type *, string> &TypeNames) {
102 if (M && M->hasSymbolTable()) {
103 const SymbolTable *ST = M->getSymbolTable();
104 SymbolTable::const_iterator PI = ST->find(Type::TypeTy);
105 if (PI != ST->end()) {
106 SymbolTable::type_const_iterator I = PI->second.begin();
107 for (; I != PI->second.end(); ++I) {
108 // As a heuristic, don't insert pointer to primitive types, because
109 // they are used too often to have a single useful name.
111 const Type *Ty = cast<const Type>(I->second);
112 if (!isa<PointerType>(Ty) ||
113 !cast<PointerType>(Ty)->getValueType()->isPrimitiveType())
114 TypeNames.insert(make_pair(Ty, "%"+I->first));
122 static string calcTypeName(const Type *Ty, vector<const Type *> &TypeStack,
123 map<const Type *, string> &TypeNames) {
124 if (Ty->isPrimitiveType()) return Ty->getDescription(); // Base case
126 // Check to see if the type is named.
127 map<const Type *, string>::iterator I = TypeNames.find(Ty);
128 if (I != TypeNames.end()) return I->second;
130 // Check to see if the Type is already on the stack...
131 unsigned Slot = 0, CurSize = TypeStack.size();
132 while (Slot < CurSize && TypeStack[Slot] != Ty) ++Slot; // Scan for type
134 // This is another base case for the recursion. In this case, we know
135 // that we have looped back to a type that we have previously visited.
136 // Generate the appropriate upreference to handle this.
139 return "\\" + utostr(CurSize-Slot); // Here's the upreference
141 TypeStack.push_back(Ty); // Recursive case: Add us to the stack..
144 switch (Ty->getPrimitiveID()) {
145 case Type::MethodTyID: {
146 const MethodType *MTy = cast<const MethodType>(Ty);
147 Result = calcTypeName(MTy->getReturnType(), TypeStack, TypeNames) + " (";
148 for (MethodType::ParamTypes::const_iterator
149 I = MTy->getParamTypes().begin(),
150 E = MTy->getParamTypes().end(); I != E; ++I) {
151 if (I != MTy->getParamTypes().begin())
153 Result += calcTypeName(*I, TypeStack, TypeNames);
155 if (MTy->isVarArg()) {
156 if (!MTy->getParamTypes().empty()) Result += ", ";
162 case Type::StructTyID: {
163 const StructType *STy = cast<const StructType>(Ty);
165 for (StructType::ElementTypes::const_iterator
166 I = STy->getElementTypes().begin(),
167 E = STy->getElementTypes().end(); I != E; ++I) {
168 if (I != STy->getElementTypes().begin())
170 Result += calcTypeName(*I, TypeStack, TypeNames);
175 case Type::PointerTyID:
176 Result = calcTypeName(cast<const PointerType>(Ty)->getValueType(),
177 TypeStack, TypeNames) + " *";
179 case Type::ArrayTyID: {
180 const ArrayType *ATy = cast<const ArrayType>(Ty);
181 int NumElements = ATy->getNumElements();
183 if (NumElements != -1) Result += itostr(NumElements) + " x ";
184 Result += calcTypeName(ATy->getElementType(), TypeStack, TypeNames) + "]";
188 assert(0 && "Unhandled case in getTypeProps!");
192 TypeStack.pop_back(); // Remove self from stack...
197 // printTypeInt - The internal guts of printing out a type that has a
198 // potentially named portion.
200 static ostream &printTypeInt(ostream &Out, const Type *Ty,
201 map<const Type *, string> &TypeNames) {
202 // Primitive types always print out their description, regardless of whether
203 // they have been named or not.
205 if (Ty->isPrimitiveType()) return Out << Ty->getDescription();
207 // Check to see if the type is named.
208 map<const Type *, string>::iterator I = TypeNames.find(Ty);
209 if (I != TypeNames.end()) return Out << I->second;
211 // Otherwise we have a type that has not been named but is a derived type.
212 // Carefully recurse the type hierarchy to print out any contained symbolic
215 vector<const Type *> TypeStack;
216 string TypeName = calcTypeName(Ty, TypeStack, TypeNames);
217 TypeNames.insert(make_pair(Ty, TypeName)); // Cache type name for later use
218 return Out << TypeName;
222 // WriteTypeSymbolic - This attempts to write the specified type as a symbolic
223 // type, iff there is an entry in the modules symbol table for the specified
224 // type or one of it's component types. This is slower than a simple x << Type;
226 ostream &WriteTypeSymbolic(ostream &Out, const Type *Ty, const Module *M) {
229 // If they want us to print out a type, attempt to make it symbolic if there
230 // is a symbol table in the module...
231 if (M && M->hasSymbolTable()) {
232 map<const Type *, string> TypeNames;
233 fillTypeNameTable(M, TypeNames);
235 return printTypeInt(Out, Ty, TypeNames);
237 return Out << Ty->getDescription();
242 // WriteAsOperand - Write the name of the specified value out to the specified
243 // ostream. This can be useful when you just want to print int %reg126, not the
244 // whole instruction that generated it.
246 ostream &WriteAsOperand(ostream &Out, const Value *V, bool PrintType,
247 bool PrintName, SlotCalculator *Table) {
249 WriteTypeSymbolic(Out, V->getType(), getModuleFromVal(V));
251 WriteAsOperandInternal(Out, V, PrintName, Table);
257 class AssemblyWriter {
259 SlotCalculator &Table;
260 const Module *TheModule;
261 map<const Type *, string> TypeNames;
263 inline AssemblyWriter(ostream &o, SlotCalculator &Tab, const Module *M)
264 : Out(o), Table(Tab), TheModule(M) {
266 // If the module has a symbol table, take all global types and stuff their
267 // names into the TypeNames map.
269 fillTypeNameTable(M, TypeNames);
272 inline void write(const Module *M) { printModule(M); }
273 inline void write(const GlobalVariable *G) { printGlobal(G); }
274 inline void write(const Method *M) { printMethod(M); }
275 inline void write(const BasicBlock *BB) { printBasicBlock(BB); }
276 inline void write(const Instruction *I) { printInstruction(I); }
277 inline void write(const ConstPoolVal *CPV) { printConstant(CPV); }
280 void printModule(const Module *M);
281 void printSymbolTable(const SymbolTable &ST);
282 void printConstant(const ConstPoolVal *CPV);
283 void printGlobal(const GlobalVariable *GV);
284 void printMethod(const Method *M);
285 void printMethodArgument(const MethodArgument *MA);
286 void printBasicBlock(const BasicBlock *BB);
287 void printInstruction(const Instruction *I);
288 ostream &printType(const Type *Ty);
290 void writeOperand(const Value *Op, bool PrintType, bool PrintName = true);
292 // printInfoComment - Print a little comment after the instruction indicating
293 // which slot it occupies.
294 void printInfoComment(const Value *V);
298 void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType,
300 if (PrintType) { Out << " "; printType(Operand->getType()); }
301 WriteAsOperandInternal(Out, Operand, PrintName, &Table);
305 void AssemblyWriter::printModule(const Module *M) {
306 // Loop over the symbol table, emitting all named constants...
307 if (M->hasSymbolTable())
308 printSymbolTable(*M->getSymbolTable());
310 for_each(M->gbegin(), M->gend(),
311 bind_obj(this, &AssemblyWriter::printGlobal));
313 Out << "implementation\n";
315 // Output all of the methods...
316 for_each(M->begin(), M->end(), bind_obj(this,&AssemblyWriter::printMethod));
319 void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
320 if (GV->hasName()) Out << "%" << GV->getName() << " = ";
322 if (!GV->hasInitializer()) Out << "uninitialized ";
324 Out << (GV->isConstant() ? "constant " : "global ");
325 printType(GV->getType()->getValueType());
327 if (GV->hasInitializer())
328 writeOperand(GV->getInitializer(), false, false);
330 printInfoComment(GV);
335 // printSymbolTable - Run through symbol table looking for named constants
336 // if a named constant is found, emit it's declaration...
338 void AssemblyWriter::printSymbolTable(const SymbolTable &ST) {
339 for (SymbolTable::const_iterator TI = ST.begin(); TI != ST.end(); ++TI) {
340 SymbolTable::type_const_iterator I = ST.type_begin(TI->first);
341 SymbolTable::type_const_iterator End = ST.type_end(TI->first);
343 for (; I != End; ++I) {
344 const Value *V = I->second;
345 if (const ConstPoolVal *CPV = dyn_cast<const ConstPoolVal>(V)) {
347 } else if (const Type *Ty = dyn_cast<const Type>(V)) {
348 Out << "\t%" << I->first << " = type " << Ty->getDescription() << endl;
355 // printConstant - Print out a constant pool entry...
357 void AssemblyWriter::printConstant(const ConstPoolVal *CPV) {
358 // Don't print out unnamed constants, they will be inlined
359 if (!CPV->hasName()) return;
362 Out << "\t%" << CPV->getName() << " = ";
364 // Print out the constant type...
365 printType(CPV->getType());
367 // Write the value out now...
368 writeOperand(CPV, false, false);
370 if (!CPV->hasName() && CPV->getType() != Type::VoidTy) {
371 int Slot = Table.getValSlot(CPV); // Print out the def slot taken...
373 printType(CPV->getType()) << ">:";
374 if (Slot >= 0) Out << Slot;
375 else Out << "<badref>";
381 // printMethod - Print all aspects of a method.
383 void AssemblyWriter::printMethod(const Method *M) {
384 // Print out the return type and name...
385 Out << "\n" << (M->isExternal() ? "declare " : "");
386 printType(M->getReturnType()) << " \"" << M->getName() << "\"(";
387 Table.incorporateMethod(M);
389 // Loop over the arguments, printing them...
390 const MethodType *MT = cast<const MethodType>(M->getMethodType());
392 if (!M->isExternal()) {
393 for_each(M->getArgumentList().begin(), M->getArgumentList().end(),
394 bind_obj(this, &AssemblyWriter::printMethodArgument));
396 // Loop over the arguments, printing them...
397 const MethodType *MT = cast<const MethodType>(M->getMethodType());
398 for (MethodType::ParamTypes::const_iterator I = MT->getParamTypes().begin(),
399 E = MT->getParamTypes().end(); I != E; ++I) {
400 if (I != MT->getParamTypes().begin()) Out << ", ";
405 // Finish printing arguments...
406 if (MT->isVarArg()) {
407 if (MT->getParamTypes().size()) Out << ", ";
408 Out << "..."; // Output varargs portion of signature!
412 if (!M->isExternal()) {
413 // Loop over the symbol table, emitting all named constants...
414 if (M->hasSymbolTable())
415 printSymbolTable(*M->getSymbolTable());
419 // Output all of its basic blocks... for the method
420 for_each(M->begin(), M->end(),
421 bind_obj(this, &AssemblyWriter::printBasicBlock));
429 // printMethodArgument - This member is called for every argument that
430 // is passed into the method. Simply print it out
432 void AssemblyWriter::printMethodArgument(const MethodArgument *Arg) {
433 // Insert commas as we go... the first arg doesn't get a comma
434 if (Arg != Arg->getParent()->getArgumentList().front()) Out << ", ";
437 printType(Arg->getType());
439 // Output name, if available...
441 Out << " %" << Arg->getName();
442 else if (Table.getValSlot(Arg) < 0)
446 // printBasicBlock - This member is called for each basic block in a methd.
448 void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {
449 if (BB->hasName()) { // Print out the label if it exists...
450 Out << "\n" << BB->getName() << ":";
452 int Slot = Table.getValSlot(BB);
453 Out << "\n; <label>:";
455 Out << Slot; // Extra newline seperates out label's
459 Out << "\t\t\t\t\t;[#uses=" << BB->use_size() << "]\n"; // Output # uses
461 // Output all of the instructions in the basic block...
462 for_each(BB->begin(), BB->end(),
463 bind_obj(this, &AssemblyWriter::printInstruction));
467 // printInfoComment - Print a little comment after the instruction indicating
468 // which slot it occupies.
470 void AssemblyWriter::printInfoComment(const Value *V) {
471 if (V->getType() != Type::VoidTy) {
473 printType(V->getType()) << ">";
476 int Slot = Table.getValSlot(V); // Print out the def slot taken...
477 if (Slot >= 0) Out << ":" << Slot;
478 else Out << ":<badref>";
480 Out << "\t[#uses=" << V->use_size() << "]"; // Output # uses
484 // printInstruction - This member is called for each Instruction in a methd.
486 void AssemblyWriter::printInstruction(const Instruction *I) {
489 // Print out name if it exists...
490 if (I && I->hasName())
491 Out << "%" << I->getName() << " = ";
493 // Print out the opcode...
494 Out << I->getOpcodeName();
496 // Print out the type of the operands...
497 const Value *Operand = I->getNumOperands() ? I->getOperand(0) : 0;
499 // Special case conditional branches to swizzle the condition out to the front
500 if (I->getOpcode() == Instruction::Br && I->getNumOperands() > 1) {
501 writeOperand(I->getOperand(2), true);
503 writeOperand(Operand, true);
505 writeOperand(I->getOperand(1), true);
507 } else if (I->getOpcode() == Instruction::Switch) {
508 // Special case switch statement to get formatting nice and correct...
509 writeOperand(Operand , true); Out << ",";
510 writeOperand(I->getOperand(1), true); Out << " [";
512 for (unsigned op = 2, Eop = I->getNumOperands(); op < Eop; op += 2) {
514 writeOperand(I->getOperand(op ), true); Out << ",";
515 writeOperand(I->getOperand(op+1), true);
518 } else if (isa<PHINode>(I)) {
520 printType(Operand->getType());
522 Out << " ["; writeOperand(Operand, false); Out << ",";
523 writeOperand(I->getOperand(1), false); Out << " ]";
524 for (unsigned op = 2, Eop = I->getNumOperands(); op < Eop; op += 2) {
526 writeOperand(I->getOperand(op ), false); Out << ",";
527 writeOperand(I->getOperand(op+1), false); Out << " ]";
529 } else if (isa<ReturnInst>(I) && !Operand) {
531 } else if (isa<CallInst>(I)) {
532 // TODO: Should try to print out short form of the Call instruction
533 writeOperand(Operand, true);
535 if (I->getNumOperands() > 1) writeOperand(I->getOperand(1), true);
536 for (unsigned op = 2, Eop = I->getNumOperands(); op < Eop; ++op) {
538 writeOperand(I->getOperand(op), true);
542 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(I)) {
543 // TODO: Should try to print out short form of the Invoke instruction
544 writeOperand(Operand, true);
546 if (I->getNumOperands() > 3) writeOperand(I->getOperand(3), true);
547 for (unsigned op = 4, Eop = I->getNumOperands(); op < Eop; ++op) {
549 writeOperand(I->getOperand(op), true);
552 Out << " )\n\t\t\tto";
553 writeOperand(II->getNormalDest(), true);
555 writeOperand(II->getExceptionalDest(), true);
557 } else if (I->getOpcode() == Instruction::Malloc ||
558 I->getOpcode() == Instruction::Alloca) {
560 printType(cast<const PointerType>(I->getType())->getValueType());
561 if (I->getNumOperands()) {
563 writeOperand(I->getOperand(0), true);
565 } else if (isa<CastInst>(I)) {
566 writeOperand(Operand, true);
568 printType(I->getType());
569 } else if (Operand) { // Print the normal way...
571 // PrintAllTypes - Instructions who have operands of all the same type
572 // omit the type from all but the first operand. If the instruction has
573 // different type operands (for example br), then they are all printed.
574 bool PrintAllTypes = false;
575 const Type *TheType = Operand->getType();
577 for (unsigned i = 1, E = I->getNumOperands(); i != E; ++i) {
578 Operand = I->getOperand(i);
579 if (Operand->getType() != TheType) {
580 PrintAllTypes = true; // We have differing types! Print them all!
585 // Shift Left & Right print both types even for Ubyte LHS
586 if (isa<ShiftInst>(I)) PrintAllTypes = true;
588 if (!PrintAllTypes) {
590 printType(I->getOperand(0)->getType());
593 for (unsigned i = 0, E = I->getNumOperands(); i != E; ++i) {
595 writeOperand(I->getOperand(i), PrintAllTypes);
604 // printType - Go to extreme measures to attempt to print out a short, symbolic
605 // version of a type name.
607 ostream &AssemblyWriter::printType(const Type *Ty) {
608 return printTypeInt(Out, Ty, TypeNames);
612 //===----------------------------------------------------------------------===//
613 // External Interface declarations
614 //===----------------------------------------------------------------------===//
618 void WriteToAssembly(const Module *M, ostream &o) {
619 if (M == 0) { o << "<null> module\n"; return; }
620 SlotCalculator SlotTable(M, true);
621 AssemblyWriter W(o, SlotTable, M);
626 void WriteToAssembly(const GlobalVariable *G, ostream &o) {
627 if (G == 0) { o << "<null> global variable\n"; return; }
628 SlotCalculator SlotTable(G->getParent(), true);
629 AssemblyWriter W(o, SlotTable, G->getParent());
633 void WriteToAssembly(const Method *M, ostream &o) {
634 if (M == 0) { o << "<null> method\n"; return; }
635 SlotCalculator SlotTable(M->getParent(), true);
636 AssemblyWriter W(o, SlotTable, M->getParent());
642 void WriteToAssembly(const BasicBlock *BB, ostream &o) {
643 if (BB == 0) { o << "<null> basic block\n"; return; }
645 SlotCalculator SlotTable(BB->getParent(), true);
646 AssemblyWriter W(o, SlotTable,
647 BB->getParent() ? BB->getParent()->getParent() : 0);
652 void WriteToAssembly(const ConstPoolVal *CPV, ostream &o) {
653 if (CPV == 0) { o << "<null> constant pool value\n"; return; }
654 o << " " << CPV->getType()->getDescription() << " " << CPV->getStrValue();
657 void WriteToAssembly(const Instruction *I, ostream &o) {
658 if (I == 0) { o << "<null> instruction\n"; return; }
660 const Method *M = I->getParent() ? I->getParent()->getParent() : 0;
661 SlotCalculator SlotTable(M, true);
662 AssemblyWriter W(o, SlotTable, M ? M->getParent() : 0);