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/Analysis/SlotCalculator.h"
30 #include "llvm/SymbolTable.h"
31 #include "llvm/Support/CFG.h"
32 #include "Support/StringExtras.h"
33 #include "Support/STLExtras.h"
37 static RegisterPass<PrintModulePass>
38 X("printm", "Print module to stderr",PassInfo::Analysis|PassInfo::Optimization);
39 static RegisterPass<PrintFunctionPass>
40 Y("print","Print function to stderr",PassInfo::Analysis|PassInfo::Optimization);
42 static void WriteAsOperandInternal(std::ostream &Out, const Value *V,
44 std::map<const Type *, std::string> &TypeTable,
45 SlotCalculator *Table);
47 static const Module *getModuleFromVal(const Value *V) {
48 if (const Argument *MA = dyn_cast<Argument>(V))
49 return MA->getParent() ? MA->getParent()->getParent() : 0;
50 else if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
51 return BB->getParent() ? BB->getParent()->getParent() : 0;
52 else if (const Instruction *I = dyn_cast<Instruction>(V)) {
53 const Function *M = I->getParent() ? I->getParent()->getParent() : 0;
54 return M ? M->getParent() : 0;
55 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
56 return GV->getParent();
60 static SlotCalculator *createSlotCalculator(const Value *V) {
61 assert(!isa<Type>(V) && "Can't create an SC for a type!");
62 if (const Argument *FA = dyn_cast<Argument>(V)) {
63 return new SlotCalculator(FA->getParent(), false);
64 } else if (const Instruction *I = dyn_cast<Instruction>(V)) {
65 return new SlotCalculator(I->getParent()->getParent(), false);
66 } else if (const BasicBlock *BB = dyn_cast<BasicBlock>(V)) {
67 return new SlotCalculator(BB->getParent(), false);
68 } else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V)){
69 return new SlotCalculator(GV->getParent(), false);
70 } else if (const Function *Func = dyn_cast<Function>(V)) {
71 return new SlotCalculator(Func, false);
76 // getLLVMName - Turn the specified string into an 'LLVM name', which is either
77 // prefixed with % (if the string only contains simple characters) or is
78 // surrounded with ""'s (if it has special chars in it).
79 static std::string getLLVMName(const std::string &Name) {
80 assert(!Name.empty() && "Cannot get empty name!");
82 // First character cannot start with a number...
83 if (Name[0] >= '0' && Name[0] <= '9')
84 return "\"" + Name + "\"";
86 // Scan to see if we have any characters that are not on the "white list"
87 for (unsigned i = 0, e = Name.size(); i != e; ++i) {
89 assert(C != '"' && "Illegal character in LLVM value name!");
90 if ((C < 'a' || C > 'z') && (C < 'A' || C > 'Z') && (C < '0' || C > '9') &&
91 C != '-' && C != '.' && C != '_')
92 return "\"" + Name + "\"";
95 // If we get here, then the identifier is legal to use as a "VarID".
100 // If the module has a symbol table, take all global types and stuff their
101 // names into the TypeNames map.
103 static void fillTypeNameTable(const Module *M,
104 std::map<const Type *, std::string> &TypeNames) {
106 const SymbolTable &ST = M->getSymbolTable();
107 SymbolTable::const_iterator PI = ST.find(Type::TypeTy);
108 if (PI != ST.end()) {
109 SymbolTable::type_const_iterator I = PI->second.begin();
110 for (; I != PI->second.end(); ++I) {
111 // As a heuristic, don't insert pointer to primitive types, because
112 // they are used too often to have a single useful name.
114 const Type *Ty = cast<Type>(I->second);
115 if (!isa<PointerType>(Ty) ||
116 !cast<PointerType>(Ty)->getElementType()->isPrimitiveType() ||
117 isa<OpaqueType>(cast<PointerType>(Ty)->getElementType()))
118 TypeNames.insert(std::make_pair(Ty, getLLVMName(I->first)));
125 static std::string calcTypeName(const Type *Ty,
126 std::vector<const Type *> &TypeStack,
127 std::map<const Type *, std::string> &TypeNames){
128 if (Ty->isPrimitiveType() && !isa<OpaqueType>(Ty))
129 return Ty->getDescription(); // Base case
131 // Check to see if the type is named.
132 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
133 if (I != TypeNames.end()) return I->second;
135 if (isa<OpaqueType>(Ty))
138 // Check to see if the Type is already on the stack...
139 unsigned Slot = 0, CurSize = TypeStack.size();
140 while (Slot < CurSize && TypeStack[Slot] != Ty) ++Slot; // Scan for type
142 // This is another base case for the recursion. In this case, we know
143 // that we have looped back to a type that we have previously visited.
144 // Generate the appropriate upreference to handle this.
147 return "\\" + utostr(CurSize-Slot); // Here's the upreference
149 TypeStack.push_back(Ty); // Recursive case: Add us to the stack..
152 switch (Ty->getPrimitiveID()) {
153 case Type::FunctionTyID: {
154 const FunctionType *FTy = cast<FunctionType>(Ty);
155 Result = calcTypeName(FTy->getReturnType(), TypeStack, TypeNames) + " (";
156 for (FunctionType::param_iterator I = FTy->param_begin(),
157 E = FTy->param_end(); I != E; ++I) {
158 if (I != FTy->param_begin())
160 Result += calcTypeName(*I, TypeStack, TypeNames);
162 if (FTy->isVarArg()) {
163 if (FTy->getNumParams()) 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 &llvm::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 WriteAsOperandInternal(Out, PR->getValue(), true, TypeTable, Table);
372 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
373 Out << CE->getOpcodeName() << " (";
375 for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) {
376 printTypeInt(Out, (*OI)->getType(), TypeTable);
377 WriteAsOperandInternal(Out, *OI, PrintName, TypeTable, Table);
378 if (OI+1 != CE->op_end())
382 if (CE->getOpcode() == Instruction::Cast) {
384 printTypeInt(Out, CE->getType(), TypeTable);
389 Out << "<placeholder or erroneous Constant>";
394 // WriteAsOperand - Write the name of the specified value out to the specified
395 // ostream. This can be useful when you just want to print int %reg126, not the
396 // whole instruction that generated it.
398 static void WriteAsOperandInternal(std::ostream &Out, const Value *V,
400 std::map<const Type*, std::string> &TypeTable,
401 SlotCalculator *Table) {
403 if (PrintName && V->hasName()) {
404 Out << getLLVMName(V->getName());
406 if (const Constant *CV = dyn_cast<Constant>(V)) {
407 WriteConstantInt(Out, CV, PrintName, TypeTable, Table);
411 Slot = Table->getSlot(V);
413 if (const Type *Ty = dyn_cast<Type>(V)) {
414 Out << Ty->getDescription();
418 Table = createSlotCalculator(V);
419 if (Table == 0) { Out << "BAD VALUE TYPE!"; return; }
421 Slot = Table->getSlot(V);
424 if (Slot >= 0) Out << "%" << Slot;
426 Out << "<badref>"; // Not embedded into a location?
433 // WriteAsOperand - Write the name of the specified value out to the specified
434 // ostream. This can be useful when you just want to print int %reg126, not the
435 // whole instruction that generated it.
437 std::ostream &llvm::WriteAsOperand(std::ostream &Out, const Value *V,
439 bool PrintName, const Module *Context) {
440 std::map<const Type *, std::string> TypeNames;
441 if (Context == 0) Context = getModuleFromVal(V);
444 fillTypeNameTable(Context, TypeNames);
447 printTypeInt(Out, V->getType(), TypeNames);
449 if (const Type *Ty = dyn_cast<Type> (V))
450 printTypeInt(Out, Ty, TypeNames);
452 WriteAsOperandInternal(Out, V, PrintName, TypeNames, 0);
458 class AssemblyWriter {
460 SlotCalculator &Table;
461 const Module *TheModule;
462 std::map<const Type *, std::string> TypeNames;
463 AssemblyAnnotationWriter *AnnotationWriter;
465 inline AssemblyWriter(std::ostream &o, SlotCalculator &Tab, const Module *M,
466 AssemblyAnnotationWriter *AAW)
467 : Out(o), Table(Tab), TheModule(M), AnnotationWriter(AAW) {
469 // If the module has a symbol table, take all global types and stuff their
470 // names into the TypeNames map.
472 fillTypeNameTable(M, TypeNames);
475 inline void write(const Module *M) { printModule(M); }
476 inline void write(const GlobalVariable *G) { printGlobal(G); }
477 inline void write(const Function *F) { printFunction(F); }
478 inline void write(const BasicBlock *BB) { printBasicBlock(BB); }
479 inline void write(const Instruction *I) { printInstruction(*I); }
480 inline void write(const Constant *CPV) { printConstant(CPV); }
481 inline void write(const Type *Ty) { printType(Ty); }
483 void writeOperand(const Value *Op, bool PrintType, bool PrintName = true);
486 void printModule(const Module *M);
487 void printSymbolTable(const SymbolTable &ST);
488 void printConstant(const Constant *CPV);
489 void printGlobal(const GlobalVariable *GV);
490 void printFunction(const Function *F);
491 void printArgument(const Argument *FA);
492 void printBasicBlock(const BasicBlock *BB);
493 void printInstruction(const Instruction &I);
495 // printType - Go to extreme measures to attempt to print out a short,
496 // symbolic version of a type name.
498 std::ostream &printType(const Type *Ty) {
499 return printTypeInt(Out, Ty, TypeNames);
502 // printTypeAtLeastOneLevel - Print out one level of the possibly complex type
503 // without considering any symbolic types that we may have equal to it.
505 std::ostream &printTypeAtLeastOneLevel(const Type *Ty);
507 // printInfoComment - Print a little comment after the instruction indicating
508 // which slot it occupies.
509 void printInfoComment(const Value &V);
511 } // end of anonymous namespace
513 // printTypeAtLeastOneLevel - Print out one level of the possibly complex type
514 // without considering any symbolic types that we may have equal to it.
516 std::ostream &AssemblyWriter::printTypeAtLeastOneLevel(const Type *Ty) {
517 if (const FunctionType *FTy = dyn_cast<FunctionType>(Ty)) {
518 printType(FTy->getReturnType()) << " (";
519 for (FunctionType::param_iterator I = FTy->param_begin(),
520 E = FTy->param_end(); I != E; ++I) {
521 if (I != FTy->param_begin())
525 if (FTy->isVarArg()) {
526 if (FTy->getNumParams()) Out << ", ";
530 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
532 for (StructType::ElementTypes::const_iterator
533 I = STy->getElementTypes().begin(),
534 E = STy->getElementTypes().end(); I != E; ++I) {
535 if (I != STy->getElementTypes().begin())
540 } else if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
541 printType(PTy->getElementType()) << "*";
542 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
543 Out << "[" << ATy->getNumElements() << " x ";
544 printType(ATy->getElementType()) << "]";
545 } else if (const OpaqueType *OTy = dyn_cast<OpaqueType>(Ty)) {
548 if (!Ty->isPrimitiveType())
549 Out << "<unknown derived type>";
556 void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType,
558 if (PrintType) { Out << " "; printType(Operand->getType()); }
559 WriteAsOperandInternal(Out, Operand, PrintName, TypeNames, &Table);
563 void AssemblyWriter::printModule(const Module *M) {
564 switch (M->getEndianness()) {
565 case Module::LittleEndian: Out << "target endian = little\n"; break;
566 case Module::BigEndian: Out << "target endian = big\n"; break;
567 case Module::AnyEndianness: break;
569 switch (M->getPointerSize()) {
570 case Module::Pointer32: Out << "target pointersize = 32\n"; break;
571 case Module::Pointer64: Out << "target pointersize = 64\n"; break;
572 case Module::AnyPointerSize: break;
575 // Loop over the symbol table, emitting all named constants...
576 printSymbolTable(M->getSymbolTable());
578 for (Module::const_giterator I = M->gbegin(), E = M->gend(); I != E; ++I)
581 Out << "\nimplementation ; Functions:\n";
583 // Output all of the functions...
584 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
588 void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
589 if (GV->hasName()) Out << getLLVMName(GV->getName()) << " = ";
591 if (!GV->hasInitializer())
594 switch (GV->getLinkage()) {
595 case GlobalValue::InternalLinkage: Out << "internal "; break;
596 case GlobalValue::LinkOnceLinkage: Out << "linkonce "; break;
597 case GlobalValue::WeakLinkage: Out << "weak "; break;
598 case GlobalValue::AppendingLinkage: Out << "appending "; break;
599 case GlobalValue::ExternalLinkage: break;
602 Out << (GV->isConstant() ? "constant " : "global ");
603 printType(GV->getType()->getElementType());
605 if (GV->hasInitializer())
606 writeOperand(GV->getInitializer(), false, false);
608 printInfoComment(*GV);
613 // printSymbolTable - Run through symbol table looking for named constants
614 // if a named constant is found, emit it's declaration...
616 void AssemblyWriter::printSymbolTable(const SymbolTable &ST) {
617 for (SymbolTable::const_iterator TI = ST.begin(); TI != ST.end(); ++TI) {
618 SymbolTable::type_const_iterator I = ST.type_begin(TI->first);
619 SymbolTable::type_const_iterator End = ST.type_end(TI->first);
621 for (; I != End; ++I) {
622 const Value *V = I->second;
623 if (const Constant *CPV = dyn_cast<Constant>(V)) {
625 } else if (const Type *Ty = dyn_cast<Type>(V)) {
626 assert(Ty->getType() == Type::TypeTy && TI->first == Type::TypeTy);
627 Out << "\t" << getLLVMName(I->first) << " = type ";
629 // Make sure we print out at least one level of the type structure, so
630 // that we do not get %FILE = type %FILE
632 printTypeAtLeastOneLevel(Ty) << "\n";
639 // printConstant - Print out a constant pool entry...
641 void AssemblyWriter::printConstant(const Constant *CPV) {
642 // Don't print out unnamed constants, they will be inlined
643 if (!CPV->hasName()) return;
646 Out << "\t" << getLLVMName(CPV->getName()) << " =";
648 // Write the value out now...
649 writeOperand(CPV, true, false);
651 printInfoComment(*CPV);
655 // printFunction - Print all aspects of a function.
657 void AssemblyWriter::printFunction(const Function *F) {
658 // Print out the return type and name...
661 if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, Out);
666 switch (F->getLinkage()) {
667 case GlobalValue::InternalLinkage: Out << "internal "; break;
668 case GlobalValue::LinkOnceLinkage: Out << "linkonce "; break;
669 case GlobalValue::WeakLinkage: Out << "weak "; break;
670 case GlobalValue::AppendingLinkage: Out << "appending "; break;
671 case GlobalValue::ExternalLinkage: break;
674 printType(F->getReturnType()) << " ";
675 if (!F->getName().empty())
676 Out << getLLVMName(F->getName());
680 Table.incorporateFunction(F);
682 // Loop over the arguments, printing them...
683 const FunctionType *FT = F->getFunctionType();
685 for(Function::const_aiterator I = F->abegin(), E = F->aend(); I != E; ++I)
688 // Finish printing arguments...
689 if (FT->isVarArg()) {
690 if (FT->getNumParams()) Out << ", ";
691 Out << "..."; // Output varargs portion of signature!
695 if (F->isExternal()) {
700 // Output all of its basic blocks... for the function
701 for (Function::const_iterator I = F->begin(), E = F->end(); I != E; ++I)
707 Table.purgeFunction();
710 // printArgument - This member is called for every argument that
711 // is passed into the function. Simply print it out
713 void AssemblyWriter::printArgument(const Argument *Arg) {
714 // Insert commas as we go... the first arg doesn't get a comma
715 if (Arg != &Arg->getParent()->afront()) Out << ", ";
718 printType(Arg->getType());
720 // Output name, if available...
722 Out << " " << getLLVMName(Arg->getName());
723 else if (Table.getSlot(Arg) < 0)
727 // printBasicBlock - This member is called for each basic block in a method.
729 void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {
730 if (BB->hasName()) { // Print out the label if it exists...
731 Out << "\n" << BB->getName() << ":";
732 } else if (!BB->use_empty()) { // Don't print block # of no uses...
733 int Slot = Table.getSlot(BB);
734 Out << "\n; <label>:";
736 Out << Slot; // Extra newline separates out label's
741 if (BB->getParent() == 0)
742 Out << "\t\t; Error: Block without parent!";
744 if (BB != &BB->getParent()->front()) { // Not the entry block?
745 // Output predecessors for the block...
747 pred_const_iterator PI = pred_begin(BB), PE = pred_end(BB);
750 Out << " No predecessors!";
753 writeOperand(*PI, false, true);
754 for (++PI; PI != PE; ++PI) {
756 writeOperand(*PI, false, true);
764 if (AnnotationWriter) AnnotationWriter->emitBasicBlockAnnot(BB, Out);
766 // Output all of the instructions in the basic block...
767 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
768 printInstruction(*I);
772 // printInfoComment - Print a little comment after the instruction indicating
773 // which slot it occupies.
775 void AssemblyWriter::printInfoComment(const Value &V) {
776 if (V.getType() != Type::VoidTy) {
778 printType(V.getType()) << ">";
781 int Slot = Table.getSlot(&V); // Print out the def slot taken...
782 if (Slot >= 0) Out << ":" << Slot;
783 else Out << ":<badref>";
785 Out << " [#uses=" << V.use_size() << "]"; // Output # uses
789 // printInstruction - This member is called for each Instruction in a method.
791 void AssemblyWriter::printInstruction(const Instruction &I) {
792 if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, Out);
796 // Print out name if it exists...
798 Out << getLLVMName(I.getName()) << " = ";
800 // If this is a volatile load or store, print out the volatile marker
801 if ((isa<LoadInst>(I) && cast<LoadInst>(I).isVolatile()) ||
802 (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile()))
805 // Print out the opcode...
806 Out << I.getOpcodeName();
808 // Print out the type of the operands...
809 const Value *Operand = I.getNumOperands() ? I.getOperand(0) : 0;
811 // Special case conditional branches to swizzle the condition out to the front
812 if (isa<BranchInst>(I) && I.getNumOperands() > 1) {
813 writeOperand(I.getOperand(2), true);
815 writeOperand(Operand, true);
817 writeOperand(I.getOperand(1), true);
819 } else if (isa<SwitchInst>(I)) {
820 // Special case switch statement to get formatting nice and correct...
821 writeOperand(Operand , true); Out << ",";
822 writeOperand(I.getOperand(1), true); Out << " [";
824 for (unsigned op = 2, Eop = I.getNumOperands(); op < Eop; op += 2) {
826 writeOperand(I.getOperand(op ), true); Out << ",";
827 writeOperand(I.getOperand(op+1), true);
830 } else if (isa<PHINode>(I)) {
832 printType(I.getType());
835 for (unsigned op = 0, Eop = I.getNumOperands(); op < Eop; op += 2) {
838 writeOperand(I.getOperand(op ), false); Out << ",";
839 writeOperand(I.getOperand(op+1), false); Out << " ]";
841 } else if (isa<ReturnInst>(I) && !Operand) {
843 } else if (isa<CallInst>(I)) {
844 const PointerType *PTy = cast<PointerType>(Operand->getType());
845 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
846 const Type *RetTy = FTy->getReturnType();
848 // If possible, print out the short form of the call instruction. We can
849 // only do this if the first argument is a pointer to a nonvararg function,
850 // and if the return type is not a pointer to a function.
852 if (!FTy->isVarArg() &&
853 (!isa<PointerType>(RetTy) ||
854 !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
855 Out << " "; printType(RetTy);
856 writeOperand(Operand, false);
858 writeOperand(Operand, true);
861 if (I.getNumOperands() > 1) writeOperand(I.getOperand(1), true);
862 for (unsigned op = 2, Eop = I.getNumOperands(); op < Eop; ++op) {
864 writeOperand(I.getOperand(op), true);
868 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
869 const PointerType *PTy = cast<PointerType>(Operand->getType());
870 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
871 const Type *RetTy = FTy->getReturnType();
873 // If possible, print out the short form of the invoke instruction. We can
874 // only do this if the first argument is a pointer to a nonvararg function,
875 // and if the return type is not a pointer to a function.
877 if (!FTy->isVarArg() &&
878 (!isa<PointerType>(RetTy) ||
879 !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
880 Out << " "; printType(RetTy);
881 writeOperand(Operand, false);
883 writeOperand(Operand, true);
887 if (I.getNumOperands() > 3) writeOperand(I.getOperand(3), true);
888 for (unsigned op = 4, Eop = I.getNumOperands(); op < Eop; ++op) {
890 writeOperand(I.getOperand(op), true);
893 Out << " )\n\t\t\tto";
894 writeOperand(II->getNormalDest(), true);
896 writeOperand(II->getUnwindDest(), true);
898 } else if (const AllocationInst *AI = dyn_cast<AllocationInst>(&I)) {
900 printType(AI->getType()->getElementType());
901 if (AI->isArrayAllocation()) {
903 writeOperand(AI->getArraySize(), true);
905 } else if (isa<CastInst>(I)) {
906 if (Operand) writeOperand(Operand, true); // Work with broken code
908 printType(I.getType());
909 } else if (isa<VAArgInst>(I)) {
910 if (Operand) writeOperand(Operand, true); // Work with broken code
912 printType(I.getType());
913 } else if (const VANextInst *VAN = dyn_cast<VANextInst>(&I)) {
914 if (Operand) writeOperand(Operand, true); // Work with broken code
916 printType(VAN->getArgType());
917 } else if (Operand) { // Print the normal way...
919 // PrintAllTypes - Instructions who have operands of all the same type
920 // omit the type from all but the first operand. If the instruction has
921 // different type operands (for example br), then they are all printed.
922 bool PrintAllTypes = false;
923 const Type *TheType = Operand->getType();
925 // Shift Left & Right print both types even for Ubyte LHS
926 if (isa<ShiftInst>(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 void Value::dump() const { print(std::cerr); }
1020 //===----------------------------------------------------------------------===//
1021 // CachedWriter Class Implementation
1022 //===----------------------------------------------------------------------===//
1024 void CachedWriter::setModule(const Module *M) {
1025 delete SC; delete AW;
1027 SC = new SlotCalculator(M, false);
1028 AW = new AssemblyWriter(Out, *SC, M, 0);
1034 CachedWriter::~CachedWriter() {
1039 CachedWriter &CachedWriter::operator<<(const Value *V) {
1040 assert(AW && SC && "CachedWriter does not have a current module!");
1041 switch (V->getValueType()) {
1042 case Value::ConstantVal:
1043 case Value::ArgumentVal: AW->writeOperand(V, true, true); break;
1044 case Value::TypeVal: AW->write(cast<Type>(V)); break;
1045 case Value::InstructionVal: AW->write(cast<Instruction>(V)); break;
1046 case Value::BasicBlockVal: AW->write(cast<BasicBlock>(V)); break;
1047 case Value::FunctionVal: AW->write(cast<Function>(V)); break;
1048 case Value::GlobalVariableVal: AW->write(cast<GlobalVariable>(V)); break;
1049 default: Out << "<unknown value type: " << V->getValueType() << ">"; break;