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/Assembly/AsmAnnotationWriter.h"
21 #include "llvm/SlotCalculator.h"
22 #include "llvm/DerivedTypes.h"
23 #include "llvm/Instruction.h"
24 #include "llvm/Module.h"
25 #include "llvm/Constants.h"
26 #include "llvm/iMemory.h"
27 #include "llvm/iTerminators.h"
28 #include "llvm/iPHINode.h"
29 #include "llvm/iOther.h"
30 #include "llvm/SymbolTable.h"
31 #include "llvm/Support/CFG.h"
32 #include "Support/StringExtras.h"
33 #include "Support/STLExtras.h"
36 static RegisterPass<PrintModulePass>
37 X("printm", "Print module to stderr",PassInfo::Analysis|PassInfo::Optimization);
38 static RegisterPass<PrintFunctionPass>
39 Y("print","Print function to stderr",PassInfo::Analysis|PassInfo::Optimization);
41 static void WriteAsOperandInternal(std::ostream &Out, const Value *V,
43 std::map<const Type *, std::string> &TypeTable,
44 SlotCalculator *Table);
46 static const Module *getModuleFromVal(const Value *V) {
47 if (const Argument *MA = dyn_cast<Argument>(V))
48 return MA->getParent() ? MA->getParent()->getParent() : 0;
49 else if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
50 return BB->getParent() ? BB->getParent()->getParent() : 0;
51 else if (const Instruction *I = dyn_cast<Instruction>(V)) {
52 const Function *M = I->getParent() ? I->getParent()->getParent() : 0;
53 return M ? M->getParent() : 0;
54 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
55 return GV->getParent();
59 static SlotCalculator *createSlotCalculator(const Value *V) {
60 assert(!isa<Type>(V) && "Can't create an SC for a type!");
61 if (const Argument *FA = dyn_cast<Argument>(V)) {
62 return new SlotCalculator(FA->getParent(), true);
63 } else if (const Instruction *I = dyn_cast<Instruction>(V)) {
64 return new SlotCalculator(I->getParent()->getParent(), true);
65 } else if (const BasicBlock *BB = dyn_cast<BasicBlock>(V)) {
66 return new SlotCalculator(BB->getParent(), true);
67 } else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V)){
68 return new SlotCalculator(GV->getParent(), true);
69 } else if (const Function *Func = dyn_cast<Function>(V)) {
70 return new SlotCalculator(Func, true);
75 // getLLVMName - Turn the specified string into an 'LLVM name', which is either
76 // prefixed with % (if the string only contains simple characters) or is
77 // surrounded with ""'s (if it has special chars in it).
78 static std::string getLLVMName(const std::string &Name) {
79 assert(!Name.empty() && "Cannot get empty name!");
81 // First character cannot start with a number...
82 if (Name[0] >= '0' && Name[0] <= '9')
83 return "\"" + Name + "\"";
85 // Scan to see if we have any characters that are not on the "white list"
86 for (unsigned i = 0, e = Name.size(); i != e; ++i) {
88 assert(C != '"' && "Illegal character in LLVM value name!");
89 if ((C < 'a' || C > 'z') && (C < 'A' || C > 'Z') && (C < '0' || C > '9') &&
90 C != '-' && C != '.' && C != '_')
91 return "\"" + Name + "\"";
94 // If we get here, then the identifier is legal to use as a "VarID".
99 // If the module has a symbol table, take all global types and stuff their
100 // names into the TypeNames map.
102 static void fillTypeNameTable(const Module *M,
103 std::map<const Type *, std::string> &TypeNames) {
105 const SymbolTable &ST = M->getSymbolTable();
106 SymbolTable::const_iterator PI = ST.find(Type::TypeTy);
107 if (PI != ST.end()) {
108 SymbolTable::type_const_iterator I = PI->second.begin();
109 for (; I != PI->second.end(); ++I) {
110 // As a heuristic, don't insert pointer to primitive types, because
111 // they are used too often to have a single useful name.
113 const Type *Ty = cast<Type>(I->second);
114 if (!isa<PointerType>(Ty) ||
115 !cast<PointerType>(Ty)->getElementType()->isPrimitiveType() ||
116 isa<OpaqueType>(cast<PointerType>(Ty)->getElementType()))
117 TypeNames.insert(std::make_pair(Ty, getLLVMName(I->first)));
124 static std::string calcTypeName(const Type *Ty,
125 std::vector<const Type *> &TypeStack,
126 std::map<const Type *, std::string> &TypeNames){
127 if (Ty->isPrimitiveType() && !isa<OpaqueType>(Ty))
128 return Ty->getDescription(); // Base case
130 // Check to see if the type is named.
131 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
132 if (I != TypeNames.end()) return I->second;
134 if (isa<OpaqueType>(Ty))
137 // Check to see if the Type is already on the stack...
138 unsigned Slot = 0, CurSize = TypeStack.size();
139 while (Slot < CurSize && TypeStack[Slot] != Ty) ++Slot; // Scan for type
141 // This is another base case for the recursion. In this case, we know
142 // that we have looped back to a type that we have previously visited.
143 // Generate the appropriate upreference to handle this.
146 return "\\" + utostr(CurSize-Slot); // Here's the upreference
148 TypeStack.push_back(Ty); // Recursive case: Add us to the stack..
151 switch (Ty->getPrimitiveID()) {
152 case Type::FunctionTyID: {
153 const FunctionType *FTy = cast<FunctionType>(Ty);
154 Result = calcTypeName(FTy->getReturnType(), TypeStack, TypeNames) + " (";
155 for (FunctionType::ParamTypes::const_iterator
156 I = FTy->getParamTypes().begin(),
157 E = FTy->getParamTypes().end(); I != E; ++I) {
158 if (I != FTy->getParamTypes().begin())
160 Result += calcTypeName(*I, TypeStack, TypeNames);
162 if (FTy->isVarArg()) {
163 if (!FTy->getParamTypes().empty()) Result += ", ";
169 case Type::StructTyID: {
170 const StructType *STy = cast<StructType>(Ty);
172 for (StructType::ElementTypes::const_iterator
173 I = STy->getElementTypes().begin(),
174 E = STy->getElementTypes().end(); I != E; ++I) {
175 if (I != STy->getElementTypes().begin())
177 Result += calcTypeName(*I, TypeStack, TypeNames);
182 case Type::PointerTyID:
183 Result = calcTypeName(cast<PointerType>(Ty)->getElementType(),
184 TypeStack, TypeNames) + "*";
186 case Type::ArrayTyID: {
187 const ArrayType *ATy = cast<ArrayType>(Ty);
188 Result = "[" + utostr(ATy->getNumElements()) + " x ";
189 Result += calcTypeName(ATy->getElementType(), TypeStack, TypeNames) + "]";
192 case Type::OpaqueTyID:
196 Result = "<unrecognized-type>";
199 TypeStack.pop_back(); // Remove self from stack...
204 // printTypeInt - The internal guts of printing out a type that has a
205 // potentially named portion.
207 static std::ostream &printTypeInt(std::ostream &Out, const Type *Ty,
208 std::map<const Type *, std::string> &TypeNames) {
209 // Primitive types always print out their description, regardless of whether
210 // they have been named or not.
212 if (Ty->isPrimitiveType() && !isa<OpaqueType>(Ty))
213 return Out << Ty->getDescription();
215 // Check to see if the type is named.
216 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
217 if (I != TypeNames.end()) return Out << I->second;
219 // Otherwise we have a type that has not been named but is a derived type.
220 // Carefully recurse the type hierarchy to print out any contained symbolic
223 std::vector<const Type *> TypeStack;
224 std::string TypeName = calcTypeName(Ty, TypeStack, TypeNames);
225 TypeNames.insert(std::make_pair(Ty, TypeName));//Cache type name for later use
226 return Out << TypeName;
230 // WriteTypeSymbolic - This attempts to write the specified type as a symbolic
231 // type, iff there is an entry in the modules symbol table for the specified
232 // type or one of it's component types. This is slower than a simple x << Type;
234 std::ostream &WriteTypeSymbolic(std::ostream &Out, const Type *Ty,
238 // If they want us to print out a type, attempt to make it symbolic if there
239 // is a symbol table in the module...
241 std::map<const Type *, std::string> TypeNames;
242 fillTypeNameTable(M, TypeNames);
244 return printTypeInt(Out, Ty, TypeNames);
246 return Out << Ty->getDescription();
250 static void WriteConstantInt(std::ostream &Out, const Constant *CV,
252 std::map<const Type *, std::string> &TypeTable,
253 SlotCalculator *Table) {
254 if (const ConstantBool *CB = dyn_cast<ConstantBool>(CV)) {
255 Out << (CB == ConstantBool::True ? "true" : "false");
256 } else if (const ConstantSInt *CI = dyn_cast<ConstantSInt>(CV)) {
257 Out << CI->getValue();
258 } else if (const ConstantUInt *CI = dyn_cast<ConstantUInt>(CV)) {
259 Out << CI->getValue();
260 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
261 // We would like to output the FP constant value in exponential notation,
262 // but we cannot do this if doing so will lose precision. Check here to
263 // make sure that we only output it in exponential format if we can parse
264 // the value back and get the same value.
266 std::string StrVal = ftostr(CFP->getValue());
268 // Check to make sure that the stringized number is not some string like
269 // "Inf" or NaN, that atof will accept, but the lexer will not. Check that
270 // the string matches the "[-+]?[0-9]" regex.
272 if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
273 ((StrVal[0] == '-' || StrVal[0] == '+') &&
274 (StrVal[1] >= '0' && StrVal[1] <= '9')))
275 // Reparse stringized version!
276 if (atof(StrVal.c_str()) == CFP->getValue()) {
277 Out << StrVal; return;
280 // Otherwise we could not reparse it to exactly the same value, so we must
281 // output the string in hexadecimal format!
283 // Behave nicely in the face of C TBAA rules... see:
284 // http://www.nullstone.com/htmls/category/aliastyp.htm
286 double Val = CFP->getValue();
287 char *Ptr = (char*)&Val;
288 assert(sizeof(double) == sizeof(uint64_t) && sizeof(double) == 8 &&
289 "assuming that double is 64 bits!");
290 Out << "0x" << utohexstr(*(uint64_t*)Ptr);
292 } else if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
293 if (CA->getNumOperands() > 5 && CA->isNullValue()) {
294 Out << "zeroinitializer";
298 // As a special case, print the array as a string if it is an array of
299 // ubytes or an array of sbytes with positive values.
301 const Type *ETy = CA->getType()->getElementType();
302 bool isString = (ETy == Type::SByteTy || ETy == Type::UByteTy);
304 if (ETy == Type::SByteTy)
305 for (unsigned i = 0; i < CA->getNumOperands(); ++i)
306 if (cast<ConstantSInt>(CA->getOperand(i))->getValue() < 0) {
313 for (unsigned i = 0; i < CA->getNumOperands(); ++i) {
314 unsigned char C = cast<ConstantInt>(CA->getOperand(i))->getRawValue();
316 if (isprint(C) && C != '"' && C != '\\') {
320 << (char) ((C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A'))
321 << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
326 } else { // Cannot output in string format...
328 if (CA->getNumOperands()) {
330 printTypeInt(Out, ETy, TypeTable);
331 WriteAsOperandInternal(Out, CA->getOperand(0),
332 PrintName, TypeTable, Table);
333 for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
335 printTypeInt(Out, ETy, TypeTable);
336 WriteAsOperandInternal(Out, CA->getOperand(i), PrintName,
342 } else if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
343 if (CS->getNumOperands() > 5 && CS->isNullValue()) {
344 Out << "zeroinitializer";
349 if (CS->getNumOperands()) {
351 printTypeInt(Out, CS->getOperand(0)->getType(), TypeTable);
353 WriteAsOperandInternal(Out, CS->getOperand(0),
354 PrintName, TypeTable, Table);
356 for (unsigned i = 1; i < CS->getNumOperands(); i++) {
358 printTypeInt(Out, CS->getOperand(i)->getType(), TypeTable);
360 WriteAsOperandInternal(Out, CS->getOperand(i),
361 PrintName, TypeTable, Table);
366 } else if (isa<ConstantPointerNull>(CV)) {
369 } else if (const ConstantPointerRef *PR = dyn_cast<ConstantPointerRef>(CV)) {
370 const GlobalValue *V = PR->getValue();
372 Out << getLLVMName(V->getName());
374 int Slot = Table->getSlot(V);
378 Out << "<pointer reference badref>";
380 Out << "<pointer reference without context info>";
383 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
384 Out << CE->getOpcodeName() << " (";
386 for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) {
387 printTypeInt(Out, (*OI)->getType(), TypeTable);
388 WriteAsOperandInternal(Out, *OI, PrintName, TypeTable, Table);
389 if (OI+1 != CE->op_end())
393 if (CE->getOpcode() == Instruction::Cast) {
395 printTypeInt(Out, CE->getType(), TypeTable);
400 Out << "<placeholder or erroneous Constant>";
405 // WriteAsOperand - Write the name of the specified value out to the specified
406 // ostream. This can be useful when you just want to print int %reg126, not the
407 // whole instruction that generated it.
409 static void WriteAsOperandInternal(std::ostream &Out, const Value *V,
411 std::map<const Type*, std::string> &TypeTable,
412 SlotCalculator *Table) {
414 if (PrintName && V->hasName()) {
415 Out << getLLVMName(V->getName());
417 if (const Constant *CV = dyn_cast<Constant>(V)) {
418 WriteConstantInt(Out, CV, PrintName, TypeTable, Table);
422 Slot = Table->getSlot(V);
424 if (const Type *Ty = dyn_cast<Type>(V)) {
425 Out << Ty->getDescription();
429 Table = createSlotCalculator(V);
430 if (Table == 0) { Out << "BAD VALUE TYPE!"; return; }
432 Slot = Table->getSlot(V);
435 if (Slot >= 0) Out << "%" << Slot;
437 Out << "<badref>"; // Not embedded into a location?
444 // WriteAsOperand - Write the name of the specified value out to the specified
445 // ostream. This can be useful when you just want to print int %reg126, not the
446 // whole instruction that generated it.
448 std::ostream &WriteAsOperand(std::ostream &Out, const Value *V, bool PrintType,
449 bool PrintName, const Module *Context) {
450 std::map<const Type *, std::string> TypeNames;
451 if (Context == 0) Context = getModuleFromVal(V);
454 fillTypeNameTable(Context, TypeNames);
457 printTypeInt(Out, V->getType(), TypeNames);
459 WriteAsOperandInternal(Out, V, PrintName, TypeNames, 0);
465 class AssemblyWriter {
467 SlotCalculator &Table;
468 const Module *TheModule;
469 std::map<const Type *, std::string> TypeNames;
470 AssemblyAnnotationWriter *AnnotationWriter;
472 inline AssemblyWriter(std::ostream &o, SlotCalculator &Tab, const Module *M,
473 AssemblyAnnotationWriter *AAW)
474 : Out(o), Table(Tab), TheModule(M), AnnotationWriter(AAW) {
476 // If the module has a symbol table, take all global types and stuff their
477 // names into the TypeNames map.
479 fillTypeNameTable(M, TypeNames);
482 inline void write(const Module *M) { printModule(M); }
483 inline void write(const GlobalVariable *G) { printGlobal(G); }
484 inline void write(const Function *F) { printFunction(F); }
485 inline void write(const BasicBlock *BB) { printBasicBlock(BB); }
486 inline void write(const Instruction *I) { printInstruction(*I); }
487 inline void write(const Constant *CPV) { printConstant(CPV); }
488 inline void write(const Type *Ty) { printType(Ty); }
490 void writeOperand(const Value *Op, bool PrintType, bool PrintName = true);
493 void printModule(const Module *M);
494 void printSymbolTable(const SymbolTable &ST);
495 void printConstant(const Constant *CPV);
496 void printGlobal(const GlobalVariable *GV);
497 void printFunction(const Function *F);
498 void printArgument(const Argument *FA);
499 void printBasicBlock(const BasicBlock *BB);
500 void printInstruction(const Instruction &I);
502 // printType - Go to extreme measures to attempt to print out a short,
503 // symbolic version of a type name.
505 std::ostream &printType(const Type *Ty) {
506 return printTypeInt(Out, Ty, TypeNames);
509 // printTypeAtLeastOneLevel - Print out one level of the possibly complex type
510 // without considering any symbolic types that we may have equal to it.
512 std::ostream &printTypeAtLeastOneLevel(const Type *Ty);
514 // printInfoComment - Print a little comment after the instruction indicating
515 // which slot it occupies.
516 void printInfoComment(const Value &V);
520 // printTypeAtLeastOneLevel - Print out one level of the possibly complex type
521 // without considering any symbolic types that we may have equal to it.
523 std::ostream &AssemblyWriter::printTypeAtLeastOneLevel(const Type *Ty) {
524 if (const FunctionType *FTy = dyn_cast<FunctionType>(Ty)) {
525 printType(FTy->getReturnType()) << " (";
526 for (FunctionType::ParamTypes::const_iterator
527 I = FTy->getParamTypes().begin(),
528 E = FTy->getParamTypes().end(); I != E; ++I) {
529 if (I != FTy->getParamTypes().begin())
533 if (FTy->isVarArg()) {
534 if (!FTy->getParamTypes().empty()) Out << ", ";
538 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
540 for (StructType::ElementTypes::const_iterator
541 I = STy->getElementTypes().begin(),
542 E = STy->getElementTypes().end(); I != E; ++I) {
543 if (I != STy->getElementTypes().begin())
548 } else if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
549 printType(PTy->getElementType()) << "*";
550 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
551 Out << "[" << ATy->getNumElements() << " x ";
552 printType(ATy->getElementType()) << "]";
553 } else if (const OpaqueType *OTy = dyn_cast<OpaqueType>(Ty)) {
556 if (!Ty->isPrimitiveType())
557 Out << "<unknown derived type>";
564 void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType,
566 if (PrintType) { Out << " "; printType(Operand->getType()); }
567 WriteAsOperandInternal(Out, Operand, PrintName, TypeNames, &Table);
571 void AssemblyWriter::printModule(const Module *M) {
572 switch (M->getEndianness()) {
573 case Module::LittleEndian: Out << "target endian = little\n"; break;
574 case Module::BigEndian: Out << "target endian = big\n"; break;
575 case Module::AnyEndianness: break;
577 switch (M->getPointerSize()) {
578 case Module::Pointer32: Out << "target pointersize = 32\n"; break;
579 case Module::Pointer64: Out << "target pointersize = 64\n"; break;
580 case Module::AnyPointerSize: break;
583 // Loop over the symbol table, emitting all named constants...
584 printSymbolTable(M->getSymbolTable());
586 for (Module::const_giterator I = M->gbegin(), E = M->gend(); I != E; ++I)
589 Out << "\nimplementation ; Functions:\n";
591 // Output all of the functions...
592 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
596 void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
597 if (GV->hasName()) Out << getLLVMName(GV->getName()) << " = ";
599 if (!GV->hasInitializer())
602 switch (GV->getLinkage()) {
603 case GlobalValue::InternalLinkage: Out << "internal "; break;
604 case GlobalValue::LinkOnceLinkage: Out << "linkonce "; break;
605 case GlobalValue::WeakLinkage: Out << "weak "; break;
606 case GlobalValue::AppendingLinkage: Out << "appending "; break;
607 case GlobalValue::ExternalLinkage: break;
610 Out << (GV->isConstant() ? "constant " : "global ");
611 printType(GV->getType()->getElementType());
613 if (GV->hasInitializer())
614 writeOperand(GV->getInitializer(), false, false);
616 printInfoComment(*GV);
621 // printSymbolTable - Run through symbol table looking for named constants
622 // if a named constant is found, emit it's declaration...
624 void AssemblyWriter::printSymbolTable(const SymbolTable &ST) {
625 for (SymbolTable::const_iterator TI = ST.begin(); TI != ST.end(); ++TI) {
626 SymbolTable::type_const_iterator I = ST.type_begin(TI->first);
627 SymbolTable::type_const_iterator End = ST.type_end(TI->first);
629 for (; I != End; ++I) {
630 const Value *V = I->second;
631 if (const Constant *CPV = dyn_cast<Constant>(V)) {
633 } else if (const Type *Ty = dyn_cast<Type>(V)) {
634 Out << "\t" << getLLVMName(I->first) << " = type ";
636 // Make sure we print out at least one level of the type structure, so
637 // that we do not get %FILE = type %FILE
639 printTypeAtLeastOneLevel(Ty) << "\n";
646 // printConstant - Print out a constant pool entry...
648 void AssemblyWriter::printConstant(const Constant *CPV) {
649 // Don't print out unnamed constants, they will be inlined
650 if (!CPV->hasName()) return;
653 Out << "\t" << getLLVMName(CPV->getName()) << " =";
655 // Write the value out now...
656 writeOperand(CPV, true, false);
658 printInfoComment(*CPV);
662 // printFunction - Print all aspects of a function.
664 void AssemblyWriter::printFunction(const Function *F) {
665 // Print out the return type and name...
668 if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, Out);
673 switch (F->getLinkage()) {
674 case GlobalValue::InternalLinkage: Out << "internal "; break;
675 case GlobalValue::LinkOnceLinkage: Out << "linkonce "; break;
676 case GlobalValue::WeakLinkage: Out << "weak "; break;
677 case GlobalValue::AppendingLinkage: Out << "appending "; break;
678 case GlobalValue::ExternalLinkage: break;
681 printType(F->getReturnType()) << " ";
682 if (!F->getName().empty())
683 Out << getLLVMName(F->getName());
687 Table.incorporateFunction(F);
689 // Loop over the arguments, printing them...
690 const FunctionType *FT = F->getFunctionType();
692 for(Function::const_aiterator I = F->abegin(), E = F->aend(); I != E; ++I)
695 // Finish printing arguments...
696 if (FT->isVarArg()) {
697 if (FT->getParamTypes().size()) Out << ", ";
698 Out << "..."; // Output varargs portion of signature!
702 if (F->isExternal()) {
707 // Output all of its basic blocks... for the function
708 for (Function::const_iterator I = F->begin(), E = F->end(); I != E; ++I)
714 Table.purgeFunction();
717 // printArgument - This member is called for every argument that
718 // is passed into the function. Simply print it out
720 void AssemblyWriter::printArgument(const Argument *Arg) {
721 // Insert commas as we go... the first arg doesn't get a comma
722 if (Arg != &Arg->getParent()->afront()) Out << ", ";
725 printType(Arg->getType());
727 // Output name, if available...
729 Out << " " << getLLVMName(Arg->getName());
730 else if (Table.getSlot(Arg) < 0)
734 // printBasicBlock - This member is called for each basic block in a method.
736 void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {
737 if (BB->hasName()) { // Print out the label if it exists...
738 Out << "\n" << BB->getName() << ":";
739 } else if (!BB->use_empty()) { // Don't print block # of no uses...
740 int Slot = Table.getSlot(BB);
741 Out << "\n; <label>:";
743 Out << Slot; // Extra newline separates out label's
748 // Output predecessors for the block...
750 pred_const_iterator PI = pred_begin(BB), PE = pred_end(BB);
753 Out << " No predecessors!";
756 writeOperand(*PI, false, true);
757 for (++PI; PI != PE; ++PI) {
759 writeOperand(*PI, false, true);
765 if (AnnotationWriter) AnnotationWriter->emitBasicBlockAnnot(BB, Out);
767 // Output all of the instructions in the basic block...
768 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
769 printInstruction(*I);
773 // printInfoComment - Print a little comment after the instruction indicating
774 // which slot it occupies.
776 void AssemblyWriter::printInfoComment(const Value &V) {
777 if (V.getType() != Type::VoidTy) {
779 printType(V.getType()) << ">";
782 int Slot = Table.getSlot(&V); // Print out the def slot taken...
783 if (Slot >= 0) Out << ":" << Slot;
784 else Out << ":<badref>";
786 Out << " [#uses=" << V.use_size() << "]"; // Output # uses
790 // printInstruction - This member is called for each Instruction in a method.
792 void AssemblyWriter::printInstruction(const Instruction &I) {
793 if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, Out);
797 // Print out name if it exists...
799 Out << getLLVMName(I.getName()) << " = ";
801 // If this is a volatile load or store, print out the volatile marker
802 if ((isa<LoadInst>(I) && cast<LoadInst>(I).isVolatile()) ||
803 (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile()))
806 // Print out the opcode...
807 Out << I.getOpcodeName();
809 // Print out the type of the operands...
810 const Value *Operand = I.getNumOperands() ? I.getOperand(0) : 0;
812 // Special case conditional branches to swizzle the condition out to the front
813 if (isa<BranchInst>(I) && I.getNumOperands() > 1) {
814 writeOperand(I.getOperand(2), true);
816 writeOperand(Operand, true);
818 writeOperand(I.getOperand(1), true);
820 } else if (isa<SwitchInst>(I)) {
821 // Special case switch statement to get formatting nice and correct...
822 writeOperand(Operand , true); Out << ",";
823 writeOperand(I.getOperand(1), true); Out << " [";
825 for (unsigned op = 2, Eop = I.getNumOperands(); op < Eop; op += 2) {
827 writeOperand(I.getOperand(op ), true); Out << ",";
828 writeOperand(I.getOperand(op+1), true);
831 } else if (isa<PHINode>(I)) {
833 printType(I.getType());
836 for (unsigned op = 0, Eop = I.getNumOperands(); op < Eop; op += 2) {
839 writeOperand(I.getOperand(op ), false); Out << ",";
840 writeOperand(I.getOperand(op+1), false); Out << " ]";
842 } else if (isa<ReturnInst>(I) && !Operand) {
844 } else if (isa<CallInst>(I)) {
845 const PointerType *PTy = cast<PointerType>(Operand->getType());
846 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
847 const Type *RetTy = FTy->getReturnType();
849 // If possible, print out the short form of the call instruction. We can
850 // only do this if the first argument is a pointer to a nonvararg function,
851 // and if the return type is not a pointer to a function.
853 if (!FTy->isVarArg() &&
854 (!isa<PointerType>(RetTy) ||
855 !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
856 Out << " "; printType(RetTy);
857 writeOperand(Operand, false);
859 writeOperand(Operand, true);
862 if (I.getNumOperands() > 1) writeOperand(I.getOperand(1), true);
863 for (unsigned op = 2, Eop = I.getNumOperands(); op < Eop; ++op) {
865 writeOperand(I.getOperand(op), true);
869 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
870 const PointerType *PTy = cast<PointerType>(Operand->getType());
871 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
872 const Type *RetTy = FTy->getReturnType();
874 // If possible, print out the short form of the invoke instruction. We can
875 // only do this if the first argument is a pointer to a nonvararg function,
876 // and if the return type is not a pointer to a function.
878 if (!FTy->isVarArg() &&
879 (!isa<PointerType>(RetTy) ||
880 !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
881 Out << " "; printType(RetTy);
882 writeOperand(Operand, false);
884 writeOperand(Operand, true);
888 if (I.getNumOperands() > 3) writeOperand(I.getOperand(3), true);
889 for (unsigned op = 4, Eop = I.getNumOperands(); op < Eop; ++op) {
891 writeOperand(I.getOperand(op), true);
894 Out << " )\n\t\t\tto";
895 writeOperand(II->getNormalDest(), true);
897 writeOperand(II->getExceptionalDest(), true);
899 } else if (const AllocationInst *AI = dyn_cast<AllocationInst>(&I)) {
901 printType(AI->getType()->getElementType());
902 if (AI->isArrayAllocation()) {
904 writeOperand(AI->getArraySize(), true);
906 } else if (isa<CastInst>(I)) {
907 writeOperand(Operand, true);
909 printType(I.getType());
910 } else if (isa<VAArgInst>(I)) {
911 writeOperand(Operand, true);
913 printType(I.getType());
914 } else if (const VANextInst *VAN = dyn_cast<VANextInst>(&I)) {
915 writeOperand(Operand, true);
917 printType(VAN->getArgType());
918 } else if (Operand) { // Print the normal way...
920 // PrintAllTypes - Instructions who have operands of all the same type
921 // omit the type from all but the first operand. If the instruction has
922 // different type operands (for example br), then they are all printed.
923 bool PrintAllTypes = false;
924 const Type *TheType = Operand->getType();
926 // Shift Left & Right print both types even for Ubyte LHS
927 if (isa<ShiftInst>(I)) {
928 PrintAllTypes = true;
930 for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) {
931 Operand = I.getOperand(i);
932 if (Operand->getType() != TheType) {
933 PrintAllTypes = true; // We have differing types! Print them all!
939 if (!PrintAllTypes) {
944 for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) {
946 writeOperand(I.getOperand(i), PrintAllTypes);
955 //===----------------------------------------------------------------------===//
956 // External Interface declarations
957 //===----------------------------------------------------------------------===//
959 void Module::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
960 SlotCalculator SlotTable(this, true);
961 AssemblyWriter W(o, SlotTable, this, AAW);
965 void GlobalVariable::print(std::ostream &o) const {
966 SlotCalculator SlotTable(getParent(), true);
967 AssemblyWriter W(o, SlotTable, getParent(), 0);
971 void Function::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
972 SlotCalculator SlotTable(getParent(), true);
973 AssemblyWriter W(o, SlotTable, getParent(), AAW);
978 void BasicBlock::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
979 SlotCalculator SlotTable(getParent(), true);
980 AssemblyWriter W(o, SlotTable,
981 getParent() ? getParent()->getParent() : 0, AAW);
985 void Instruction::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
986 const Function *F = getParent() ? getParent()->getParent() : 0;
987 SlotCalculator SlotTable(F, true);
988 AssemblyWriter W(o, SlotTable, F ? F->getParent() : 0, AAW);
993 void Constant::print(std::ostream &o) const {
994 if (this == 0) { o << "<null> constant value\n"; return; }
996 // Handle CPR's special, because they have context information...
997 if (const ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(this)) {
998 CPR->getValue()->print(o); // Print as a global value, with context info.
1002 o << " " << getType()->getDescription() << " ";
1004 std::map<const Type *, std::string> TypeTable;
1005 WriteConstantInt(o, this, false, TypeTable, 0);
1008 void Type::print(std::ostream &o) const {
1012 o << getDescription();
1015 void Argument::print(std::ostream &o) const {
1016 o << getType() << " " << getName();
1019 void Value::dump() const { print(std::cerr); }
1021 //===----------------------------------------------------------------------===//
1022 // CachedWriter Class Implementation
1023 //===----------------------------------------------------------------------===//
1025 void CachedWriter::setModule(const Module *M) {
1026 delete SC; delete AW;
1028 SC = new SlotCalculator(M, true);
1029 AW = new AssemblyWriter(Out, *SC, M, 0);
1035 CachedWriter::~CachedWriter() {
1040 CachedWriter &CachedWriter::operator<<(const Value *V) {
1041 assert(AW && SC && "CachedWriter does not have a current module!");
1042 switch (V->getValueType()) {
1043 case Value::ConstantVal:
1044 case Value::ArgumentVal: AW->writeOperand(V, true, true); break;
1045 case Value::TypeVal: AW->write(cast<Type>(V)); break;
1046 case Value::InstructionVal: AW->write(cast<Instruction>(V)); break;
1047 case Value::BasicBlockVal: AW->write(cast<BasicBlock>(V)); break;
1048 case Value::FunctionVal: AW->write(cast<Function>(V)); break;
1049 case Value::GlobalVariableVal: AW->write(cast<GlobalVariable>(V)); break;
1050 default: Out << "<unknown value type: " << V->getValueType() << ">"; break;