1 //===-- AsmWriter.cpp - Printing LLVM as an assembly file -----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This library implements the functionality defined in llvm/Assembly/Writer.h
12 // Note that these routines must be extremely tolerant of various errors in the
13 // LLVM code, because it can be used for debugging transformations.
15 //===----------------------------------------------------------------------===//
17 #include "llvm/Assembly/CachedWriter.h"
18 #include "llvm/Assembly/Writer.h"
19 #include "llvm/Assembly/PrintModulePass.h"
20 #include "llvm/SlotCalculator.h"
21 #include "llvm/DerivedTypes.h"
22 #include "llvm/Instruction.h"
23 #include "llvm/Module.h"
24 #include "llvm/Constants.h"
25 #include "llvm/iMemory.h"
26 #include "llvm/iTerminators.h"
27 #include "llvm/iPHINode.h"
28 #include "llvm/iOther.h"
29 #include "llvm/SymbolTable.h"
30 #include "llvm/Support/CFG.h"
31 #include "Support/StringExtras.h"
32 #include "Support/STLExtras.h"
35 static RegisterPass<PrintModulePass>
36 X("printm", "Print module to stderr",PassInfo::Analysis|PassInfo::Optimization);
37 static RegisterPass<PrintFunctionPass>
38 Y("print","Print function to stderr",PassInfo::Analysis|PassInfo::Optimization);
40 static void WriteAsOperandInternal(std::ostream &Out, const Value *V,
42 std::map<const Type *, std::string> &TypeTable,
43 SlotCalculator *Table);
45 static const Module *getModuleFromVal(const Value *V) {
46 if (const Argument *MA = dyn_cast<Argument>(V))
47 return MA->getParent() ? MA->getParent()->getParent() : 0;
48 else if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
49 return BB->getParent() ? BB->getParent()->getParent() : 0;
50 else if (const Instruction *I = dyn_cast<Instruction>(V)) {
51 const Function *M = I->getParent() ? I->getParent()->getParent() : 0;
52 return M ? M->getParent() : 0;
53 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
54 return GV->getParent();
58 static SlotCalculator *createSlotCalculator(const Value *V) {
59 assert(!isa<Type>(V) && "Can't create an SC for a type!");
60 if (const Argument *FA = dyn_cast<Argument>(V)) {
61 return new SlotCalculator(FA->getParent(), true);
62 } else if (const Instruction *I = dyn_cast<Instruction>(V)) {
63 return new SlotCalculator(I->getParent()->getParent(), true);
64 } else if (const BasicBlock *BB = dyn_cast<BasicBlock>(V)) {
65 return new SlotCalculator(BB->getParent(), true);
66 } else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V)){
67 return new SlotCalculator(GV->getParent(), true);
68 } else if (const Function *Func = dyn_cast<Function>(V)) {
69 return new SlotCalculator(Func, true);
74 // getLLVMName - Turn the specified string into an 'LLVM name', which is either
75 // prefixed with % (if the string only contains simple characters) or is
76 // surrounded with ""'s (if it has special chars in it).
77 static std::string getLLVMName(const std::string &Name) {
78 assert(!Name.empty() && "Cannot get empty name!");
80 // First character cannot start with a number...
81 if (Name[0] >= '0' && Name[0] <= '9')
82 return "\"" + Name + "\"";
84 // Scan to see if we have any characters that are not on the "white list"
85 for (unsigned i = 0, e = Name.size(); i != e; ++i) {
87 assert(C != '"' && "Illegal character in LLVM value name!");
88 if ((C < 'a' || C > 'z') && (C < 'A' || C > 'Z') && (C < '0' || C > '9') &&
89 C != '-' && C != '.' && C != '_')
90 return "\"" + Name + "\"";
93 // If we get here, then the identifier is legal to use as a "VarID".
98 // If the module has a symbol table, take all global types and stuff their
99 // names into the TypeNames map.
101 static void fillTypeNameTable(const Module *M,
102 std::map<const Type *, std::string> &TypeNames) {
104 const SymbolTable &ST = M->getSymbolTable();
105 SymbolTable::const_iterator PI = ST.find(Type::TypeTy);
106 if (PI != ST.end()) {
107 SymbolTable::type_const_iterator I = PI->second.begin();
108 for (; I != PI->second.end(); ++I) {
109 // As a heuristic, don't insert pointer to primitive types, because
110 // they are used too often to have a single useful name.
112 const Type *Ty = cast<Type>(I->second);
113 if (!isa<PointerType>(Ty) ||
114 !cast<PointerType>(Ty)->getElementType()->isPrimitiveType() ||
115 isa<OpaqueType>(cast<PointerType>(Ty)->getElementType()))
116 TypeNames.insert(std::make_pair(Ty, getLLVMName(I->first)));
123 static std::string calcTypeName(const Type *Ty,
124 std::vector<const Type *> &TypeStack,
125 std::map<const Type *, std::string> &TypeNames){
126 if (Ty->isPrimitiveType() && !isa<OpaqueType>(Ty))
127 return Ty->getDescription(); // Base case
129 // Check to see if the type is named.
130 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
131 if (I != TypeNames.end()) return I->second;
133 if (isa<OpaqueType>(Ty))
136 // Check to see if the Type is already on the stack...
137 unsigned Slot = 0, CurSize = TypeStack.size();
138 while (Slot < CurSize && TypeStack[Slot] != Ty) ++Slot; // Scan for type
140 // This is another base case for the recursion. In this case, we know
141 // that we have looped back to a type that we have previously visited.
142 // Generate the appropriate upreference to handle this.
145 return "\\" + utostr(CurSize-Slot); // Here's the upreference
147 TypeStack.push_back(Ty); // Recursive case: Add us to the stack..
150 switch (Ty->getPrimitiveID()) {
151 case Type::FunctionTyID: {
152 const FunctionType *FTy = cast<FunctionType>(Ty);
153 Result = calcTypeName(FTy->getReturnType(), TypeStack, TypeNames) + " (";
154 for (FunctionType::ParamTypes::const_iterator
155 I = FTy->getParamTypes().begin(),
156 E = FTy->getParamTypes().end(); I != E; ++I) {
157 if (I != FTy->getParamTypes().begin())
159 Result += calcTypeName(*I, TypeStack, TypeNames);
161 if (FTy->isVarArg()) {
162 if (!FTy->getParamTypes().empty()) Result += ", ";
168 case Type::StructTyID: {
169 const StructType *STy = cast<StructType>(Ty);
171 for (StructType::ElementTypes::const_iterator
172 I = STy->getElementTypes().begin(),
173 E = STy->getElementTypes().end(); I != E; ++I) {
174 if (I != STy->getElementTypes().begin())
176 Result += calcTypeName(*I, TypeStack, TypeNames);
181 case Type::PointerTyID:
182 Result = calcTypeName(cast<PointerType>(Ty)->getElementType(),
183 TypeStack, TypeNames) + "*";
185 case Type::ArrayTyID: {
186 const ArrayType *ATy = cast<ArrayType>(Ty);
187 Result = "[" + utostr(ATy->getNumElements()) + " x ";
188 Result += calcTypeName(ATy->getElementType(), TypeStack, TypeNames) + "]";
191 case Type::OpaqueTyID:
195 Result = "<unrecognized-type>";
198 TypeStack.pop_back(); // Remove self from stack...
203 // printTypeInt - The internal guts of printing out a type that has a
204 // potentially named portion.
206 static std::ostream &printTypeInt(std::ostream &Out, const Type *Ty,
207 std::map<const Type *, std::string> &TypeNames) {
208 // Primitive types always print out their description, regardless of whether
209 // they have been named or not.
211 if (Ty->isPrimitiveType() && !isa<OpaqueType>(Ty))
212 return Out << Ty->getDescription();
214 // Check to see if the type is named.
215 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
216 if (I != TypeNames.end()) return Out << I->second;
218 // Otherwise we have a type that has not been named but is a derived type.
219 // Carefully recurse the type hierarchy to print out any contained symbolic
222 std::vector<const Type *> TypeStack;
223 std::string TypeName = calcTypeName(Ty, TypeStack, TypeNames);
224 TypeNames.insert(std::make_pair(Ty, TypeName));//Cache type name for later use
225 return Out << TypeName;
229 // WriteTypeSymbolic - This attempts to write the specified type as a symbolic
230 // type, iff there is an entry in the modules symbol table for the specified
231 // type or one of it's component types. This is slower than a simple x << Type;
233 std::ostream &WriteTypeSymbolic(std::ostream &Out, const Type *Ty,
237 // If they want us to print out a type, attempt to make it symbolic if there
238 // is a symbol table in the module...
240 std::map<const Type *, std::string> TypeNames;
241 fillTypeNameTable(M, TypeNames);
243 return printTypeInt(Out, Ty, TypeNames);
245 return Out << Ty->getDescription();
249 static void WriteConstantInt(std::ostream &Out, const Constant *CV,
251 std::map<const Type *, std::string> &TypeTable,
252 SlotCalculator *Table) {
253 if (const ConstantBool *CB = dyn_cast<ConstantBool>(CV)) {
254 Out << (CB == ConstantBool::True ? "true" : "false");
255 } else if (const ConstantSInt *CI = dyn_cast<ConstantSInt>(CV)) {
256 Out << CI->getValue();
257 } else if (const ConstantUInt *CI = dyn_cast<ConstantUInt>(CV)) {
258 Out << CI->getValue();
259 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
260 // We would like to output the FP constant value in exponential notation,
261 // but we cannot do this if doing so will lose precision. Check here to
262 // make sure that we only output it in exponential format if we can parse
263 // the value back and get the same value.
265 std::string StrVal = ftostr(CFP->getValue());
267 // Check to make sure that the stringized number is not some string like
268 // "Inf" or NaN, that atof will accept, but the lexer will not. Check that
269 // the string matches the "[-+]?[0-9]" regex.
271 if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
272 ((StrVal[0] == '-' || StrVal[0] == '+') &&
273 (StrVal[1] >= '0' && StrVal[1] <= '9')))
274 // Reparse stringized version!
275 if (atof(StrVal.c_str()) == CFP->getValue()) {
276 Out << StrVal; return;
279 // Otherwise we could not reparse it to exactly the same value, so we must
280 // output the string in hexadecimal format!
282 // Behave nicely in the face of C TBAA rules... see:
283 // http://www.nullstone.com/htmls/category/aliastyp.htm
285 double Val = CFP->getValue();
286 char *Ptr = (char*)&Val;
287 assert(sizeof(double) == sizeof(uint64_t) && sizeof(double) == 8 &&
288 "assuming that double is 64 bits!");
289 Out << "0x" << utohexstr(*(uint64_t*)Ptr);
291 } else if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
292 if (CA->getNumOperands() > 5 && CA->isNullValue()) {
293 Out << "zeroinitializer";
297 // As a special case, print the array as a string if it is an array of
298 // ubytes or an array of sbytes with positive values.
300 const Type *ETy = CA->getType()->getElementType();
301 bool isString = (ETy == Type::SByteTy || ETy == Type::UByteTy);
303 if (ETy == Type::SByteTy)
304 for (unsigned i = 0; i < CA->getNumOperands(); ++i)
305 if (cast<ConstantSInt>(CA->getOperand(i))->getValue() < 0) {
312 for (unsigned i = 0; i < CA->getNumOperands(); ++i) {
313 unsigned char C = cast<ConstantInt>(CA->getOperand(i))->getRawValue();
315 if (isprint(C) && C != '"' && C != '\\') {
319 << (char) ((C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A'))
320 << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
325 } else { // Cannot output in string format...
327 if (CA->getNumOperands()) {
329 printTypeInt(Out, ETy, TypeTable);
330 WriteAsOperandInternal(Out, CA->getOperand(0),
331 PrintName, TypeTable, Table);
332 for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
334 printTypeInt(Out, ETy, TypeTable);
335 WriteAsOperandInternal(Out, CA->getOperand(i), PrintName,
341 } else if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
342 if (CS->getNumOperands() > 5 && CS->isNullValue()) {
343 Out << "zeroinitializer";
348 if (CS->getNumOperands()) {
350 printTypeInt(Out, CS->getOperand(0)->getType(), TypeTable);
352 WriteAsOperandInternal(Out, CS->getOperand(0),
353 PrintName, TypeTable, Table);
355 for (unsigned i = 1; i < CS->getNumOperands(); i++) {
357 printTypeInt(Out, CS->getOperand(i)->getType(), TypeTable);
359 WriteAsOperandInternal(Out, CS->getOperand(i),
360 PrintName, TypeTable, Table);
365 } else if (isa<ConstantPointerNull>(CV)) {
368 } else if (const ConstantPointerRef *PR = dyn_cast<ConstantPointerRef>(CV)) {
369 const GlobalValue *V = PR->getValue();
371 Out << getLLVMName(V->getName());
373 int Slot = Table->getSlot(V);
377 Out << "<pointer reference badref>";
379 Out << "<pointer reference without context info>";
382 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
383 Out << CE->getOpcodeName() << " (";
385 for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) {
386 printTypeInt(Out, (*OI)->getType(), TypeTable);
387 WriteAsOperandInternal(Out, *OI, PrintName, TypeTable, Table);
388 if (OI+1 != CE->op_end())
392 if (CE->getOpcode() == Instruction::Cast) {
394 printTypeInt(Out, CE->getType(), TypeTable);
399 Out << "<placeholder or erroneous Constant>";
404 // WriteAsOperand - Write the name of the specified value out to the specified
405 // ostream. This can be useful when you just want to print int %reg126, not the
406 // whole instruction that generated it.
408 static void WriteAsOperandInternal(std::ostream &Out, const Value *V,
410 std::map<const Type*, std::string> &TypeTable,
411 SlotCalculator *Table) {
413 if (PrintName && V->hasName()) {
414 Out << getLLVMName(V->getName());
416 if (const Constant *CV = dyn_cast<Constant>(V)) {
417 WriteConstantInt(Out, CV, PrintName, TypeTable, Table);
421 Slot = Table->getSlot(V);
423 if (const Type *Ty = dyn_cast<Type>(V)) {
424 Out << Ty->getDescription();
428 Table = createSlotCalculator(V);
429 if (Table == 0) { Out << "BAD VALUE TYPE!"; return; }
431 Slot = Table->getSlot(V);
434 if (Slot >= 0) Out << "%" << Slot;
436 Out << "<badref>"; // Not embedded into a location?
443 // WriteAsOperand - Write the name of the specified value out to the specified
444 // ostream. This can be useful when you just want to print int %reg126, not the
445 // whole instruction that generated it.
447 std::ostream &WriteAsOperand(std::ostream &Out, const Value *V, bool PrintType,
448 bool PrintName, const Module *Context) {
449 std::map<const Type *, std::string> TypeNames;
450 if (Context == 0) Context = getModuleFromVal(V);
453 fillTypeNameTable(Context, TypeNames);
456 printTypeInt(Out, V->getType(), TypeNames);
458 WriteAsOperandInternal(Out, V, PrintName, TypeNames, 0);
464 class AssemblyWriter {
466 SlotCalculator &Table;
467 const Module *TheModule;
468 std::map<const Type *, std::string> TypeNames;
470 inline AssemblyWriter(std::ostream &o, SlotCalculator &Tab, const Module *M)
471 : Out(o), Table(Tab), TheModule(M) {
473 // If the module has a symbol table, take all global types and stuff their
474 // names into the TypeNames map.
476 fillTypeNameTable(M, TypeNames);
479 inline void write(const Module *M) { printModule(M); }
480 inline void write(const GlobalVariable *G) { printGlobal(G); }
481 inline void write(const Function *F) { printFunction(F); }
482 inline void write(const BasicBlock *BB) { printBasicBlock(BB); }
483 inline void write(const Instruction *I) { printInstruction(*I); }
484 inline void write(const Constant *CPV) { printConstant(CPV); }
485 inline void write(const Type *Ty) { printType(Ty); }
487 void writeOperand(const Value *Op, bool PrintType, bool PrintName = true);
490 void printModule(const Module *M);
491 void printSymbolTable(const SymbolTable &ST);
492 void printConstant(const Constant *CPV);
493 void printGlobal(const GlobalVariable *GV);
494 void printFunction(const Function *F);
495 void printArgument(const Argument *FA);
496 void printBasicBlock(const BasicBlock *BB);
497 void printInstruction(const Instruction &I);
499 // printType - Go to extreme measures to attempt to print out a short,
500 // symbolic version of a type name.
502 std::ostream &printType(const Type *Ty) {
503 return printTypeInt(Out, Ty, TypeNames);
506 // printTypeAtLeastOneLevel - Print out one level of the possibly complex type
507 // without considering any symbolic types that we may have equal to it.
509 std::ostream &printTypeAtLeastOneLevel(const Type *Ty);
511 // printInfoComment - Print a little comment after the instruction indicating
512 // which slot it occupies.
513 void printInfoComment(const Value &V);
517 // printTypeAtLeastOneLevel - Print out one level of the possibly complex type
518 // without considering any symbolic types that we may have equal to it.
520 std::ostream &AssemblyWriter::printTypeAtLeastOneLevel(const Type *Ty) {
521 if (const FunctionType *FTy = dyn_cast<FunctionType>(Ty)) {
522 printType(FTy->getReturnType()) << " (";
523 for (FunctionType::ParamTypes::const_iterator
524 I = FTy->getParamTypes().begin(),
525 E = FTy->getParamTypes().end(); I != E; ++I) {
526 if (I != FTy->getParamTypes().begin())
530 if (FTy->isVarArg()) {
531 if (!FTy->getParamTypes().empty()) Out << ", ";
535 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
537 for (StructType::ElementTypes::const_iterator
538 I = STy->getElementTypes().begin(),
539 E = STy->getElementTypes().end(); I != E; ++I) {
540 if (I != STy->getElementTypes().begin())
545 } else if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
546 printType(PTy->getElementType()) << "*";
547 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
548 Out << "[" << ATy->getNumElements() << " x ";
549 printType(ATy->getElementType()) << "]";
550 } else if (const OpaqueType *OTy = dyn_cast<OpaqueType>(Ty)) {
553 if (!Ty->isPrimitiveType())
554 Out << "<unknown derived type>";
561 void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType,
563 if (PrintType) { Out << " "; printType(Operand->getType()); }
564 WriteAsOperandInternal(Out, Operand, PrintName, TypeNames, &Table);
568 void AssemblyWriter::printModule(const Module *M) {
569 switch (M->getEndianness()) {
570 case Module::LittleEndian: Out << "target endian = little\n"; break;
571 case Module::BigEndian: Out << "target endian = big\n"; break;
572 case Module::AnyEndianness: break;
574 switch (M->getPointerSize()) {
575 case Module::Pointer32: Out << "target pointersize = 32\n"; break;
576 case Module::Pointer64: Out << "target pointersize = 64\n"; break;
577 case Module::AnyPointerSize: break;
580 // Loop over the symbol table, emitting all named constants...
581 printSymbolTable(M->getSymbolTable());
583 for (Module::const_giterator I = M->gbegin(), E = M->gend(); I != E; ++I)
586 Out << "\nimplementation ; Functions:\n";
588 // Output all of the functions...
589 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
593 void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
594 if (GV->hasName()) Out << getLLVMName(GV->getName()) << " = ";
596 if (!GV->hasInitializer())
599 switch (GV->getLinkage()) {
600 case GlobalValue::InternalLinkage: Out << "internal "; break;
601 case GlobalValue::LinkOnceLinkage: Out << "linkonce "; break;
602 case GlobalValue::WeakLinkage: Out << "weak "; break;
603 case GlobalValue::AppendingLinkage: Out << "appending "; break;
604 case GlobalValue::ExternalLinkage: break;
607 Out << (GV->isConstant() ? "constant " : "global ");
608 printType(GV->getType()->getElementType());
610 if (GV->hasInitializer())
611 writeOperand(GV->getInitializer(), false, false);
613 printInfoComment(*GV);
618 // printSymbolTable - Run through symbol table looking for named constants
619 // if a named constant is found, emit it's declaration...
621 void AssemblyWriter::printSymbolTable(const SymbolTable &ST) {
622 for (SymbolTable::const_iterator TI = ST.begin(); TI != ST.end(); ++TI) {
623 SymbolTable::type_const_iterator I = ST.type_begin(TI->first);
624 SymbolTable::type_const_iterator End = ST.type_end(TI->first);
626 for (; I != End; ++I) {
627 const Value *V = I->second;
628 if (const Constant *CPV = dyn_cast<Constant>(V)) {
630 } else if (const Type *Ty = dyn_cast<Type>(V)) {
631 Out << "\t" << getLLVMName(I->first) << " = type ";
633 // Make sure we print out at least one level of the type structure, so
634 // that we do not get %FILE = type %FILE
636 printTypeAtLeastOneLevel(Ty) << "\n";
643 // printConstant - Print out a constant pool entry...
645 void AssemblyWriter::printConstant(const Constant *CPV) {
646 // Don't print out unnamed constants, they will be inlined
647 if (!CPV->hasName()) return;
650 Out << "\t" << getLLVMName(CPV->getName()) << " =";
652 // Write the value out now...
653 writeOperand(CPV, true, false);
655 printInfoComment(*CPV);
659 // printFunction - Print all aspects of a function.
661 void AssemblyWriter::printFunction(const Function *F) {
662 // Print out the return type and name...
668 switch (F->getLinkage()) {
669 case GlobalValue::InternalLinkage: Out << "internal "; break;
670 case GlobalValue::LinkOnceLinkage: Out << "linkonce "; break;
671 case GlobalValue::WeakLinkage: Out << "weak "; break;
672 case GlobalValue::AppendingLinkage: Out << "appending "; break;
673 case GlobalValue::ExternalLinkage: break;
676 printType(F->getReturnType()) << " ";
677 if (!F->getName().empty())
678 Out << getLLVMName(F->getName());
682 Table.incorporateFunction(F);
684 // Loop over the arguments, printing them...
685 const FunctionType *FT = F->getFunctionType();
687 for(Function::const_aiterator I = F->abegin(), E = F->aend(); I != E; ++I)
690 // Finish printing arguments...
691 if (FT->isVarArg()) {
692 if (FT->getParamTypes().size()) Out << ", ";
693 Out << "..."; // Output varargs portion of signature!
697 if (F->isExternal()) {
702 // Output all of its basic blocks... for the function
703 for (Function::const_iterator I = F->begin(), E = F->end(); I != E; ++I)
709 Table.purgeFunction();
712 // printArgument - This member is called for every argument that
713 // is passed into the function. Simply print it out
715 void AssemblyWriter::printArgument(const Argument *Arg) {
716 // Insert commas as we go... the first arg doesn't get a comma
717 if (Arg != &Arg->getParent()->afront()) Out << ", ";
720 printType(Arg->getType());
722 // Output name, if available...
724 Out << " " << getLLVMName(Arg->getName());
725 else if (Table.getSlot(Arg) < 0)
729 // printBasicBlock - This member is called for each basic block in a method.
731 void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {
732 if (BB->hasName()) { // Print out the label if it exists...
733 Out << "\n" << BB->getName() << ":";
734 } else if (!BB->use_empty()) { // Don't print block # of no uses...
735 int Slot = Table.getSlot(BB);
736 Out << "\n; <label>:";
738 Out << Slot; // Extra newline separates out label's
743 // Output predecessors for the block...
745 pred_const_iterator PI = pred_begin(BB), PE = pred_end(BB);
748 Out << " No predecessors!";
751 writeOperand(*PI, false, true);
752 for (++PI; PI != PE; ++PI) {
754 writeOperand(*PI, false, true);
760 // Output all of the instructions in the basic block...
761 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
762 printInstruction(*I);
766 // printInfoComment - Print a little comment after the instruction indicating
767 // which slot it occupies.
769 void AssemblyWriter::printInfoComment(const Value &V) {
770 if (V.getType() != Type::VoidTy) {
772 printType(V.getType()) << ">";
775 int Slot = Table.getSlot(&V); // Print out the def slot taken...
776 if (Slot >= 0) Out << ":" << Slot;
777 else Out << ":<badref>";
779 Out << " [#uses=" << V.use_size() << "]"; // Output # uses
783 // printInstruction - This member is called for each Instruction in a method.
785 void AssemblyWriter::printInstruction(const Instruction &I) {
788 // Print out name if it exists...
790 Out << getLLVMName(I.getName()) << " = ";
792 // If this is a volatile load or store, print out the volatile marker
793 if ((isa<LoadInst>(I) && cast<LoadInst>(I).isVolatile()) ||
794 (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile()))
797 // Print out the opcode...
798 Out << I.getOpcodeName();
800 // Print out the type of the operands...
801 const Value *Operand = I.getNumOperands() ? I.getOperand(0) : 0;
803 // Special case conditional branches to swizzle the condition out to the front
804 if (isa<BranchInst>(I) && I.getNumOperands() > 1) {
805 writeOperand(I.getOperand(2), true);
807 writeOperand(Operand, true);
809 writeOperand(I.getOperand(1), true);
811 } else if (isa<SwitchInst>(I)) {
812 // Special case switch statement to get formatting nice and correct...
813 writeOperand(Operand , true); Out << ",";
814 writeOperand(I.getOperand(1), true); Out << " [";
816 for (unsigned op = 2, Eop = I.getNumOperands(); op < Eop; op += 2) {
818 writeOperand(I.getOperand(op ), true); Out << ",";
819 writeOperand(I.getOperand(op+1), true);
822 } else if (isa<PHINode>(I)) {
824 printType(I.getType());
827 for (unsigned op = 0, Eop = I.getNumOperands(); op < Eop; op += 2) {
830 writeOperand(I.getOperand(op ), false); Out << ",";
831 writeOperand(I.getOperand(op+1), false); Out << " ]";
833 } else if (isa<ReturnInst>(I) && !Operand) {
835 } else if (isa<CallInst>(I)) {
836 const PointerType *PTy = cast<PointerType>(Operand->getType());
837 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
838 const Type *RetTy = FTy->getReturnType();
840 // If possible, print out the short form of the call instruction. We can
841 // only do this if the first argument is a pointer to a nonvararg function,
842 // and if the return type is not a pointer to a function.
844 if (!FTy->isVarArg() &&
845 (!isa<PointerType>(RetTy) ||
846 !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
847 Out << " "; printType(RetTy);
848 writeOperand(Operand, false);
850 writeOperand(Operand, true);
853 if (I.getNumOperands() > 1) writeOperand(I.getOperand(1), true);
854 for (unsigned op = 2, Eop = I.getNumOperands(); op < Eop; ++op) {
856 writeOperand(I.getOperand(op), true);
860 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
861 const PointerType *PTy = cast<PointerType>(Operand->getType());
862 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
863 const Type *RetTy = FTy->getReturnType();
865 // If possible, print out the short form of the invoke instruction. We can
866 // only do this if the first argument is a pointer to a nonvararg function,
867 // and if the return type is not a pointer to a function.
869 if (!FTy->isVarArg() &&
870 (!isa<PointerType>(RetTy) ||
871 !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
872 Out << " "; printType(RetTy);
873 writeOperand(Operand, false);
875 writeOperand(Operand, true);
879 if (I.getNumOperands() > 3) writeOperand(I.getOperand(3), true);
880 for (unsigned op = 4, Eop = I.getNumOperands(); op < Eop; ++op) {
882 writeOperand(I.getOperand(op), true);
885 Out << " )\n\t\t\tto";
886 writeOperand(II->getNormalDest(), true);
888 writeOperand(II->getExceptionalDest(), true);
890 } else if (const AllocationInst *AI = dyn_cast<AllocationInst>(&I)) {
892 printType(AI->getType()->getElementType());
893 if (AI->isArrayAllocation()) {
895 writeOperand(AI->getArraySize(), true);
897 } else if (isa<CastInst>(I)) {
898 writeOperand(Operand, true);
900 printType(I.getType());
901 } else if (isa<VAArgInst>(I)) {
902 writeOperand(Operand, true);
904 printType(I.getType());
905 } else if (const VANextInst *VAN = dyn_cast<VANextInst>(&I)) {
906 writeOperand(Operand, true);
908 printType(VAN->getArgType());
909 } else if (Operand) { // Print the normal way...
911 // PrintAllTypes - Instructions who have operands of all the same type
912 // omit the type from all but the first operand. If the instruction has
913 // different type operands (for example br), then they are all printed.
914 bool PrintAllTypes = false;
915 const Type *TheType = Operand->getType();
917 // Shift Left & Right print both types even for Ubyte LHS
918 if (isa<ShiftInst>(I)) {
919 PrintAllTypes = true;
921 for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) {
922 Operand = I.getOperand(i);
923 if (Operand->getType() != TheType) {
924 PrintAllTypes = true; // We have differing types! Print them all!
930 if (!PrintAllTypes) {
935 for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) {
937 writeOperand(I.getOperand(i), PrintAllTypes);
946 //===----------------------------------------------------------------------===//
947 // External Interface declarations
948 //===----------------------------------------------------------------------===//
951 void Module::print(std::ostream &o) const {
952 SlotCalculator SlotTable(this, true);
953 AssemblyWriter W(o, SlotTable, this);
957 void GlobalVariable::print(std::ostream &o) const {
958 SlotCalculator SlotTable(getParent(), true);
959 AssemblyWriter W(o, SlotTable, getParent());
963 void Function::print(std::ostream &o) const {
964 SlotCalculator SlotTable(getParent(), true);
965 AssemblyWriter W(o, SlotTable, getParent());
970 void BasicBlock::print(std::ostream &o) const {
971 SlotCalculator SlotTable(getParent(), true);
972 AssemblyWriter W(o, SlotTable,
973 getParent() ? getParent()->getParent() : 0);
977 void Instruction::print(std::ostream &o) const {
978 const Function *F = getParent() ? getParent()->getParent() : 0;
979 SlotCalculator SlotTable(F, true);
980 AssemblyWriter W(o, SlotTable, F ? F->getParent() : 0);
985 void Constant::print(std::ostream &o) const {
986 if (this == 0) { o << "<null> constant value\n"; return; }
988 // Handle CPR's special, because they have context information...
989 if (const ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(this)) {
990 CPR->getValue()->print(o); // Print as a global value, with context info.
994 o << " " << getType()->getDescription() << " ";
996 std::map<const Type *, std::string> TypeTable;
997 WriteConstantInt(o, this, false, TypeTable, 0);
1000 void Type::print(std::ostream &o) const {
1004 o << getDescription();
1007 void Argument::print(std::ostream &o) const {
1008 o << getType() << " " << getName();
1011 void Value::dump() const { print(std::cerr); }
1013 //===----------------------------------------------------------------------===//
1014 // CachedWriter Class Implementation
1015 //===----------------------------------------------------------------------===//
1017 void CachedWriter::setModule(const Module *M) {
1018 delete SC; delete AW;
1020 SC = new SlotCalculator(M, true);
1021 AW = new AssemblyWriter(Out, *SC, M);
1027 CachedWriter::~CachedWriter() {
1032 CachedWriter &CachedWriter::operator<<(const Value *V) {
1033 assert(AW && SC && "CachedWriter does not have a current module!");
1034 switch (V->getValueType()) {
1035 case Value::ConstantVal:
1036 case Value::ArgumentVal: AW->writeOperand(V, true, true); break;
1037 case Value::TypeVal: AW->write(cast<Type>(V)); break;
1038 case Value::InstructionVal: AW->write(cast<Instruction>(V)); break;
1039 case Value::BasicBlockVal: AW->write(cast<BasicBlock>(V)); break;
1040 case Value::FunctionVal: AW->write(cast<Function>(V)); break;
1041 case Value::GlobalVariableVal: AW->write(cast<GlobalVariable>(V)); break;
1042 default: Out << "<unknown value type: " << V->getValueType() << ">"; break;