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 it can be used for debugging transformations.
8 //===----------------------------------------------------------------------===//
10 #include "llvm/Assembly/CachedWriter.h"
11 #include "llvm/Assembly/Writer.h"
12 #include "llvm/Assembly/PrintModulePass.h"
13 #include "llvm/SlotCalculator.h"
14 #include "llvm/DerivedTypes.h"
15 #include "llvm/Instruction.h"
16 #include "llvm/Module.h"
17 #include "llvm/Constants.h"
18 #include "llvm/iMemory.h"
19 #include "llvm/iTerminators.h"
20 #include "llvm/iPHINode.h"
21 #include "llvm/iOther.h"
22 #include "llvm/SymbolTable.h"
23 #include "llvm/Support/CFG.h"
24 #include "Support/StringExtras.h"
25 #include "Support/STLExtras.h"
28 static RegisterPass<PrintModulePass>
29 X("printm", "Print module to stderr",PassInfo::Analysis|PassInfo::Optimization);
30 static RegisterPass<PrintFunctionPass>
31 Y("print","Print function to stderr",PassInfo::Analysis|PassInfo::Optimization);
33 static void WriteAsOperandInternal(std::ostream &Out, const Value *V,
35 std::map<const Type *, std::string> &TypeTable,
36 SlotCalculator *Table);
38 static const Module *getModuleFromVal(const Value *V) {
39 if (const Argument *MA = dyn_cast<const Argument>(V))
40 return MA->getParent() ? MA->getParent()->getParent() : 0;
41 else if (const BasicBlock *BB = dyn_cast<const BasicBlock>(V))
42 return BB->getParent() ? BB->getParent()->getParent() : 0;
43 else if (const Instruction *I = dyn_cast<const Instruction>(V)) {
44 const Function *M = I->getParent() ? I->getParent()->getParent() : 0;
45 return M ? M->getParent() : 0;
46 } else if (const GlobalValue *GV = dyn_cast<const GlobalValue>(V))
47 return GV->getParent();
51 static SlotCalculator *createSlotCalculator(const Value *V) {
52 assert(!isa<Type>(V) && "Can't create an SC for a type!");
53 if (const Argument *FA = dyn_cast<const Argument>(V)) {
54 return new SlotCalculator(FA->getParent(), true);
55 } else if (const Instruction *I = dyn_cast<const Instruction>(V)) {
56 return new SlotCalculator(I->getParent()->getParent(), true);
57 } else if (const BasicBlock *BB = dyn_cast<const BasicBlock>(V)) {
58 return new SlotCalculator(BB->getParent(), true);
59 } else if (const GlobalVariable *GV = dyn_cast<const GlobalVariable>(V)){
60 return new SlotCalculator(GV->getParent(), true);
61 } else if (const Function *Func = dyn_cast<const Function>(V)) {
62 return new SlotCalculator(Func, true);
68 // If the module has a symbol table, take all global types and stuff their
69 // names into the TypeNames map.
71 static void fillTypeNameTable(const Module *M,
72 std::map<const Type *, std::string> &TypeNames) {
74 const SymbolTable &ST = M->getSymbolTable();
75 SymbolTable::const_iterator PI = ST.find(Type::TypeTy);
77 SymbolTable::type_const_iterator I = PI->second.begin();
78 for (; I != PI->second.end(); ++I) {
79 // As a heuristic, don't insert pointer to primitive types, because
80 // they are used too often to have a single useful name.
82 const Type *Ty = cast<const Type>(I->second);
83 if (!isa<PointerType>(Ty) ||
84 !cast<PointerType>(Ty)->getElementType()->isPrimitiveType())
85 TypeNames.insert(std::make_pair(Ty, "%"+I->first));
92 static std::string calcTypeName(const Type *Ty,
93 std::vector<const Type *> &TypeStack,
94 std::map<const Type *, std::string> &TypeNames){
95 if (Ty->isPrimitiveType()) return Ty->getDescription(); // Base case
97 // Check to see if the type is named.
98 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
99 if (I != TypeNames.end()) return I->second;
101 // Check to see if the Type is already on the stack...
102 unsigned Slot = 0, CurSize = TypeStack.size();
103 while (Slot < CurSize && TypeStack[Slot] != Ty) ++Slot; // Scan for type
105 // This is another base case for the recursion. In this case, we know
106 // that we have looped back to a type that we have previously visited.
107 // Generate the appropriate upreference to handle this.
110 return "\\" + utostr(CurSize-Slot); // Here's the upreference
112 TypeStack.push_back(Ty); // Recursive case: Add us to the stack..
115 switch (Ty->getPrimitiveID()) {
116 case Type::FunctionTyID: {
117 const FunctionType *FTy = cast<const FunctionType>(Ty);
118 Result = calcTypeName(FTy->getReturnType(), TypeStack, TypeNames) + " (";
119 for (FunctionType::ParamTypes::const_iterator
120 I = FTy->getParamTypes().begin(),
121 E = FTy->getParamTypes().end(); I != E; ++I) {
122 if (I != FTy->getParamTypes().begin())
124 Result += calcTypeName(*I, TypeStack, TypeNames);
126 if (FTy->isVarArg()) {
127 if (!FTy->getParamTypes().empty()) Result += ", ";
133 case Type::StructTyID: {
134 const StructType *STy = cast<const StructType>(Ty);
136 for (StructType::ElementTypes::const_iterator
137 I = STy->getElementTypes().begin(),
138 E = STy->getElementTypes().end(); I != E; ++I) {
139 if (I != STy->getElementTypes().begin())
141 Result += calcTypeName(*I, TypeStack, TypeNames);
146 case Type::PointerTyID:
147 Result = calcTypeName(cast<const PointerType>(Ty)->getElementType(),
148 TypeStack, TypeNames) + "*";
150 case Type::ArrayTyID: {
151 const ArrayType *ATy = cast<const ArrayType>(Ty);
152 Result = "[" + utostr(ATy->getNumElements()) + " x ";
153 Result += calcTypeName(ATy->getElementType(), TypeStack, TypeNames) + "]";
157 Result = "<unrecognized-type>";
160 TypeStack.pop_back(); // Remove self from stack...
165 // printTypeInt - The internal guts of printing out a type that has a
166 // potentially named portion.
168 static std::ostream &printTypeInt(std::ostream &Out, const Type *Ty,
169 std::map<const Type *, std::string> &TypeNames) {
170 // Primitive types always print out their description, regardless of whether
171 // they have been named or not.
173 if (Ty->isPrimitiveType()) return Out << Ty->getDescription();
175 // Check to see if the type is named.
176 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
177 if (I != TypeNames.end()) return Out << I->second;
179 // Otherwise we have a type that has not been named but is a derived type.
180 // Carefully recurse the type hierarchy to print out any contained symbolic
183 std::vector<const Type *> TypeStack;
184 std::string TypeName = calcTypeName(Ty, TypeStack, TypeNames);
185 TypeNames.insert(std::make_pair(Ty, TypeName));//Cache type name for later use
186 return Out << TypeName;
190 // WriteTypeSymbolic - This attempts to write the specified type as a symbolic
191 // type, iff there is an entry in the modules symbol table for the specified
192 // type or one of it's component types. This is slower than a simple x << Type;
194 std::ostream &WriteTypeSymbolic(std::ostream &Out, const Type *Ty,
198 // If they want us to print out a type, attempt to make it symbolic if there
199 // is a symbol table in the module...
201 std::map<const Type *, std::string> TypeNames;
202 fillTypeNameTable(M, TypeNames);
204 return printTypeInt(Out, Ty, TypeNames);
206 return Out << Ty->getDescription();
210 static void WriteConstantInt(std::ostream &Out, const Constant *CV,
212 std::map<const Type *, std::string> &TypeTable,
213 SlotCalculator *Table) {
214 if (const ConstantBool *CB = dyn_cast<ConstantBool>(CV)) {
215 Out << (CB == ConstantBool::True ? "true" : "false");
216 } else if (const ConstantSInt *CI = dyn_cast<ConstantSInt>(CV)) {
217 Out << CI->getValue();
218 } else if (const ConstantUInt *CI = dyn_cast<ConstantUInt>(CV)) {
219 Out << CI->getValue();
220 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
221 // We would like to output the FP constant value in exponential notation,
222 // but we cannot do this if doing so will lose precision. Check here to
223 // make sure that we only output it in exponential format if we can parse
224 // the value back and get the same value.
226 std::string StrVal = ftostr(CFP->getValue());
228 // Check to make sure that the stringized number is not some string like
229 // "Inf" or NaN, that atof will accept, but the lexer will not. Check that
230 // the string matches the "[-+]?[0-9]" regex.
232 if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
233 ((StrVal[0] == '-' || StrVal[0] == '+') &&
234 (StrVal[0] >= '0' && StrVal[0] <= '9')))
235 // Reparse stringized version!
236 if (atof(StrVal.c_str()) == CFP->getValue()) {
237 Out << StrVal; return;
240 // Otherwise we could not reparse it to exactly the same value, so we must
241 // output the string in hexadecimal format!
243 // Behave nicely in the face of C TBAA rules... see:
244 // http://www.nullstone.com/htmls/category/aliastyp.htm
246 double Val = CFP->getValue();
247 char *Ptr = (char*)&Val;
248 assert(sizeof(double) == sizeof(uint64_t) && sizeof(double) == 8 &&
249 "assuming that double is 64 bits!");
250 Out << "0x" << utohexstr(*(uint64_t*)Ptr);
252 } else if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
253 // As a special case, print the array as a string if it is an array of
254 // ubytes or an array of sbytes with positive values.
256 const Type *ETy = CA->getType()->getElementType();
257 bool isString = (ETy == Type::SByteTy || ETy == Type::UByteTy);
259 if (ETy == Type::SByteTy)
260 for (unsigned i = 0; i < CA->getNumOperands(); ++i)
261 if (cast<ConstantSInt>(CA->getOperand(i))->getValue() < 0) {
268 for (unsigned i = 0; i < CA->getNumOperands(); ++i) {
269 unsigned char C = (ETy == Type::SByteTy) ?
270 (unsigned char)cast<ConstantSInt>(CA->getOperand(i))->getValue() :
271 (unsigned char)cast<ConstantUInt>(CA->getOperand(i))->getValue();
273 if (isprint(C) && C != '"' && C != '\\') {
277 << (char) ((C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A'))
278 << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
283 } else { // Cannot output in string format...
285 if (CA->getNumOperands()) {
287 printTypeInt(Out, ETy, TypeTable);
288 WriteAsOperandInternal(Out, CA->getOperand(0),
289 PrintName, TypeTable, Table);
290 for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
292 printTypeInt(Out, ETy, TypeTable);
293 WriteAsOperandInternal(Out, CA->getOperand(i), PrintName,
299 } else if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
301 if (CS->getNumOperands()) {
303 printTypeInt(Out, CS->getOperand(0)->getType(), TypeTable);
305 WriteAsOperandInternal(Out, CS->getOperand(0),
306 PrintName, TypeTable, Table);
308 for (unsigned i = 1; i < CS->getNumOperands(); i++) {
310 printTypeInt(Out, CS->getOperand(i)->getType(), TypeTable);
312 WriteAsOperandInternal(Out, CS->getOperand(i),
313 PrintName, TypeTable, Table);
318 } else if (isa<ConstantPointerNull>(CV)) {
321 } else if (const ConstantPointerRef *PR = dyn_cast<ConstantPointerRef>(CV)) {
322 const GlobalValue *V = PR->getValue();
324 Out << "%" << V->getName();
326 int Slot = Table->getValSlot(V);
330 Out << "<pointer reference badref>";
332 Out << "<pointer reference without context info>";
335 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
336 Out << CE->getOpcodeName() << " (";
338 for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) {
339 printTypeInt(Out, (*OI)->getType(), TypeTable);
340 WriteAsOperandInternal(Out, *OI, PrintName, TypeTable, Table);
341 if (OI+1 != CE->op_end())
345 if (CE->getOpcode() == Instruction::Cast) {
347 printTypeInt(Out, CE->getType(), TypeTable);
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(std::ostream &Out, const Value *V,
363 std::map<const Type*, std::string> &TypeTable,
364 SlotCalculator *Table) {
366 if (PrintName && V->hasName()) {
367 Out << "%" << V->getName();
369 if (const Constant *CV = dyn_cast<const Constant>(V)) {
370 WriteConstantInt(Out, CV, PrintName, TypeTable, Table);
374 Slot = Table->getValSlot(V);
376 if (const Type *Ty = dyn_cast<const Type>(V)) {
377 Out << Ty->getDescription();
381 Table = createSlotCalculator(V);
382 if (Table == 0) { Out << "BAD VALUE TYPE!"; return; }
384 Slot = Table->getValSlot(V);
387 if (Slot >= 0) Out << "%" << Slot;
389 Out << "<badref>"; // Not embeded into a location?
396 // WriteAsOperand - Write the name of the specified value out to the specified
397 // ostream. This can be useful when you just want to print int %reg126, not the
398 // whole instruction that generated it.
400 std::ostream &WriteAsOperand(std::ostream &Out, const Value *V, bool PrintType,
401 bool PrintName, const Module *Context) {
402 std::map<const Type *, std::string> TypeNames;
403 if (Context == 0) Context = getModuleFromVal(V);
406 fillTypeNameTable(Context, TypeNames);
409 printTypeInt(Out, V->getType(), TypeNames);
411 WriteAsOperandInternal(Out, V, PrintName, TypeNames, 0);
417 class AssemblyWriter {
419 SlotCalculator &Table;
420 const Module *TheModule;
421 std::map<const Type *, std::string> TypeNames;
423 inline AssemblyWriter(std::ostream &o, SlotCalculator &Tab, const Module *M)
424 : Out(o), Table(Tab), TheModule(M) {
426 // If the module has a symbol table, take all global types and stuff their
427 // names into the TypeNames map.
429 fillTypeNameTable(M, TypeNames);
432 inline void write(const Module *M) { printModule(M); }
433 inline void write(const GlobalVariable *G) { printGlobal(G); }
434 inline void write(const Function *F) { printFunction(F); }
435 inline void write(const BasicBlock *BB) { printBasicBlock(BB); }
436 inline void write(const Instruction *I) { printInstruction(*I); }
437 inline void write(const Constant *CPV) { printConstant(CPV); }
438 inline void write(const Type *Ty) { printType(Ty); }
440 void writeOperand(const Value *Op, bool PrintType, bool PrintName = true);
443 void printModule(const Module *M);
444 void printSymbolTable(const SymbolTable &ST);
445 void printConstant(const Constant *CPV);
446 void printGlobal(const GlobalVariable *GV);
447 void printFunction(const Function *F);
448 void printArgument(const Argument *FA);
449 void printBasicBlock(const BasicBlock *BB);
450 void printInstruction(const Instruction &I);
452 // printType - Go to extreme measures to attempt to print out a short,
453 // symbolic version of a type name.
455 std::ostream &printType(const Type *Ty) {
456 return printTypeInt(Out, Ty, TypeNames);
459 // printTypeAtLeastOneLevel - Print out one level of the possibly complex type
460 // without considering any symbolic types that we may have equal to it.
462 std::ostream &printTypeAtLeastOneLevel(const Type *Ty);
464 // printInfoComment - Print a little comment after the instruction indicating
465 // which slot it occupies.
466 void printInfoComment(const Value &V);
470 // printTypeAtLeastOneLevel - Print out one level of the possibly complex type
471 // without considering any symbolic types that we may have equal to it.
473 std::ostream &AssemblyWriter::printTypeAtLeastOneLevel(const Type *Ty) {
474 if (const FunctionType *FTy = dyn_cast<FunctionType>(Ty)) {
475 printType(FTy->getReturnType()) << " (";
476 for (FunctionType::ParamTypes::const_iterator
477 I = FTy->getParamTypes().begin(),
478 E = FTy->getParamTypes().end(); I != E; ++I) {
479 if (I != FTy->getParamTypes().begin())
483 if (FTy->isVarArg()) {
484 if (!FTy->getParamTypes().empty()) Out << ", ";
488 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
490 for (StructType::ElementTypes::const_iterator
491 I = STy->getElementTypes().begin(),
492 E = STy->getElementTypes().end(); I != E; ++I) {
493 if (I != STy->getElementTypes().begin())
498 } else if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
499 printType(PTy->getElementType()) << "*";
500 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
501 Out << "[" << ATy->getNumElements() << " x ";
502 printType(ATy->getElementType()) << "]";
503 } else if (const OpaqueType *OTy = dyn_cast<OpaqueType>(Ty)) {
504 Out << OTy->getDescription();
506 if (!Ty->isPrimitiveType())
507 Out << "<unknown derived type>";
514 void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType,
516 if (PrintType) { Out << " "; printType(Operand->getType()); }
517 WriteAsOperandInternal(Out, Operand, PrintName, TypeNames, &Table);
521 void AssemblyWriter::printModule(const Module *M) {
522 Out << "target endian = " << (M->isLittleEndian() ? "little" : "big") << "\n";
523 Out << "target pointersize = " << (M->has32BitPointers() ? 32 : 64) << "\n";
525 // Loop over the symbol table, emitting all named constants...
526 printSymbolTable(M->getSymbolTable());
528 for (Module::const_giterator I = M->gbegin(), E = M->gend(); I != E; ++I)
531 Out << "\nimplementation ; Functions:\n";
533 // Output all of the functions...
534 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
538 void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
539 if (GV->hasName()) Out << "%" << GV->getName() << " = ";
541 if (!GV->hasInitializer())
544 switch (GV->getLinkage()) {
545 case GlobalValue::InternalLinkage: Out << "internal "; break;
546 case GlobalValue::LinkOnceLinkage: Out << "linkonce "; break;
547 case GlobalValue::AppendingLinkage: Out << "appending "; break;
548 case GlobalValue::ExternalLinkage: break;
551 Out << (GV->isConstant() ? "constant " : "global ");
552 printType(GV->getType()->getElementType());
554 if (GV->hasInitializer())
555 writeOperand(GV->getInitializer(), false, false);
557 printInfoComment(*GV);
562 // printSymbolTable - Run through symbol table looking for named constants
563 // if a named constant is found, emit it's declaration...
565 void AssemblyWriter::printSymbolTable(const SymbolTable &ST) {
566 for (SymbolTable::const_iterator TI = ST.begin(); TI != ST.end(); ++TI) {
567 SymbolTable::type_const_iterator I = ST.type_begin(TI->first);
568 SymbolTable::type_const_iterator End = ST.type_end(TI->first);
570 for (; I != End; ++I) {
571 const Value *V = I->second;
572 if (const Constant *CPV = dyn_cast<const Constant>(V)) {
574 } else if (const Type *Ty = dyn_cast<const Type>(V)) {
575 Out << "\t%" << I->first << " = type ";
577 // Make sure we print out at least one level of the type structure, so
578 // that we do not get %FILE = type %FILE
580 printTypeAtLeastOneLevel(Ty) << "\n";
587 // printConstant - Print out a constant pool entry...
589 void AssemblyWriter::printConstant(const Constant *CPV) {
590 // Don't print out unnamed constants, they will be inlined
591 if (!CPV->hasName()) return;
594 Out << "\t%" << CPV->getName() << " =";
596 // Write the value out now...
597 writeOperand(CPV, true, false);
599 printInfoComment(*CPV);
603 // printFunction - Print all aspects of a function.
605 void AssemblyWriter::printFunction(const Function *F) {
606 // Print out the return type and name...
612 switch (F->getLinkage()) {
613 case GlobalValue::InternalLinkage: Out << "internal "; break;
614 case GlobalValue::LinkOnceLinkage: Out << "linkonce "; break;
615 case GlobalValue::AppendingLinkage: Out << "appending "; break;
616 case GlobalValue::ExternalLinkage: break;
619 printType(F->getReturnType()) << " %" << F->getName() << "(";
620 Table.incorporateFunction(F);
622 // Loop over the arguments, printing them...
623 const FunctionType *FT = F->getFunctionType();
625 for(Function::const_aiterator I = F->abegin(), E = F->aend(); I != E; ++I)
628 // Finish printing arguments...
629 if (FT->isVarArg()) {
630 if (FT->getParamTypes().size()) Out << ", ";
631 Out << "..."; // Output varargs portion of signature!
635 if (F->isExternal()) {
640 // Output all of its basic blocks... for the function
641 for (Function::const_iterator I = F->begin(), E = F->end(); I != E; ++I)
647 Table.purgeFunction();
650 // printArgument - This member is called for every argument that
651 // is passed into the function. Simply print it out
653 void AssemblyWriter::printArgument(const Argument *Arg) {
654 // Insert commas as we go... the first arg doesn't get a comma
655 if (Arg != &Arg->getParent()->afront()) Out << ", ";
658 printType(Arg->getType());
660 // Output name, if available...
662 Out << " %" << Arg->getName();
663 else if (Table.getValSlot(Arg) < 0)
667 // printBasicBlock - This member is called for each basic block in a methd.
669 void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {
670 if (BB->hasName()) { // Print out the label if it exists...
671 Out << "\n" << BB->getName() << ":";
672 } else if (!BB->use_empty()) { // Don't print block # of no uses...
673 int Slot = Table.getValSlot(BB);
674 Out << "\n; <label>:";
676 Out << Slot; // Extra newline seperates out label's
681 // Output predecessors for the block...
683 pred_const_iterator PI = pred_begin(BB), PE = pred_end(BB);
686 Out << " No predecessors!";
689 writeOperand(*PI, false, true);
690 for (++PI; PI != PE; ++PI) {
692 writeOperand(*PI, false, true);
698 // Output all of the instructions in the basic block...
699 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
700 printInstruction(*I);
704 // printInfoComment - Print a little comment after the instruction indicating
705 // which slot it occupies.
707 void AssemblyWriter::printInfoComment(const Value &V) {
708 if (V.getType() != Type::VoidTy) {
710 printType(V.getType()) << ">";
713 int Slot = Table.getValSlot(&V); // Print out the def slot taken...
714 if (Slot >= 0) Out << ":" << Slot;
715 else Out << ":<badref>";
717 Out << " [#uses=" << V.use_size() << "]"; // Output # uses
721 // printInstruction - This member is called for each Instruction in a methd.
723 void AssemblyWriter::printInstruction(const Instruction &I) {
726 // Print out name if it exists...
728 Out << "%" << I.getName() << " = ";
730 // Print out the opcode...
731 Out << I.getOpcodeName();
733 // Print out the type of the operands...
734 const Value *Operand = I.getNumOperands() ? I.getOperand(0) : 0;
736 // Special case conditional branches to swizzle the condition out to the front
737 if (isa<BranchInst>(I) && I.getNumOperands() > 1) {
738 writeOperand(I.getOperand(2), true);
740 writeOperand(Operand, true);
742 writeOperand(I.getOperand(1), true);
744 } else if (isa<SwitchInst>(I)) {
745 // Special case switch statement to get formatting nice and correct...
746 writeOperand(Operand , true); Out << ",";
747 writeOperand(I.getOperand(1), true); Out << " [";
749 for (unsigned op = 2, Eop = I.getNumOperands(); op < Eop; op += 2) {
751 writeOperand(I.getOperand(op ), true); Out << ",";
752 writeOperand(I.getOperand(op+1), true);
755 } else if (isa<PHINode>(I)) {
757 printType(I.getType());
760 for (unsigned op = 0, Eop = I.getNumOperands(); op < Eop; op += 2) {
763 writeOperand(I.getOperand(op ), false); Out << ",";
764 writeOperand(I.getOperand(op+1), false); Out << " ]";
766 } else if (isa<ReturnInst>(I) && !Operand) {
768 } else if (isa<CallInst>(I)) {
769 const PointerType *PTy = dyn_cast<PointerType>(Operand->getType());
770 const FunctionType*MTy = PTy ? dyn_cast<FunctionType>(PTy->getElementType()):0;
771 const Type *RetTy = MTy ? MTy->getReturnType() : 0;
773 // If possible, print out the short form of the call instruction, but we can
774 // only do this if the first argument is a pointer to a nonvararg function,
775 // and if the value returned is not a pointer to a function.
777 if (RetTy && MTy && !MTy->isVarArg() &&
778 (!isa<PointerType>(RetTy) ||
779 !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
780 Out << " "; printType(RetTy);
781 writeOperand(Operand, false);
783 writeOperand(Operand, true);
786 if (I.getNumOperands() > 1) writeOperand(I.getOperand(1), true);
787 for (unsigned op = 2, Eop = I.getNumOperands(); op < Eop; ++op) {
789 writeOperand(I.getOperand(op), true);
793 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
794 // TODO: Should try to print out short form of the Invoke instruction
795 writeOperand(Operand, true);
797 if (I.getNumOperands() > 3) writeOperand(I.getOperand(3), true);
798 for (unsigned op = 4, Eop = I.getNumOperands(); op < Eop; ++op) {
800 writeOperand(I.getOperand(op), true);
803 Out << " )\n\t\t\tto";
804 writeOperand(II->getNormalDest(), true);
806 writeOperand(II->getExceptionalDest(), true);
808 } else if (const AllocationInst *AI = dyn_cast<AllocationInst>(&I)) {
810 printType(AI->getType()->getElementType());
811 if (AI->isArrayAllocation()) {
813 writeOperand(AI->getArraySize(), true);
815 } else if (isa<CastInst>(I)) {
816 writeOperand(Operand, true);
818 printType(I.getType());
819 } else if (isa<VarArgInst>(I)) {
820 writeOperand(Operand, true);
822 printType(I.getType());
823 } else if (Operand) { // Print the normal way...
825 // PrintAllTypes - Instructions who have operands of all the same type
826 // omit the type from all but the first operand. If the instruction has
827 // different type operands (for example br), then they are all printed.
828 bool PrintAllTypes = false;
829 const Type *TheType = Operand->getType();
831 // Shift Left & Right print both types even for Ubyte LHS
832 if (isa<ShiftInst>(I)) {
833 PrintAllTypes = true;
835 for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) {
836 Operand = I.getOperand(i);
837 if (Operand->getType() != TheType) {
838 PrintAllTypes = true; // We have differing types! Print them all!
844 if (!PrintAllTypes) {
849 for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) {
851 writeOperand(I.getOperand(i), PrintAllTypes);
860 //===----------------------------------------------------------------------===//
861 // External Interface declarations
862 //===----------------------------------------------------------------------===//
865 void Module::print(std::ostream &o) const {
866 SlotCalculator SlotTable(this, true);
867 AssemblyWriter W(o, SlotTable, this);
871 void GlobalVariable::print(std::ostream &o) const {
872 SlotCalculator SlotTable(getParent(), true);
873 AssemblyWriter W(o, SlotTable, getParent());
877 void Function::print(std::ostream &o) const {
878 SlotCalculator SlotTable(getParent(), true);
879 AssemblyWriter W(o, SlotTable, getParent());
884 void BasicBlock::print(std::ostream &o) const {
885 SlotCalculator SlotTable(getParent(), true);
886 AssemblyWriter W(o, SlotTable,
887 getParent() ? getParent()->getParent() : 0);
891 void Instruction::print(std::ostream &o) const {
892 const Function *F = getParent() ? getParent()->getParent() : 0;
893 SlotCalculator SlotTable(F, true);
894 AssemblyWriter W(o, SlotTable, F ? F->getParent() : 0);
899 void Constant::print(std::ostream &o) const {
900 if (this == 0) { o << "<null> constant value\n"; return; }
902 // Handle CPR's special, because they have context information...
903 if (const ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(this)) {
904 CPR->getValue()->print(o); // Print as a global value, with context info.
908 o << " " << getType()->getDescription() << " ";
910 std::map<const Type *, std::string> TypeTable;
911 WriteConstantInt(o, this, false, TypeTable, 0);
914 void Type::print(std::ostream &o) const {
918 o << getDescription();
921 void Argument::print(std::ostream &o) const {
922 o << getType() << " " << getName();
925 void Value::dump() const { print(std::cerr); }
927 //===----------------------------------------------------------------------===//
928 // CachedWriter Class Implementation
929 //===----------------------------------------------------------------------===//
931 void CachedWriter::setModule(const Module *M) {
932 delete SC; delete AW;
934 SC = new SlotCalculator(M, true);
935 AW = new AssemblyWriter(Out, *SC, M);
941 CachedWriter::~CachedWriter() {
946 CachedWriter &CachedWriter::operator<<(const Value *V) {
947 assert(AW && SC && "CachedWriter does not have a current module!");
948 switch (V->getValueType()) {
949 case Value::ConstantVal:
950 case Value::ArgumentVal: AW->writeOperand(V, true, true); break;
951 case Value::TypeVal: AW->write(cast<const Type>(V)); break;
952 case Value::InstructionVal: AW->write(cast<Instruction>(V)); break;
953 case Value::BasicBlockVal: AW->write(cast<BasicBlock>(V)); break;
954 case Value::FunctionVal: AW->write(cast<Function>(V)); break;
955 case Value::GlobalVariableVal: AW->write(cast<GlobalVariable>(V)); break;
956 default: Out << "<unknown value type: " << V->getValueType() << ">"; break;