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 //===----------------------------------------------------------------------===//
44 //===----------------------------------------------------------------------===//
46 static const Module *getModuleFromVal(const Value *V) {
47 if (const Argument *MA = dyn_cast<Argument>(V))
48 return MA->getParent() ? MA->getParent()->getParent() : 0;
50 if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
51 return BB->getParent() ? BB->getParent()->getParent() : 0;
53 if (const Instruction *I = dyn_cast<Instruction>(V)) {
54 const Function *M = I->getParent() ? I->getParent()->getParent() : 0;
55 return M ? M->getParent() : 0;
58 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
59 return GV->getParent();
63 // PrintEscapedString - Print each character of the specified string, escaping
64 // it if it is not printable or if it is an escape char.
65 static void PrintEscapedString(const char *Str, unsigned Length,
67 for (unsigned i = 0; i != Length; ++i) {
68 unsigned char C = Str[i];
69 if (isprint(C) && C != '\\' && C != '"' && isprint(C))
72 Out << '\\' << hexdigit(C >> 4) << hexdigit(C & 0x0F);
76 // PrintEscapedString - Print each character of the specified string, escaping
77 // it if it is not printable or if it is an escape char.
78 static void PrintEscapedString(const std::string &Str, raw_ostream &Out) {
79 PrintEscapedString(Str.c_str(), Str.size(), Out);
89 /// PrintLLVMName - Turn the specified name into an 'LLVM name', which is either
90 /// prefixed with % (if the string only contains simple characters) or is
91 /// surrounded with ""'s (if it has special chars in it). Print it out.
92 static void PrintLLVMName(raw_ostream &OS, const char *NameStr,
93 unsigned NameLen, PrefixType Prefix) {
94 assert(NameStr && "Cannot get empty name!");
96 default: assert(0 && "Bad prefix!");
98 case GlobalPrefix: OS << '@'; break;
99 case LabelPrefix: break;
100 case LocalPrefix: OS << '%'; break;
103 // Scan the name to see if it needs quotes first.
104 bool NeedsQuotes = isdigit(NameStr[0]);
106 for (unsigned i = 0; i != NameLen; ++i) {
108 if (!isalnum(C) && C != '-' && C != '.' && C != '_') {
115 // If we didn't need any quotes, just write out the name in one blast.
117 OS.write(NameStr, NameLen);
121 // Okay, we need quotes. Output the quotes and escape any scary characters as
124 PrintEscapedString(NameStr, NameLen, OS);
128 /// getLLVMName - Turn the specified string into an 'LLVM name', which is
129 /// surrounded with ""'s and escaped if it has special chars in it.
130 static std::string getLLVMName(const std::string &Name) {
131 assert(!Name.empty() && "Cannot get empty name!");
133 raw_string_ostream OS(result);
134 PrintLLVMName(OS, Name.c_str(), Name.length(), NoPrefix);
138 /// PrintLLVMName - Turn the specified name into an 'LLVM name', which is either
139 /// prefixed with % (if the string only contains simple characters) or is
140 /// surrounded with ""'s (if it has special chars in it). Print it out.
141 static void PrintLLVMName(raw_ostream &OS, const Value *V) {
142 PrintLLVMName(OS, V->getNameStart(), V->getNameLen(),
143 isa<GlobalValue>(V) ? GlobalPrefix : LocalPrefix);
146 //===----------------------------------------------------------------------===//
147 // TypePrinting Class: Type printing machinery
148 //===----------------------------------------------------------------------===//
151 /// TypePrinting - Type printing machinery.
153 std::map<const Type *, std::string> TypeNames;
156 TypePrinting(const Module *M, raw_ostream &os);
158 void print(const Type *Ty);
159 void printAtLeastOneLevel(const Type *Ty);
161 } // end anonymous namespace.
163 TypePrinting::TypePrinting(const Module *M, raw_ostream &os) : OS(os) {
166 // If the module has a symbol table, take all global types and stuff their
167 // names into the TypeNames map.
168 const TypeSymbolTable &ST = M->getTypeSymbolTable();
169 for (TypeSymbolTable::const_iterator TI = ST.begin(), E = ST.end();
171 // As a heuristic, don't insert pointer to primitive types, because
172 // they are used too often to have a single useful name.
174 const Type *Ty = cast<Type>(TI->second);
175 if (!isa<PointerType>(Ty) ||
176 !cast<PointerType>(Ty)->getElementType()->isPrimitiveType() ||
177 !cast<PointerType>(Ty)->getElementType()->isInteger() ||
178 isa<OpaqueType>(cast<PointerType>(Ty)->getElementType()))
179 TypeNames.insert(std::make_pair(Ty, '%' + getLLVMName(TI->first)));
183 static void calcTypeName(const Type *Ty,
184 std::vector<const Type *> &TypeStack,
185 std::map<const Type *, std::string> &TypeNames,
186 std::string &Result) {
187 if (Ty->isInteger() || (Ty->isPrimitiveType() && !isa<OpaqueType>(Ty))) {
188 Result += Ty->getDescription(); // Base case
192 // Check to see if the type is named.
193 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
194 if (I != TypeNames.end()) {
199 if (isa<OpaqueType>(Ty)) {
204 // Check to see if the Type is already on the stack...
205 unsigned Slot = 0, CurSize = TypeStack.size();
206 while (Slot < CurSize && TypeStack[Slot] != Ty) ++Slot; // Scan for type
208 // This is another base case for the recursion. In this case, we know
209 // that we have looped back to a type that we have previously visited.
210 // Generate the appropriate upreference to handle this.
211 if (Slot < CurSize) {
212 Result += "\\" + utostr(CurSize-Slot); // Here's the upreference
216 TypeStack.push_back(Ty); // Recursive case: Add us to the stack..
218 switch (Ty->getTypeID()) {
219 case Type::IntegerTyID: {
220 unsigned BitWidth = cast<IntegerType>(Ty)->getBitWidth();
221 Result += "i" + utostr(BitWidth);
224 case Type::FunctionTyID: {
225 const FunctionType *FTy = cast<FunctionType>(Ty);
226 calcTypeName(FTy->getReturnType(), TypeStack, TypeNames, Result);
228 for (FunctionType::param_iterator I = FTy->param_begin(),
229 E = FTy->param_end(); I != E; ++I) {
230 if (I != FTy->param_begin())
232 calcTypeName(*I, TypeStack, TypeNames, Result);
234 if (FTy->isVarArg()) {
235 if (FTy->getNumParams()) Result += ", ";
241 case Type::StructTyID: {
242 const StructType *STy = cast<StructType>(Ty);
246 for (StructType::element_iterator I = STy->element_begin(),
247 E = STy->element_end(); I != E; ++I) {
248 calcTypeName(*I, TypeStack, TypeNames, Result);
249 if (next(I) != STy->element_end())
258 case Type::PointerTyID: {
259 const PointerType *PTy = cast<PointerType>(Ty);
260 calcTypeName(PTy->getElementType(), TypeStack, TypeNames, Result);
261 if (unsigned AddressSpace = PTy->getAddressSpace())
262 Result += " addrspace(" + utostr(AddressSpace) + ")";
266 case Type::ArrayTyID: {
267 const ArrayType *ATy = cast<ArrayType>(Ty);
268 Result += "[" + utostr(ATy->getNumElements()) + " x ";
269 calcTypeName(ATy->getElementType(), TypeStack, TypeNames, Result);
273 case Type::VectorTyID: {
274 const VectorType *PTy = cast<VectorType>(Ty);
275 Result += "<" + utostr(PTy->getNumElements()) + " x ";
276 calcTypeName(PTy->getElementType(), TypeStack, TypeNames, Result);
280 case Type::OpaqueTyID:
284 Result += "<unrecognized-type>";
288 TypeStack.pop_back(); // Remove self from stack...
291 /// printTypeInt - The internal guts of printing out a type that has a
292 /// potentially named portion.
294 void TypePrinting::print(const Type *Ty) {
295 // Primitive types always print out their description, regardless of whether
296 // they have been named or not.
297 if (Ty->isInteger() || (Ty->isPrimitiveType() && !isa<OpaqueType>(Ty))) {
298 OS << Ty->getDescription();
302 // Check to see if the type is named.
303 std::map<const Type*, std::string>::iterator I = TypeNames.find(Ty);
304 if (I != TypeNames.end()) {
309 // Otherwise we have a type that has not been named but is a derived type.
310 // Carefully recurse the type hierarchy to print out any contained symbolic
312 std::vector<const Type *> TypeStack;
313 std::string TypeName;
314 calcTypeName(Ty, TypeStack, TypeNames, TypeName);
315 TypeNames.insert(std::make_pair(Ty, TypeName));//Cache type name for later use
319 /// printAtLeastOneLevel - Print out one level of the possibly complex type
320 /// without considering any symbolic types that we may have equal to it.
321 void TypePrinting::printAtLeastOneLevel(const Type *Ty) {
322 // FIXME: Just call calcTypeName!
323 if (const FunctionType *FTy = dyn_cast<FunctionType>(Ty)) {
324 print(FTy->getReturnType());
326 for (FunctionType::param_iterator I = FTy->param_begin(),
327 E = FTy->param_end(); I != E; ++I) {
328 if (I != FTy->param_begin())
332 if (FTy->isVarArg()) {
333 if (FTy->getNumParams()) OS << ", ";
340 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
344 for (StructType::element_iterator I = STy->element_begin(),
345 E = STy->element_end(); I != E; ++I) {
346 if (I != STy->element_begin())
356 if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
357 print(PTy->getElementType());
358 if (unsigned AddressSpace = PTy->getAddressSpace())
359 OS << " addrspace(" << AddressSpace << ")";
364 if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
365 OS << '[' << ATy->getNumElements() << " x ";
366 print(ATy->getElementType());
371 if (const VectorType *PTy = dyn_cast<VectorType>(Ty)) {
372 OS << '<' << PTy->getNumElements() << " x ";
373 print(PTy->getElementType());
378 if (isa<OpaqueType>(Ty)) {
383 if (!Ty->isPrimitiveType() && !isa<IntegerType>(Ty))
384 OS << "<unknown derived type>";
391 /// WriteTypeSymbolic - This attempts to write the specified type as a symbolic
392 /// type, iff there is an entry in the modules symbol table for the specified
393 /// type or one of it's component types. This is slower than a simple x << Type
395 void llvm::WriteTypeSymbolic(raw_ostream &Out, const Type *Ty, const Module *M){
396 // FIXME: Remove this space.
399 // If they want us to print out a type, but there is no context, we can't
400 // print it symbolically.
402 Out << Ty->getDescription();
404 TypePrinting(M, Out).print(Ty);
408 // std::ostream adaptor.
409 void llvm::WriteTypeSymbolic(std::ostream &Out, const Type *Ty,
411 raw_os_ostream RO(Out);
412 WriteTypeSymbolic(RO, Ty, M);
416 //===----------------------------------------------------------------------===//
417 // SlotTracker Class: Enumerate slot numbers for unnamed values
418 //===----------------------------------------------------------------------===//
422 /// This class provides computation of slot numbers for LLVM Assembly writing.
426 /// ValueMap - A mapping of Values to slot numbers
427 typedef DenseMap<const Value*, unsigned> ValueMap;
430 /// TheModule - The module for which we are holding slot numbers
431 const Module* TheModule;
433 /// TheFunction - The function for which we are holding slot numbers
434 const Function* TheFunction;
435 bool FunctionProcessed;
437 /// mMap - The TypePlanes map for the module level data
441 /// fMap - The TypePlanes map for the function level data
446 /// Construct from a module
447 explicit SlotTracker(const Module *M);
448 /// Construct from a function, starting out in incorp state.
449 explicit SlotTracker(const Function *F);
451 /// Return the slot number of the specified value in it's type
452 /// plane. If something is not in the SlotTracker, return -1.
453 int getLocalSlot(const Value *V);
454 int getGlobalSlot(const GlobalValue *V);
456 /// If you'd like to deal with a function instead of just a module, use
457 /// this method to get its data into the SlotTracker.
458 void incorporateFunction(const Function *F) {
460 FunctionProcessed = false;
463 /// After calling incorporateFunction, use this method to remove the
464 /// most recently incorporated function from the SlotTracker. This
465 /// will reset the state of the machine back to just the module contents.
466 void purgeFunction();
468 // Implementation Details
470 /// This function does the actual initialization.
471 inline void initialize();
473 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
474 void CreateModuleSlot(const GlobalValue *V);
476 /// CreateFunctionSlot - Insert the specified Value* into the slot table.
477 void CreateFunctionSlot(const Value *V);
479 /// Add all of the module level global variables (and their initializers)
480 /// and function declarations, but not the contents of those functions.
481 void processModule();
483 /// Add all of the functions arguments, basic blocks, and instructions
484 void processFunction();
486 SlotTracker(const SlotTracker &); // DO NOT IMPLEMENT
487 void operator=(const SlotTracker &); // DO NOT IMPLEMENT
490 } // end anonymous namespace
493 static SlotTracker *createSlotTracker(const Value *V) {
494 if (const Argument *FA = dyn_cast<Argument>(V))
495 return new SlotTracker(FA->getParent());
497 if (const Instruction *I = dyn_cast<Instruction>(V))
498 return new SlotTracker(I->getParent()->getParent());
500 if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
501 return new SlotTracker(BB->getParent());
503 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
504 return new SlotTracker(GV->getParent());
506 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
507 return new SlotTracker(GA->getParent());
509 if (const Function *Func = dyn_cast<Function>(V))
510 return new SlotTracker(Func);
516 #define ST_DEBUG(X) cerr << X
521 // Module level constructor. Causes the contents of the Module (sans functions)
522 // to be added to the slot table.
523 SlotTracker::SlotTracker(const Module *M)
524 : TheModule(M), TheFunction(0), FunctionProcessed(false), mNext(0), fNext(0) {
527 // Function level constructor. Causes the contents of the Module and the one
528 // function provided to be added to the slot table.
529 SlotTracker::SlotTracker(const Function *F)
530 : TheModule(F ? F->getParent() : 0), TheFunction(F), FunctionProcessed(false),
534 inline void SlotTracker::initialize() {
537 TheModule = 0; ///< Prevent re-processing next time we're called.
540 if (TheFunction && !FunctionProcessed)
544 // Iterate through all the global variables, functions, and global
545 // variable initializers and create slots for them.
546 void SlotTracker::processModule() {
547 ST_DEBUG("begin processModule!\n");
549 // Add all of the unnamed global variables to the value table.
550 for (Module::const_global_iterator I = TheModule->global_begin(),
551 E = TheModule->global_end(); I != E; ++I)
555 // Add all the unnamed functions to the table.
556 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
561 ST_DEBUG("end processModule!\n");
565 // Process the arguments, basic blocks, and instructions of a function.
566 void SlotTracker::processFunction() {
567 ST_DEBUG("begin processFunction!\n");
570 // Add all the function arguments with no names.
571 for(Function::const_arg_iterator AI = TheFunction->arg_begin(),
572 AE = TheFunction->arg_end(); AI != AE; ++AI)
574 CreateFunctionSlot(AI);
576 ST_DEBUG("Inserting Instructions:\n");
578 // Add all of the basic blocks and instructions with no names.
579 for (Function::const_iterator BB = TheFunction->begin(),
580 E = TheFunction->end(); BB != E; ++BB) {
582 CreateFunctionSlot(BB);
583 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
584 if (I->getType() != Type::VoidTy && !I->hasName())
585 CreateFunctionSlot(I);
588 FunctionProcessed = true;
590 ST_DEBUG("end processFunction!\n");
593 /// Clean up after incorporating a function. This is the only way to get out of
594 /// the function incorporation state that affects get*Slot/Create*Slot. Function
595 /// incorporation state is indicated by TheFunction != 0.
596 void SlotTracker::purgeFunction() {
597 ST_DEBUG("begin purgeFunction!\n");
598 fMap.clear(); // Simply discard the function level map
600 FunctionProcessed = false;
601 ST_DEBUG("end purgeFunction!\n");
604 /// getGlobalSlot - Get the slot number of a global value.
605 int SlotTracker::getGlobalSlot(const GlobalValue *V) {
606 // Check for uninitialized state and do lazy initialization.
609 // Find the type plane in the module map
610 ValueMap::iterator MI = mMap.find(V);
611 return MI == mMap.end() ? -1 : (int)MI->second;
615 /// getLocalSlot - Get the slot number for a value that is local to a function.
616 int SlotTracker::getLocalSlot(const Value *V) {
617 assert(!isa<Constant>(V) && "Can't get a constant or global slot with this!");
619 // Check for uninitialized state and do lazy initialization.
622 ValueMap::iterator FI = fMap.find(V);
623 return FI == fMap.end() ? -1 : (int)FI->second;
627 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
628 void SlotTracker::CreateModuleSlot(const GlobalValue *V) {
629 assert(V && "Can't insert a null Value into SlotTracker!");
630 assert(V->getType() != Type::VoidTy && "Doesn't need a slot!");
631 assert(!V->hasName() && "Doesn't need a slot!");
633 unsigned DestSlot = mNext++;
636 ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" <<
638 // G = Global, F = Function, A = Alias, o = other
639 ST_DEBUG((isa<GlobalVariable>(V) ? 'G' :
640 (isa<Function>(V) ? 'F' :
641 (isa<GlobalAlias>(V) ? 'A' : 'o'))) << "]\n");
645 /// CreateSlot - Create a new slot for the specified value if it has no name.
646 void SlotTracker::CreateFunctionSlot(const Value *V) {
647 assert(V->getType() != Type::VoidTy && !V->hasName() &&
648 "Doesn't need a slot!");
650 unsigned DestSlot = fNext++;
653 // G = Global, F = Function, o = other
654 ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" <<
655 DestSlot << " [o]\n");
660 //===----------------------------------------------------------------------===//
661 // AsmWriter Implementation
662 //===----------------------------------------------------------------------===//
664 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
665 TypePrinting &TypePrinter,
666 SlotTracker *Machine);
670 static const char *getPredicateText(unsigned predicate) {
671 const char * pred = "unknown";
673 case FCmpInst::FCMP_FALSE: pred = "false"; break;
674 case FCmpInst::FCMP_OEQ: pred = "oeq"; break;
675 case FCmpInst::FCMP_OGT: pred = "ogt"; break;
676 case FCmpInst::FCMP_OGE: pred = "oge"; break;
677 case FCmpInst::FCMP_OLT: pred = "olt"; break;
678 case FCmpInst::FCMP_OLE: pred = "ole"; break;
679 case FCmpInst::FCMP_ONE: pred = "one"; break;
680 case FCmpInst::FCMP_ORD: pred = "ord"; break;
681 case FCmpInst::FCMP_UNO: pred = "uno"; break;
682 case FCmpInst::FCMP_UEQ: pred = "ueq"; break;
683 case FCmpInst::FCMP_UGT: pred = "ugt"; break;
684 case FCmpInst::FCMP_UGE: pred = "uge"; break;
685 case FCmpInst::FCMP_ULT: pred = "ult"; break;
686 case FCmpInst::FCMP_ULE: pred = "ule"; break;
687 case FCmpInst::FCMP_UNE: pred = "une"; break;
688 case FCmpInst::FCMP_TRUE: pred = "true"; break;
689 case ICmpInst::ICMP_EQ: pred = "eq"; break;
690 case ICmpInst::ICMP_NE: pred = "ne"; break;
691 case ICmpInst::ICMP_SGT: pred = "sgt"; break;
692 case ICmpInst::ICMP_SGE: pred = "sge"; break;
693 case ICmpInst::ICMP_SLT: pred = "slt"; break;
694 case ICmpInst::ICMP_SLE: pred = "sle"; break;
695 case ICmpInst::ICMP_UGT: pred = "ugt"; break;
696 case ICmpInst::ICMP_UGE: pred = "uge"; break;
697 case ICmpInst::ICMP_ULT: pred = "ult"; break;
698 case ICmpInst::ICMP_ULE: pred = "ule"; break;
703 static void WriteConstantInt(raw_ostream &Out, const Constant *CV,
704 TypePrinting &TypePrinter, SlotTracker *Machine) {
705 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
706 if (CI->getType() == Type::Int1Ty) {
707 Out << (CI->getZExtValue() ? "true" : "false");
710 Out << CI->getValue();
714 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
715 if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEdouble ||
716 &CFP->getValueAPF().getSemantics() == &APFloat::IEEEsingle) {
717 // We would like to output the FP constant value in exponential notation,
718 // but we cannot do this if doing so will lose precision. Check here to
719 // make sure that we only output it in exponential format if we can parse
720 // the value back and get the same value.
723 bool isDouble = &CFP->getValueAPF().getSemantics()==&APFloat::IEEEdouble;
724 double Val = isDouble ? CFP->getValueAPF().convertToDouble() :
725 CFP->getValueAPF().convertToFloat();
726 std::string StrVal = ftostr(CFP->getValueAPF());
728 // Check to make sure that the stringized number is not some string like
729 // "Inf" or NaN, that atof will accept, but the lexer will not. Check
730 // that the string matches the "[-+]?[0-9]" regex.
732 if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
733 ((StrVal[0] == '-' || StrVal[0] == '+') &&
734 (StrVal[1] >= '0' && StrVal[1] <= '9'))) {
735 // Reparse stringized version!
736 if (atof(StrVal.c_str()) == Val) {
741 // Otherwise we could not reparse it to exactly the same value, so we must
742 // output the string in hexadecimal format! Note that loading and storing
743 // floating point types changes the bits of NaNs on some hosts, notably
744 // x86, so we must not use these types.
745 assert(sizeof(double) == sizeof(uint64_t) &&
746 "assuming that double is 64 bits!");
748 APFloat apf = CFP->getValueAPF();
749 // Floats are represented in ASCII IR as double, convert.
751 apf.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
754 utohex_buffer(uint64_t(apf.bitcastToAPInt().getZExtValue()),
759 // Some form of long double. These appear as a magic letter identifying
760 // the type, then a fixed number of hex digits.
762 if (&CFP->getValueAPF().getSemantics() == &APFloat::x87DoubleExtended)
764 else if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEquad)
766 else if (&CFP->getValueAPF().getSemantics() == &APFloat::PPCDoubleDouble)
769 assert(0 && "Unsupported floating point type");
770 // api needed to prevent premature destruction
771 APInt api = CFP->getValueAPF().bitcastToAPInt();
772 const uint64_t* p = api.getRawData();
775 int width = api.getBitWidth();
776 for (int j=0; j<width; j+=4, shiftcount-=4) {
777 unsigned int nibble = (word>>shiftcount) & 15;
779 Out << (unsigned char)(nibble + '0');
781 Out << (unsigned char)(nibble - 10 + 'A');
782 if (shiftcount == 0 && j+4 < width) {
786 shiftcount = width-j-4;
792 if (isa<ConstantAggregateZero>(CV)) {
793 Out << "zeroinitializer";
797 if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
798 // As a special case, print the array as a string if it is an array of
799 // i8 with ConstantInt values.
801 const Type *ETy = CA->getType()->getElementType();
802 if (CA->isString()) {
804 PrintEscapedString(CA->getAsString(), Out);
806 } else { // Cannot output in string format...
808 if (CA->getNumOperands()) {
809 TypePrinter.print(ETy);
811 WriteAsOperandInternal(Out, CA->getOperand(0),
812 TypePrinter, Machine);
813 for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
815 TypePrinter.print(ETy);
817 WriteAsOperandInternal(Out, CA->getOperand(i), TypePrinter, Machine);
825 if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
826 if (CS->getType()->isPacked())
829 unsigned N = CS->getNumOperands();
832 TypePrinter.print(CS->getOperand(0)->getType());
835 WriteAsOperandInternal(Out, CS->getOperand(0), TypePrinter, Machine);
837 for (unsigned i = 1; i < N; i++) {
839 TypePrinter.print(CS->getOperand(i)->getType());
842 WriteAsOperandInternal(Out, CS->getOperand(i), TypePrinter, Machine);
848 if (CS->getType()->isPacked())
853 if (const ConstantVector *CP = dyn_cast<ConstantVector>(CV)) {
854 const Type *ETy = CP->getType()->getElementType();
855 assert(CP->getNumOperands() > 0 &&
856 "Number of operands for a PackedConst must be > 0");
858 TypePrinter.print(ETy);
860 WriteAsOperandInternal(Out, CP->getOperand(0), TypePrinter, Machine);
861 for (unsigned i = 1, e = CP->getNumOperands(); i != e; ++i) {
863 TypePrinter.print(ETy);
865 WriteAsOperandInternal(Out, CP->getOperand(i), TypePrinter, Machine);
871 if (isa<ConstantPointerNull>(CV)) {
876 if (isa<UndefValue>(CV)) {
881 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
882 Out << CE->getOpcodeName();
884 Out << ' ' << getPredicateText(CE->getPredicate());
887 for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) {
888 TypePrinter.print((*OI)->getType());
890 WriteAsOperandInternal(Out, *OI, TypePrinter, Machine);
891 if (OI+1 != CE->op_end())
895 if (CE->hasIndices()) {
896 const SmallVector<unsigned, 4> &Indices = CE->getIndices();
897 for (unsigned i = 0, e = Indices.size(); i != e; ++i)
898 Out << ", " << Indices[i];
903 TypePrinter.print(CE->getType());
910 Out << "<placeholder or erroneous Constant>";
914 /// WriteAsOperand - Write the name of the specified value out to the specified
915 /// ostream. This can be useful when you just want to print int %reg126, not
916 /// the whole instruction that generated it.
918 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
919 TypePrinting &TypePrinter,
920 SlotTracker *Machine) {
922 PrintLLVMName(Out, V);
926 const Constant *CV = dyn_cast<Constant>(V);
927 if (CV && !isa<GlobalValue>(CV)) {
928 WriteConstantInt(Out, CV, TypePrinter, Machine);
932 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
934 if (IA->hasSideEffects())
935 Out << "sideeffect ";
937 PrintEscapedString(IA->getAsmString(), Out);
939 PrintEscapedString(IA->getConstraintString(), Out);
947 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
948 Slot = Machine->getGlobalSlot(GV);
951 Slot = Machine->getLocalSlot(V);
954 Machine = createSlotTracker(V);
956 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
957 Slot = Machine->getGlobalSlot(GV);
960 Slot = Machine->getLocalSlot(V);
969 Out << Prefix << Slot;
974 /// WriteAsOperand - Write the name of the specified value out to the specified
975 /// ostream. This can be useful when you just want to print int %reg126, not
976 /// the whole instruction that generated it.
978 void llvm::WriteAsOperand(std::ostream &Out, const Value *V, bool PrintType,
979 const Module *Context) {
980 raw_os_ostream OS(Out);
981 WriteAsOperand(OS, V, PrintType, Context);
984 void llvm::WriteAsOperand(raw_ostream &Out, const Value *V, bool PrintType,
985 const Module *Context) {
986 if (Context == 0) Context = getModuleFromVal(V);
988 TypePrinting TypePrinter(Context, Out);
990 TypePrinter.print(V->getType());
994 WriteAsOperandInternal(Out, V, TypePrinter, 0);
1000 class AssemblyWriter {
1002 SlotTracker &Machine;
1003 const Module *TheModule;
1004 TypePrinting TypePrinter;
1005 AssemblyAnnotationWriter *AnnotationWriter;
1007 inline AssemblyWriter(raw_ostream &o, SlotTracker &Mac, const Module *M,
1008 AssemblyAnnotationWriter *AAW)
1009 : Out(o), Machine(Mac), TheModule(M), TypePrinter(M, Out),
1010 AnnotationWriter(AAW) {
1013 void write(const Module *M) { printModule(M); }
1015 void write(const GlobalValue *G) {
1016 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(G))
1018 else if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(G))
1020 else if (const Function *F = dyn_cast<Function>(G))
1023 assert(0 && "Unknown global");
1026 void write(const BasicBlock *BB) { printBasicBlock(BB); }
1027 void write(const Instruction *I) { printInstruction(*I); }
1028 // void write(const Type *Ty) { printType(Ty); }
1030 void writeOperand(const Value *Op, bool PrintType);
1031 void writeParamOperand(const Value *Operand, Attributes Attrs);
1033 const Module* getModule() { return TheModule; }
1036 void printModule(const Module *M);
1037 void printTypeSymbolTable(const TypeSymbolTable &ST);
1038 void printGlobal(const GlobalVariable *GV);
1039 void printAlias(const GlobalAlias *GV);
1040 void printFunction(const Function *F);
1041 void printArgument(const Argument *FA, Attributes Attrs);
1042 void printBasicBlock(const BasicBlock *BB);
1043 void printInstruction(const Instruction &I);
1045 // printType - Go to extreme measures to attempt to print out a short,
1046 // symbolic version of a type name.
1048 void printType(const Type *Ty) {
1049 TypePrinter.print(Ty);
1052 // printInfoComment - Print a little comment after the instruction indicating
1053 // which slot it occupies.
1054 void printInfoComment(const Value &V);
1056 } // end of llvm namespace
1059 void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType) {
1061 Out << "<null operand!>";
1064 printType(Operand->getType());
1067 WriteAsOperandInternal(Out, Operand, TypePrinter, &Machine);
1071 void AssemblyWriter::writeParamOperand(const Value *Operand,
1074 Out << "<null operand!>";
1077 printType(Operand->getType());
1078 // Print parameter attributes list
1079 if (Attrs != Attribute::None)
1080 Out << ' ' << Attribute::getAsString(Attrs);
1082 // Print the operand
1083 WriteAsOperandInternal(Out, Operand, TypePrinter, &Machine);
1087 void AssemblyWriter::printModule(const Module *M) {
1088 if (!M->getModuleIdentifier().empty() &&
1089 // Don't print the ID if it will start a new line (which would
1090 // require a comment char before it).
1091 M->getModuleIdentifier().find('\n') == std::string::npos)
1092 Out << "; ModuleID = '" << M->getModuleIdentifier() << "'\n";
1094 if (!M->getDataLayout().empty())
1095 Out << "target datalayout = \"" << M->getDataLayout() << "\"\n";
1096 if (!M->getTargetTriple().empty())
1097 Out << "target triple = \"" << M->getTargetTriple() << "\"\n";
1099 if (!M->getModuleInlineAsm().empty()) {
1100 // Split the string into lines, to make it easier to read the .ll file.
1101 std::string Asm = M->getModuleInlineAsm();
1103 size_t NewLine = Asm.find_first_of('\n', CurPos);
1104 while (NewLine != std::string::npos) {
1105 // We found a newline, print the portion of the asm string from the
1106 // last newline up to this newline.
1107 Out << "module asm \"";
1108 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.begin()+NewLine),
1112 NewLine = Asm.find_first_of('\n', CurPos);
1114 Out << "module asm \"";
1115 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.end()), Out);
1119 // Loop over the dependent libraries and emit them.
1120 Module::lib_iterator LI = M->lib_begin();
1121 Module::lib_iterator LE = M->lib_end();
1123 Out << "deplibs = [ ";
1125 Out << '"' << *LI << '"';
1133 // Loop over the symbol table, emitting all named constants.
1134 printTypeSymbolTable(M->getTypeSymbolTable());
1136 for (Module::const_global_iterator I = M->global_begin(), E = M->global_end();
1140 // Output all aliases.
1141 if (!M->alias_empty()) Out << "\n";
1142 for (Module::const_alias_iterator I = M->alias_begin(), E = M->alias_end();
1146 // Output all of the functions.
1147 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
1151 static void PrintLinkage(GlobalValue::LinkageTypes LT, raw_ostream &Out) {
1153 case GlobalValue::PrivateLinkage: Out << "private "; break;
1154 case GlobalValue::InternalLinkage: Out << "internal "; break;
1155 case GlobalValue::LinkOnceLinkage: Out << "linkonce "; break;
1156 case GlobalValue::WeakLinkage: Out << "weak "; break;
1157 case GlobalValue::CommonLinkage: Out << "common "; break;
1158 case GlobalValue::AppendingLinkage: Out << "appending "; break;
1159 case GlobalValue::DLLImportLinkage: Out << "dllimport "; break;
1160 case GlobalValue::DLLExportLinkage: Out << "dllexport "; break;
1161 case GlobalValue::ExternalWeakLinkage: Out << "extern_weak "; break;
1162 case GlobalValue::ExternalLinkage: break;
1163 case GlobalValue::GhostLinkage:
1164 Out << "GhostLinkage not allowed in AsmWriter!\n";
1170 static void PrintVisibility(GlobalValue::VisibilityTypes Vis,
1173 default: assert(0 && "Invalid visibility style!");
1174 case GlobalValue::DefaultVisibility: break;
1175 case GlobalValue::HiddenVisibility: Out << "hidden "; break;
1176 case GlobalValue::ProtectedVisibility: Out << "protected "; break;
1180 void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
1181 if (GV->hasName()) {
1182 PrintLLVMName(Out, GV);
1186 if (!GV->hasInitializer() && GV->hasExternalLinkage())
1189 PrintLinkage(GV->getLinkage(), Out);
1190 PrintVisibility(GV->getVisibility(), Out);
1192 if (GV->isThreadLocal()) Out << "thread_local ";
1193 if (unsigned AddressSpace = GV->getType()->getAddressSpace())
1194 Out << "addrspace(" << AddressSpace << ") ";
1195 Out << (GV->isConstant() ? "constant " : "global ");
1196 printType(GV->getType()->getElementType());
1198 if (GV->hasInitializer()) {
1200 writeOperand(GV->getInitializer(), false);
1203 if (GV->hasSection())
1204 Out << ", section \"" << GV->getSection() << '"';
1205 if (GV->getAlignment())
1206 Out << ", align " << GV->getAlignment();
1208 printInfoComment(*GV);
1212 void AssemblyWriter::printAlias(const GlobalAlias *GA) {
1213 // Don't crash when dumping partially built GA
1215 Out << "<<nameless>> = ";
1217 PrintLLVMName(Out, GA);
1220 PrintVisibility(GA->getVisibility(), Out);
1224 PrintLinkage(GA->getLinkage(), Out);
1226 const Constant *Aliasee = GA->getAliasee();
1228 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Aliasee)) {
1229 printType(GV->getType());
1231 PrintLLVMName(Out, GV);
1232 } else if (const Function *F = dyn_cast<Function>(Aliasee)) {
1233 printType(F->getFunctionType());
1236 WriteAsOperandInternal(Out, F, TypePrinter, &Machine);
1237 } else if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(Aliasee)) {
1238 printType(GA->getType());
1240 PrintLLVMName(Out, GA);
1242 const ConstantExpr *CE = 0;
1243 if ((CE = dyn_cast<ConstantExpr>(Aliasee)) &&
1244 (CE->getOpcode() == Instruction::BitCast)) {
1245 writeOperand(CE, false);
1247 assert(0 && "Unsupported aliasee");
1250 printInfoComment(*GA);
1254 void AssemblyWriter::printTypeSymbolTable(const TypeSymbolTable &ST) {
1256 for (TypeSymbolTable::const_iterator TI = ST.begin(), TE = ST.end();
1259 PrintLLVMName(Out, &TI->first[0], TI->first.size(), LocalPrefix);
1262 // Make sure we print out at least one level of the type structure, so
1263 // that we do not get %FILE = type %FILE
1264 TypePrinter.printAtLeastOneLevel(TI->second);
1269 /// printFunction - Print all aspects of a function.
1271 void AssemblyWriter::printFunction(const Function *F) {
1272 // Print out the return type and name.
1275 if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, Out);
1277 if (F->isDeclaration())
1282 PrintLinkage(F->getLinkage(), Out);
1283 PrintVisibility(F->getVisibility(), Out);
1285 // Print the calling convention.
1286 switch (F->getCallingConv()) {
1287 case CallingConv::C: break; // default
1288 case CallingConv::Fast: Out << "fastcc "; break;
1289 case CallingConv::Cold: Out << "coldcc "; break;
1290 case CallingConv::X86_StdCall: Out << "x86_stdcallcc "; break;
1291 case CallingConv::X86_FastCall: Out << "x86_fastcallcc "; break;
1292 default: Out << "cc" << F->getCallingConv() << " "; break;
1295 const FunctionType *FT = F->getFunctionType();
1296 const AttrListPtr &Attrs = F->getAttributes();
1297 Attributes RetAttrs = Attrs.getRetAttributes();
1298 if (RetAttrs != Attribute::None)
1299 Out << Attribute::getAsString(Attrs.getRetAttributes()) << ' ';
1300 printType(F->getReturnType());
1302 WriteAsOperandInternal(Out, F, TypePrinter, &Machine);
1304 Machine.incorporateFunction(F);
1306 // Loop over the arguments, printing them...
1309 if (!F->isDeclaration()) {
1310 // If this isn't a declaration, print the argument names as well.
1311 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
1313 // Insert commas as we go... the first arg doesn't get a comma
1314 if (I != F->arg_begin()) Out << ", ";
1315 printArgument(I, Attrs.getParamAttributes(Idx));
1319 // Otherwise, print the types from the function type.
1320 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
1321 // Insert commas as we go... the first arg doesn't get a comma
1325 printType(FT->getParamType(i));
1327 Attributes ArgAttrs = Attrs.getParamAttributes(i+1);
1328 if (ArgAttrs != Attribute::None)
1329 Out << ' ' << Attribute::getAsString(ArgAttrs);
1333 // Finish printing arguments...
1334 if (FT->isVarArg()) {
1335 if (FT->getNumParams()) Out << ", ";
1336 Out << "..."; // Output varargs portion of signature!
1339 Attributes FnAttrs = Attrs.getFnAttributes();
1340 if (FnAttrs != Attribute::None)
1341 Out << ' ' << Attribute::getAsString(Attrs.getFnAttributes());
1342 if (F->hasSection())
1343 Out << " section \"" << F->getSection() << '"';
1344 if (F->getAlignment())
1345 Out << " align " << F->getAlignment();
1347 Out << " gc \"" << F->getGC() << '"';
1348 if (F->isDeclaration()) {
1353 // Output all of its basic blocks... for the function
1354 for (Function::const_iterator I = F->begin(), E = F->end(); I != E; ++I)
1360 Machine.purgeFunction();
1363 /// printArgument - This member is called for every argument that is passed into
1364 /// the function. Simply print it out
1366 void AssemblyWriter::printArgument(const Argument *Arg,
1369 printType(Arg->getType());
1371 // Output parameter attributes list
1372 if (Attrs != Attribute::None)
1373 Out << ' ' << Attribute::getAsString(Attrs);
1375 // Output name, if available...
1376 if (Arg->hasName()) {
1378 PrintLLVMName(Out, Arg);
1382 /// printBasicBlock - This member is called for each basic block in a method.
1384 void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {
1385 if (BB->hasName()) { // Print out the label if it exists...
1387 PrintLLVMName(Out, BB->getNameStart(), BB->getNameLen(), LabelPrefix);
1389 } else if (!BB->use_empty()) { // Don't print block # of no uses...
1390 Out << "\n; <label>:";
1391 int Slot = Machine.getLocalSlot(BB);
1398 if (BB->getParent() == 0)
1399 Out << "\t\t; Error: Block without parent!";
1400 else if (BB != &BB->getParent()->getEntryBlock()) { // Not the entry block?
1401 // Output predecessors for the block...
1403 pred_const_iterator PI = pred_begin(BB), PE = pred_end(BB);
1406 Out << " No predecessors!";
1409 writeOperand(*PI, false);
1410 for (++PI; PI != PE; ++PI) {
1412 writeOperand(*PI, false);
1419 if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(BB, Out);
1421 // Output all of the instructions in the basic block...
1422 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
1423 printInstruction(*I);
1425 if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(BB, Out);
1429 /// printInfoComment - Print a little comment after the instruction indicating
1430 /// which slot it occupies.
1432 void AssemblyWriter::printInfoComment(const Value &V) {
1433 if (V.getType() != Type::VoidTy) {
1435 printType(V.getType());
1438 if (!V.hasName() && !isa<Instruction>(V)) {
1440 if (const GlobalValue *GV = dyn_cast<GlobalValue>(&V))
1441 SlotNum = Machine.getGlobalSlot(GV);
1443 SlotNum = Machine.getLocalSlot(&V);
1447 Out << ':' << SlotNum; // Print out the def slot taken.
1449 Out << " [#uses=" << V.getNumUses() << ']'; // Output # uses
1453 // This member is called for each Instruction in a function..
1454 void AssemblyWriter::printInstruction(const Instruction &I) {
1455 if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, Out);
1459 // Print out name if it exists...
1461 PrintLLVMName(Out, &I);
1463 } else if (I.getType() != Type::VoidTy) {
1464 // Print out the def slot taken.
1465 int SlotNum = Machine.getLocalSlot(&I);
1467 Out << "<badref> = ";
1469 Out << '%' << SlotNum << " = ";
1472 // If this is a volatile load or store, print out the volatile marker.
1473 if ((isa<LoadInst>(I) && cast<LoadInst>(I).isVolatile()) ||
1474 (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile())) {
1476 } else if (isa<CallInst>(I) && cast<CallInst>(I).isTailCall()) {
1477 // If this is a call, check if it's a tail call.
1481 // Print out the opcode...
1482 Out << I.getOpcodeName();
1484 // Print out the compare instruction predicates
1485 if (const CmpInst *CI = dyn_cast<CmpInst>(&I))
1486 Out << ' ' << getPredicateText(CI->getPredicate());
1488 // Print out the type of the operands...
1489 const Value *Operand = I.getNumOperands() ? I.getOperand(0) : 0;
1491 // Special case conditional branches to swizzle the condition out to the front
1492 if (isa<BranchInst>(I) && cast<BranchInst>(I).isConditional()) {
1493 BranchInst &BI(cast<BranchInst>(I));
1495 writeOperand(BI.getCondition(), true);
1497 writeOperand(BI.getSuccessor(0), true);
1499 writeOperand(BI.getSuccessor(1), true);
1501 } else if (isa<SwitchInst>(I)) {
1502 // Special case switch statement to get formatting nice and correct...
1504 writeOperand(Operand , true);
1506 writeOperand(I.getOperand(1), true);
1509 for (unsigned op = 2, Eop = I.getNumOperands(); op < Eop; op += 2) {
1511 writeOperand(I.getOperand(op ), true);
1513 writeOperand(I.getOperand(op+1), true);
1516 } else if (isa<PHINode>(I)) {
1518 printType(I.getType());
1521 for (unsigned op = 0, Eop = I.getNumOperands(); op < Eop; op += 2) {
1522 if (op) Out << ", ";
1524 writeOperand(I.getOperand(op ), false); Out << ", ";
1525 writeOperand(I.getOperand(op+1), false); Out << " ]";
1527 } else if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&I)) {
1529 writeOperand(I.getOperand(0), true);
1530 for (const unsigned *i = EVI->idx_begin(), *e = EVI->idx_end(); i != e; ++i)
1532 } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&I)) {
1534 writeOperand(I.getOperand(0), true); Out << ", ";
1535 writeOperand(I.getOperand(1), true);
1536 for (const unsigned *i = IVI->idx_begin(), *e = IVI->idx_end(); i != e; ++i)
1538 } else if (isa<ReturnInst>(I) && !Operand) {
1540 } else if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
1541 // Print the calling convention being used.
1542 switch (CI->getCallingConv()) {
1543 case CallingConv::C: break; // default
1544 case CallingConv::Fast: Out << " fastcc"; break;
1545 case CallingConv::Cold: Out << " coldcc"; break;
1546 case CallingConv::X86_StdCall: Out << " x86_stdcallcc"; break;
1547 case CallingConv::X86_FastCall: Out << " x86_fastcallcc"; break;
1548 default: Out << " cc" << CI->getCallingConv(); break;
1551 const PointerType *PTy = cast<PointerType>(Operand->getType());
1552 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1553 const Type *RetTy = FTy->getReturnType();
1554 const AttrListPtr &PAL = CI->getAttributes();
1556 if (PAL.getRetAttributes() != Attribute::None)
1557 Out << ' ' << Attribute::getAsString(PAL.getRetAttributes());
1559 // If possible, print out the short form of the call instruction. We can
1560 // only do this if the first argument is a pointer to a nonvararg function,
1561 // and if the return type is not a pointer to a function.
1564 if (!FTy->isVarArg() &&
1565 (!isa<PointerType>(RetTy) ||
1566 !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
1569 writeOperand(Operand, false);
1571 writeOperand(Operand, true);
1574 for (unsigned op = 1, Eop = I.getNumOperands(); op < Eop; ++op) {
1577 writeParamOperand(I.getOperand(op), PAL.getParamAttributes(op));
1580 if (PAL.getFnAttributes() != Attribute::None)
1581 Out << ' ' << Attribute::getAsString(PAL.getFnAttributes());
1582 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
1583 const PointerType *PTy = cast<PointerType>(Operand->getType());
1584 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1585 const Type *RetTy = FTy->getReturnType();
1586 const AttrListPtr &PAL = II->getAttributes();
1588 // Print the calling convention being used.
1589 switch (II->getCallingConv()) {
1590 case CallingConv::C: break; // default
1591 case CallingConv::Fast: Out << " fastcc"; break;
1592 case CallingConv::Cold: Out << " coldcc"; break;
1593 case CallingConv::X86_StdCall: Out << " x86_stdcallcc"; break;
1594 case CallingConv::X86_FastCall: Out << " x86_fastcallcc"; break;
1595 default: Out << " cc" << II->getCallingConv(); break;
1598 if (PAL.getRetAttributes() != Attribute::None)
1599 Out << ' ' << Attribute::getAsString(PAL.getRetAttributes());
1601 // If possible, print out the short form of the invoke instruction. We can
1602 // only do this if the first argument is a pointer to a nonvararg function,
1603 // and if the return type is not a pointer to a function.
1606 if (!FTy->isVarArg() &&
1607 (!isa<PointerType>(RetTy) ||
1608 !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
1611 writeOperand(Operand, false);
1613 writeOperand(Operand, true);
1616 for (unsigned op = 3, Eop = I.getNumOperands(); op < Eop; ++op) {
1619 writeParamOperand(I.getOperand(op), PAL.getParamAttributes(op-2));
1623 if (PAL.getFnAttributes() != Attribute::None)
1624 Out << ' ' << Attribute::getAsString(PAL.getFnAttributes());
1626 Out << "\n\t\t\tto ";
1627 writeOperand(II->getNormalDest(), true);
1629 writeOperand(II->getUnwindDest(), true);
1631 } else if (const AllocationInst *AI = dyn_cast<AllocationInst>(&I)) {
1633 printType(AI->getType()->getElementType());
1634 if (AI->isArrayAllocation()) {
1636 writeOperand(AI->getArraySize(), true);
1638 if (AI->getAlignment()) {
1639 Out << ", align " << AI->getAlignment();
1641 } else if (isa<CastInst>(I)) {
1644 writeOperand(Operand, true); // Work with broken code
1647 printType(I.getType());
1648 } else if (isa<VAArgInst>(I)) {
1651 writeOperand(Operand, true); // Work with broken code
1654 printType(I.getType());
1655 } else if (Operand) { // Print the normal way...
1657 // PrintAllTypes - Instructions who have operands of all the same type
1658 // omit the type from all but the first operand. If the instruction has
1659 // different type operands (for example br), then they are all printed.
1660 bool PrintAllTypes = false;
1661 const Type *TheType = Operand->getType();
1663 // Select, Store and ShuffleVector always print all types.
1664 if (isa<SelectInst>(I) || isa<StoreInst>(I) || isa<ShuffleVectorInst>(I)
1665 || isa<ReturnInst>(I)) {
1666 PrintAllTypes = true;
1668 for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) {
1669 Operand = I.getOperand(i);
1670 // note that Operand shouldn't be null, but the test helps make dump()
1671 // more tolerant of malformed IR
1672 if (Operand && Operand->getType() != TheType) {
1673 PrintAllTypes = true; // We have differing types! Print them all!
1679 if (!PrintAllTypes) {
1685 for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) {
1687 writeOperand(I.getOperand(i), PrintAllTypes);
1691 // Print post operand alignment for load/store
1692 if (isa<LoadInst>(I) && cast<LoadInst>(I).getAlignment()) {
1693 Out << ", align " << cast<LoadInst>(I).getAlignment();
1694 } else if (isa<StoreInst>(I) && cast<StoreInst>(I).getAlignment()) {
1695 Out << ", align " << cast<StoreInst>(I).getAlignment();
1698 printInfoComment(I);
1703 //===----------------------------------------------------------------------===//
1704 // External Interface declarations
1705 //===----------------------------------------------------------------------===//
1707 void Module::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1708 raw_os_ostream OS(o);
1711 void Module::print(raw_ostream &OS, AssemblyAnnotationWriter *AAW) const {
1712 SlotTracker SlotTable(this);
1713 AssemblyWriter W(OS, SlotTable, this, AAW);
1717 void Type::print(std::ostream &o) const {
1718 raw_os_ostream OS(o);
1722 void Type::print(raw_ostream &o) const {
1726 o << getDescription();
1729 void Value::print(raw_ostream &OS, AssemblyAnnotationWriter *AAW) const {
1731 OS << "printing a <null> value\n";
1735 if (const Instruction *I = dyn_cast<Instruction>(this)) {
1736 const Function *F = I->getParent() ? I->getParent()->getParent() : 0;
1737 SlotTracker SlotTable(F);
1738 AssemblyWriter W(OS, SlotTable, F ? F->getParent() : 0, AAW);
1740 } else if (const BasicBlock *BB = dyn_cast<BasicBlock>(this)) {
1741 SlotTracker SlotTable(BB->getParent());
1742 AssemblyWriter W(OS, SlotTable,
1743 BB->getParent() ? BB->getParent()->getParent() : 0, AAW);
1745 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(this)) {
1746 SlotTracker SlotTable(GV->getParent());
1747 AssemblyWriter W(OS, SlotTable, GV->getParent(), 0);
1749 } else if (const Constant *C = dyn_cast<Constant>(this)) {
1750 OS << C->getType()->getDescription() << ' ';
1751 TypePrinting TypePrinter(0, OS);
1752 WriteConstantInt(OS, C, TypePrinter, 0);
1753 } else if (const Argument *A = dyn_cast<Argument>(this)) {
1754 WriteAsOperand(OS, this, true,
1755 A->getParent() ? A->getParent()->getParent() : 0);
1756 } else if (isa<InlineAsm>(this)) {
1757 WriteAsOperand(OS, this, true, 0);
1759 assert(0 && "Unknown value to print out!");
1763 void Value::print(std::ostream &O, AssemblyAnnotationWriter *AAW) const {
1764 raw_os_ostream OS(O);
1768 // Value::dump - allow easy printing of Values from the debugger.
1769 void Value::dump() const { print(errs()); errs() << '\n'; errs().flush(); }
1771 // Type::dump - allow easy printing of Types from the debugger.
1772 void Type::dump() const { print(errs()); errs() << '\n'; errs().flush(); }
1774 // Type::dump - allow easy printing of Types from the debugger.
1775 // This one uses type names from the given context module
1776 void Type::dump(const Module *Context) const {
1777 WriteTypeSymbolic(errs(), this, Context);
1782 // Module::dump() - Allow printing of Modules from the debugger.
1783 void Module::dump() const { print(errs(), 0); errs().flush(); }