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/Constants.h"
22 #include "llvm/DerivedTypes.h"
23 #include "llvm/Instruction.h"
24 #include "llvm/iMemory.h"
25 #include "llvm/iTerminators.h"
26 #include "llvm/iPHINode.h"
27 #include "llvm/iOther.h"
28 #include "llvm/Module.h"
29 #include "llvm/SymbolTable.h"
30 #include "llvm/Analysis/SlotCalculator.h"
31 #include "llvm/Assembly/Writer.h"
32 #include "llvm/Support/CFG.h"
33 #include "Support/StringExtras.h"
34 #include "Support/STLExtras.h"
38 static RegisterPass<PrintModulePass>
39 X("printm", "Print module to stderr",PassInfo::Analysis|PassInfo::Optimization);
40 static RegisterPass<PrintFunctionPass>
41 Y("print","Print function to stderr",PassInfo::Analysis|PassInfo::Optimization);
43 static void WriteAsOperandInternal(std::ostream &Out, const Value *V,
45 std::map<const Type *, std::string> &TypeTable,
46 SlotCalculator *Table);
48 static const Module *getModuleFromVal(const Value *V) {
49 if (const Argument *MA = dyn_cast<Argument>(V))
50 return MA->getParent() ? MA->getParent()->getParent() : 0;
51 else if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
52 return BB->getParent() ? BB->getParent()->getParent() : 0;
53 else if (const Instruction *I = dyn_cast<Instruction>(V)) {
54 const Function *M = I->getParent() ? I->getParent()->getParent() : 0;
55 return M ? M->getParent() : 0;
56 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
57 return GV->getParent();
61 static SlotCalculator *createSlotCalculator(const Value *V) {
62 assert(!isa<Type>(V) && "Can't create an SC for a type!");
63 if (const Argument *FA = dyn_cast<Argument>(V)) {
64 return new SlotCalculator(FA->getParent(), false);
65 } else if (const Instruction *I = dyn_cast<Instruction>(V)) {
66 return new SlotCalculator(I->getParent()->getParent(), false);
67 } else if (const BasicBlock *BB = dyn_cast<BasicBlock>(V)) {
68 return new SlotCalculator(BB->getParent(), false);
69 } else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V)){
70 return new SlotCalculator(GV->getParent(), false);
71 } else if (const Function *Func = dyn_cast<Function>(V)) {
72 return new SlotCalculator(Func, false);
77 // getLLVMName - Turn the specified string into an 'LLVM name', which is either
78 // prefixed with % (if the string only contains simple characters) or is
79 // surrounded with ""'s (if it has special chars in it).
80 static std::string getLLVMName(const std::string &Name) {
81 assert(!Name.empty() && "Cannot get empty name!");
83 // First character cannot start with a number...
84 if (Name[0] >= '0' && Name[0] <= '9')
85 return "\"" + Name + "\"";
87 // Scan to see if we have any characters that are not on the "white list"
88 for (unsigned i = 0, e = Name.size(); i != e; ++i) {
90 assert(C != '"' && "Illegal character in LLVM value name!");
91 if ((C < 'a' || C > 'z') && (C < 'A' || C > 'Z') && (C < '0' || C > '9') &&
92 C != '-' && C != '.' && C != '_')
93 return "\"" + Name + "\"";
96 // If we get here, then the identifier is legal to use as a "VarID".
101 /// fillTypeNameTable - If the module has a symbol table, take all global types
102 /// and stuff their names into the TypeNames map.
104 static void fillTypeNameTable(const Module *M,
105 std::map<const Type *, std::string> &TypeNames) {
107 const SymbolTable &ST = M->getSymbolTable();
108 SymbolTable::type_const_iterator TI = ST.type_begin();
109 for (; TI != ST.type_end(); ++TI ) {
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>(TI->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(TI->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.
144 return "\\" + utostr(CurSize-Slot); // Here's the upreference
146 TypeStack.push_back(Ty); // Recursive case: Add us to the stack..
149 switch (Ty->getPrimitiveID()) {
150 case Type::FunctionTyID: {
151 const FunctionType *FTy = cast<FunctionType>(Ty);
152 Result = calcTypeName(FTy->getReturnType(), TypeStack, TypeNames) + " (";
153 for (FunctionType::param_iterator I = FTy->param_begin(),
154 E = FTy->param_end(); I != E; ++I) {
155 if (I != FTy->param_begin())
157 Result += calcTypeName(*I, TypeStack, TypeNames);
159 if (FTy->isVarArg()) {
160 if (FTy->getNumParams()) Result += ", ";
166 case Type::StructTyID: {
167 const StructType *STy = cast<StructType>(Ty);
169 for (StructType::element_iterator I = STy->element_begin(),
170 E = STy->element_end(); I != E; ++I) {
171 if (I != STy->element_begin())
173 Result += calcTypeName(*I, TypeStack, TypeNames);
178 case Type::PointerTyID:
179 Result = calcTypeName(cast<PointerType>(Ty)->getElementType(),
180 TypeStack, TypeNames) + "*";
182 case Type::ArrayTyID: {
183 const ArrayType *ATy = cast<ArrayType>(Ty);
184 Result = "[" + utostr(ATy->getNumElements()) + " x ";
185 Result += calcTypeName(ATy->getElementType(), TypeStack, TypeNames) + "]";
188 case Type::OpaqueTyID:
192 Result = "<unrecognized-type>";
195 TypeStack.pop_back(); // Remove self from stack...
200 /// printTypeInt - The internal guts of printing out a type that has a
201 /// potentially named portion.
203 static std::ostream &printTypeInt(std::ostream &Out, const Type *Ty,
204 std::map<const Type *, std::string> &TypeNames) {
205 // Primitive types always print out their description, regardless of whether
206 // they have been named or not.
208 if (Ty->isPrimitiveType() && !isa<OpaqueType>(Ty))
209 return Out << Ty->getDescription();
211 // Check to see if the type is named.
212 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
213 if (I != TypeNames.end()) return Out << I->second;
215 // Otherwise we have a type that has not been named but is a derived type.
216 // Carefully recurse the type hierarchy to print out any contained symbolic
219 std::vector<const Type *> TypeStack;
220 std::string TypeName = calcTypeName(Ty, TypeStack, TypeNames);
221 TypeNames.insert(std::make_pair(Ty, TypeName));//Cache type name for later use
222 return Out << TypeName;
226 /// WriteTypeSymbolic - This attempts to write the specified type as a symbolic
227 /// type, iff there is an entry in the modules symbol table for the specified
228 /// type or one of it's component types. This is slower than a simple x << Type
230 std::ostream &llvm::WriteTypeSymbolic(std::ostream &Out, const Type *Ty,
234 // If they want us to print out a type, attempt to make it symbolic if there
235 // is a symbol table in the module...
237 std::map<const Type *, std::string> TypeNames;
238 fillTypeNameTable(M, TypeNames);
240 return printTypeInt(Out, Ty, TypeNames);
242 return Out << Ty->getDescription();
246 static void WriteConstantInt(std::ostream &Out, const Constant *CV,
248 std::map<const Type *, std::string> &TypeTable,
249 SlotCalculator *Table) {
250 if (const ConstantBool *CB = dyn_cast<ConstantBool>(CV)) {
251 Out << (CB == ConstantBool::True ? "true" : "false");
252 } else if (const ConstantSInt *CI = dyn_cast<ConstantSInt>(CV)) {
253 Out << CI->getValue();
254 } else if (const ConstantUInt *CI = dyn_cast<ConstantUInt>(CV)) {
255 Out << CI->getValue();
256 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
257 // We would like to output the FP constant value in exponential notation,
258 // but we cannot do this if doing so will lose precision. Check here to
259 // make sure that we only output it in exponential format if we can parse
260 // the value back and get the same value.
262 std::string StrVal = ftostr(CFP->getValue());
264 // Check to make sure that the stringized number is not some string like
265 // "Inf" or NaN, that atof will accept, but the lexer will not. Check that
266 // the string matches the "[-+]?[0-9]" regex.
268 if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
269 ((StrVal[0] == '-' || StrVal[0] == '+') &&
270 (StrVal[1] >= '0' && StrVal[1] <= '9')))
271 // Reparse stringized version!
272 if (atof(StrVal.c_str()) == CFP->getValue()) {
273 Out << StrVal; return;
276 // Otherwise we could not reparse it to exactly the same value, so we must
277 // output the string in hexadecimal format!
279 // Behave nicely in the face of C TBAA rules... see:
280 // http://www.nullstone.com/htmls/category/aliastyp.htm
282 double Val = CFP->getValue();
283 char *Ptr = (char*)&Val;
284 assert(sizeof(double) == sizeof(uint64_t) && sizeof(double) == 8 &&
285 "assuming that double is 64 bits!");
286 Out << "0x" << utohexstr(*(uint64_t*)Ptr);
288 } else if (isa<ConstantAggregateZero>(CV)) {
289 Out << "zeroinitializer";
290 } else if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
291 // As a special case, print the array as a string if it is an array of
292 // ubytes or an array of sbytes with positive values.
294 const Type *ETy = CA->getType()->getElementType();
295 bool isString = (ETy == Type::SByteTy || ETy == Type::UByteTy);
297 if (ETy == Type::SByteTy)
298 for (unsigned i = 0; i < CA->getNumOperands(); ++i)
299 if (cast<ConstantSInt>(CA->getOperand(i))->getValue() < 0) {
306 for (unsigned i = 0; i < CA->getNumOperands(); ++i) {
307 unsigned char C = cast<ConstantInt>(CA->getOperand(i))->getRawValue();
309 if (isprint(C) && C != '"' && C != '\\') {
313 << (char) ((C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A'))
314 << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
319 } else { // Cannot output in string format...
321 if (CA->getNumOperands()) {
323 printTypeInt(Out, ETy, TypeTable);
324 WriteAsOperandInternal(Out, CA->getOperand(0),
325 PrintName, TypeTable, Table);
326 for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
328 printTypeInt(Out, ETy, TypeTable);
329 WriteAsOperandInternal(Out, CA->getOperand(i), PrintName,
335 } else if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
337 if (CS->getNumOperands()) {
339 printTypeInt(Out, CS->getOperand(0)->getType(), TypeTable);
341 WriteAsOperandInternal(Out, CS->getOperand(0),
342 PrintName, TypeTable, Table);
344 for (unsigned i = 1; i < CS->getNumOperands(); i++) {
346 printTypeInt(Out, CS->getOperand(i)->getType(), TypeTable);
348 WriteAsOperandInternal(Out, CS->getOperand(i),
349 PrintName, TypeTable, Table);
354 } else if (isa<ConstantPointerNull>(CV)) {
357 } else if (const ConstantPointerRef *PR = dyn_cast<ConstantPointerRef>(CV)) {
358 WriteAsOperandInternal(Out, PR->getValue(), true, TypeTable, Table);
360 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
361 Out << CE->getOpcodeName() << " (";
363 for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) {
364 printTypeInt(Out, (*OI)->getType(), TypeTable);
365 WriteAsOperandInternal(Out, *OI, PrintName, TypeTable, Table);
366 if (OI+1 != CE->op_end())
370 if (CE->getOpcode() == Instruction::Cast) {
372 printTypeInt(Out, CE->getType(), TypeTable);
377 Out << "<placeholder or erroneous Constant>";
382 /// WriteAsOperand - Write the name of the specified value out to the specified
383 /// ostream. This can be useful when you just want to print int %reg126, not
384 /// the whole instruction that generated it.
386 static void WriteAsOperandInternal(std::ostream &Out, const Value *V,
388 std::map<const Type*, std::string> &TypeTable,
389 SlotCalculator *Table) {
391 if (PrintName && V->hasName()) {
392 Out << getLLVMName(V->getName());
394 if (const Constant *CV = dyn_cast<Constant>(V)) {
395 WriteConstantInt(Out, CV, PrintName, TypeTable, Table);
399 Slot = Table->getSlot(V);
401 if (const Type *Ty = dyn_cast<Type>(V)) {
402 Out << Ty->getDescription();
406 Table = createSlotCalculator(V);
407 if (Table == 0) { Out << "BAD VALUE TYPE!"; return; }
409 Slot = Table->getSlot(V);
412 if (Slot >= 0) Out << "%" << Slot;
415 Out << "<badref: " << getLLVMName(V->getName()) << ">";
417 Out << "<badref>"; // Not embedded into a location?
423 /// WriteAsOperand - Write the name of the specified value out to the specified
424 /// ostream. This can be useful when you just want to print int %reg126, not
425 /// the whole instruction that generated it.
427 std::ostream &llvm::WriteAsOperand(std::ostream &Out, const Value *V,
428 bool PrintType, bool PrintName,
429 const Module *Context) {
430 std::map<const Type *, std::string> TypeNames;
431 if (Context == 0) Context = getModuleFromVal(V);
434 fillTypeNameTable(Context, TypeNames);
437 printTypeInt(Out, V->getType(), TypeNames);
439 if (const Type *Ty = dyn_cast<Type> (V))
440 printTypeInt(Out, Ty, TypeNames);
442 WriteAsOperandInternal(Out, V, PrintName, TypeNames, 0);
448 class AssemblyWriter {
450 SlotCalculator &Table;
451 const Module *TheModule;
452 std::map<const Type *, std::string> TypeNames;
453 AssemblyAnnotationWriter *AnnotationWriter;
455 inline AssemblyWriter(std::ostream &o, SlotCalculator &Tab, const Module *M,
456 AssemblyAnnotationWriter *AAW)
457 : Out(&o), Table(Tab), TheModule(M), AnnotationWriter(AAW) {
459 // If the module has a symbol table, take all global types and stuff their
460 // names into the TypeNames map.
462 fillTypeNameTable(M, TypeNames);
465 inline void write(const Module *M) { printModule(M); }
466 inline void write(const GlobalVariable *G) { printGlobal(G); }
467 inline void write(const Function *F) { printFunction(F); }
468 inline void write(const BasicBlock *BB) { printBasicBlock(BB); }
469 inline void write(const Instruction *I) { printInstruction(*I); }
470 inline void write(const Constant *CPV) { printConstant(CPV); }
471 inline void write(const Type *Ty) { printType(Ty); }
473 void writeOperand(const Value *Op, bool PrintType, bool PrintName = true);
475 const Module* getModule() { return TheModule; }
476 void setStream(std::ostream &os) { Out = &os; }
479 void printModule(const Module *M);
480 void printSymbolTable(const SymbolTable &ST);
481 void printConstant(const Constant *CPV);
482 void printGlobal(const GlobalVariable *GV);
483 void printFunction(const Function *F);
484 void printArgument(const Argument *FA);
485 void printBasicBlock(const BasicBlock *BB);
486 void printInstruction(const Instruction &I);
488 // printType - Go to extreme measures to attempt to print out a short,
489 // symbolic version of a type name.
491 std::ostream &printType(const Type *Ty) {
492 return printTypeInt(*Out, Ty, TypeNames);
495 // printTypeAtLeastOneLevel - Print out one level of the possibly complex type
496 // without considering any symbolic types that we may have equal to it.
498 std::ostream &printTypeAtLeastOneLevel(const Type *Ty);
500 // printInfoComment - Print a little comment after the instruction indicating
501 // which slot it occupies.
502 void printInfoComment(const Value &V);
504 } // end of anonymous namespace
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 &AssemblyWriter::printTypeAtLeastOneLevel(const Type *Ty) {
510 if (const FunctionType *FTy = dyn_cast<FunctionType>(Ty)) {
511 printType(FTy->getReturnType()) << " (";
512 for (FunctionType::param_iterator I = FTy->param_begin(),
513 E = FTy->param_end(); I != E; ++I) {
514 if (I != FTy->param_begin())
518 if (FTy->isVarArg()) {
519 if (FTy->getNumParams()) *Out << ", ";
523 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
525 for (StructType::element_iterator I = STy->element_begin(),
526 E = STy->element_end(); I != E; ++I) {
527 if (I != STy->element_begin())
532 } else if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
533 printType(PTy->getElementType()) << "*";
534 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
535 *Out << "[" << ATy->getNumElements() << " x ";
536 printType(ATy->getElementType()) << "]";
537 } else if (const OpaqueType *OTy = dyn_cast<OpaqueType>(Ty)) {
540 if (!Ty->isPrimitiveType())
541 *Out << "<unknown derived type>";
548 void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType,
550 if (PrintType) { *Out << " "; printType(Operand->getType()); }
551 WriteAsOperandInternal(*Out, Operand, PrintName, TypeNames, &Table);
555 void AssemblyWriter::printModule(const Module *M) {
556 switch (M->getEndianness()) {
557 case Module::LittleEndian: *Out << "target endian = little\n"; break;
558 case Module::BigEndian: *Out << "target endian = big\n"; break;
559 case Module::AnyEndianness: break;
561 switch (M->getPointerSize()) {
562 case Module::Pointer32: *Out << "target pointersize = 32\n"; break;
563 case Module::Pointer64: *Out << "target pointersize = 64\n"; break;
564 case Module::AnyPointerSize: break;
567 // Loop over the symbol table, emitting all named constants...
568 printSymbolTable(M->getSymbolTable());
570 for (Module::const_giterator I = M->gbegin(), E = M->gend(); I != E; ++I)
573 *Out << "\nimplementation ; Functions:\n";
575 // Output all of the functions...
576 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
580 void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
581 if (GV->hasName()) *Out << getLLVMName(GV->getName()) << " = ";
583 if (!GV->hasInitializer())
586 switch (GV->getLinkage()) {
587 case GlobalValue::InternalLinkage: *Out << "internal "; break;
588 case GlobalValue::LinkOnceLinkage: *Out << "linkonce "; break;
589 case GlobalValue::WeakLinkage: *Out << "weak "; break;
590 case GlobalValue::AppendingLinkage: *Out << "appending "; break;
591 case GlobalValue::ExternalLinkage: break;
594 *Out << (GV->isConstant() ? "constant " : "global ");
595 printType(GV->getType()->getElementType());
597 if (GV->hasInitializer())
598 writeOperand(GV->getInitializer(), false, false);
600 printInfoComment(*GV);
605 // printSymbolTable - Run through symbol table looking for constants
606 // and types. Emit their declarations.
607 void AssemblyWriter::printSymbolTable(const SymbolTable &ST) {
610 for (SymbolTable::type_const_iterator TI = ST.type_begin();
611 TI != ST.type_end(); ++TI ) {
612 *Out << "\t" << getLLVMName(TI->first) << " = type ";
614 // Make sure we print out at least one level of the type structure, so
615 // that we do not get %FILE = type %FILE
617 printTypeAtLeastOneLevel(TI->second) << "\n";
620 // Print the constants, in type plane order.
621 for (SymbolTable::plane_const_iterator PI = ST.plane_begin();
622 PI != ST.plane_end(); ++PI ) {
623 SymbolTable::value_const_iterator VI = ST.value_begin(PI->first);
624 SymbolTable::value_const_iterator VE = ST.value_end(PI->first);
626 for (; VI != VE; ++VI) {
627 const Value *V = VI->second;
628 if (const Constant *CPV = dyn_cast<Constant>(V)) {
636 /// printConstant - Print out a constant pool entry...
638 void AssemblyWriter::printConstant(const Constant *CPV) {
639 // Don't print out unnamed constants, they will be inlined
640 if (!CPV->hasName()) return;
643 *Out << "\t" << getLLVMName(CPV->getName()) << " =";
645 // Write the value out now...
646 writeOperand(CPV, true, false);
648 printInfoComment(*CPV);
652 /// printFunction - Print all aspects of a function.
654 void AssemblyWriter::printFunction(const Function *F) {
655 // Print out the return type and name...
658 if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, *Out);
663 switch (F->getLinkage()) {
664 case GlobalValue::InternalLinkage: *Out << "internal "; break;
665 case GlobalValue::LinkOnceLinkage: *Out << "linkonce "; break;
666 case GlobalValue::WeakLinkage: *Out << "weak "; break;
667 case GlobalValue::AppendingLinkage: *Out << "appending "; break;
668 case GlobalValue::ExternalLinkage: break;
671 printType(F->getReturnType()) << " ";
672 if (!F->getName().empty())
673 *Out << getLLVMName(F->getName());
677 Table.incorporateFunction(F);
679 // Loop over the arguments, printing them...
680 const FunctionType *FT = F->getFunctionType();
682 for(Function::const_aiterator I = F->abegin(), E = F->aend(); I != E; ++I)
685 // Finish printing arguments...
686 if (FT->isVarArg()) {
687 if (FT->getNumParams()) *Out << ", ";
688 *Out << "..."; // Output varargs portion of signature!
692 if (F->isExternal()) {
697 // Output all of its basic blocks... for the function
698 for (Function::const_iterator I = F->begin(), E = F->end(); I != E; ++I)
704 Table.purgeFunction();
707 /// printArgument - This member is called for every argument that is passed into
708 /// the function. Simply print it out
710 void AssemblyWriter::printArgument(const Argument *Arg) {
711 // Insert commas as we go... the first arg doesn't get a comma
712 if (Arg != &Arg->getParent()->afront()) *Out << ", ";
715 printType(Arg->getType());
717 // Output name, if available...
719 *Out << " " << getLLVMName(Arg->getName());
720 else if (Table.getSlot(Arg) < 0)
724 /// printBasicBlock - This member is called for each basic block in a method.
726 void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {
727 if (BB->hasName()) { // Print out the label if it exists...
728 *Out << "\n" << BB->getName() << ":";
729 } else if (!BB->use_empty()) { // Don't print block # of no uses...
730 int Slot = Table.getSlot(BB);
731 *Out << "\n; <label>:";
733 *Out << Slot; // Extra newline separates out label's
738 if (BB->getParent() == 0)
739 *Out << "\t\t; Error: Block without parent!";
741 if (BB != &BB->getParent()->front()) { // Not the entry block?
742 // Output predecessors for the block...
744 pred_const_iterator PI = pred_begin(BB), PE = pred_end(BB);
747 *Out << " No predecessors!";
750 writeOperand(*PI, false, true);
751 for (++PI; PI != PE; ++PI) {
753 writeOperand(*PI, false, true);
761 if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(BB, *Out);
763 // Output all of the instructions in the basic block...
764 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
765 printInstruction(*I);
767 if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(BB, *Out);
771 /// printInfoComment - Print a little comment after the instruction indicating
772 /// which slot it occupies.
774 void AssemblyWriter::printInfoComment(const Value &V) {
775 if (V.getType() != Type::VoidTy) {
777 printType(V.getType()) << ">";
780 int Slot = Table.getSlot(&V); // Print out the def slot taken...
781 if (Slot >= 0) *Out << ":" << Slot;
782 else *Out << ":<badref>";
784 *Out << " [#uses=" << V.use_size() << "]"; // Output # uses
788 /// printInstruction - This member is called for each Instruction in a method.
790 void AssemblyWriter::printInstruction(const Instruction &I) {
791 if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, *Out);
795 // Print out name if it exists...
797 *Out << getLLVMName(I.getName()) << " = ";
799 // If this is a volatile load or store, print out the volatile marker
800 if ((isa<LoadInst>(I) && cast<LoadInst>(I).isVolatile()) ||
801 (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile()))
804 // Print out the opcode...
805 *Out << I.getOpcodeName();
807 // Print out the type of the operands...
808 const Value *Operand = I.getNumOperands() ? I.getOperand(0) : 0;
810 // Special case conditional branches to swizzle the condition out to the front
811 if (isa<BranchInst>(I) && I.getNumOperands() > 1) {
812 writeOperand(I.getOperand(2), true);
814 writeOperand(Operand, true);
816 writeOperand(I.getOperand(1), true);
818 } else if (isa<SwitchInst>(I)) {
819 // Special case switch statement to get formatting nice and correct...
820 writeOperand(Operand , true); *Out << ",";
821 writeOperand(I.getOperand(1), true); *Out << " [";
823 for (unsigned op = 2, Eop = I.getNumOperands(); op < Eop; op += 2) {
825 writeOperand(I.getOperand(op ), true); *Out << ",";
826 writeOperand(I.getOperand(op+1), true);
829 } else if (isa<PHINode>(I)) {
831 printType(I.getType());
834 for (unsigned op = 0, Eop = I.getNumOperands(); op < Eop; op += 2) {
835 if (op) *Out << ", ";
837 writeOperand(I.getOperand(op ), false); *Out << ",";
838 writeOperand(I.getOperand(op+1), false); *Out << " ]";
840 } else if (isa<ReturnInst>(I) && !Operand) {
842 } else if (isa<CallInst>(I)) {
843 const PointerType *PTy = cast<PointerType>(Operand->getType());
844 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
845 const Type *RetTy = FTy->getReturnType();
847 // If possible, print out the short form of the call instruction. We can
848 // only do this if the first argument is a pointer to a nonvararg function,
849 // and if the return type is not a pointer to a function.
851 if (!FTy->isVarArg() &&
852 (!isa<PointerType>(RetTy) ||
853 !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
854 *Out << " "; printType(RetTy);
855 writeOperand(Operand, false);
857 writeOperand(Operand, true);
860 if (I.getNumOperands() > 1) writeOperand(I.getOperand(1), true);
861 for (unsigned op = 2, Eop = I.getNumOperands(); op < Eop; ++op) {
863 writeOperand(I.getOperand(op), true);
867 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
868 const PointerType *PTy = cast<PointerType>(Operand->getType());
869 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
870 const Type *RetTy = FTy->getReturnType();
872 // If possible, print out the short form of the invoke instruction. We can
873 // only do this if the first argument is a pointer to a nonvararg function,
874 // and if the return type is not a pointer to a function.
876 if (!FTy->isVarArg() &&
877 (!isa<PointerType>(RetTy) ||
878 !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
879 *Out << " "; printType(RetTy);
880 writeOperand(Operand, false);
882 writeOperand(Operand, true);
886 if (I.getNumOperands() > 3) writeOperand(I.getOperand(3), true);
887 for (unsigned op = 4, Eop = I.getNumOperands(); op < Eop; ++op) {
889 writeOperand(I.getOperand(op), true);
892 *Out << " )\n\t\t\tto";
893 writeOperand(II->getNormalDest(), true);
895 writeOperand(II->getUnwindDest(), true);
897 } else if (const AllocationInst *AI = dyn_cast<AllocationInst>(&I)) {
899 printType(AI->getType()->getElementType());
900 if (AI->isArrayAllocation()) {
902 writeOperand(AI->getArraySize(), true);
904 } else if (isa<CastInst>(I)) {
905 if (Operand) writeOperand(Operand, true); // Work with broken code
907 printType(I.getType());
908 } else if (isa<VAArgInst>(I)) {
909 if (Operand) writeOperand(Operand, true); // Work with broken code
911 printType(I.getType());
912 } else if (const VANextInst *VAN = dyn_cast<VANextInst>(&I)) {
913 if (Operand) writeOperand(Operand, true); // Work with broken code
915 printType(VAN->getArgType());
916 } else if (Operand) { // Print the normal way...
918 // PrintAllTypes - Instructions who have operands of all the same type
919 // omit the type from all but the first operand. If the instruction has
920 // different type operands (for example br), then they are all printed.
921 bool PrintAllTypes = false;
922 const Type *TheType = Operand->getType();
924 // Shift Left & Right print both types even for Ubyte LHS, and select prints
925 // types even if all operands are bools.
926 if (isa<ShiftInst>(I) || isa<SelectInst>(I)) {
927 PrintAllTypes = true;
929 for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) {
930 Operand = I.getOperand(i);
931 if (Operand->getType() != TheType) {
932 PrintAllTypes = true; // We have differing types! Print them all!
938 if (!PrintAllTypes) {
943 for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) {
945 writeOperand(I.getOperand(i), PrintAllTypes);
954 //===----------------------------------------------------------------------===//
955 // External Interface declarations
956 //===----------------------------------------------------------------------===//
958 void Module::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
959 SlotCalculator SlotTable(this, false);
960 AssemblyWriter W(o, SlotTable, this, AAW);
964 void GlobalVariable::print(std::ostream &o) const {
965 SlotCalculator SlotTable(getParent(), false);
966 AssemblyWriter W(o, SlotTable, getParent(), 0);
970 void Function::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
971 SlotCalculator SlotTable(getParent(), false);
972 AssemblyWriter W(o, SlotTable, getParent(), AAW);
977 void BasicBlock::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
978 SlotCalculator SlotTable(getParent(), false);
979 AssemblyWriter W(o, SlotTable,
980 getParent() ? getParent()->getParent() : 0, AAW);
984 void Instruction::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
985 const Function *F = getParent() ? getParent()->getParent() : 0;
986 SlotCalculator SlotTable(F, false);
987 AssemblyWriter W(o, SlotTable, F ? F->getParent() : 0, AAW);
992 void Constant::print(std::ostream &o) const {
993 if (this == 0) { o << "<null> constant value\n"; return; }
995 // Handle CPR's special, because they have context information...
996 if (const ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(this)) {
997 CPR->getValue()->print(o); // Print as a global value, with context info.
1001 o << " " << getType()->getDescription() << " ";
1003 std::map<const Type *, std::string> TypeTable;
1004 WriteConstantInt(o, this, false, TypeTable, 0);
1007 void Type::print(std::ostream &o) const {
1011 o << getDescription();
1014 void Argument::print(std::ostream &o) const {
1015 o << getType() << " " << getName();
1018 // Value::dump - allow easy printing of Values from the debugger.
1019 // Located here because so much of the needed functionality is here.
1020 void Value::dump() const { print(std::cerr); }
1022 // Type::dump - allow easy printing of Values from the debugger.
1023 // Located here because so much of the needed functionality is here.
1024 void Type::dump() const { print(std::cerr); }
1026 //===----------------------------------------------------------------------===//
1027 // CachedWriter Class Implementation
1028 //===----------------------------------------------------------------------===//
1030 void CachedWriter::setModule(const Module *M) {
1031 delete SC; delete AW;
1033 SC = new SlotCalculator(M, false);
1034 AW = new AssemblyWriter(*Out, *SC, M, 0);
1040 CachedWriter::~CachedWriter() {
1045 CachedWriter &CachedWriter::operator<<(const Value *V) {
1046 assert(AW && SC && "CachedWriter does not have a current module!");
1047 switch (V->getValueType()) {
1048 case Value::ConstantVal:
1049 case Value::ArgumentVal: AW->writeOperand(V, true, true); break;
1050 case Value::TypeVal: AW->write(cast<Type>(V)); break;
1051 case Value::InstructionVal: AW->write(cast<Instruction>(V)); break;
1052 case Value::BasicBlockVal: AW->write(cast<BasicBlock>(V)); break;
1053 case Value::FunctionVal: AW->write(cast<Function>(V)); break;
1054 case Value::GlobalVariableVal: AW->write(cast<GlobalVariable>(V)); break;
1055 default: *Out << "<unknown value type: " << V->getValueType() << ">"; break;
1060 CachedWriter& CachedWriter::operator<<(const Type *X) {
1061 if (SymbolicTypes) {
1062 const Module *M = AW->getModule();
1063 if (M) WriteTypeSymbolic(*Out, X, M);
1066 return *this << (const Value*)X;
1069 void CachedWriter::setStream(std::ostream &os) {
1071 if (AW) AW->setStream(os);