1 //===-- AsmWriter.cpp - Printing LLVM as an assembly file -----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // 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/Writer.h"
18 #include "llvm/Assembly/PrintModulePass.h"
19 #include "llvm/Assembly/AsmAnnotationWriter.h"
20 #include "llvm/CallingConv.h"
21 #include "llvm/Constants.h"
22 #include "llvm/DerivedTypes.h"
23 #include "llvm/InlineAsm.h"
24 #include "llvm/Instruction.h"
25 #include "llvm/Instructions.h"
26 #include "llvm/Module.h"
27 #include "llvm/ValueSymbolTable.h"
28 #include "llvm/TypeSymbolTable.h"
29 #include "llvm/ADT/DenseMap.h"
30 #include "llvm/ADT/StringExtras.h"
31 #include "llvm/ADT/STLExtras.h"
32 #include "llvm/Support/CFG.h"
33 #include "llvm/Support/MathExtras.h"
34 #include "llvm/Support/raw_ostream.h"
39 // Make virtual table appear in this compilation unit.
40 AssemblyAnnotationWriter::~AssemblyAnnotationWriter() {}
42 char PrintModulePass::ID = 0;
43 static RegisterPass<PrintModulePass>
44 X("print-module", "Print module to stderr");
45 char PrintFunctionPass::ID = 0;
46 static RegisterPass<PrintFunctionPass>
47 Y("print-function","Print function to stderr");
50 //===----------------------------------------------------------------------===//
52 //===----------------------------------------------------------------------===//
54 static const Module *getModuleFromVal(const Value *V) {
55 if (const Argument *MA = dyn_cast<Argument>(V))
56 return MA->getParent() ? MA->getParent()->getParent() : 0;
58 if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
59 return BB->getParent() ? BB->getParent()->getParent() : 0;
61 if (const Instruction *I = dyn_cast<Instruction>(V)) {
62 const Function *M = I->getParent() ? I->getParent()->getParent() : 0;
63 return M ? M->getParent() : 0;
66 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
67 return GV->getParent();
72 /// NameNeedsQuotes - Return true if the specified llvm name should be wrapped
74 static std::string QuoteNameIfNeeded(const std::string &Name) {
76 bool needsQuotes = Name[0] >= '0' && Name[0] <= '9';
77 // Scan the name to see if it needs quotes and to replace funky chars with
78 // their octal equivalent.
79 for (unsigned i = 0, e = Name.size(); i != e; ++i) {
81 assert(C != '"' && "Illegal character in LLVM value name!");
82 if (isalnum(C) || C == '-' || C == '.' || C == '_')
87 } else if (isprint(C)) {
93 char hex1 = (C >> 4) & 0x0F;
97 result += hex1 - 10 + 'A';
100 result += hex2 + '0';
102 result += hex2 - 10 + 'A';
106 result.insert(0,"\"");
112 /// getLLVMName - Turn the specified string into an 'LLVM name', which is
113 /// surrounded with ""'s and escaped if it has special chars in it.
114 static std::string getLLVMName(const std::string &Name) {
115 assert(!Name.empty() && "Cannot get empty name!");
116 return QuoteNameIfNeeded(Name);
125 /// PrintLLVMName - Turn the specified name into an 'LLVM name', which is either
126 /// prefixed with % (if the string only contains simple characters) or is
127 /// surrounded with ""'s (if it has special chars in it). Print it out.
128 static void PrintLLVMName(raw_ostream &OS, const char *NameStr,
129 unsigned NameLen, PrefixType Prefix) {
130 assert(NameStr && "Cannot get empty name!");
132 default: assert(0 && "Bad prefix!");
133 case GlobalPrefix: OS << '@'; break;
134 case LabelPrefix: break;
135 case LocalPrefix: OS << '%'; break;
138 // Scan the name to see if it needs quotes first.
139 bool NeedsQuotes = NameStr[0] >= '0' && NameStr[0] <= '9';
141 for (unsigned i = 0; i != NameLen; ++i) {
143 if (!isalnum(C) && C != '-' && C != '.' && C != '_') {
150 // If we didn't need any quotes, just write out the name in one blast.
152 OS.write(NameStr, NameLen);
156 // Okay, we need quotes. Output the quotes and escape any scary characters as
159 for (unsigned i = 0; i != NameLen; ++i) {
161 assert(C != '"' && "Illegal character in LLVM value name!");
164 } else if (isprint(C)) {
168 char hex1 = (C >> 4) & 0x0F;
170 OS << (char)(hex1 + '0');
172 OS << (char)(hex1 - 10 + 'A');
173 char hex2 = C & 0x0F;
175 OS << (char)(hex2 + '0');
177 OS << (char)(hex2 - 10 + 'A');
183 /// PrintLLVMName - Turn the specified name into an 'LLVM name', which is either
184 /// prefixed with % (if the string only contains simple characters) or is
185 /// surrounded with ""'s (if it has special chars in it). Print it out.
186 static void PrintLLVMName(raw_ostream &OS, const Value *V) {
187 PrintLLVMName(OS, V->getNameStart(), V->getNameLen(),
188 isa<GlobalValue>(V) ? GlobalPrefix : LocalPrefix);
193 //===----------------------------------------------------------------------===//
194 // SlotTracker Class: Enumerate slot numbers for unnamed values
195 //===----------------------------------------------------------------------===//
199 /// This class provides computation of slot numbers for LLVM Assembly writing.
203 /// ValueMap - A mapping of Values to slot numbers
204 typedef DenseMap<const Value*, unsigned> ValueMap;
207 /// TheModule - The module for which we are holding slot numbers
208 const Module* TheModule;
210 /// TheFunction - The function for which we are holding slot numbers
211 const Function* TheFunction;
212 bool FunctionProcessed;
214 /// mMap - The TypePlanes map for the module level data
218 /// fMap - The TypePlanes map for the function level data
223 /// Construct from a module
224 explicit SlotTracker(const Module *M);
225 /// Construct from a function, starting out in incorp state.
226 explicit SlotTracker(const Function *F);
228 /// Return the slot number of the specified value in it's type
229 /// plane. If something is not in the SlotTracker, return -1.
230 int getLocalSlot(const Value *V);
231 int getGlobalSlot(const GlobalValue *V);
233 /// If you'd like to deal with a function instead of just a module, use
234 /// this method to get its data into the SlotTracker.
235 void incorporateFunction(const Function *F) {
237 FunctionProcessed = false;
240 /// After calling incorporateFunction, use this method to remove the
241 /// most recently incorporated function from the SlotTracker. This
242 /// will reset the state of the machine back to just the module contents.
243 void purgeFunction();
245 // Implementation Details
247 /// This function does the actual initialization.
248 inline void initialize();
250 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
251 void CreateModuleSlot(const GlobalValue *V);
253 /// CreateFunctionSlot - Insert the specified Value* into the slot table.
254 void CreateFunctionSlot(const Value *V);
256 /// Add all of the module level global variables (and their initializers)
257 /// and function declarations, but not the contents of those functions.
258 void processModule();
260 /// Add all of the functions arguments, basic blocks, and instructions
261 void processFunction();
263 SlotTracker(const SlotTracker &); // DO NOT IMPLEMENT
264 void operator=(const SlotTracker &); // DO NOT IMPLEMENT
267 } // end anonymous namespace
270 static SlotTracker *createSlotTracker(const Value *V) {
271 if (const Argument *FA = dyn_cast<Argument>(V))
272 return new SlotTracker(FA->getParent());
274 if (const Instruction *I = dyn_cast<Instruction>(V))
275 return new SlotTracker(I->getParent()->getParent());
277 if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
278 return new SlotTracker(BB->getParent());
280 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
281 return new SlotTracker(GV->getParent());
283 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
284 return new SlotTracker(GA->getParent());
286 if (const Function *Func = dyn_cast<Function>(V))
287 return new SlotTracker(Func);
293 #define ST_DEBUG(X) cerr << X
298 // Module level constructor. Causes the contents of the Module (sans functions)
299 // to be added to the slot table.
300 SlotTracker::SlotTracker(const Module *M)
301 : TheModule(M), TheFunction(0), FunctionProcessed(false), mNext(0), fNext(0) {
304 // Function level constructor. Causes the contents of the Module and the one
305 // function provided to be added to the slot table.
306 SlotTracker::SlotTracker(const Function *F)
307 : TheModule(F ? F->getParent() : 0), TheFunction(F), FunctionProcessed(false),
311 inline void SlotTracker::initialize() {
314 TheModule = 0; ///< Prevent re-processing next time we're called.
317 if (TheFunction && !FunctionProcessed)
321 // Iterate through all the global variables, functions, and global
322 // variable initializers and create slots for them.
323 void SlotTracker::processModule() {
324 ST_DEBUG("begin processModule!\n");
326 // Add all of the unnamed global variables to the value table.
327 for (Module::const_global_iterator I = TheModule->global_begin(),
328 E = TheModule->global_end(); I != E; ++I)
332 // Add all the unnamed functions to the table.
333 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
338 ST_DEBUG("end processModule!\n");
342 // Process the arguments, basic blocks, and instructions of a function.
343 void SlotTracker::processFunction() {
344 ST_DEBUG("begin processFunction!\n");
347 // Add all the function arguments with no names.
348 for(Function::const_arg_iterator AI = TheFunction->arg_begin(),
349 AE = TheFunction->arg_end(); AI != AE; ++AI)
351 CreateFunctionSlot(AI);
353 ST_DEBUG("Inserting Instructions:\n");
355 // Add all of the basic blocks and instructions with no names.
356 for (Function::const_iterator BB = TheFunction->begin(),
357 E = TheFunction->end(); BB != E; ++BB) {
359 CreateFunctionSlot(BB);
360 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
361 if (I->getType() != Type::VoidTy && !I->hasName())
362 CreateFunctionSlot(I);
365 FunctionProcessed = true;
367 ST_DEBUG("end processFunction!\n");
370 /// Clean up after incorporating a function. This is the only way to get out of
371 /// the function incorporation state that affects get*Slot/Create*Slot. Function
372 /// incorporation state is indicated by TheFunction != 0.
373 void SlotTracker::purgeFunction() {
374 ST_DEBUG("begin purgeFunction!\n");
375 fMap.clear(); // Simply discard the function level map
377 FunctionProcessed = false;
378 ST_DEBUG("end purgeFunction!\n");
381 /// getGlobalSlot - Get the slot number of a global value.
382 int SlotTracker::getGlobalSlot(const GlobalValue *V) {
383 // Check for uninitialized state and do lazy initialization.
386 // Find the type plane in the module map
387 ValueMap::iterator MI = mMap.find(V);
388 return MI == mMap.end() ? -1 : MI->second;
392 /// getLocalSlot - Get the slot number for a value that is local to a function.
393 int SlotTracker::getLocalSlot(const Value *V) {
394 assert(!isa<Constant>(V) && "Can't get a constant or global slot with this!");
396 // Check for uninitialized state and do lazy initialization.
399 ValueMap::iterator FI = fMap.find(V);
400 return FI == fMap.end() ? -1 : FI->second;
404 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
405 void SlotTracker::CreateModuleSlot(const GlobalValue *V) {
406 assert(V && "Can't insert a null Value into SlotTracker!");
407 assert(V->getType() != Type::VoidTy && "Doesn't need a slot!");
408 assert(!V->hasName() && "Doesn't need a slot!");
410 unsigned DestSlot = mNext++;
413 ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" <<
415 // G = Global, F = Function, A = Alias, o = other
416 ST_DEBUG((isa<GlobalVariable>(V) ? 'G' :
417 (isa<Function>(V) ? 'F' :
418 (isa<GlobalAlias>(V) ? 'A' : 'o'))) << "]\n");
422 /// CreateSlot - Create a new slot for the specified value if it has no name.
423 void SlotTracker::CreateFunctionSlot(const Value *V) {
424 assert(V->getType() != Type::VoidTy && !V->hasName() &&
425 "Doesn't need a slot!");
427 unsigned DestSlot = fNext++;
430 // G = Global, F = Function, o = other
431 ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" <<
432 DestSlot << " [o]\n");
437 //===----------------------------------------------------------------------===//
438 // AsmWriter Implementation
439 //===----------------------------------------------------------------------===//
441 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
442 std::map<const Type *, std::string> &TypeTable,
443 SlotTracker *Machine);
447 /// fillTypeNameTable - If the module has a symbol table, take all global types
448 /// and stuff their names into the TypeNames map.
450 static void fillTypeNameTable(const Module *M,
451 std::map<const Type *, std::string> &TypeNames) {
453 const TypeSymbolTable &ST = M->getTypeSymbolTable();
454 TypeSymbolTable::const_iterator TI = ST.begin();
455 for (; TI != ST.end(); ++TI) {
456 // As a heuristic, don't insert pointer to primitive types, because
457 // they are used too often to have a single useful name.
459 const Type *Ty = cast<Type>(TI->second);
460 if (!isa<PointerType>(Ty) ||
461 !cast<PointerType>(Ty)->getElementType()->isPrimitiveType() ||
462 !cast<PointerType>(Ty)->getElementType()->isInteger() ||
463 isa<OpaqueType>(cast<PointerType>(Ty)->getElementType()))
464 TypeNames.insert(std::make_pair(Ty, '%' + getLLVMName(TI->first)));
470 static void calcTypeName(const Type *Ty,
471 std::vector<const Type *> &TypeStack,
472 std::map<const Type *, std::string> &TypeNames,
473 std::string &Result) {
474 if (Ty->isInteger() || (Ty->isPrimitiveType() && !isa<OpaqueType>(Ty))) {
475 Result += Ty->getDescription(); // Base case
479 // Check to see if the type is named.
480 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
481 if (I != TypeNames.end()) {
486 if (isa<OpaqueType>(Ty)) {
491 // Check to see if the Type is already on the stack...
492 unsigned Slot = 0, CurSize = TypeStack.size();
493 while (Slot < CurSize && TypeStack[Slot] != Ty) ++Slot; // Scan for type
495 // This is another base case for the recursion. In this case, we know
496 // that we have looped back to a type that we have previously visited.
497 // Generate the appropriate upreference to handle this.
498 if (Slot < CurSize) {
499 Result += "\\" + utostr(CurSize-Slot); // Here's the upreference
503 TypeStack.push_back(Ty); // Recursive case: Add us to the stack..
505 switch (Ty->getTypeID()) {
506 case Type::IntegerTyID: {
507 unsigned BitWidth = cast<IntegerType>(Ty)->getBitWidth();
508 Result += "i" + utostr(BitWidth);
511 case Type::FunctionTyID: {
512 const FunctionType *FTy = cast<FunctionType>(Ty);
513 calcTypeName(FTy->getReturnType(), TypeStack, TypeNames, Result);
515 for (FunctionType::param_iterator I = FTy->param_begin(),
516 E = FTy->param_end(); I != E; ++I) {
517 if (I != FTy->param_begin())
519 calcTypeName(*I, TypeStack, TypeNames, Result);
521 if (FTy->isVarArg()) {
522 if (FTy->getNumParams()) Result += ", ";
528 case Type::StructTyID: {
529 const StructType *STy = cast<StructType>(Ty);
533 for (StructType::element_iterator I = STy->element_begin(),
534 E = STy->element_end(); I != E; ++I) {
535 calcTypeName(*I, TypeStack, TypeNames, Result);
536 if (next(I) != STy->element_end())
545 case Type::PointerTyID: {
546 const PointerType *PTy = cast<PointerType>(Ty);
547 calcTypeName(PTy->getElementType(), TypeStack, TypeNames, Result);
548 if (unsigned AddressSpace = PTy->getAddressSpace())
549 Result += " addrspace(" + utostr(AddressSpace) + ")";
553 case Type::ArrayTyID: {
554 const ArrayType *ATy = cast<ArrayType>(Ty);
555 Result += "[" + utostr(ATy->getNumElements()) + " x ";
556 calcTypeName(ATy->getElementType(), TypeStack, TypeNames, Result);
560 case Type::VectorTyID: {
561 const VectorType *PTy = cast<VectorType>(Ty);
562 Result += "<" + utostr(PTy->getNumElements()) + " x ";
563 calcTypeName(PTy->getElementType(), TypeStack, TypeNames, Result);
567 case Type::OpaqueTyID:
571 Result += "<unrecognized-type>";
575 TypeStack.pop_back(); // Remove self from stack...
579 /// printTypeInt - The internal guts of printing out a type that has a
580 /// potentially named portion.
582 static void printTypeInt(raw_ostream &Out, const Type *Ty,
583 std::map<const Type *, std::string> &TypeNames) {
584 // Primitive types always print out their description, regardless of whether
585 // they have been named or not.
587 if (Ty->isInteger() || (Ty->isPrimitiveType() && !isa<OpaqueType>(Ty))) {
588 Out << Ty->getDescription();
592 // Check to see if the type is named.
593 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
594 if (I != TypeNames.end()) {
599 // Otherwise we have a type that has not been named but is a derived type.
600 // Carefully recurse the type hierarchy to print out any contained symbolic
603 std::vector<const Type *> TypeStack;
604 std::string TypeName;
605 calcTypeName(Ty, TypeStack, TypeNames, TypeName);
606 TypeNames.insert(std::make_pair(Ty, TypeName));//Cache type name for later use
611 /// WriteTypeSymbolic - This attempts to write the specified type as a symbolic
612 /// type, iff there is an entry in the modules symbol table for the specified
613 /// type or one of it's component types. This is slower than a simple x << Type
615 void llvm::WriteTypeSymbolic(std::ostream &Out, const Type *Ty,
617 raw_os_ostream RO(Out);
618 WriteTypeSymbolic(RO, Ty, M);
621 void llvm::WriteTypeSymbolic(raw_ostream &Out, const Type *Ty, const Module *M){
624 // If they want us to print out a type, but there is no context, we can't
625 // print it symbolically.
627 Out << Ty->getDescription();
629 std::map<const Type *, std::string> TypeNames;
630 fillTypeNameTable(M, TypeNames);
631 printTypeInt(Out, Ty, TypeNames);
635 // PrintEscapedString - Print each character of the specified string, escaping
636 // it if it is not printable or if it is an escape char.
637 static void PrintEscapedString(const std::string &Str, raw_ostream &Out) {
638 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
639 unsigned char C = Str[i];
640 if (isprint(C) && C != '"' && C != '\\') {
644 << (char) ((C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A'))
645 << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
650 static const char *getPredicateText(unsigned predicate) {
651 const char * pred = "unknown";
653 case FCmpInst::FCMP_FALSE: pred = "false"; break;
654 case FCmpInst::FCMP_OEQ: pred = "oeq"; break;
655 case FCmpInst::FCMP_OGT: pred = "ogt"; break;
656 case FCmpInst::FCMP_OGE: pred = "oge"; break;
657 case FCmpInst::FCMP_OLT: pred = "olt"; break;
658 case FCmpInst::FCMP_OLE: pred = "ole"; break;
659 case FCmpInst::FCMP_ONE: pred = "one"; break;
660 case FCmpInst::FCMP_ORD: pred = "ord"; break;
661 case FCmpInst::FCMP_UNO: pred = "uno"; break;
662 case FCmpInst::FCMP_UEQ: pred = "ueq"; break;
663 case FCmpInst::FCMP_UGT: pred = "ugt"; break;
664 case FCmpInst::FCMP_UGE: pred = "uge"; break;
665 case FCmpInst::FCMP_ULT: pred = "ult"; break;
666 case FCmpInst::FCMP_ULE: pred = "ule"; break;
667 case FCmpInst::FCMP_UNE: pred = "une"; break;
668 case FCmpInst::FCMP_TRUE: pred = "true"; break;
669 case ICmpInst::ICMP_EQ: pred = "eq"; break;
670 case ICmpInst::ICMP_NE: pred = "ne"; break;
671 case ICmpInst::ICMP_SGT: pred = "sgt"; break;
672 case ICmpInst::ICMP_SGE: pred = "sge"; break;
673 case ICmpInst::ICMP_SLT: pred = "slt"; break;
674 case ICmpInst::ICMP_SLE: pred = "sle"; break;
675 case ICmpInst::ICMP_UGT: pred = "ugt"; break;
676 case ICmpInst::ICMP_UGE: pred = "uge"; break;
677 case ICmpInst::ICMP_ULT: pred = "ult"; break;
678 case ICmpInst::ICMP_ULE: pred = "ule"; break;
683 static void WriteConstantInt(raw_ostream &Out, const Constant *CV,
684 std::map<const Type *, std::string> &TypeTable,
685 SlotTracker *Machine) {
686 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
687 if (CI->getType() == Type::Int1Ty) {
688 Out << (CI->getZExtValue() ? "true" : "false");
691 Out << CI->getValue();
695 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
696 if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEdouble ||
697 &CFP->getValueAPF().getSemantics() == &APFloat::IEEEsingle) {
698 // We would like to output the FP constant value in exponential notation,
699 // but we cannot do this if doing so will lose precision. Check here to
700 // make sure that we only output it in exponential format if we can parse
701 // the value back and get the same value.
703 bool isDouble = &CFP->getValueAPF().getSemantics()==&APFloat::IEEEdouble;
704 double Val = isDouble ? CFP->getValueAPF().convertToDouble() :
705 CFP->getValueAPF().convertToFloat();
706 std::string StrVal = ftostr(CFP->getValueAPF());
708 // Check to make sure that the stringized number is not some string like
709 // "Inf" or NaN, that atof will accept, but the lexer will not. Check
710 // that the string matches the "[-+]?[0-9]" regex.
712 if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
713 ((StrVal[0] == '-' || StrVal[0] == '+') &&
714 (StrVal[1] >= '0' && StrVal[1] <= '9'))) {
715 // Reparse stringized version!
716 if (atof(StrVal.c_str()) == Val) {
721 // Otherwise we could not reparse it to exactly the same value, so we must
722 // output the string in hexadecimal format!
723 assert(sizeof(double) == sizeof(uint64_t) &&
724 "assuming that double is 64 bits!");
725 Out << "0x" << utohexstr(DoubleToBits(Val));
729 // Some form of long double. These appear as a magic letter identifying
730 // the type, then a fixed number of hex digits.
732 if (&CFP->getValueAPF().getSemantics() == &APFloat::x87DoubleExtended)
734 else if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEquad)
736 else if (&CFP->getValueAPF().getSemantics() == &APFloat::PPCDoubleDouble)
739 assert(0 && "Unsupported floating point type");
740 // api needed to prevent premature destruction
741 APInt api = CFP->getValueAPF().convertToAPInt();
742 const uint64_t* p = api.getRawData();
745 int width = api.getBitWidth();
746 for (int j=0; j<width; j+=4, shiftcount-=4) {
747 unsigned int nibble = (word>>shiftcount) & 15;
749 Out << (unsigned char)(nibble + '0');
751 Out << (unsigned char)(nibble - 10 + 'A');
752 if (shiftcount == 0 && j+4 < width) {
756 shiftcount = width-j-4;
762 if (isa<ConstantAggregateZero>(CV)) {
763 Out << "zeroinitializer";
767 if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
768 // As a special case, print the array as a string if it is an array of
769 // i8 with ConstantInt values.
771 const Type *ETy = CA->getType()->getElementType();
772 if (CA->isString()) {
774 PrintEscapedString(CA->getAsString(), Out);
776 } else { // Cannot output in string format...
778 if (CA->getNumOperands()) {
780 printTypeInt(Out, ETy, TypeTable);
782 WriteAsOperandInternal(Out, CA->getOperand(0),
784 for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
786 printTypeInt(Out, ETy, TypeTable);
788 WriteAsOperandInternal(Out, CA->getOperand(i), TypeTable, Machine);
797 if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
798 if (CS->getType()->isPacked())
801 unsigned N = CS->getNumOperands();
804 printTypeInt(Out, CS->getOperand(0)->getType(), TypeTable);
807 WriteAsOperandInternal(Out, CS->getOperand(0), TypeTable, Machine);
809 for (unsigned i = 1; i < N; i++) {
811 printTypeInt(Out, CS->getOperand(i)->getType(), TypeTable);
814 WriteAsOperandInternal(Out, CS->getOperand(i), TypeTable, Machine);
820 if (CS->getType()->isPacked())
825 if (const ConstantVector *CP = dyn_cast<ConstantVector>(CV)) {
826 const Type *ETy = CP->getType()->getElementType();
827 assert(CP->getNumOperands() > 0 &&
828 "Number of operands for a PackedConst must be > 0");
830 printTypeInt(Out, ETy, TypeTable);
832 WriteAsOperandInternal(Out, CP->getOperand(0), TypeTable, Machine);
833 for (unsigned i = 1, e = CP->getNumOperands(); i != e; ++i) {
835 printTypeInt(Out, ETy, TypeTable);
837 WriteAsOperandInternal(Out, CP->getOperand(i), TypeTable, Machine);
843 if (isa<ConstantPointerNull>(CV)) {
848 if (isa<UndefValue>(CV)) {
853 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
854 Out << CE->getOpcodeName();
856 Out << ' ' << getPredicateText(CE->getPredicate());
859 for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) {
860 printTypeInt(Out, (*OI)->getType(), TypeTable);
862 WriteAsOperandInternal(Out, *OI, TypeTable, Machine);
863 if (OI+1 != CE->op_end())
867 if (CE->hasIndices()) {
868 const SmallVector<unsigned, 4> &Indices = CE->getIndices();
869 for (unsigned i = 0, e = Indices.size(); i != e; ++i)
870 Out << ", " << Indices[i];
875 printTypeInt(Out, CE->getType(), TypeTable);
882 Out << "<placeholder or erroneous Constant>";
886 /// WriteAsOperand - Write the name of the specified value out to the specified
887 /// ostream. This can be useful when you just want to print int %reg126, not
888 /// the whole instruction that generated it.
890 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
891 std::map<const Type*, std::string> &TypeTable,
892 SlotTracker *Machine) {
894 PrintLLVMName(Out, V);
898 const Constant *CV = dyn_cast<Constant>(V);
899 if (CV && !isa<GlobalValue>(CV)) {
900 WriteConstantInt(Out, CV, TypeTable, Machine);
904 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
906 if (IA->hasSideEffects())
907 Out << "sideeffect ";
909 PrintEscapedString(IA->getAsmString(), Out);
911 PrintEscapedString(IA->getConstraintString(), Out);
919 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
920 Slot = Machine->getGlobalSlot(GV);
923 Slot = Machine->getLocalSlot(V);
926 Machine = createSlotTracker(V);
928 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
929 Slot = Machine->getGlobalSlot(GV);
932 Slot = Machine->getLocalSlot(V);
941 Out << Prefix << Slot;
946 /// WriteAsOperand - Write the name of the specified value out to the specified
947 /// ostream. This can be useful when you just want to print int %reg126, not
948 /// the whole instruction that generated it.
950 void llvm::WriteAsOperand(std::ostream &Out, const Value *V, bool PrintType,
951 const Module *Context) {
952 raw_os_ostream OS(Out);
953 WriteAsOperand(OS, V, PrintType, Context);
956 void llvm::WriteAsOperand(raw_ostream &Out, const Value *V, bool PrintType,
957 const Module *Context) {
958 std::map<const Type *, std::string> TypeNames;
959 if (Context == 0) Context = getModuleFromVal(V);
962 fillTypeNameTable(Context, TypeNames);
965 printTypeInt(Out, V->getType(), TypeNames);
969 WriteAsOperandInternal(Out, V, TypeNames, 0);
975 class AssemblyWriter {
977 SlotTracker &Machine;
978 const Module *TheModule;
979 std::map<const Type *, std::string> TypeNames;
980 AssemblyAnnotationWriter *AnnotationWriter;
982 inline AssemblyWriter(raw_ostream &o, SlotTracker &Mac, const Module *M,
983 AssemblyAnnotationWriter *AAW)
984 : Out(o), Machine(Mac), TheModule(M), AnnotationWriter(AAW) {
986 // If the module has a symbol table, take all global types and stuff their
987 // names into the TypeNames map.
989 fillTypeNameTable(M, TypeNames);
992 void write(const Module *M) { printModule(M); }
994 void write(const GlobalValue *G) {
995 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(G))
997 else if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(G))
999 else if (const Function *F = dyn_cast<Function>(G))
1002 assert(0 && "Unknown global");
1005 void write(const BasicBlock *BB) { printBasicBlock(BB); }
1006 void write(const Instruction *I) { printInstruction(*I); }
1007 void write(const Type *Ty) { printType(Ty); }
1009 void writeOperand(const Value *Op, bool PrintType);
1010 void writeParamOperand(const Value *Operand, Attributes Attrs);
1012 const Module* getModule() { return TheModule; }
1015 void printModule(const Module *M);
1016 void printTypeSymbolTable(const TypeSymbolTable &ST);
1017 void printGlobal(const GlobalVariable *GV);
1018 void printAlias(const GlobalAlias *GV);
1019 void printFunction(const Function *F);
1020 void printArgument(const Argument *FA, Attributes Attrs);
1021 void printBasicBlock(const BasicBlock *BB);
1022 void printInstruction(const Instruction &I);
1024 // printType - Go to extreme measures to attempt to print out a short,
1025 // symbolic version of a type name.
1027 void printType(const Type *Ty) {
1028 printTypeInt(Out, Ty, TypeNames);
1031 // printTypeAtLeastOneLevel - Print out one level of the possibly complex type
1032 // without considering any symbolic types that we may have equal to it.
1034 void printTypeAtLeastOneLevel(const Type *Ty);
1036 // printInfoComment - Print a little comment after the instruction indicating
1037 // which slot it occupies.
1038 void printInfoComment(const Value &V);
1040 } // end of llvm namespace
1042 /// printTypeAtLeastOneLevel - Print out one level of the possibly complex type
1043 /// without considering any symbolic types that we may have equal to it.
1045 void AssemblyWriter::printTypeAtLeastOneLevel(const Type *Ty) {
1046 if (const IntegerType *ITy = dyn_cast<IntegerType>(Ty)) {
1047 Out << "i" << utostr(ITy->getBitWidth());
1051 if (const FunctionType *FTy = dyn_cast<FunctionType>(Ty)) {
1052 printType(FTy->getReturnType());
1054 for (FunctionType::param_iterator I = FTy->param_begin(),
1055 E = FTy->param_end(); I != E; ++I) {
1056 if (I != FTy->param_begin())
1060 if (FTy->isVarArg()) {
1061 if (FTy->getNumParams()) Out << ", ";
1068 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1069 if (STy->isPacked())
1072 for (StructType::element_iterator I = STy->element_begin(),
1073 E = STy->element_end(); I != E; ++I) {
1074 if (I != STy->element_begin())
1079 if (STy->isPacked())
1084 if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
1085 printType(PTy->getElementType());
1086 if (unsigned AddressSpace = PTy->getAddressSpace())
1087 Out << " addrspace(" << AddressSpace << ")";
1092 if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1093 Out << '[' << ATy->getNumElements() << " x ";
1094 printType(ATy->getElementType());
1099 if (const VectorType *PTy = dyn_cast<VectorType>(Ty)) {
1100 Out << '<' << PTy->getNumElements() << " x ";
1101 printType(PTy->getElementType());
1106 if (isa<OpaqueType>(Ty)) {
1111 if (!Ty->isPrimitiveType())
1112 Out << "<unknown derived type>";
1117 void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType) {
1119 Out << "<null operand!>";
1122 printType(Operand->getType());
1125 WriteAsOperandInternal(Out, Operand, TypeNames, &Machine);
1129 void AssemblyWriter::writeParamOperand(const Value *Operand,
1132 Out << "<null operand!>";
1135 printType(Operand->getType());
1136 // Print parameter attributes list
1137 if (Attrs != Attribute::None)
1138 Out << ' ' << Attribute::getAsString(Attrs);
1140 // Print the operand
1141 WriteAsOperandInternal(Out, Operand, TypeNames, &Machine);
1145 void AssemblyWriter::printModule(const Module *M) {
1146 if (!M->getModuleIdentifier().empty() &&
1147 // Don't print the ID if it will start a new line (which would
1148 // require a comment char before it).
1149 M->getModuleIdentifier().find('\n') == std::string::npos)
1150 Out << "; ModuleID = '" << M->getModuleIdentifier() << "'\n";
1152 if (!M->getDataLayout().empty())
1153 Out << "target datalayout = \"" << M->getDataLayout() << "\"\n";
1154 if (!M->getTargetTriple().empty())
1155 Out << "target triple = \"" << M->getTargetTriple() << "\"\n";
1157 if (!M->getModuleInlineAsm().empty()) {
1158 // Split the string into lines, to make it easier to read the .ll file.
1159 std::string Asm = M->getModuleInlineAsm();
1161 size_t NewLine = Asm.find_first_of('\n', CurPos);
1162 while (NewLine != std::string::npos) {
1163 // We found a newline, print the portion of the asm string from the
1164 // last newline up to this newline.
1165 Out << "module asm \"";
1166 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.begin()+NewLine),
1170 NewLine = Asm.find_first_of('\n', CurPos);
1172 Out << "module asm \"";
1173 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.end()), Out);
1177 // Loop over the dependent libraries and emit them.
1178 Module::lib_iterator LI = M->lib_begin();
1179 Module::lib_iterator LE = M->lib_end();
1181 Out << "deplibs = [ ";
1183 Out << '"' << *LI << '"';
1191 // Loop over the symbol table, emitting all named constants.
1192 printTypeSymbolTable(M->getTypeSymbolTable());
1194 for (Module::const_global_iterator I = M->global_begin(), E = M->global_end();
1198 // Output all aliases.
1199 if (!M->alias_empty()) Out << "\n";
1200 for (Module::const_alias_iterator I = M->alias_begin(), E = M->alias_end();
1204 // Output all of the functions.
1205 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
1209 static void PrintLinkage(GlobalValue::LinkageTypes LT, raw_ostream &Out) {
1211 case GlobalValue::InternalLinkage: Out << "internal "; break;
1212 case GlobalValue::LinkOnceLinkage: Out << "linkonce "; break;
1213 case GlobalValue::WeakLinkage: Out << "weak "; break;
1214 case GlobalValue::CommonLinkage: Out << "common "; break;
1215 case GlobalValue::AppendingLinkage: Out << "appending "; break;
1216 case GlobalValue::DLLImportLinkage: Out << "dllimport "; break;
1217 case GlobalValue::DLLExportLinkage: Out << "dllexport "; break;
1218 case GlobalValue::ExternalWeakLinkage: Out << "extern_weak "; break;
1219 case GlobalValue::ExternalLinkage: break;
1220 case GlobalValue::GhostLinkage:
1221 Out << "GhostLinkage not allowed in AsmWriter!\n";
1227 static void PrintVisibility(GlobalValue::VisibilityTypes Vis,
1230 default: assert(0 && "Invalid visibility style!");
1231 case GlobalValue::DefaultVisibility: break;
1232 case GlobalValue::HiddenVisibility: Out << "hidden "; break;
1233 case GlobalValue::ProtectedVisibility: Out << "protected "; break;
1237 void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
1238 if (GV->hasName()) {
1239 PrintLLVMName(Out, GV);
1243 if (!GV->hasInitializer() && GV->hasExternalLinkage())
1246 PrintLinkage(GV->getLinkage(), Out);
1247 PrintVisibility(GV->getVisibility(), Out);
1249 if (GV->isThreadLocal()) Out << "thread_local ";
1250 Out << (GV->isConstant() ? "constant " : "global ");
1251 printType(GV->getType()->getElementType());
1253 if (GV->hasInitializer()) {
1255 writeOperand(GV->getInitializer(), false);
1258 if (unsigned AddressSpace = GV->getType()->getAddressSpace())
1259 Out << " addrspace(" << AddressSpace << ") ";
1261 if (GV->hasSection())
1262 Out << ", section \"" << GV->getSection() << '"';
1263 if (GV->getAlignment())
1264 Out << ", align " << GV->getAlignment();
1266 printInfoComment(*GV);
1270 void AssemblyWriter::printAlias(const GlobalAlias *GA) {
1271 // Don't crash when dumping partially built GA
1273 Out << "<<nameless>> = ";
1275 PrintLLVMName(Out, GA);
1278 PrintVisibility(GA->getVisibility(), Out);
1282 PrintLinkage(GA->getLinkage(), Out);
1284 const Constant *Aliasee = GA->getAliasee();
1286 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Aliasee)) {
1287 printType(GV->getType());
1289 PrintLLVMName(Out, GV);
1290 } else if (const Function *F = dyn_cast<Function>(Aliasee)) {
1291 printType(F->getFunctionType());
1295 PrintLLVMName(Out, F);
1298 } else if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(Aliasee)) {
1299 printType(GA->getType());
1301 PrintLLVMName(Out, GA);
1303 const ConstantExpr *CE = 0;
1304 if ((CE = dyn_cast<ConstantExpr>(Aliasee)) &&
1305 (CE->getOpcode() == Instruction::BitCast)) {
1306 writeOperand(CE, false);
1308 assert(0 && "Unsupported aliasee");
1311 printInfoComment(*GA);
1315 void AssemblyWriter::printTypeSymbolTable(const TypeSymbolTable &ST) {
1317 for (TypeSymbolTable::const_iterator TI = ST.begin(), TE = ST.end();
1320 PrintLLVMName(Out, &TI->first[0], TI->first.size(), LocalPrefix);
1323 // Make sure we print out at least one level of the type structure, so
1324 // that we do not get %FILE = type %FILE
1326 printTypeAtLeastOneLevel(TI->second);
1331 /// printFunction - Print all aspects of a function.
1333 void AssemblyWriter::printFunction(const Function *F) {
1334 // Print out the return type and name.
1337 if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, Out);
1339 if (F->isDeclaration())
1344 PrintLinkage(F->getLinkage(), Out);
1345 PrintVisibility(F->getVisibility(), Out);
1347 // Print the calling convention.
1348 switch (F->getCallingConv()) {
1349 case CallingConv::C: break; // default
1350 case CallingConv::Fast: Out << "fastcc "; break;
1351 case CallingConv::Cold: Out << "coldcc "; break;
1352 case CallingConv::X86_StdCall: Out << "x86_stdcallcc "; break;
1353 case CallingConv::X86_FastCall: Out << "x86_fastcallcc "; break;
1354 case CallingConv::X86_SSECall: Out << "x86_ssecallcc "; break;
1355 default: Out << "cc" << F->getCallingConv() << " "; break;
1358 const FunctionType *FT = F->getFunctionType();
1359 const AttrListPtr &Attrs = F->getAttributes();
1360 printType(F->getReturnType());
1363 PrintLLVMName(Out, F);
1367 Machine.incorporateFunction(F);
1369 // Loop over the arguments, printing them...
1372 if (!F->isDeclaration()) {
1373 // If this isn't a declaration, print the argument names as well.
1374 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
1376 // Insert commas as we go... the first arg doesn't get a comma
1377 if (I != F->arg_begin()) Out << ", ";
1378 printArgument(I, Attrs.getAttributes(Idx));
1382 // Otherwise, print the types from the function type.
1383 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
1384 // Insert commas as we go... the first arg doesn't get a comma
1388 printType(FT->getParamType(i));
1390 Attributes ArgAttrs = Attrs.getAttributes(i+1);
1391 if (ArgAttrs != Attribute::None)
1392 Out << ' ' << Attribute::getAsString(ArgAttrs);
1396 // Finish printing arguments...
1397 if (FT->isVarArg()) {
1398 if (FT->getNumParams()) Out << ", ";
1399 Out << "..."; // Output varargs portion of signature!
1402 Attributes RetAttrs = Attrs.getAttributes(0);
1403 if (RetAttrs != Attribute::None)
1404 Out << ' ' << Attribute::getAsString(Attrs.getAttributes(0));
1405 if (F->hasSection())
1406 Out << " section \"" << F->getSection() << '"';
1407 if (F->getAlignment())
1408 Out << " align " << F->getAlignment();
1410 Out << " gc \"" << F->getGC() << '"';
1411 if (F->isDeclaration()) {
1415 bool insideNotes = false;
1416 if (F->hasNote(Attribute::AlwaysInline)) {
1419 Out << "inline=always";
1421 if (F->hasNote(Attribute::NoInline)) {
1428 Out << "inline=never";
1430 if (F->hasNote(Attribute::OptimizeForSize)) {
1444 // Output all of its basic blocks... for the function
1445 for (Function::const_iterator I = F->begin(), E = F->end(); I != E; ++I)
1451 Machine.purgeFunction();
1454 /// printArgument - This member is called for every argument that is passed into
1455 /// the function. Simply print it out
1457 void AssemblyWriter::printArgument(const Argument *Arg,
1460 printType(Arg->getType());
1462 // Output parameter attributes list
1463 if (Attrs != Attribute::None)
1464 Out << ' ' << Attribute::getAsString(Attrs);
1466 // Output name, if available...
1467 if (Arg->hasName()) {
1469 PrintLLVMName(Out, Arg);
1473 /// printBasicBlock - This member is called for each basic block in a method.
1475 void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {
1476 if (BB->hasName()) { // Print out the label if it exists...
1478 PrintLLVMName(Out, BB->getNameStart(), BB->getNameLen(), LabelPrefix);
1480 } else if (!BB->use_empty()) { // Don't print block # of no uses...
1481 Out << "\n; <label>:";
1482 int Slot = Machine.getLocalSlot(BB);
1489 if (BB->getParent() == 0)
1490 Out << "\t\t; Error: Block without parent!";
1491 else if (BB != &BB->getParent()->getEntryBlock()) { // Not the entry block?
1492 // Output predecessors for the block...
1494 pred_const_iterator PI = pred_begin(BB), PE = pred_end(BB);
1497 Out << " No predecessors!";
1500 writeOperand(*PI, false);
1501 for (++PI; PI != PE; ++PI) {
1503 writeOperand(*PI, false);
1510 if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(BB, Out);
1512 // Output all of the instructions in the basic block...
1513 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
1514 printInstruction(*I);
1516 if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(BB, Out);
1520 /// printInfoComment - Print a little comment after the instruction indicating
1521 /// which slot it occupies.
1523 void AssemblyWriter::printInfoComment(const Value &V) {
1524 if (V.getType() != Type::VoidTy) {
1526 printType(V.getType());
1529 if (!V.hasName() && !isa<Instruction>(V)) {
1531 if (const GlobalValue *GV = dyn_cast<GlobalValue>(&V))
1532 SlotNum = Machine.getGlobalSlot(GV);
1534 SlotNum = Machine.getLocalSlot(&V);
1538 Out << ':' << SlotNum; // Print out the def slot taken.
1540 Out << " [#uses=" << V.getNumUses() << ']'; // Output # uses
1544 // This member is called for each Instruction in a function..
1545 void AssemblyWriter::printInstruction(const Instruction &I) {
1546 if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, Out);
1550 // Print out name if it exists...
1552 PrintLLVMName(Out, &I);
1554 } else if (I.getType() != Type::VoidTy) {
1555 // Print out the def slot taken.
1556 int SlotNum = Machine.getLocalSlot(&I);
1558 Out << "<badref> = ";
1560 Out << '%' << SlotNum << " = ";
1563 // If this is a volatile load or store, print out the volatile marker.
1564 if ((isa<LoadInst>(I) && cast<LoadInst>(I).isVolatile()) ||
1565 (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile())) {
1567 } else if (isa<CallInst>(I) && cast<CallInst>(I).isTailCall()) {
1568 // If this is a call, check if it's a tail call.
1572 // Print out the opcode...
1573 Out << I.getOpcodeName();
1575 // Print out the compare instruction predicates
1576 if (const CmpInst *CI = dyn_cast<CmpInst>(&I))
1577 Out << ' ' << getPredicateText(CI->getPredicate());
1579 // Print out the type of the operands...
1580 const Value *Operand = I.getNumOperands() ? I.getOperand(0) : 0;
1582 // Special case conditional branches to swizzle the condition out to the front
1583 if (isa<BranchInst>(I) && I.getNumOperands() > 1) {
1585 writeOperand(I.getOperand(2), true);
1587 writeOperand(Operand, true);
1589 writeOperand(I.getOperand(1), true);
1591 } else if (isa<SwitchInst>(I)) {
1592 // Special case switch statement to get formatting nice and correct...
1594 writeOperand(Operand , true);
1596 writeOperand(I.getOperand(1), true);
1599 for (unsigned op = 2, Eop = I.getNumOperands(); op < Eop; op += 2) {
1601 writeOperand(I.getOperand(op ), true);
1603 writeOperand(I.getOperand(op+1), true);
1606 } else if (isa<PHINode>(I)) {
1608 printType(I.getType());
1611 for (unsigned op = 0, Eop = I.getNumOperands(); op < Eop; op += 2) {
1612 if (op) Out << ", ";
1614 writeOperand(I.getOperand(op ), false); Out << ", ";
1615 writeOperand(I.getOperand(op+1), false); Out << " ]";
1617 } else if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&I)) {
1619 writeOperand(I.getOperand(0), true);
1620 for (const unsigned *i = EVI->idx_begin(), *e = EVI->idx_end(); i != e; ++i)
1622 } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&I)) {
1624 writeOperand(I.getOperand(0), true); Out << ", ";
1625 writeOperand(I.getOperand(1), true);
1626 for (const unsigned *i = IVI->idx_begin(), *e = IVI->idx_end(); i != e; ++i)
1628 } else if (isa<ReturnInst>(I) && !Operand) {
1630 } else if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
1631 // Print the calling convention being used.
1632 switch (CI->getCallingConv()) {
1633 case CallingConv::C: break; // default
1634 case CallingConv::Fast: Out << " fastcc"; break;
1635 case CallingConv::Cold: Out << " coldcc"; break;
1636 case CallingConv::X86_StdCall: Out << " x86_stdcallcc"; break;
1637 case CallingConv::X86_FastCall: Out << " x86_fastcallcc"; break;
1638 case CallingConv::X86_SSECall: Out << " x86_ssecallcc"; break;
1639 default: Out << " cc" << CI->getCallingConv(); break;
1642 const PointerType *PTy = cast<PointerType>(Operand->getType());
1643 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1644 const Type *RetTy = FTy->getReturnType();
1645 const AttrListPtr &PAL = CI->getAttributes();
1647 // If possible, print out the short form of the call instruction. We can
1648 // only do this if the first argument is a pointer to a nonvararg function,
1649 // and if the return type is not a pointer to a function.
1652 if (!FTy->isVarArg() &&
1653 (!isa<PointerType>(RetTy) ||
1654 !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
1657 writeOperand(Operand, false);
1659 writeOperand(Operand, true);
1662 for (unsigned op = 1, Eop = I.getNumOperands(); op < Eop; ++op) {
1665 writeParamOperand(I.getOperand(op), PAL.getAttributes(op));
1668 if (PAL.getAttributes(0) != Attribute::None)
1669 Out << ' ' << Attribute::getAsString(PAL.getAttributes(0));
1670 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
1671 const PointerType *PTy = cast<PointerType>(Operand->getType());
1672 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1673 const Type *RetTy = FTy->getReturnType();
1674 const AttrListPtr &PAL = II->getAttributes();
1676 // Print the calling convention being used.
1677 switch (II->getCallingConv()) {
1678 case CallingConv::C: break; // default
1679 case CallingConv::Fast: Out << " fastcc"; break;
1680 case CallingConv::Cold: Out << " coldcc"; break;
1681 case CallingConv::X86_StdCall: Out << " x86_stdcallcc"; break;
1682 case CallingConv::X86_FastCall: Out << " x86_fastcallcc"; break;
1683 case CallingConv::X86_SSECall: Out << " x86_ssecallcc"; break;
1684 default: Out << " cc" << II->getCallingConv(); break;
1687 // If possible, print out the short form of the invoke instruction. We can
1688 // only do this if the first argument is a pointer to a nonvararg function,
1689 // and if the return type is not a pointer to a function.
1691 if (!FTy->isVarArg() &&
1692 (!isa<PointerType>(RetTy) ||
1693 !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
1694 Out << ' '; printType(RetTy);
1695 writeOperand(Operand, false);
1698 writeOperand(Operand, true);
1702 for (unsigned op = 3, Eop = I.getNumOperands(); op < Eop; ++op) {
1705 writeParamOperand(I.getOperand(op), PAL.getAttributes(op-2));
1709 if (PAL.getAttributes(0) != Attribute::None)
1710 Out << ' ' << Attribute::getAsString(PAL.getAttributes(0));
1711 Out << "\n\t\t\tto ";
1712 writeOperand(II->getNormalDest(), true);
1714 writeOperand(II->getUnwindDest(), true);
1716 } else if (const AllocationInst *AI = dyn_cast<AllocationInst>(&I)) {
1718 printType(AI->getType()->getElementType());
1719 if (AI->isArrayAllocation()) {
1721 writeOperand(AI->getArraySize(), true);
1723 if (AI->getAlignment()) {
1724 Out << ", align " << AI->getAlignment();
1726 } else if (isa<CastInst>(I)) {
1729 writeOperand(Operand, true); // Work with broken code
1732 printType(I.getType());
1733 } else if (isa<VAArgInst>(I)) {
1736 writeOperand(Operand, true); // Work with broken code
1739 printType(I.getType());
1740 } else if (Operand) { // Print the normal way...
1742 // PrintAllTypes - Instructions who have operands of all the same type
1743 // omit the type from all but the first operand. If the instruction has
1744 // different type operands (for example br), then they are all printed.
1745 bool PrintAllTypes = false;
1746 const Type *TheType = Operand->getType();
1748 // Select, Store and ShuffleVector always print all types.
1749 if (isa<SelectInst>(I) || isa<StoreInst>(I) || isa<ShuffleVectorInst>(I)
1750 || isa<ReturnInst>(I)) {
1751 PrintAllTypes = true;
1753 for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) {
1754 Operand = I.getOperand(i);
1755 if (Operand->getType() != TheType) {
1756 PrintAllTypes = true; // We have differing types! Print them all!
1762 if (!PrintAllTypes) {
1768 for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) {
1770 writeOperand(I.getOperand(i), PrintAllTypes);
1774 // Print post operand alignment for load/store
1775 if (isa<LoadInst>(I) && cast<LoadInst>(I).getAlignment()) {
1776 Out << ", align " << cast<LoadInst>(I).getAlignment();
1777 } else if (isa<StoreInst>(I) && cast<StoreInst>(I).getAlignment()) {
1778 Out << ", align " << cast<StoreInst>(I).getAlignment();
1781 printInfoComment(I);
1786 //===----------------------------------------------------------------------===//
1787 // External Interface declarations
1788 //===----------------------------------------------------------------------===//
1790 void Module::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1791 raw_os_ostream OS(o);
1794 void Module::print(raw_ostream &OS, AssemblyAnnotationWriter *AAW) const {
1795 SlotTracker SlotTable(this);
1796 AssemblyWriter W(OS, SlotTable, this, AAW);
1800 void Type::print(std::ostream &o) const {
1801 raw_os_ostream OS(o);
1805 void Type::print(raw_ostream &o) const {
1809 o << getDescription();
1812 void Value::print(raw_ostream &OS, AssemblyAnnotationWriter *AAW) const {
1814 OS << "printing a <null> value\n";
1818 if (const Instruction *I = dyn_cast<Instruction>(this)) {
1819 const Function *F = I->getParent() ? I->getParent()->getParent() : 0;
1820 SlotTracker SlotTable(F);
1821 AssemblyWriter W(OS, SlotTable, F ? F->getParent() : 0, AAW);
1823 } else if (const BasicBlock *BB = dyn_cast<BasicBlock>(this)) {
1824 SlotTracker SlotTable(BB->getParent());
1825 AssemblyWriter W(OS, SlotTable,
1826 BB->getParent() ? BB->getParent()->getParent() : 0, AAW);
1828 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(this)) {
1829 SlotTracker SlotTable(GV->getParent());
1830 AssemblyWriter W(OS, SlotTable, GV->getParent(), 0);
1832 } else if (const Constant *C = dyn_cast<Constant>(this)) {
1833 OS << ' ' << C->getType()->getDescription() << ' ';
1834 std::map<const Type *, std::string> TypeTable;
1835 WriteConstantInt(OS, C, TypeTable, 0);
1836 } else if (const Argument *A = dyn_cast<Argument>(this)) {
1837 WriteAsOperand(OS, this, true,
1838 A->getParent() ? A->getParent()->getParent() : 0);
1839 } else if (isa<InlineAsm>(this)) {
1840 WriteAsOperand(OS, this, true, 0);
1842 // FIXME: PseudoSourceValue breaks this!
1843 //assert(0 && "Unknown value to print out!");
1847 void Value::print(std::ostream &O, AssemblyAnnotationWriter *AAW) const {
1848 raw_os_ostream OS(O);
1852 // Value::dump - allow easy printing of Values from the debugger.
1853 void Value::dump() const { print(errs()); errs() << '\n'; errs().flush(); }
1855 // Type::dump - allow easy printing of Types from the debugger.
1856 void Type::dump() const { print(errs()); errs() << '\n'; errs().flush(); }
1858 // Module::dump() - Allow printing of Modules from the debugger.
1859 void Module::dump() const { print(errs(), 0); errs().flush(); }