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::ParamTypes::const_iterator
157 I = FTy->getParamTypes().begin(),
158 E = FTy->getParamTypes().end(); I != E; ++I) {
159 if (I != FTy->getParamTypes().begin())
161 Result += calcTypeName(*I, TypeStack, TypeNames);
163 if (FTy->isVarArg()) {
164 if (!FTy->getParamTypes().empty()) Result += ", ";
170 case Type::StructTyID: {
171 const StructType *STy = cast<StructType>(Ty);
173 for (StructType::ElementTypes::const_iterator
174 I = STy->getElementTypes().begin(),
175 E = STy->getElementTypes().end(); I != E; ++I) {
176 if (I != STy->getElementTypes().begin())
178 Result += calcTypeName(*I, TypeStack, TypeNames);
183 case Type::PointerTyID:
184 Result = calcTypeName(cast<PointerType>(Ty)->getElementType(),
185 TypeStack, TypeNames) + "*";
187 case Type::ArrayTyID: {
188 const ArrayType *ATy = cast<ArrayType>(Ty);
189 Result = "[" + utostr(ATy->getNumElements()) + " x ";
190 Result += calcTypeName(ATy->getElementType(), TypeStack, TypeNames) + "]";
193 case Type::OpaqueTyID:
197 Result = "<unrecognized-type>";
200 TypeStack.pop_back(); // Remove self from stack...
205 // printTypeInt - The internal guts of printing out a type that has a
206 // potentially named portion.
208 static std::ostream &printTypeInt(std::ostream &Out, const Type *Ty,
209 std::map<const Type *, std::string> &TypeNames) {
210 // Primitive types always print out their description, regardless of whether
211 // they have been named or not.
213 if (Ty->isPrimitiveType() && !isa<OpaqueType>(Ty))
214 return Out << Ty->getDescription();
216 // Check to see if the type is named.
217 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
218 if (I != TypeNames.end()) return Out << I->second;
220 // Otherwise we have a type that has not been named but is a derived type.
221 // Carefully recurse the type hierarchy to print out any contained symbolic
224 std::vector<const Type *> TypeStack;
225 std::string TypeName = calcTypeName(Ty, TypeStack, TypeNames);
226 TypeNames.insert(std::make_pair(Ty, TypeName));//Cache type name for later use
227 return Out << TypeName;
231 // WriteTypeSymbolic - This attempts to write the specified type as a symbolic
232 // type, iff there is an entry in the modules symbol table for the specified
233 // type or one of it's component types. This is slower than a simple x << Type;
235 std::ostream &llvm::WriteTypeSymbolic(std::ostream &Out, const Type *Ty,
239 // If they want us to print out a type, attempt to make it symbolic if there
240 // is a symbol table in the module...
242 std::map<const Type *, std::string> TypeNames;
243 fillTypeNameTable(M, TypeNames);
245 return printTypeInt(Out, Ty, TypeNames);
247 return Out << Ty->getDescription();
251 static void WriteConstantInt(std::ostream &Out, const Constant *CV,
253 std::map<const Type *, std::string> &TypeTable,
254 SlotCalculator *Table) {
255 if (const ConstantBool *CB = dyn_cast<ConstantBool>(CV)) {
256 Out << (CB == ConstantBool::True ? "true" : "false");
257 } else if (const ConstantSInt *CI = dyn_cast<ConstantSInt>(CV)) {
258 Out << CI->getValue();
259 } else if (const ConstantUInt *CI = dyn_cast<ConstantUInt>(CV)) {
260 Out << CI->getValue();
261 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
262 // We would like to output the FP constant value in exponential notation,
263 // but we cannot do this if doing so will lose precision. Check here to
264 // make sure that we only output it in exponential format if we can parse
265 // the value back and get the same value.
267 std::string StrVal = ftostr(CFP->getValue());
269 // Check to make sure that the stringized number is not some string like
270 // "Inf" or NaN, that atof will accept, but the lexer will not. Check that
271 // the string matches the "[-+]?[0-9]" regex.
273 if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
274 ((StrVal[0] == '-' || StrVal[0] == '+') &&
275 (StrVal[1] >= '0' && StrVal[1] <= '9')))
276 // Reparse stringized version!
277 if (atof(StrVal.c_str()) == CFP->getValue()) {
278 Out << StrVal; return;
281 // Otherwise we could not reparse it to exactly the same value, so we must
282 // output the string in hexadecimal format!
284 // Behave nicely in the face of C TBAA rules... see:
285 // http://www.nullstone.com/htmls/category/aliastyp.htm
287 double Val = CFP->getValue();
288 char *Ptr = (char*)&Val;
289 assert(sizeof(double) == sizeof(uint64_t) && sizeof(double) == 8 &&
290 "assuming that double is 64 bits!");
291 Out << "0x" << utohexstr(*(uint64_t*)Ptr);
293 } else if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
294 if (CA->getNumOperands() > 5 && CA->isNullValue()) {
295 Out << "zeroinitializer";
299 // As a special case, print the array as a string if it is an array of
300 // ubytes or an array of sbytes with positive values.
302 const Type *ETy = CA->getType()->getElementType();
303 bool isString = (ETy == Type::SByteTy || ETy == Type::UByteTy);
305 if (ETy == Type::SByteTy)
306 for (unsigned i = 0; i < CA->getNumOperands(); ++i)
307 if (cast<ConstantSInt>(CA->getOperand(i))->getValue() < 0) {
314 for (unsigned i = 0; i < CA->getNumOperands(); ++i) {
315 unsigned char C = cast<ConstantInt>(CA->getOperand(i))->getRawValue();
317 if (isprint(C) && C != '"' && C != '\\') {
321 << (char) ((C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A'))
322 << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
327 } else { // Cannot output in string format...
329 if (CA->getNumOperands()) {
331 printTypeInt(Out, ETy, TypeTable);
332 WriteAsOperandInternal(Out, CA->getOperand(0),
333 PrintName, TypeTable, Table);
334 for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
336 printTypeInt(Out, ETy, TypeTable);
337 WriteAsOperandInternal(Out, CA->getOperand(i), PrintName,
343 } else if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
344 if (CS->getNumOperands() > 5 && CS->isNullValue()) {
345 Out << "zeroinitializer";
350 if (CS->getNumOperands()) {
352 printTypeInt(Out, CS->getOperand(0)->getType(), TypeTable);
354 WriteAsOperandInternal(Out, CS->getOperand(0),
355 PrintName, TypeTable, Table);
357 for (unsigned i = 1; i < CS->getNumOperands(); i++) {
359 printTypeInt(Out, CS->getOperand(i)->getType(), TypeTable);
361 WriteAsOperandInternal(Out, CS->getOperand(i),
362 PrintName, TypeTable, Table);
367 } else if (isa<ConstantPointerNull>(CV)) {
370 } else if (const ConstantPointerRef *PR = dyn_cast<ConstantPointerRef>(CV)) {
371 WriteAsOperandInternal(Out, PR->getValue(), true, TypeTable, Table);
373 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
374 Out << CE->getOpcodeName() << " (";
376 for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) {
377 printTypeInt(Out, (*OI)->getType(), TypeTable);
378 WriteAsOperandInternal(Out, *OI, PrintName, TypeTable, Table);
379 if (OI+1 != CE->op_end())
383 if (CE->getOpcode() == Instruction::Cast) {
385 printTypeInt(Out, CE->getType(), TypeTable);
390 Out << "<placeholder or erroneous Constant>";
395 // WriteAsOperand - Write the name of the specified value out to the specified
396 // ostream. This can be useful when you just want to print int %reg126, not the
397 // whole instruction that generated it.
399 static void WriteAsOperandInternal(std::ostream &Out, const Value *V,
401 std::map<const Type*, std::string> &TypeTable,
402 SlotCalculator *Table) {
404 if (PrintName && V->hasName()) {
405 Out << getLLVMName(V->getName());
407 if (const Constant *CV = dyn_cast<Constant>(V)) {
408 WriteConstantInt(Out, CV, PrintName, TypeTable, Table);
412 Slot = Table->getSlot(V);
414 if (const Type *Ty = dyn_cast<Type>(V)) {
415 Out << Ty->getDescription();
419 Table = createSlotCalculator(V);
420 if (Table == 0) { Out << "BAD VALUE TYPE!"; return; }
422 Slot = Table->getSlot(V);
425 if (Slot >= 0) Out << "%" << Slot;
427 Out << "<badref>"; // Not embedded into a location?
434 // WriteAsOperand - Write the name of the specified value out to the specified
435 // ostream. This can be useful when you just want to print int %reg126, not the
436 // whole instruction that generated it.
438 std::ostream &llvm::WriteAsOperand(std::ostream &Out, const Value *V,
440 bool PrintName, const Module *Context) {
441 std::map<const Type *, std::string> TypeNames;
442 if (Context == 0) Context = getModuleFromVal(V);
445 fillTypeNameTable(Context, TypeNames);
448 printTypeInt(Out, V->getType(), TypeNames);
450 if (const Type *Ty = dyn_cast<Type> (V))
451 printTypeInt(Out, Ty, TypeNames);
453 WriteAsOperandInternal(Out, V, PrintName, TypeNames, 0);
459 class AssemblyWriter {
461 SlotCalculator &Table;
462 const Module *TheModule;
463 std::map<const Type *, std::string> TypeNames;
464 AssemblyAnnotationWriter *AnnotationWriter;
466 inline AssemblyWriter(std::ostream &o, SlotCalculator &Tab, const Module *M,
467 AssemblyAnnotationWriter *AAW)
468 : Out(o), Table(Tab), TheModule(M), AnnotationWriter(AAW) {
470 // If the module has a symbol table, take all global types and stuff their
471 // names into the TypeNames map.
473 fillTypeNameTable(M, TypeNames);
476 inline void write(const Module *M) { printModule(M); }
477 inline void write(const GlobalVariable *G) { printGlobal(G); }
478 inline void write(const Function *F) { printFunction(F); }
479 inline void write(const BasicBlock *BB) { printBasicBlock(BB); }
480 inline void write(const Instruction *I) { printInstruction(*I); }
481 inline void write(const Constant *CPV) { printConstant(CPV); }
482 inline void write(const Type *Ty) { printType(Ty); }
484 void writeOperand(const Value *Op, bool PrintType, bool PrintName = true);
487 void printModule(const Module *M);
488 void printSymbolTable(const SymbolTable &ST);
489 void printConstant(const Constant *CPV);
490 void printGlobal(const GlobalVariable *GV);
491 void printFunction(const Function *F);
492 void printArgument(const Argument *FA);
493 void printBasicBlock(const BasicBlock *BB);
494 void printInstruction(const Instruction &I);
496 // printType - Go to extreme measures to attempt to print out a short,
497 // symbolic version of a type name.
499 std::ostream &printType(const Type *Ty) {
500 return printTypeInt(Out, Ty, TypeNames);
503 // printTypeAtLeastOneLevel - Print out one level of the possibly complex type
504 // without considering any symbolic types that we may have equal to it.
506 std::ostream &printTypeAtLeastOneLevel(const Type *Ty);
508 // printInfoComment - Print a little comment after the instruction indicating
509 // which slot it occupies.
510 void printInfoComment(const Value &V);
512 } // end of anonymous namespace
514 // printTypeAtLeastOneLevel - Print out one level of the possibly complex type
515 // without considering any symbolic types that we may have equal to it.
517 std::ostream &AssemblyWriter::printTypeAtLeastOneLevel(const Type *Ty) {
518 if (const FunctionType *FTy = dyn_cast<FunctionType>(Ty)) {
519 printType(FTy->getReturnType()) << " (";
520 for (FunctionType::ParamTypes::const_iterator
521 I = FTy->getParamTypes().begin(),
522 E = FTy->getParamTypes().end(); I != E; ++I) {
523 if (I != FTy->getParamTypes().begin())
527 if (FTy->isVarArg()) {
528 if (!FTy->getParamTypes().empty()) Out << ", ";
532 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
534 for (StructType::ElementTypes::const_iterator
535 I = STy->getElementTypes().begin(),
536 E = STy->getElementTypes().end(); I != E; ++I) {
537 if (I != STy->getElementTypes().begin())
542 } else if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
543 printType(PTy->getElementType()) << "*";
544 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
545 Out << "[" << ATy->getNumElements() << " x ";
546 printType(ATy->getElementType()) << "]";
547 } else if (const OpaqueType *OTy = dyn_cast<OpaqueType>(Ty)) {
550 if (!Ty->isPrimitiveType())
551 Out << "<unknown derived type>";
558 void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType,
560 if (PrintType) { Out << " "; printType(Operand->getType()); }
561 WriteAsOperandInternal(Out, Operand, PrintName, TypeNames, &Table);
565 void AssemblyWriter::printModule(const Module *M) {
566 switch (M->getEndianness()) {
567 case Module::LittleEndian: Out << "target endian = little\n"; break;
568 case Module::BigEndian: Out << "target endian = big\n"; break;
569 case Module::AnyEndianness: break;
571 switch (M->getPointerSize()) {
572 case Module::Pointer32: Out << "target pointersize = 32\n"; break;
573 case Module::Pointer64: Out << "target pointersize = 64\n"; break;
574 case Module::AnyPointerSize: break;
577 // Loop over the symbol table, emitting all named constants...
578 printSymbolTable(M->getSymbolTable());
580 for (Module::const_giterator I = M->gbegin(), E = M->gend(); I != E; ++I)
583 Out << "\nimplementation ; Functions:\n";
585 // Output all of the functions...
586 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
590 void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
591 if (GV->hasName()) Out << getLLVMName(GV->getName()) << " = ";
593 if (!GV->hasInitializer())
596 switch (GV->getLinkage()) {
597 case GlobalValue::InternalLinkage: Out << "internal "; break;
598 case GlobalValue::LinkOnceLinkage: Out << "linkonce "; break;
599 case GlobalValue::WeakLinkage: Out << "weak "; break;
600 case GlobalValue::AppendingLinkage: Out << "appending "; break;
601 case GlobalValue::ExternalLinkage: break;
604 Out << (GV->isConstant() ? "constant " : "global ");
605 printType(GV->getType()->getElementType());
607 if (GV->hasInitializer())
608 writeOperand(GV->getInitializer(), false, false);
610 printInfoComment(*GV);
615 // printSymbolTable - Run through symbol table looking for named constants
616 // if a named constant is found, emit it's declaration...
618 void AssemblyWriter::printSymbolTable(const SymbolTable &ST) {
619 for (SymbolTable::const_iterator TI = ST.begin(); TI != ST.end(); ++TI) {
620 SymbolTable::type_const_iterator I = ST.type_begin(TI->first);
621 SymbolTable::type_const_iterator End = ST.type_end(TI->first);
623 for (; I != End; ++I) {
624 const Value *V = I->second;
625 if (const Constant *CPV = dyn_cast<Constant>(V)) {
627 } else if (const Type *Ty = dyn_cast<Type>(V)) {
628 assert(Ty->getType() == Type::TypeTy && TI->first == Type::TypeTy);
629 Out << "\t" << getLLVMName(I->first) << " = type ";
631 // Make sure we print out at least one level of the type structure, so
632 // that we do not get %FILE = type %FILE
634 printTypeAtLeastOneLevel(Ty) << "\n";
641 // printConstant - Print out a constant pool entry...
643 void AssemblyWriter::printConstant(const Constant *CPV) {
644 // Don't print out unnamed constants, they will be inlined
645 if (!CPV->hasName()) return;
648 Out << "\t" << getLLVMName(CPV->getName()) << " =";
650 // Write the value out now...
651 writeOperand(CPV, true, false);
653 printInfoComment(*CPV);
657 // printFunction - Print all aspects of a function.
659 void AssemblyWriter::printFunction(const Function *F) {
660 // Print out the return type and name...
663 if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, Out);
668 switch (F->getLinkage()) {
669 case GlobalValue::InternalLinkage: Out << "internal "; break;
670 case GlobalValue::LinkOnceLinkage: Out << "linkonce "; break;
671 case GlobalValue::WeakLinkage: Out << "weak "; break;
672 case GlobalValue::AppendingLinkage: Out << "appending "; break;
673 case GlobalValue::ExternalLinkage: break;
676 printType(F->getReturnType()) << " ";
677 if (!F->getName().empty())
678 Out << getLLVMName(F->getName());
682 Table.incorporateFunction(F);
684 // Loop over the arguments, printing them...
685 const FunctionType *FT = F->getFunctionType();
687 for(Function::const_aiterator I = F->abegin(), E = F->aend(); I != E; ++I)
690 // Finish printing arguments...
691 if (FT->isVarArg()) {
692 if (FT->getParamTypes().size()) Out << ", ";
693 Out << "..."; // Output varargs portion of signature!
697 if (F->isExternal()) {
702 // Output all of its basic blocks... for the function
703 for (Function::const_iterator I = F->begin(), E = F->end(); I != E; ++I)
709 Table.purgeFunction();
712 // printArgument - This member is called for every argument that
713 // is passed into the function. Simply print it out
715 void AssemblyWriter::printArgument(const Argument *Arg) {
716 // Insert commas as we go... the first arg doesn't get a comma
717 if (Arg != &Arg->getParent()->afront()) Out << ", ";
720 printType(Arg->getType());
722 // Output name, if available...
724 Out << " " << getLLVMName(Arg->getName());
725 else if (Table.getSlot(Arg) < 0)
729 // printBasicBlock - This member is called for each basic block in a method.
731 void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {
732 if (BB->hasName()) { // Print out the label if it exists...
733 Out << "\n" << BB->getName() << ":";
734 } else if (!BB->use_empty()) { // Don't print block # of no uses...
735 int Slot = Table.getSlot(BB);
736 Out << "\n; <label>:";
738 Out << Slot; // Extra newline separates out label's
743 if (BB->getParent() == 0)
744 Out << "\t\t; Error: Block without parent!";
746 if (BB != &BB->getParent()->front()) { // Not the entry block?
747 // Output predecessors for the block...
749 pred_const_iterator PI = pred_begin(BB), PE = pred_end(BB);
752 Out << " No predecessors!";
755 writeOperand(*PI, false, true);
756 for (++PI; PI != PE; ++PI) {
758 writeOperand(*PI, false, true);
766 if (AnnotationWriter) AnnotationWriter->emitBasicBlockAnnot(BB, Out);
768 // Output all of the instructions in the basic block...
769 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
770 printInstruction(*I);
774 // printInfoComment - Print a little comment after the instruction indicating
775 // which slot it occupies.
777 void AssemblyWriter::printInfoComment(const Value &V) {
778 if (V.getType() != Type::VoidTy) {
780 printType(V.getType()) << ">";
783 int Slot = Table.getSlot(&V); // Print out the def slot taken...
784 if (Slot >= 0) Out << ":" << Slot;
785 else Out << ":<badref>";
787 Out << " [#uses=" << V.use_size() << "]"; // Output # uses
791 // printInstruction - This member is called for each Instruction in a method.
793 void AssemblyWriter::printInstruction(const Instruction &I) {
794 if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, Out);
798 // Print out name if it exists...
800 Out << getLLVMName(I.getName()) << " = ";
802 // If this is a volatile load or store, print out the volatile marker
803 if ((isa<LoadInst>(I) && cast<LoadInst>(I).isVolatile()) ||
804 (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile()))
807 // Print out the opcode...
808 Out << I.getOpcodeName();
810 // Print out the type of the operands...
811 const Value *Operand = I.getNumOperands() ? I.getOperand(0) : 0;
813 // Special case conditional branches to swizzle the condition out to the front
814 if (isa<BranchInst>(I) && I.getNumOperands() > 1) {
815 writeOperand(I.getOperand(2), true);
817 writeOperand(Operand, true);
819 writeOperand(I.getOperand(1), true);
821 } else if (isa<SwitchInst>(I)) {
822 // Special case switch statement to get formatting nice and correct...
823 writeOperand(Operand , true); Out << ",";
824 writeOperand(I.getOperand(1), true); Out << " [";
826 for (unsigned op = 2, Eop = I.getNumOperands(); op < Eop; op += 2) {
828 writeOperand(I.getOperand(op ), true); Out << ",";
829 writeOperand(I.getOperand(op+1), true);
832 } else if (isa<PHINode>(I)) {
834 printType(I.getType());
837 for (unsigned op = 0, Eop = I.getNumOperands(); op < Eop; op += 2) {
840 writeOperand(I.getOperand(op ), false); Out << ",";
841 writeOperand(I.getOperand(op+1), false); Out << " ]";
843 } else if (isa<ReturnInst>(I) && !Operand) {
845 } else if (isa<CallInst>(I)) {
846 const PointerType *PTy = cast<PointerType>(Operand->getType());
847 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
848 const Type *RetTy = FTy->getReturnType();
850 // If possible, print out the short form of the call instruction. We can
851 // only do this if the first argument is a pointer to a nonvararg function,
852 // and if the return type is not a pointer to a function.
854 if (!FTy->isVarArg() &&
855 (!isa<PointerType>(RetTy) ||
856 !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
857 Out << " "; printType(RetTy);
858 writeOperand(Operand, false);
860 writeOperand(Operand, true);
863 if (I.getNumOperands() > 1) writeOperand(I.getOperand(1), true);
864 for (unsigned op = 2, Eop = I.getNumOperands(); op < Eop; ++op) {
866 writeOperand(I.getOperand(op), true);
870 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
871 const PointerType *PTy = cast<PointerType>(Operand->getType());
872 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
873 const Type *RetTy = FTy->getReturnType();
875 // If possible, print out the short form of the invoke instruction. We can
876 // only do this if the first argument is a pointer to a nonvararg function,
877 // and if the return type is not a pointer to a function.
879 if (!FTy->isVarArg() &&
880 (!isa<PointerType>(RetTy) ||
881 !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
882 Out << " "; printType(RetTy);
883 writeOperand(Operand, false);
885 writeOperand(Operand, true);
889 if (I.getNumOperands() > 3) writeOperand(I.getOperand(3), true);
890 for (unsigned op = 4, Eop = I.getNumOperands(); op < Eop; ++op) {
892 writeOperand(I.getOperand(op), true);
895 Out << " )\n\t\t\tto";
896 writeOperand(II->getNormalDest(), true);
898 writeOperand(II->getUnwindDest(), true);
900 } else if (const AllocationInst *AI = dyn_cast<AllocationInst>(&I)) {
902 printType(AI->getType()->getElementType());
903 if (AI->isArrayAllocation()) {
905 writeOperand(AI->getArraySize(), true);
907 } else if (isa<CastInst>(I)) {
908 if (Operand) writeOperand(Operand, true); // Work with broken code
910 printType(I.getType());
911 } else if (isa<VAArgInst>(I)) {
912 if (Operand) writeOperand(Operand, true); // Work with broken code
914 printType(I.getType());
915 } else if (const VANextInst *VAN = dyn_cast<VANextInst>(&I)) {
916 if (Operand) writeOperand(Operand, true); // Work with broken code
918 printType(VAN->getArgType());
919 } else if (Operand) { // Print the normal way...
921 // PrintAllTypes - Instructions who have operands of all the same type
922 // omit the type from all but the first operand. If the instruction has
923 // different type operands (for example br), then they are all printed.
924 bool PrintAllTypes = false;
925 const Type *TheType = Operand->getType();
927 // Shift Left & Right print both types even for Ubyte LHS
928 if (isa<ShiftInst>(I)) {
929 PrintAllTypes = true;
931 for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) {
932 Operand = I.getOperand(i);
933 if (Operand->getType() != TheType) {
934 PrintAllTypes = true; // We have differing types! Print them all!
940 if (!PrintAllTypes) {
945 for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) {
947 writeOperand(I.getOperand(i), PrintAllTypes);
956 //===----------------------------------------------------------------------===//
957 // External Interface declarations
958 //===----------------------------------------------------------------------===//
960 void Module::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
961 SlotCalculator SlotTable(this, false);
962 AssemblyWriter W(o, SlotTable, this, AAW);
966 void GlobalVariable::print(std::ostream &o) const {
967 SlotCalculator SlotTable(getParent(), false);
968 AssemblyWriter W(o, SlotTable, getParent(), 0);
972 void Function::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
973 SlotCalculator SlotTable(getParent(), false);
974 AssemblyWriter W(o, SlotTable, getParent(), AAW);
979 void BasicBlock::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
980 SlotCalculator SlotTable(getParent(), false);
981 AssemblyWriter W(o, SlotTable,
982 getParent() ? getParent()->getParent() : 0, AAW);
986 void Instruction::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
987 const Function *F = getParent() ? getParent()->getParent() : 0;
988 SlotCalculator SlotTable(F, false);
989 AssemblyWriter W(o, SlotTable, F ? F->getParent() : 0, AAW);
994 void Constant::print(std::ostream &o) const {
995 if (this == 0) { o << "<null> constant value\n"; return; }
997 // Handle CPR's special, because they have context information...
998 if (const ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(this)) {
999 CPR->getValue()->print(o); // Print as a global value, with context info.
1003 o << " " << getType()->getDescription() << " ";
1005 std::map<const Type *, std::string> TypeTable;
1006 WriteConstantInt(o, this, false, TypeTable, 0);
1009 void Type::print(std::ostream &o) const {
1013 o << getDescription();
1016 void Argument::print(std::ostream &o) const {
1017 o << getType() << " " << getName();
1020 void Value::dump() const { print(std::cerr); }
1022 //===----------------------------------------------------------------------===//
1023 // CachedWriter Class Implementation
1024 //===----------------------------------------------------------------------===//
1026 void CachedWriter::setModule(const Module *M) {
1027 delete SC; delete AW;
1029 SC = new SlotCalculator(M, false);
1030 AW = new AssemblyWriter(Out, *SC, M, 0);
1036 CachedWriter::~CachedWriter() {
1041 CachedWriter &CachedWriter::operator<<(const Value *V) {
1042 assert(AW && SC && "CachedWriter does not have a current module!");
1043 switch (V->getValueType()) {
1044 case Value::ConstantVal:
1045 case Value::ArgumentVal: AW->writeOperand(V, true, true); break;
1046 case Value::TypeVal: AW->write(cast<Type>(V)); break;
1047 case Value::InstructionVal: AW->write(cast<Instruction>(V)); break;
1048 case Value::BasicBlockVal: AW->write(cast<BasicBlock>(V)); break;
1049 case Value::FunctionVal: AW->write(cast<Function>(V)); break;
1050 case Value::GlobalVariableVal: AW->write(cast<GlobalVariable>(V)); break;
1051 default: Out << "<unknown value type: " << V->getValueType() << ">"; break;