1 //===-- AsmWriter.cpp - Printing LLVM as an assembly file -----------------===//
3 // This library implements the functionality defined in llvm/Assembly/Writer.h
5 // Note that these routines must be extremely tolerant of various errors in the
6 // LLVM code, because of of the primary uses of it is for debugging
9 //===----------------------------------------------------------------------===//
11 #include "llvm/Assembly/CachedWriter.h"
12 #include "llvm/Assembly/Writer.h"
13 #include "llvm/Assembly/PrintModulePass.h"
14 #include "llvm/SlotCalculator.h"
15 #include "llvm/DerivedTypes.h"
16 #include "llvm/Instruction.h"
17 #include "llvm/Module.h"
18 #include "llvm/Constants.h"
19 #include "llvm/iMemory.h"
20 #include "llvm/iTerminators.h"
21 #include "llvm/iPHINode.h"
22 #include "llvm/iOther.h"
23 #include "llvm/SymbolTable.h"
24 #include "Support/StringExtras.h"
25 #include "Support/STLExtras.h"
32 static RegisterPass<PrintModulePass>
33 X("printm", "Print module to stderr",PassInfo::Analysis|PassInfo::Optimization);
34 static RegisterPass<PrintFunctionPass>
35 Y("print","Print function to stderr",PassInfo::Analysis|PassInfo::Optimization);
37 static void WriteAsOperandInternal(ostream &Out, const Value *V, bool PrintName,
38 map<const Type *, string> &TypeTable,
39 SlotCalculator *Table);
41 static const Module *getModuleFromVal(const Value *V) {
42 if (const Argument *MA = dyn_cast<const Argument>(V))
43 return MA->getParent() ? MA->getParent()->getParent() : 0;
44 else if (const BasicBlock *BB = dyn_cast<const BasicBlock>(V))
45 return BB->getParent() ? BB->getParent()->getParent() : 0;
46 else if (const Instruction *I = dyn_cast<const Instruction>(V)) {
47 const Function *M = I->getParent() ? I->getParent()->getParent() : 0;
48 return M ? M->getParent() : 0;
49 } else if (const GlobalValue *GV = dyn_cast<const GlobalValue>(V))
50 return GV->getParent();
54 static SlotCalculator *createSlotCalculator(const Value *V) {
55 assert(!isa<Type>(V) && "Can't create an SC for a type!");
56 if (const Argument *FA = dyn_cast<const Argument>(V)) {
57 return new SlotCalculator(FA->getParent(), true);
58 } else if (const Instruction *I = dyn_cast<const Instruction>(V)) {
59 return new SlotCalculator(I->getParent()->getParent(), true);
60 } else if (const BasicBlock *BB = dyn_cast<const BasicBlock>(V)) {
61 return new SlotCalculator(BB->getParent(), true);
62 } else if (const GlobalVariable *GV = dyn_cast<const GlobalVariable>(V)){
63 return new SlotCalculator(GV->getParent(), true);
64 } else if (const Function *Func = dyn_cast<const Function>(V)) {
65 return new SlotCalculator(Func, true);
71 // If the module has a symbol table, take all global types and stuff their
72 // names into the TypeNames map.
74 static void fillTypeNameTable(const Module *M,
75 map<const Type *, string> &TypeNames) {
76 if (M && M->hasSymbolTable()) {
77 const SymbolTable *ST = M->getSymbolTable();
78 SymbolTable::const_iterator PI = ST->find(Type::TypeTy);
79 if (PI != ST->end()) {
80 SymbolTable::type_const_iterator I = PI->second.begin();
81 for (; I != PI->second.end(); ++I) {
82 // As a heuristic, don't insert pointer to primitive types, because
83 // they are used too often to have a single useful name.
85 const Type *Ty = cast<const Type>(I->second);
86 if (!isa<PointerType>(Ty) ||
87 !cast<PointerType>(Ty)->getElementType()->isPrimitiveType())
88 TypeNames.insert(std::make_pair(Ty, "%"+I->first));
96 static string calcTypeName(const Type *Ty, vector<const Type *> &TypeStack,
97 map<const Type *, string> &TypeNames) {
98 if (Ty->isPrimitiveType()) return Ty->getDescription(); // Base case
100 // Check to see if the type is named.
101 map<const Type *, string>::iterator I = TypeNames.find(Ty);
102 if (I != TypeNames.end()) return I->second;
104 // Check to see if the Type is already on the stack...
105 unsigned Slot = 0, CurSize = TypeStack.size();
106 while (Slot < CurSize && TypeStack[Slot] != Ty) ++Slot; // Scan for type
108 // This is another base case for the recursion. In this case, we know
109 // that we have looped back to a type that we have previously visited.
110 // Generate the appropriate upreference to handle this.
113 return "\\" + utostr(CurSize-Slot); // Here's the upreference
115 TypeStack.push_back(Ty); // Recursive case: Add us to the stack..
118 switch (Ty->getPrimitiveID()) {
119 case Type::FunctionTyID: {
120 const FunctionType *FTy = cast<const FunctionType>(Ty);
121 Result = calcTypeName(FTy->getReturnType(), TypeStack, TypeNames) + " (";
122 for (FunctionType::ParamTypes::const_iterator
123 I = FTy->getParamTypes().begin(),
124 E = FTy->getParamTypes().end(); I != E; ++I) {
125 if (I != FTy->getParamTypes().begin())
127 Result += calcTypeName(*I, TypeStack, TypeNames);
129 if (FTy->isVarArg()) {
130 if (!FTy->getParamTypes().empty()) Result += ", ";
136 case Type::StructTyID: {
137 const StructType *STy = cast<const StructType>(Ty);
139 for (StructType::ElementTypes::const_iterator
140 I = STy->getElementTypes().begin(),
141 E = STy->getElementTypes().end(); I != E; ++I) {
142 if (I != STy->getElementTypes().begin())
144 Result += calcTypeName(*I, TypeStack, TypeNames);
149 case Type::PointerTyID:
150 Result = calcTypeName(cast<const PointerType>(Ty)->getElementType(),
151 TypeStack, TypeNames) + "*";
153 case Type::ArrayTyID: {
154 const ArrayType *ATy = cast<const ArrayType>(Ty);
155 Result = "[" + utostr(ATy->getNumElements()) + " x ";
156 Result += calcTypeName(ATy->getElementType(), TypeStack, TypeNames) + "]";
160 Result = "<unrecognized-type>";
163 TypeStack.pop_back(); // Remove self from stack...
168 // printTypeInt - The internal guts of printing out a type that has a
169 // potentially named portion.
171 static ostream &printTypeInt(ostream &Out, const Type *Ty,
172 map<const Type *, string> &TypeNames) {
173 // Primitive types always print out their description, regardless of whether
174 // they have been named or not.
176 if (Ty->isPrimitiveType()) return Out << Ty->getDescription();
178 // Check to see if the type is named.
179 map<const Type *, string>::iterator I = TypeNames.find(Ty);
180 if (I != TypeNames.end()) return Out << I->second;
182 // Otherwise we have a type that has not been named but is a derived type.
183 // Carefully recurse the type hierarchy to print out any contained symbolic
186 vector<const Type *> TypeStack;
187 string TypeName = calcTypeName(Ty, TypeStack, TypeNames);
188 TypeNames.insert(std::make_pair(Ty, TypeName));//Cache type name for later use
189 return Out << TypeName;
193 // WriteTypeSymbolic - This attempts to write the specified type as a symbolic
194 // type, iff there is an entry in the modules symbol table for the specified
195 // type or one of it's component types. This is slower than a simple x << Type;
197 ostream &WriteTypeSymbolic(ostream &Out, const Type *Ty, const Module *M) {
200 // If they want us to print out a type, attempt to make it symbolic if there
201 // is a symbol table in the module...
202 if (M && M->hasSymbolTable()) {
203 map<const Type *, string> TypeNames;
204 fillTypeNameTable(M, TypeNames);
206 return printTypeInt(Out, Ty, TypeNames);
208 return Out << Ty->getDescription();
212 static void WriteConstantInt(ostream &Out, const Constant *CV, bool PrintName,
213 map<const Type *, string> &TypeTable,
214 SlotCalculator *Table) {
215 if (const ConstantBool *CB = dyn_cast<ConstantBool>(CV)) {
216 Out << (CB == ConstantBool::True ? "true" : "false");
217 } else if (const ConstantSInt *CI = dyn_cast<ConstantSInt>(CV)) {
218 Out << CI->getValue();
219 } else if (const ConstantUInt *CI = dyn_cast<ConstantUInt>(CV)) {
220 Out << CI->getValue();
221 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
222 // We would like to output the FP constant value in exponential notation,
223 // but we cannot do this if doing so will lose precision. Check here to
224 // make sure that we only output it in exponential format if we can parse
225 // the value back and get the same value.
227 std::string StrVal = ftostr(CFP->getValue());
229 // Check to make sure that the stringized number is not some string like
230 // "Inf" or NaN, that atof will accept, but the lexer will not. Check that
231 // the string matches the "[-+]?[0-9]" regex.
233 if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
234 ((StrVal[0] == '-' || StrVal[0] == '+') &&
235 (StrVal[0] >= '0' && StrVal[0] <= '9')))
236 // Reparse stringized version!
237 if (atof(StrVal.c_str()) == CFP->getValue()) {
238 Out << StrVal; return;
241 // Otherwise we could not reparse it to exactly the same value, so we must
242 // output the string in hexadecimal format!
244 // Behave nicely in the face of C TBAA rules... see:
245 // http://www.nullstone.com/htmls/category/aliastyp.htm
247 double Val = CFP->getValue();
248 char *Ptr = (char*)&Val;
249 assert(sizeof(double) == sizeof(uint64_t) && sizeof(double) == 8 &&
250 "assuming that double is 64 bits!");
251 Out << "0x" << utohexstr(*(uint64_t*)Ptr);
253 } else if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
254 // As a special case, print the array as a string if it is an array of
255 // ubytes or an array of sbytes with positive values.
257 const Type *ETy = CA->getType()->getElementType();
258 bool isString = (ETy == Type::SByteTy || ETy == Type::UByteTy);
260 if (ETy == Type::SByteTy)
261 for (unsigned i = 0; i < CA->getNumOperands(); ++i)
262 if (cast<ConstantSInt>(CA->getOperand(i))->getValue() < 0) {
269 for (unsigned i = 0; i < CA->getNumOperands(); ++i) {
270 unsigned char C = (ETy == Type::SByteTy) ?
271 (unsigned char)cast<ConstantSInt>(CA->getOperand(i))->getValue() :
272 (unsigned char)cast<ConstantUInt>(CA->getOperand(i))->getValue();
274 if (isprint(C) && C != '"') {
278 << (char) ((C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A'))
279 << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
284 } else { // Cannot output in string format...
286 if (CA->getNumOperands()) {
288 printTypeInt(Out, ETy, TypeTable);
289 WriteAsOperandInternal(Out, CA->getOperand(0),
290 PrintName, TypeTable, Table);
291 for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
293 printTypeInt(Out, ETy, TypeTable);
294 WriteAsOperandInternal(Out, CA->getOperand(i), PrintName,
300 } else if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
302 if (CS->getNumOperands()) {
304 printTypeInt(Out, CS->getOperand(0)->getType(), TypeTable);
306 WriteAsOperandInternal(Out, CS->getOperand(0),
307 PrintName, TypeTable, Table);
309 for (unsigned i = 1; i < CS->getNumOperands(); i++) {
311 printTypeInt(Out, CS->getOperand(i)->getType(), TypeTable);
313 WriteAsOperandInternal(Out, CS->getOperand(i),
314 PrintName, TypeTable, Table);
319 } else if (isa<ConstantPointerNull>(CV)) {
322 } else if (const ConstantPointerRef *PR = dyn_cast<ConstantPointerRef>(CV)) {
323 const GlobalValue *V = PR->getValue();
325 Out << "%" << V->getName();
327 int Slot = Table->getValSlot(V);
331 Out << "<pointer reference badref>";
333 Out << "<pointer reference without context info>";
336 } else if (const ConstantExpr *CE=dyn_cast<ConstantExpr>(CV)) {
337 Out << CE->getOpcodeName();
339 bool isGEP = CE->getOpcode() == Instruction::GetElementPtr;
340 Out << (isGEP? " (" : " ");
342 for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) {
343 printTypeInt(Out, (*OI)->getType(), TypeTable);
344 WriteAsOperandInternal(Out, *OI, PrintName, TypeTable, Table);
345 if (OI+1 != CE->op_end())
346 Out << ", "; // ((isGEP && OI == CE->op_begin())? " " : ", ");
352 Out << "<placeholder or erroneous Constant>";
357 // WriteAsOperand - Write the name of the specified value out to the specified
358 // ostream. This can be useful when you just want to print int %reg126, not the
359 // whole instruction that generated it.
361 static void WriteAsOperandInternal(ostream &Out, const Value *V, bool PrintName,
362 map<const Type *, string> &TypeTable,
363 SlotCalculator *Table) {
365 if (PrintName && V->hasName()) {
366 Out << "%" << V->getName();
368 if (const Constant *CV = dyn_cast<const Constant>(V)) {
369 WriteConstantInt(Out, CV, PrintName, TypeTable, Table);
373 Slot = Table->getValSlot(V);
375 if (const Type *Ty = dyn_cast<const Type>(V)) {
376 Out << Ty->getDescription();
380 Table = createSlotCalculator(V);
381 if (Table == 0) { Out << "BAD VALUE TYPE!"; return; }
383 Slot = Table->getValSlot(V);
386 if (Slot >= 0) Out << "%" << Slot;
388 Out << "<badref>"; // Not embeded into a location?
395 // WriteAsOperand - Write the name of the specified value out to the specified
396 // ostream. This can be useful when you just want to print int %reg126, not the
397 // whole instruction that generated it.
399 ostream &WriteAsOperand(ostream &Out, const Value *V, bool PrintType,
400 bool PrintName, const Module *Context) {
401 map<const Type *, string> TypeNames;
402 if (Context == 0) Context = getModuleFromVal(V);
404 if (Context && Context->hasSymbolTable())
405 fillTypeNameTable(Context, TypeNames);
408 printTypeInt(Out, V->getType(), TypeNames);
410 WriteAsOperandInternal(Out, V, PrintName, TypeNames, 0);
416 class AssemblyWriter {
418 SlotCalculator &Table;
419 const Module *TheModule;
420 map<const Type *, string> TypeNames;
422 inline AssemblyWriter(ostream &o, SlotCalculator &Tab, const Module *M)
423 : Out(o), Table(Tab), TheModule(M) {
425 // If the module has a symbol table, take all global types and stuff their
426 // names into the TypeNames map.
428 fillTypeNameTable(M, TypeNames);
431 inline void write(const Module *M) { printModule(M); }
432 inline void write(const GlobalVariable *G) { printGlobal(G); }
433 inline void write(const Function *F) { printFunction(F); }
434 inline void write(const BasicBlock *BB) { printBasicBlock(BB); }
435 inline void write(const Instruction *I) { printInstruction(*I); }
436 inline void write(const Constant *CPV) { printConstant(CPV); }
437 inline void write(const Type *Ty) { printType(Ty); }
439 void writeOperand(const Value *Op, bool PrintType, bool PrintName = true);
442 void printModule(const Module *M);
443 void printSymbolTable(const SymbolTable &ST);
444 void printConstant(const Constant *CPV);
445 void printGlobal(const GlobalVariable *GV);
446 void printFunction(const Function *F);
447 void printArgument(const Argument *FA);
448 void printBasicBlock(const BasicBlock *BB);
449 void printInstruction(const Instruction &I);
451 // printType - Go to extreme measures to attempt to print out a short,
452 // symbolic version of a type name.
454 ostream &printType(const Type *Ty) {
455 return printTypeInt(Out, Ty, TypeNames);
458 // printTypeAtLeastOneLevel - Print out one level of the possibly complex type
459 // without considering any symbolic types that we may have equal to it.
461 ostream &printTypeAtLeastOneLevel(const Type *Ty);
463 // printInfoComment - Print a little comment after the instruction indicating
464 // which slot it occupies.
465 void printInfoComment(const Value &V);
469 // printTypeAtLeastOneLevel - Print out one level of the possibly complex type
470 // without considering any symbolic types that we may have equal to it.
472 ostream &AssemblyWriter::printTypeAtLeastOneLevel(const Type *Ty) {
473 if (const FunctionType *FTy = dyn_cast<FunctionType>(Ty)) {
474 printType(FTy->getReturnType()) << " (";
475 for (FunctionType::ParamTypes::const_iterator
476 I = FTy->getParamTypes().begin(),
477 E = FTy->getParamTypes().end(); I != E; ++I) {
478 if (I != FTy->getParamTypes().begin())
482 if (FTy->isVarArg()) {
483 if (!FTy->getParamTypes().empty()) Out << ", ";
487 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
489 for (StructType::ElementTypes::const_iterator
490 I = STy->getElementTypes().begin(),
491 E = STy->getElementTypes().end(); I != E; ++I) {
492 if (I != STy->getElementTypes().begin())
497 } else if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
498 printType(PTy->getElementType()) << "*";
499 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
500 Out << "[" << ATy->getNumElements() << " x ";
501 printType(ATy->getElementType()) << "]";
502 } else if (const OpaqueType *OTy = dyn_cast<OpaqueType>(Ty)) {
503 Out << OTy->getDescription();
505 if (!Ty->isPrimitiveType())
506 Out << "<unknown derived type>";
513 void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType,
515 if (PrintType) { Out << " "; printType(Operand->getType()); }
516 WriteAsOperandInternal(Out, Operand, PrintName, TypeNames, &Table);
520 void AssemblyWriter::printModule(const Module *M) {
521 // Loop over the symbol table, emitting all named constants...
522 if (M->hasSymbolTable())
523 printSymbolTable(*M->getSymbolTable());
525 for (Module::const_giterator I = M->gbegin(), E = M->gend(); I != E; ++I)
528 Out << "\nimplementation ; Functions:\n";
530 // Output all of the functions...
531 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
535 void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
536 if (GV->hasName()) Out << "%" << GV->getName() << " = ";
538 if (GV->hasInternalLinkage()) Out << "internal ";
539 if (!GV->hasInitializer()) Out << "uninitialized ";
541 Out << (GV->isConstant() ? "constant " : "global ");
542 printType(GV->getType()->getElementType());
544 if (GV->hasInitializer())
545 writeOperand(GV->getInitializer(), false, false);
547 printInfoComment(*GV);
552 // printSymbolTable - Run through symbol table looking for named constants
553 // if a named constant is found, emit it's declaration...
555 void AssemblyWriter::printSymbolTable(const SymbolTable &ST) {
556 for (SymbolTable::const_iterator TI = ST.begin(); TI != ST.end(); ++TI) {
557 SymbolTable::type_const_iterator I = ST.type_begin(TI->first);
558 SymbolTable::type_const_iterator End = ST.type_end(TI->first);
560 for (; I != End; ++I) {
561 const Value *V = I->second;
562 if (const Constant *CPV = dyn_cast<const Constant>(V)) {
564 } else if (const Type *Ty = dyn_cast<const Type>(V)) {
565 Out << "\t%" << I->first << " = type ";
567 // Make sure we print out at least one level of the type structure, so
568 // that we do not get %FILE = type %FILE
570 printTypeAtLeastOneLevel(Ty) << "\n";
577 // printConstant - Print out a constant pool entry...
579 void AssemblyWriter::printConstant(const Constant *CPV) {
580 // Don't print out unnamed constants, they will be inlined
581 if (!CPV->hasName()) return;
584 Out << "\t%" << CPV->getName() << " =";
586 // Write the value out now...
587 writeOperand(CPV, true, false);
589 printInfoComment(*CPV);
593 // printFunction - Print all aspects of a function.
595 void AssemblyWriter::printFunction(const Function *F) {
596 // Print out the return type and name...
597 Out << "\n" << (F->isExternal() ? "declare " : "")
598 << (F->hasInternalLinkage() ? "internal " : "");
599 printType(F->getReturnType()) << " %" << F->getName() << "(";
600 Table.incorporateFunction(F);
602 // Loop over the arguments, printing them...
603 const FunctionType *FT = F->getFunctionType();
605 if (!F->isExternal()) {
606 for(Function::const_aiterator I = F->abegin(), E = F->aend(); I != E; ++I)
609 // Loop over the arguments, printing them...
610 for (FunctionType::ParamTypes::const_iterator I = FT->getParamTypes().begin(),
611 E = FT->getParamTypes().end(); I != E; ++I) {
612 if (I != FT->getParamTypes().begin()) Out << ", ";
617 // Finish printing arguments...
618 if (FT->isVarArg()) {
619 if (FT->getParamTypes().size()) Out << ", ";
620 Out << "..."; // Output varargs portion of signature!
624 if (F->isExternal()) {
629 // Output all of its basic blocks... for the function
630 for (Function::const_iterator I = F->begin(), E = F->end(); I != E; ++I)
636 Table.purgeFunction();
639 // printArgument - This member is called for every argument that
640 // is passed into the function. Simply print it out
642 void AssemblyWriter::printArgument(const Argument *Arg) {
643 // Insert commas as we go... the first arg doesn't get a comma
644 if (Arg != &Arg->getParent()->afront()) Out << ", ";
647 printType(Arg->getType());
649 // Output name, if available...
651 Out << " %" << Arg->getName();
652 else if (Table.getValSlot(Arg) < 0)
656 // printBasicBlock - This member is called for each basic block in a methd.
658 void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {
659 if (BB->hasName()) { // Print out the label if it exists...
660 Out << "\n" << BB->getName() << ":\t\t\t\t\t;[#uses="
661 << BB->use_size() << "]"; // Output # uses
662 } else if (!BB->use_empty()) { // Don't print block # of no uses...
663 int Slot = Table.getValSlot(BB);
664 Out << "\n; <label>:";
666 Out << Slot; // Extra newline seperates out label's
669 Out << "\t\t\t\t\t;[#uses=" << BB->use_size() << "]"; // Output # uses
674 // Output all of the instructions in the basic block...
675 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
676 printInstruction(*I);
680 // printInfoComment - Print a little comment after the instruction indicating
681 // which slot it occupies.
683 void AssemblyWriter::printInfoComment(const Value &V) {
684 if (V.getType() != Type::VoidTy) {
686 printType(V.getType()) << ">";
689 int Slot = Table.getValSlot(&V); // Print out the def slot taken...
690 if (Slot >= 0) Out << ":" << Slot;
691 else Out << ":<badref>";
693 Out << " [#uses=" << V.use_size() << "]"; // Output # uses
697 // printInstruction - This member is called for each Instruction in a methd.
699 void AssemblyWriter::printInstruction(const Instruction &I) {
702 // Print out name if it exists...
704 Out << "%" << I.getName() << " = ";
706 // Print out the opcode...
707 Out << I.getOpcodeName();
709 // Print out the type of the operands...
710 const Value *Operand = I.getNumOperands() ? I.getOperand(0) : 0;
712 // Special case conditional branches to swizzle the condition out to the front
713 if (isa<BranchInst>(I) && I.getNumOperands() > 1) {
714 writeOperand(I.getOperand(2), true);
716 writeOperand(Operand, true);
718 writeOperand(I.getOperand(1), true);
720 } else if (isa<SwitchInst>(I)) {
721 // Special case switch statement to get formatting nice and correct...
722 writeOperand(Operand , true); Out << ",";
723 writeOperand(I.getOperand(1), true); Out << " [";
725 for (unsigned op = 2, Eop = I.getNumOperands(); op < Eop; op += 2) {
727 writeOperand(I.getOperand(op ), true); Out << ",";
728 writeOperand(I.getOperand(op+1), true);
731 } else if (isa<PHINode>(I)) {
733 printType(I.getType());
736 for (unsigned op = 0, Eop = I.getNumOperands(); op < Eop; op += 2) {
739 writeOperand(I.getOperand(op ), false); Out << ",";
740 writeOperand(I.getOperand(op+1), false); Out << " ]";
742 } else if (isa<ReturnInst>(I) && !Operand) {
744 } else if (isa<CallInst>(I)) {
745 const PointerType *PTy = dyn_cast<PointerType>(Operand->getType());
746 const FunctionType*MTy = PTy ? dyn_cast<FunctionType>(PTy->getElementType()):0;
747 const Type *RetTy = MTy ? MTy->getReturnType() : 0;
749 // If possible, print out the short form of the call instruction, but we can
750 // only do this if the first argument is a pointer to a nonvararg function,
751 // and if the value returned is not a pointer to a function.
753 if (RetTy && MTy && !MTy->isVarArg() &&
754 (!isa<PointerType>(RetTy) ||
755 !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
756 Out << " "; printType(RetTy);
757 writeOperand(Operand, false);
759 writeOperand(Operand, true);
762 if (I.getNumOperands() > 1) writeOperand(I.getOperand(1), true);
763 for (unsigned op = 2, Eop = I.getNumOperands(); op < Eop; ++op) {
765 writeOperand(I.getOperand(op), true);
769 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
770 // TODO: Should try to print out short form of the Invoke instruction
771 writeOperand(Operand, true);
773 if (I.getNumOperands() > 3) writeOperand(I.getOperand(3), true);
774 for (unsigned op = 4, Eop = I.getNumOperands(); op < Eop; ++op) {
776 writeOperand(I.getOperand(op), true);
779 Out << " )\n\t\t\tto";
780 writeOperand(II->getNormalDest(), true);
782 writeOperand(II->getExceptionalDest(), true);
784 } else if (const AllocationInst *AI = dyn_cast<AllocationInst>(&I)) {
786 printType(AI->getType()->getElementType());
787 if (AI->isArrayAllocation()) {
789 writeOperand(AI->getArraySize(), true);
791 } else if (isa<CastInst>(I)) {
792 if (Operand) writeOperand(Operand, true);
794 printType(I.getType());
795 } else if (Operand) { // Print the normal way...
797 // PrintAllTypes - Instructions who have operands of all the same type
798 // omit the type from all but the first operand. If the instruction has
799 // different type operands (for example br), then they are all printed.
800 bool PrintAllTypes = false;
801 const Type *TheType = Operand->getType();
803 for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) {
804 Operand = I.getOperand(i);
805 if (Operand->getType() != TheType) {
806 PrintAllTypes = true; // We have differing types! Print them all!
811 // Shift Left & Right print both types even for Ubyte LHS
812 if (isa<ShiftInst>(I)) PrintAllTypes = true;
814 if (!PrintAllTypes) {
816 printType(I.getOperand(0)->getType());
819 for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) {
821 writeOperand(I.getOperand(i), PrintAllTypes);
830 //===----------------------------------------------------------------------===//
831 // External Interface declarations
832 //===----------------------------------------------------------------------===//
835 void Module::print(std::ostream &o) const {
836 SlotCalculator SlotTable(this, true);
837 AssemblyWriter W(o, SlotTable, this);
841 void GlobalVariable::print(std::ostream &o) const {
842 SlotCalculator SlotTable(getParent(), true);
843 AssemblyWriter W(o, SlotTable, getParent());
847 void Function::print(std::ostream &o) const {
848 SlotCalculator SlotTable(getParent(), true);
849 AssemblyWriter W(o, SlotTable, getParent());
854 void BasicBlock::print(std::ostream &o) const {
855 SlotCalculator SlotTable(getParent(), true);
856 AssemblyWriter W(o, SlotTable,
857 getParent() ? getParent()->getParent() : 0);
861 void Instruction::print(std::ostream &o) const {
862 const Function *F = getParent() ? getParent()->getParent() : 0;
863 SlotCalculator SlotTable(F, true);
864 AssemblyWriter W(o, SlotTable, F ? F->getParent() : 0);
869 void Constant::print(std::ostream &o) const {
870 if (this == 0) { o << "<null> constant value\n"; return; }
871 o << " " << getType()->getDescription() << " ";
873 map<const Type *, string> TypeTable;
874 WriteConstantInt(o, this, false, TypeTable, 0);
877 void Type::print(std::ostream &o) const {
881 o << getDescription();
884 void Argument::print(std::ostream &o) const {
885 o << getType() << " " << getName();
888 void Value::dump() const { print(std::cerr); }
890 //===----------------------------------------------------------------------===//
891 // CachedWriter Class Implementation
892 //===----------------------------------------------------------------------===//
894 void CachedWriter::setModule(const Module *M) {
895 delete SC; delete AW;
897 SC = new SlotCalculator(M, true);
898 AW = new AssemblyWriter(Out, *SC, M);
904 CachedWriter::~CachedWriter() {
909 CachedWriter &CachedWriter::operator<<(const Value *V) {
910 assert(AW && SC && "CachedWriter does not have a current module!");
911 switch (V->getValueType()) {
912 case Value::ConstantVal:
913 case Value::ArgumentVal: AW->writeOperand(V, true, true); break;
914 case Value::TypeVal: AW->write(cast<const Type>(V)); break;
915 case Value::InstructionVal: AW->write(cast<Instruction>(V)); break;
916 case Value::BasicBlockVal: AW->write(cast<BasicBlock>(V)); break;
917 case Value::FunctionVal: AW->write(cast<Function>(V)); break;
918 case Value::GlobalVariableVal: AW->write(cast<GlobalVariable>(V)); break;
919 default: Out << "<unknown value type: " << V->getValueType() << ">"; break;