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();
78 /// PrintLLVMName - Turn the specified name into an 'LLVM name', which is either
79 /// prefixed with % (if the string only contains simple characters) or is
80 /// surrounded with ""'s (if it has special chars in it). Print it out.
81 static void PrintLLVMName(raw_ostream &OS, const char *NameStr,
82 unsigned NameLen, PrefixType Prefix) {
83 assert(NameStr && "Cannot get empty name!");
85 default: assert(0 && "Bad prefix!");
87 case GlobalPrefix: OS << '@'; break;
88 case LabelPrefix: break;
89 case LocalPrefix: OS << '%'; break;
92 // Scan the name to see if it needs quotes first.
93 bool NeedsQuotes = NameStr[0] >= '0' && NameStr[0] <= '9';
95 for (unsigned i = 0; i != NameLen; ++i) {
97 if (!isalnum(C) && C != '-' && C != '.' && C != '_') {
104 // If we didn't need any quotes, just write out the name in one blast.
106 OS.write(NameStr, NameLen);
110 // Okay, we need quotes. Output the quotes and escape any scary characters as
113 for (unsigned i = 0; i != NameLen; ++i) {
115 assert(C != '"' && "Illegal character in LLVM value name!");
118 } else if (isprint(C)) {
122 OS << hexdigit((C >> 4) & 0x0F);
123 OS << hexdigit((C >> 0) & 0x0F);
129 /// getLLVMName - Turn the specified string into an 'LLVM name', which is
130 /// surrounded with ""'s and escaped if it has special chars in it.
131 static std::string getLLVMName(const std::string &Name) {
132 assert(!Name.empty() && "Cannot get empty name!");
134 raw_string_ostream OS(result);
135 PrintLLVMName(OS, Name.c_str(), Name.length(), NoPrefix);
139 /// PrintLLVMName - Turn the specified name into an 'LLVM name', which is either
140 /// prefixed with % (if the string only contains simple characters) or is
141 /// surrounded with ""'s (if it has special chars in it). Print it out.
142 static void PrintLLVMName(raw_ostream &OS, const Value *V) {
143 PrintLLVMName(OS, V->getNameStart(), V->getNameLen(),
144 isa<GlobalValue>(V) ? GlobalPrefix : LocalPrefix);
149 //===----------------------------------------------------------------------===//
150 // SlotTracker Class: Enumerate slot numbers for unnamed values
151 //===----------------------------------------------------------------------===//
155 /// This class provides computation of slot numbers for LLVM Assembly writing.
159 /// ValueMap - A mapping of Values to slot numbers
160 typedef DenseMap<const Value*, unsigned> ValueMap;
163 /// TheModule - The module for which we are holding slot numbers
164 const Module* TheModule;
166 /// TheFunction - The function for which we are holding slot numbers
167 const Function* TheFunction;
168 bool FunctionProcessed;
170 /// mMap - The TypePlanes map for the module level data
174 /// fMap - The TypePlanes map for the function level data
179 /// Construct from a module
180 explicit SlotTracker(const Module *M);
181 /// Construct from a function, starting out in incorp state.
182 explicit SlotTracker(const Function *F);
184 /// Return the slot number of the specified value in it's type
185 /// plane. If something is not in the SlotTracker, return -1.
186 int getLocalSlot(const Value *V);
187 int getGlobalSlot(const GlobalValue *V);
189 /// If you'd like to deal with a function instead of just a module, use
190 /// this method to get its data into the SlotTracker.
191 void incorporateFunction(const Function *F) {
193 FunctionProcessed = false;
196 /// After calling incorporateFunction, use this method to remove the
197 /// most recently incorporated function from the SlotTracker. This
198 /// will reset the state of the machine back to just the module contents.
199 void purgeFunction();
201 // Implementation Details
203 /// This function does the actual initialization.
204 inline void initialize();
206 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
207 void CreateModuleSlot(const GlobalValue *V);
209 /// CreateFunctionSlot - Insert the specified Value* into the slot table.
210 void CreateFunctionSlot(const Value *V);
212 /// Add all of the module level global variables (and their initializers)
213 /// and function declarations, but not the contents of those functions.
214 void processModule();
216 /// Add all of the functions arguments, basic blocks, and instructions
217 void processFunction();
219 SlotTracker(const SlotTracker &); // DO NOT IMPLEMENT
220 void operator=(const SlotTracker &); // DO NOT IMPLEMENT
223 } // end anonymous namespace
226 static SlotTracker *createSlotTracker(const Value *V) {
227 if (const Argument *FA = dyn_cast<Argument>(V))
228 return new SlotTracker(FA->getParent());
230 if (const Instruction *I = dyn_cast<Instruction>(V))
231 return new SlotTracker(I->getParent()->getParent());
233 if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
234 return new SlotTracker(BB->getParent());
236 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
237 return new SlotTracker(GV->getParent());
239 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
240 return new SlotTracker(GA->getParent());
242 if (const Function *Func = dyn_cast<Function>(V))
243 return new SlotTracker(Func);
249 #define ST_DEBUG(X) cerr << X
254 // Module level constructor. Causes the contents of the Module (sans functions)
255 // to be added to the slot table.
256 SlotTracker::SlotTracker(const Module *M)
257 : TheModule(M), TheFunction(0), FunctionProcessed(false), mNext(0), fNext(0) {
260 // Function level constructor. Causes the contents of the Module and the one
261 // function provided to be added to the slot table.
262 SlotTracker::SlotTracker(const Function *F)
263 : TheModule(F ? F->getParent() : 0), TheFunction(F), FunctionProcessed(false),
267 inline void SlotTracker::initialize() {
270 TheModule = 0; ///< Prevent re-processing next time we're called.
273 if (TheFunction && !FunctionProcessed)
277 // Iterate through all the global variables, functions, and global
278 // variable initializers and create slots for them.
279 void SlotTracker::processModule() {
280 ST_DEBUG("begin processModule!\n");
282 // Add all of the unnamed global variables to the value table.
283 for (Module::const_global_iterator I = TheModule->global_begin(),
284 E = TheModule->global_end(); I != E; ++I)
288 // Add all the unnamed functions to the table.
289 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
294 ST_DEBUG("end processModule!\n");
298 // Process the arguments, basic blocks, and instructions of a function.
299 void SlotTracker::processFunction() {
300 ST_DEBUG("begin processFunction!\n");
303 // Add all the function arguments with no names.
304 for(Function::const_arg_iterator AI = TheFunction->arg_begin(),
305 AE = TheFunction->arg_end(); AI != AE; ++AI)
307 CreateFunctionSlot(AI);
309 ST_DEBUG("Inserting Instructions:\n");
311 // Add all of the basic blocks and instructions with no names.
312 for (Function::const_iterator BB = TheFunction->begin(),
313 E = TheFunction->end(); BB != E; ++BB) {
315 CreateFunctionSlot(BB);
316 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
317 if (I->getType() != Type::VoidTy && !I->hasName())
318 CreateFunctionSlot(I);
321 FunctionProcessed = true;
323 ST_DEBUG("end processFunction!\n");
326 /// Clean up after incorporating a function. This is the only way to get out of
327 /// the function incorporation state that affects get*Slot/Create*Slot. Function
328 /// incorporation state is indicated by TheFunction != 0.
329 void SlotTracker::purgeFunction() {
330 ST_DEBUG("begin purgeFunction!\n");
331 fMap.clear(); // Simply discard the function level map
333 FunctionProcessed = false;
334 ST_DEBUG("end purgeFunction!\n");
337 /// getGlobalSlot - Get the slot number of a global value.
338 int SlotTracker::getGlobalSlot(const GlobalValue *V) {
339 // Check for uninitialized state and do lazy initialization.
342 // Find the type plane in the module map
343 ValueMap::iterator MI = mMap.find(V);
344 return MI == mMap.end() ? -1 : (int)MI->second;
348 /// getLocalSlot - Get the slot number for a value that is local to a function.
349 int SlotTracker::getLocalSlot(const Value *V) {
350 assert(!isa<Constant>(V) && "Can't get a constant or global slot with this!");
352 // Check for uninitialized state and do lazy initialization.
355 ValueMap::iterator FI = fMap.find(V);
356 return FI == fMap.end() ? -1 : (int)FI->second;
360 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
361 void SlotTracker::CreateModuleSlot(const GlobalValue *V) {
362 assert(V && "Can't insert a null Value into SlotTracker!");
363 assert(V->getType() != Type::VoidTy && "Doesn't need a slot!");
364 assert(!V->hasName() && "Doesn't need a slot!");
366 unsigned DestSlot = mNext++;
369 ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" <<
371 // G = Global, F = Function, A = Alias, o = other
372 ST_DEBUG((isa<GlobalVariable>(V) ? 'G' :
373 (isa<Function>(V) ? 'F' :
374 (isa<GlobalAlias>(V) ? 'A' : 'o'))) << "]\n");
378 /// CreateSlot - Create a new slot for the specified value if it has no name.
379 void SlotTracker::CreateFunctionSlot(const Value *V) {
380 assert(V->getType() != Type::VoidTy && !V->hasName() &&
381 "Doesn't need a slot!");
383 unsigned DestSlot = fNext++;
386 // G = Global, F = Function, o = other
387 ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" <<
388 DestSlot << " [o]\n");
393 //===----------------------------------------------------------------------===//
394 // AsmWriter Implementation
395 //===----------------------------------------------------------------------===//
397 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
398 std::map<const Type *, std::string> &TypeTable,
399 SlotTracker *Machine);
403 /// fillTypeNameTable - If the module has a symbol table, take all global types
404 /// and stuff their names into the TypeNames map.
406 static void fillTypeNameTable(const Module *M,
407 std::map<const Type *, std::string> &TypeNames) {
409 const TypeSymbolTable &ST = M->getTypeSymbolTable();
410 TypeSymbolTable::const_iterator TI = ST.begin();
411 for (; TI != ST.end(); ++TI) {
412 // As a heuristic, don't insert pointer to primitive types, because
413 // they are used too often to have a single useful name.
415 const Type *Ty = cast<Type>(TI->second);
416 if (!isa<PointerType>(Ty) ||
417 !cast<PointerType>(Ty)->getElementType()->isPrimitiveType() ||
418 !cast<PointerType>(Ty)->getElementType()->isInteger() ||
419 isa<OpaqueType>(cast<PointerType>(Ty)->getElementType()))
420 TypeNames.insert(std::make_pair(Ty, '%' + getLLVMName(TI->first)));
426 static void calcTypeName(const Type *Ty,
427 std::vector<const Type *> &TypeStack,
428 std::map<const Type *, std::string> &TypeNames,
429 std::string &Result) {
430 if (Ty->isInteger() || (Ty->isPrimitiveType() && !isa<OpaqueType>(Ty))) {
431 Result += Ty->getDescription(); // Base case
435 // Check to see if the type is named.
436 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
437 if (I != TypeNames.end()) {
442 if (isa<OpaqueType>(Ty)) {
447 // Check to see if the Type is already on the stack...
448 unsigned Slot = 0, CurSize = TypeStack.size();
449 while (Slot < CurSize && TypeStack[Slot] != Ty) ++Slot; // Scan for type
451 // This is another base case for the recursion. In this case, we know
452 // that we have looped back to a type that we have previously visited.
453 // Generate the appropriate upreference to handle this.
454 if (Slot < CurSize) {
455 Result += "\\" + utostr(CurSize-Slot); // Here's the upreference
459 TypeStack.push_back(Ty); // Recursive case: Add us to the stack..
461 switch (Ty->getTypeID()) {
462 case Type::IntegerTyID: {
463 unsigned BitWidth = cast<IntegerType>(Ty)->getBitWidth();
464 Result += "i" + utostr(BitWidth);
467 case Type::FunctionTyID: {
468 const FunctionType *FTy = cast<FunctionType>(Ty);
469 calcTypeName(FTy->getReturnType(), TypeStack, TypeNames, Result);
471 for (FunctionType::param_iterator I = FTy->param_begin(),
472 E = FTy->param_end(); I != E; ++I) {
473 if (I != FTy->param_begin())
475 calcTypeName(*I, TypeStack, TypeNames, Result);
477 if (FTy->isVarArg()) {
478 if (FTy->getNumParams()) Result += ", ";
484 case Type::StructTyID: {
485 const StructType *STy = cast<StructType>(Ty);
489 for (StructType::element_iterator I = STy->element_begin(),
490 E = STy->element_end(); I != E; ++I) {
491 calcTypeName(*I, TypeStack, TypeNames, Result);
492 if (next(I) != STy->element_end())
501 case Type::PointerTyID: {
502 const PointerType *PTy = cast<PointerType>(Ty);
503 calcTypeName(PTy->getElementType(), TypeStack, TypeNames, Result);
504 if (unsigned AddressSpace = PTy->getAddressSpace())
505 Result += " addrspace(" + utostr(AddressSpace) + ")";
509 case Type::ArrayTyID: {
510 const ArrayType *ATy = cast<ArrayType>(Ty);
511 Result += "[" + utostr(ATy->getNumElements()) + " x ";
512 calcTypeName(ATy->getElementType(), TypeStack, TypeNames, Result);
516 case Type::VectorTyID: {
517 const VectorType *PTy = cast<VectorType>(Ty);
518 Result += "<" + utostr(PTy->getNumElements()) + " x ";
519 calcTypeName(PTy->getElementType(), TypeStack, TypeNames, Result);
523 case Type::OpaqueTyID:
527 Result += "<unrecognized-type>";
531 TypeStack.pop_back(); // Remove self from stack...
535 /// printTypeInt - The internal guts of printing out a type that has a
536 /// potentially named portion.
538 static void printTypeInt(raw_ostream &Out, const Type *Ty,
539 std::map<const Type *, std::string> &TypeNames) {
540 // Primitive types always print out their description, regardless of whether
541 // they have been named or not.
543 if (Ty->isInteger() || (Ty->isPrimitiveType() && !isa<OpaqueType>(Ty))) {
544 Out << Ty->getDescription();
548 // Check to see if the type is named.
549 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
550 if (I != TypeNames.end()) {
555 // Otherwise we have a type that has not been named but is a derived type.
556 // Carefully recurse the type hierarchy to print out any contained symbolic
559 std::vector<const Type *> TypeStack;
560 std::string TypeName;
561 calcTypeName(Ty, TypeStack, TypeNames, TypeName);
562 TypeNames.insert(std::make_pair(Ty, TypeName));//Cache type name for later use
567 /// WriteTypeSymbolic - This attempts to write the specified type as a symbolic
568 /// type, iff there is an entry in the modules symbol table for the specified
569 /// type or one of it's component types. This is slower than a simple x << Type
571 void llvm::WriteTypeSymbolic(std::ostream &Out, const Type *Ty,
573 raw_os_ostream RO(Out);
574 WriteTypeSymbolic(RO, Ty, M);
577 void llvm::WriteTypeSymbolic(raw_ostream &Out, const Type *Ty, const Module *M){
580 // If they want us to print out a type, but there is no context, we can't
581 // print it symbolically.
583 Out << Ty->getDescription();
585 std::map<const Type *, std::string> TypeNames;
586 fillTypeNameTable(M, TypeNames);
587 printTypeInt(Out, Ty, TypeNames);
591 // PrintEscapedString - Print each character of the specified string, escaping
592 // it if it is not printable or if it is an escape char.
593 static void PrintEscapedString(const std::string &Str, raw_ostream &Out) {
594 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
595 unsigned char C = Str[i];
596 if (isprint(C) && C != '"' && C != '\\') {
600 << (char) ((C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A'))
601 << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
606 static const char *getPredicateText(unsigned predicate) {
607 const char * pred = "unknown";
609 case FCmpInst::FCMP_FALSE: pred = "false"; break;
610 case FCmpInst::FCMP_OEQ: pred = "oeq"; break;
611 case FCmpInst::FCMP_OGT: pred = "ogt"; break;
612 case FCmpInst::FCMP_OGE: pred = "oge"; break;
613 case FCmpInst::FCMP_OLT: pred = "olt"; break;
614 case FCmpInst::FCMP_OLE: pred = "ole"; break;
615 case FCmpInst::FCMP_ONE: pred = "one"; break;
616 case FCmpInst::FCMP_ORD: pred = "ord"; break;
617 case FCmpInst::FCMP_UNO: pred = "uno"; break;
618 case FCmpInst::FCMP_UEQ: pred = "ueq"; break;
619 case FCmpInst::FCMP_UGT: pred = "ugt"; break;
620 case FCmpInst::FCMP_UGE: pred = "uge"; break;
621 case FCmpInst::FCMP_ULT: pred = "ult"; break;
622 case FCmpInst::FCMP_ULE: pred = "ule"; break;
623 case FCmpInst::FCMP_UNE: pred = "une"; break;
624 case FCmpInst::FCMP_TRUE: pred = "true"; break;
625 case ICmpInst::ICMP_EQ: pred = "eq"; break;
626 case ICmpInst::ICMP_NE: pred = "ne"; break;
627 case ICmpInst::ICMP_SGT: pred = "sgt"; break;
628 case ICmpInst::ICMP_SGE: pred = "sge"; break;
629 case ICmpInst::ICMP_SLT: pred = "slt"; break;
630 case ICmpInst::ICMP_SLE: pred = "sle"; break;
631 case ICmpInst::ICMP_UGT: pred = "ugt"; break;
632 case ICmpInst::ICMP_UGE: pred = "uge"; break;
633 case ICmpInst::ICMP_ULT: pred = "ult"; break;
634 case ICmpInst::ICMP_ULE: pred = "ule"; break;
639 static void WriteConstantInt(raw_ostream &Out, const Constant *CV,
640 std::map<const Type *, std::string> &TypeTable,
641 SlotTracker *Machine) {
642 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
643 if (CI->getType() == Type::Int1Ty) {
644 Out << (CI->getZExtValue() ? "true" : "false");
647 Out << CI->getValue();
651 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
652 if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEdouble ||
653 &CFP->getValueAPF().getSemantics() == &APFloat::IEEEsingle) {
654 // We would like to output the FP constant value in exponential notation,
655 // but we cannot do this if doing so will lose precision. Check here to
656 // make sure that we only output it in exponential format if we can parse
657 // the value back and get the same value.
659 bool isDouble = &CFP->getValueAPF().getSemantics()==&APFloat::IEEEdouble;
660 double Val = isDouble ? CFP->getValueAPF().convertToDouble() :
661 CFP->getValueAPF().convertToFloat();
662 std::string StrVal = ftostr(CFP->getValueAPF());
664 // Check to make sure that the stringized number is not some string like
665 // "Inf" or NaN, that atof will accept, but the lexer will not. Check
666 // that the string matches the "[-+]?[0-9]" regex.
668 if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
669 ((StrVal[0] == '-' || StrVal[0] == '+') &&
670 (StrVal[1] >= '0' && StrVal[1] <= '9'))) {
671 // Reparse stringized version!
672 if (atof(StrVal.c_str()) == Val) {
677 // Otherwise we could not reparse it to exactly the same value, so we must
678 // output the string in hexadecimal format!
679 assert(sizeof(double) == sizeof(uint64_t) &&
680 "assuming that double is 64 bits!");
681 Out << "0x" << utohexstr(DoubleToBits(Val));
685 // Some form of long double. These appear as a magic letter identifying
686 // the type, then a fixed number of hex digits.
688 if (&CFP->getValueAPF().getSemantics() == &APFloat::x87DoubleExtended)
690 else if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEquad)
692 else if (&CFP->getValueAPF().getSemantics() == &APFloat::PPCDoubleDouble)
695 assert(0 && "Unsupported floating point type");
696 // api needed to prevent premature destruction
697 APInt api = CFP->getValueAPF().bitcastToAPInt();
698 const uint64_t* p = api.getRawData();
701 int width = api.getBitWidth();
702 for (int j=0; j<width; j+=4, shiftcount-=4) {
703 unsigned int nibble = (word>>shiftcount) & 15;
705 Out << (unsigned char)(nibble + '0');
707 Out << (unsigned char)(nibble - 10 + 'A');
708 if (shiftcount == 0 && j+4 < width) {
712 shiftcount = width-j-4;
718 if (isa<ConstantAggregateZero>(CV)) {
719 Out << "zeroinitializer";
723 if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
724 // As a special case, print the array as a string if it is an array of
725 // i8 with ConstantInt values.
727 const Type *ETy = CA->getType()->getElementType();
728 if (CA->isString()) {
730 PrintEscapedString(CA->getAsString(), Out);
732 } else { // Cannot output in string format...
734 if (CA->getNumOperands()) {
736 printTypeInt(Out, ETy, TypeTable);
738 WriteAsOperandInternal(Out, CA->getOperand(0),
740 for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
742 printTypeInt(Out, ETy, TypeTable);
744 WriteAsOperandInternal(Out, CA->getOperand(i), TypeTable, Machine);
753 if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
754 if (CS->getType()->isPacked())
757 unsigned N = CS->getNumOperands();
760 printTypeInt(Out, CS->getOperand(0)->getType(), TypeTable);
763 WriteAsOperandInternal(Out, CS->getOperand(0), TypeTable, Machine);
765 for (unsigned i = 1; i < N; i++) {
767 printTypeInt(Out, CS->getOperand(i)->getType(), TypeTable);
770 WriteAsOperandInternal(Out, CS->getOperand(i), TypeTable, Machine);
776 if (CS->getType()->isPacked())
781 if (const ConstantVector *CP = dyn_cast<ConstantVector>(CV)) {
782 const Type *ETy = CP->getType()->getElementType();
783 assert(CP->getNumOperands() > 0 &&
784 "Number of operands for a PackedConst must be > 0");
786 printTypeInt(Out, ETy, TypeTable);
788 WriteAsOperandInternal(Out, CP->getOperand(0), TypeTable, Machine);
789 for (unsigned i = 1, e = CP->getNumOperands(); i != e; ++i) {
791 printTypeInt(Out, ETy, TypeTable);
793 WriteAsOperandInternal(Out, CP->getOperand(i), TypeTable, Machine);
799 if (isa<ConstantPointerNull>(CV)) {
804 if (isa<UndefValue>(CV)) {
809 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
810 Out << CE->getOpcodeName();
812 Out << ' ' << getPredicateText(CE->getPredicate());
815 for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) {
816 printTypeInt(Out, (*OI)->getType(), TypeTable);
818 WriteAsOperandInternal(Out, *OI, TypeTable, Machine);
819 if (OI+1 != CE->op_end())
823 if (CE->hasIndices()) {
824 const SmallVector<unsigned, 4> &Indices = CE->getIndices();
825 for (unsigned i = 0, e = Indices.size(); i != e; ++i)
826 Out << ", " << Indices[i];
831 printTypeInt(Out, CE->getType(), TypeTable);
838 Out << "<placeholder or erroneous Constant>";
842 /// WriteAsOperand - Write the name of the specified value out to the specified
843 /// ostream. This can be useful when you just want to print int %reg126, not
844 /// the whole instruction that generated it.
846 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
847 std::map<const Type*, std::string> &TypeTable,
848 SlotTracker *Machine) {
850 PrintLLVMName(Out, V);
854 const Constant *CV = dyn_cast<Constant>(V);
855 if (CV && !isa<GlobalValue>(CV)) {
856 WriteConstantInt(Out, CV, TypeTable, Machine);
860 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
862 if (IA->hasSideEffects())
863 Out << "sideeffect ";
865 PrintEscapedString(IA->getAsmString(), Out);
867 PrintEscapedString(IA->getConstraintString(), Out);
875 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
876 Slot = Machine->getGlobalSlot(GV);
879 Slot = Machine->getLocalSlot(V);
882 Machine = createSlotTracker(V);
884 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
885 Slot = Machine->getGlobalSlot(GV);
888 Slot = Machine->getLocalSlot(V);
897 Out << Prefix << Slot;
902 /// WriteAsOperand - Write the name of the specified value out to the specified
903 /// ostream. This can be useful when you just want to print int %reg126, not
904 /// the whole instruction that generated it.
906 void llvm::WriteAsOperand(std::ostream &Out, const Value *V, bool PrintType,
907 const Module *Context) {
908 raw_os_ostream OS(Out);
909 WriteAsOperand(OS, V, PrintType, Context);
912 void llvm::WriteAsOperand(raw_ostream &Out, const Value *V, bool PrintType,
913 const Module *Context) {
914 std::map<const Type *, std::string> TypeNames;
915 if (Context == 0) Context = getModuleFromVal(V);
918 fillTypeNameTable(Context, TypeNames);
921 printTypeInt(Out, V->getType(), TypeNames);
925 WriteAsOperandInternal(Out, V, TypeNames, 0);
931 class AssemblyWriter {
933 SlotTracker &Machine;
934 const Module *TheModule;
935 std::map<const Type *, std::string> TypeNames;
936 AssemblyAnnotationWriter *AnnotationWriter;
938 inline AssemblyWriter(raw_ostream &o, SlotTracker &Mac, const Module *M,
939 AssemblyAnnotationWriter *AAW)
940 : Out(o), Machine(Mac), TheModule(M), AnnotationWriter(AAW) {
942 // If the module has a symbol table, take all global types and stuff their
943 // names into the TypeNames map.
945 fillTypeNameTable(M, TypeNames);
948 void write(const Module *M) { printModule(M); }
950 void write(const GlobalValue *G) {
951 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(G))
953 else if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(G))
955 else if (const Function *F = dyn_cast<Function>(G))
958 assert(0 && "Unknown global");
961 void write(const BasicBlock *BB) { printBasicBlock(BB); }
962 void write(const Instruction *I) { printInstruction(*I); }
963 void write(const Type *Ty) { printType(Ty); }
965 void writeOperand(const Value *Op, bool PrintType);
966 void writeParamOperand(const Value *Operand, Attributes Attrs);
968 const Module* getModule() { return TheModule; }
971 void printModule(const Module *M);
972 void printTypeSymbolTable(const TypeSymbolTable &ST);
973 void printGlobal(const GlobalVariable *GV);
974 void printAlias(const GlobalAlias *GV);
975 void printFunction(const Function *F);
976 void printArgument(const Argument *FA, Attributes Attrs);
977 void printBasicBlock(const BasicBlock *BB);
978 void printInstruction(const Instruction &I);
980 // printType - Go to extreme measures to attempt to print out a short,
981 // symbolic version of a type name.
983 void printType(const Type *Ty) {
984 printTypeInt(Out, Ty, TypeNames);
987 // printTypeAtLeastOneLevel - Print out one level of the possibly complex type
988 // without considering any symbolic types that we may have equal to it.
990 void printTypeAtLeastOneLevel(const Type *Ty);
992 // printInfoComment - Print a little comment after the instruction indicating
993 // which slot it occupies.
994 void printInfoComment(const Value &V);
996 } // end of llvm namespace
998 /// printTypeAtLeastOneLevel - Print out one level of the possibly complex type
999 /// without considering any symbolic types that we may have equal to it.
1001 void AssemblyWriter::printTypeAtLeastOneLevel(const Type *Ty) {
1002 if (const IntegerType *ITy = dyn_cast<IntegerType>(Ty)) {
1003 Out << "i" << utostr(ITy->getBitWidth());
1007 if (const FunctionType *FTy = dyn_cast<FunctionType>(Ty)) {
1008 printType(FTy->getReturnType());
1010 for (FunctionType::param_iterator I = FTy->param_begin(),
1011 E = FTy->param_end(); I != E; ++I) {
1012 if (I != FTy->param_begin())
1016 if (FTy->isVarArg()) {
1017 if (FTy->getNumParams()) Out << ", ";
1024 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1025 if (STy->isPacked())
1028 for (StructType::element_iterator I = STy->element_begin(),
1029 E = STy->element_end(); I != E; ++I) {
1030 if (I != STy->element_begin())
1035 if (STy->isPacked())
1040 if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
1041 printType(PTy->getElementType());
1042 if (unsigned AddressSpace = PTy->getAddressSpace())
1043 Out << " addrspace(" << AddressSpace << ")";
1048 if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1049 Out << '[' << ATy->getNumElements() << " x ";
1050 printType(ATy->getElementType());
1055 if (const VectorType *PTy = dyn_cast<VectorType>(Ty)) {
1056 Out << '<' << PTy->getNumElements() << " x ";
1057 printType(PTy->getElementType());
1062 if (isa<OpaqueType>(Ty)) {
1067 if (!Ty->isPrimitiveType())
1068 Out << "<unknown derived type>";
1073 void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType) {
1075 Out << "<null operand!>";
1078 printType(Operand->getType());
1081 WriteAsOperandInternal(Out, Operand, TypeNames, &Machine);
1085 void AssemblyWriter::writeParamOperand(const Value *Operand,
1088 Out << "<null operand!>";
1091 printType(Operand->getType());
1092 // Print parameter attributes list
1093 if (Attrs != Attribute::None)
1094 Out << ' ' << Attribute::getAsString(Attrs);
1096 // Print the operand
1097 WriteAsOperandInternal(Out, Operand, TypeNames, &Machine);
1101 void AssemblyWriter::printModule(const Module *M) {
1102 if (!M->getModuleIdentifier().empty() &&
1103 // Don't print the ID if it will start a new line (which would
1104 // require a comment char before it).
1105 M->getModuleIdentifier().find('\n') == std::string::npos)
1106 Out << "; ModuleID = '" << M->getModuleIdentifier() << "'\n";
1108 if (!M->getDataLayout().empty())
1109 Out << "target datalayout = \"" << M->getDataLayout() << "\"\n";
1110 if (!M->getTargetTriple().empty())
1111 Out << "target triple = \"" << M->getTargetTriple() << "\"\n";
1113 if (!M->getModuleInlineAsm().empty()) {
1114 // Split the string into lines, to make it easier to read the .ll file.
1115 std::string Asm = M->getModuleInlineAsm();
1117 size_t NewLine = Asm.find_first_of('\n', CurPos);
1118 while (NewLine != std::string::npos) {
1119 // We found a newline, print the portion of the asm string from the
1120 // last newline up to this newline.
1121 Out << "module asm \"";
1122 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.begin()+NewLine),
1126 NewLine = Asm.find_first_of('\n', CurPos);
1128 Out << "module asm \"";
1129 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.end()), Out);
1133 // Loop over the dependent libraries and emit them.
1134 Module::lib_iterator LI = M->lib_begin();
1135 Module::lib_iterator LE = M->lib_end();
1137 Out << "deplibs = [ ";
1139 Out << '"' << *LI << '"';
1147 // Loop over the symbol table, emitting all named constants.
1148 printTypeSymbolTable(M->getTypeSymbolTable());
1150 for (Module::const_global_iterator I = M->global_begin(), E = M->global_end();
1154 // Output all aliases.
1155 if (!M->alias_empty()) Out << "\n";
1156 for (Module::const_alias_iterator I = M->alias_begin(), E = M->alias_end();
1160 // Output all of the functions.
1161 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
1165 static void PrintLinkage(GlobalValue::LinkageTypes LT, raw_ostream &Out) {
1167 case GlobalValue::InternalLinkage: Out << "internal "; break;
1168 case GlobalValue::LinkOnceLinkage: Out << "linkonce "; break;
1169 case GlobalValue::WeakLinkage: Out << "weak "; break;
1170 case GlobalValue::CommonLinkage: Out << "common "; break;
1171 case GlobalValue::AppendingLinkage: Out << "appending "; break;
1172 case GlobalValue::DLLImportLinkage: Out << "dllimport "; break;
1173 case GlobalValue::DLLExportLinkage: Out << "dllexport "; break;
1174 case GlobalValue::ExternalWeakLinkage: Out << "extern_weak "; break;
1175 case GlobalValue::ExternalLinkage: break;
1176 case GlobalValue::GhostLinkage:
1177 Out << "GhostLinkage not allowed in AsmWriter!\n";
1183 static void PrintVisibility(GlobalValue::VisibilityTypes Vis,
1186 default: assert(0 && "Invalid visibility style!");
1187 case GlobalValue::DefaultVisibility: break;
1188 case GlobalValue::HiddenVisibility: Out << "hidden "; break;
1189 case GlobalValue::ProtectedVisibility: Out << "protected "; break;
1193 void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
1194 if (GV->hasName()) {
1195 PrintLLVMName(Out, GV);
1199 if (!GV->hasInitializer() && GV->hasExternalLinkage())
1202 PrintLinkage(GV->getLinkage(), Out);
1203 PrintVisibility(GV->getVisibility(), Out);
1205 if (GV->isThreadLocal()) Out << "thread_local ";
1206 Out << (GV->isConstant() ? "constant " : "global ");
1207 printType(GV->getType()->getElementType());
1209 if (GV->hasInitializer()) {
1211 writeOperand(GV->getInitializer(), false);
1214 if (unsigned AddressSpace = GV->getType()->getAddressSpace())
1215 Out << " addrspace(" << AddressSpace << ") ";
1217 if (GV->hasSection())
1218 Out << ", section \"" << GV->getSection() << '"';
1219 if (GV->getAlignment())
1220 Out << ", align " << GV->getAlignment();
1222 printInfoComment(*GV);
1226 void AssemblyWriter::printAlias(const GlobalAlias *GA) {
1227 // Don't crash when dumping partially built GA
1229 Out << "<<nameless>> = ";
1231 PrintLLVMName(Out, GA);
1234 PrintVisibility(GA->getVisibility(), Out);
1238 PrintLinkage(GA->getLinkage(), Out);
1240 const Constant *Aliasee = GA->getAliasee();
1242 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Aliasee)) {
1243 printType(GV->getType());
1245 PrintLLVMName(Out, GV);
1246 } else if (const Function *F = dyn_cast<Function>(Aliasee)) {
1247 printType(F->getFunctionType());
1251 PrintLLVMName(Out, F);
1254 } else if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(Aliasee)) {
1255 printType(GA->getType());
1257 PrintLLVMName(Out, GA);
1259 const ConstantExpr *CE = 0;
1260 if ((CE = dyn_cast<ConstantExpr>(Aliasee)) &&
1261 (CE->getOpcode() == Instruction::BitCast)) {
1262 writeOperand(CE, false);
1264 assert(0 && "Unsupported aliasee");
1267 printInfoComment(*GA);
1271 void AssemblyWriter::printTypeSymbolTable(const TypeSymbolTable &ST) {
1273 for (TypeSymbolTable::const_iterator TI = ST.begin(), TE = ST.end();
1276 PrintLLVMName(Out, &TI->first[0], TI->first.size(), LocalPrefix);
1279 // Make sure we print out at least one level of the type structure, so
1280 // that we do not get %FILE = type %FILE
1282 printTypeAtLeastOneLevel(TI->second);
1287 /// printFunction - Print all aspects of a function.
1289 void AssemblyWriter::printFunction(const Function *F) {
1290 // Print out the return type and name.
1293 if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, Out);
1295 if (F->isDeclaration())
1300 PrintLinkage(F->getLinkage(), Out);
1301 PrintVisibility(F->getVisibility(), Out);
1303 // Print the calling convention.
1304 switch (F->getCallingConv()) {
1305 case CallingConv::C: break; // default
1306 case CallingConv::Fast: Out << "fastcc "; break;
1307 case CallingConv::Cold: Out << "coldcc "; break;
1308 case CallingConv::X86_StdCall: Out << "x86_stdcallcc "; break;
1309 case CallingConv::X86_FastCall: Out << "x86_fastcallcc "; break;
1310 default: Out << "cc" << F->getCallingConv() << " "; break;
1313 const FunctionType *FT = F->getFunctionType();
1314 const AttrListPtr &Attrs = F->getAttributes();
1315 Attributes RetAttrs = Attrs.getRetAttributes();
1316 if (RetAttrs != Attribute::None)
1317 Out << Attribute::getAsString(Attrs.getRetAttributes()) << ' ';
1318 printType(F->getReturnType());
1321 PrintLLVMName(Out, F);
1325 Machine.incorporateFunction(F);
1327 // Loop over the arguments, printing them...
1330 if (!F->isDeclaration()) {
1331 // If this isn't a declaration, print the argument names as well.
1332 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
1334 // Insert commas as we go... the first arg doesn't get a comma
1335 if (I != F->arg_begin()) Out << ", ";
1336 printArgument(I, Attrs.getParamAttributes(Idx));
1340 // Otherwise, print the types from the function type.
1341 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
1342 // Insert commas as we go... the first arg doesn't get a comma
1346 printType(FT->getParamType(i));
1348 Attributes ArgAttrs = Attrs.getParamAttributes(i+1);
1349 if (ArgAttrs != Attribute::None)
1350 Out << ' ' << Attribute::getAsString(ArgAttrs);
1354 // Finish printing arguments...
1355 if (FT->isVarArg()) {
1356 if (FT->getNumParams()) Out << ", ";
1357 Out << "..."; // Output varargs portion of signature!
1360 Attributes FnAttrs = Attrs.getFnAttributes();
1361 if (FnAttrs != Attribute::None)
1362 Out << ' ' << Attribute::getAsString(Attrs.getFnAttributes());
1363 if (F->hasSection())
1364 Out << " section \"" << F->getSection() << '"';
1365 if (F->getAlignment())
1366 Out << " align " << F->getAlignment();
1368 Out << " gc \"" << F->getGC() << '"';
1369 if (F->isDeclaration()) {
1374 // Output all of its basic blocks... for the function
1375 for (Function::const_iterator I = F->begin(), E = F->end(); I != E; ++I)
1381 Machine.purgeFunction();
1384 /// printArgument - This member is called for every argument that is passed into
1385 /// the function. Simply print it out
1387 void AssemblyWriter::printArgument(const Argument *Arg,
1390 printType(Arg->getType());
1392 // Output parameter attributes list
1393 if (Attrs != Attribute::None)
1394 Out << ' ' << Attribute::getAsString(Attrs);
1396 // Output name, if available...
1397 if (Arg->hasName()) {
1399 PrintLLVMName(Out, Arg);
1403 /// printBasicBlock - This member is called for each basic block in a method.
1405 void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {
1406 if (BB->hasName()) { // Print out the label if it exists...
1408 PrintLLVMName(Out, BB->getNameStart(), BB->getNameLen(), LabelPrefix);
1410 } else if (!BB->use_empty()) { // Don't print block # of no uses...
1411 Out << "\n; <label>:";
1412 int Slot = Machine.getLocalSlot(BB);
1419 if (BB->getParent() == 0)
1420 Out << "\t\t; Error: Block without parent!";
1421 else if (BB != &BB->getParent()->getEntryBlock()) { // Not the entry block?
1422 // Output predecessors for the block...
1424 pred_const_iterator PI = pred_begin(BB), PE = pred_end(BB);
1427 Out << " No predecessors!";
1430 writeOperand(*PI, false);
1431 for (++PI; PI != PE; ++PI) {
1433 writeOperand(*PI, false);
1440 if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(BB, Out);
1442 // Output all of the instructions in the basic block...
1443 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
1444 printInstruction(*I);
1446 if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(BB, Out);
1450 /// printInfoComment - Print a little comment after the instruction indicating
1451 /// which slot it occupies.
1453 void AssemblyWriter::printInfoComment(const Value &V) {
1454 if (V.getType() != Type::VoidTy) {
1456 printType(V.getType());
1459 if (!V.hasName() && !isa<Instruction>(V)) {
1461 if (const GlobalValue *GV = dyn_cast<GlobalValue>(&V))
1462 SlotNum = Machine.getGlobalSlot(GV);
1464 SlotNum = Machine.getLocalSlot(&V);
1468 Out << ':' << SlotNum; // Print out the def slot taken.
1470 Out << " [#uses=" << V.getNumUses() << ']'; // Output # uses
1474 // This member is called for each Instruction in a function..
1475 void AssemblyWriter::printInstruction(const Instruction &I) {
1476 if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, Out);
1480 // Print out name if it exists...
1482 PrintLLVMName(Out, &I);
1484 } else if (I.getType() != Type::VoidTy) {
1485 // Print out the def slot taken.
1486 int SlotNum = Machine.getLocalSlot(&I);
1488 Out << "<badref> = ";
1490 Out << '%' << SlotNum << " = ";
1493 // If this is a volatile load or store, print out the volatile marker.
1494 if ((isa<LoadInst>(I) && cast<LoadInst>(I).isVolatile()) ||
1495 (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile())) {
1497 } else if (isa<CallInst>(I) && cast<CallInst>(I).isTailCall()) {
1498 // If this is a call, check if it's a tail call.
1502 // Print out the opcode...
1503 Out << I.getOpcodeName();
1505 // Print out the compare instruction predicates
1506 if (const CmpInst *CI = dyn_cast<CmpInst>(&I))
1507 Out << ' ' << getPredicateText(CI->getPredicate());
1509 // Print out the type of the operands...
1510 const Value *Operand = I.getNumOperands() ? I.getOperand(0) : 0;
1512 // Special case conditional branches to swizzle the condition out to the front
1513 if (isa<BranchInst>(I) && I.getNumOperands() > 1) {
1515 writeOperand(I.getOperand(2), true);
1517 writeOperand(Operand, true);
1519 writeOperand(I.getOperand(1), true);
1521 } else if (isa<SwitchInst>(I)) {
1522 // Special case switch statement to get formatting nice and correct...
1524 writeOperand(Operand , true);
1526 writeOperand(I.getOperand(1), true);
1529 for (unsigned op = 2, Eop = I.getNumOperands(); op < Eop; op += 2) {
1531 writeOperand(I.getOperand(op ), true);
1533 writeOperand(I.getOperand(op+1), true);
1536 } else if (isa<PHINode>(I)) {
1538 printType(I.getType());
1541 for (unsigned op = 0, Eop = I.getNumOperands(); op < Eop; op += 2) {
1542 if (op) Out << ", ";
1544 writeOperand(I.getOperand(op ), false); Out << ", ";
1545 writeOperand(I.getOperand(op+1), false); Out << " ]";
1547 } else if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&I)) {
1549 writeOperand(I.getOperand(0), true);
1550 for (const unsigned *i = EVI->idx_begin(), *e = EVI->idx_end(); i != e; ++i)
1552 } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&I)) {
1554 writeOperand(I.getOperand(0), true); Out << ", ";
1555 writeOperand(I.getOperand(1), true);
1556 for (const unsigned *i = IVI->idx_begin(), *e = IVI->idx_end(); i != e; ++i)
1558 } else if (isa<ReturnInst>(I) && !Operand) {
1560 } else if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
1561 // Print the calling convention being used.
1562 switch (CI->getCallingConv()) {
1563 case CallingConv::C: break; // default
1564 case CallingConv::Fast: Out << " fastcc"; break;
1565 case CallingConv::Cold: Out << " coldcc"; break;
1566 case CallingConv::X86_StdCall: Out << " x86_stdcallcc"; break;
1567 case CallingConv::X86_FastCall: Out << " x86_fastcallcc"; break;
1568 default: Out << " cc" << CI->getCallingConv(); break;
1571 const PointerType *PTy = cast<PointerType>(Operand->getType());
1572 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1573 const Type *RetTy = FTy->getReturnType();
1574 const AttrListPtr &PAL = CI->getAttributes();
1576 if (PAL.getRetAttributes() != Attribute::None)
1577 Out << ' ' << Attribute::getAsString(PAL.getRetAttributes());
1579 // If possible, print out the short form of the call instruction. We can
1580 // only do this if the first argument is a pointer to a nonvararg function,
1581 // and if the return type is not a pointer to a function.
1584 if (!FTy->isVarArg() &&
1585 (!isa<PointerType>(RetTy) ||
1586 !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
1589 writeOperand(Operand, false);
1591 writeOperand(Operand, true);
1594 for (unsigned op = 1, Eop = I.getNumOperands(); op < Eop; ++op) {
1597 writeParamOperand(I.getOperand(op), PAL.getParamAttributes(op));
1600 if (PAL.getFnAttributes() != Attribute::None)
1601 Out << ' ' << Attribute::getAsString(PAL.getFnAttributes());
1602 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
1603 const PointerType *PTy = cast<PointerType>(Operand->getType());
1604 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1605 const Type *RetTy = FTy->getReturnType();
1606 const AttrListPtr &PAL = II->getAttributes();
1608 // Print the calling convention being used.
1609 switch (II->getCallingConv()) {
1610 case CallingConv::C: break; // default
1611 case CallingConv::Fast: Out << " fastcc"; break;
1612 case CallingConv::Cold: Out << " coldcc"; break;
1613 case CallingConv::X86_StdCall: Out << " x86_stdcallcc"; break;
1614 case CallingConv::X86_FastCall: Out << " x86_fastcallcc"; break;
1615 default: Out << " cc" << II->getCallingConv(); break;
1618 if (PAL.getRetAttributes() != Attribute::None)
1619 Out << ' ' << Attribute::getAsString(PAL.getRetAttributes());
1621 // If possible, print out the short form of the invoke instruction. We can
1622 // only do this if the first argument is a pointer to a nonvararg function,
1623 // and if the return type is not a pointer to a function.
1625 if (!FTy->isVarArg() &&
1626 (!isa<PointerType>(RetTy) ||
1627 !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
1628 Out << ' '; printType(RetTy);
1629 writeOperand(Operand, false);
1632 writeOperand(Operand, true);
1636 for (unsigned op = 3, Eop = I.getNumOperands(); op < Eop; ++op) {
1639 writeParamOperand(I.getOperand(op), PAL.getParamAttributes(op-2));
1643 if (PAL.getFnAttributes() != Attribute::None)
1644 Out << ' ' << Attribute::getAsString(PAL.getFnAttributes());
1646 Out << "\n\t\t\tto ";
1647 writeOperand(II->getNormalDest(), true);
1649 writeOperand(II->getUnwindDest(), true);
1651 } else if (const AllocationInst *AI = dyn_cast<AllocationInst>(&I)) {
1653 printType(AI->getType()->getElementType());
1654 if (AI->isArrayAllocation()) {
1656 writeOperand(AI->getArraySize(), true);
1658 if (AI->getAlignment()) {
1659 Out << ", align " << AI->getAlignment();
1661 } else if (isa<CastInst>(I)) {
1664 writeOperand(Operand, true); // Work with broken code
1667 printType(I.getType());
1668 } else if (isa<VAArgInst>(I)) {
1671 writeOperand(Operand, true); // Work with broken code
1674 printType(I.getType());
1675 } else if (Operand) { // Print the normal way...
1677 // PrintAllTypes - Instructions who have operands of all the same type
1678 // omit the type from all but the first operand. If the instruction has
1679 // different type operands (for example br), then they are all printed.
1680 bool PrintAllTypes = false;
1681 const Type *TheType = Operand->getType();
1683 // Select, Store and ShuffleVector always print all types.
1684 if (isa<SelectInst>(I) || isa<StoreInst>(I) || isa<ShuffleVectorInst>(I)
1685 || isa<ReturnInst>(I)) {
1686 PrintAllTypes = true;
1688 for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) {
1689 Operand = I.getOperand(i);
1690 if (Operand->getType() != TheType) {
1691 PrintAllTypes = true; // We have differing types! Print them all!
1697 if (!PrintAllTypes) {
1703 for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) {
1705 writeOperand(I.getOperand(i), PrintAllTypes);
1709 // Print post operand alignment for load/store
1710 if (isa<LoadInst>(I) && cast<LoadInst>(I).getAlignment()) {
1711 Out << ", align " << cast<LoadInst>(I).getAlignment();
1712 } else if (isa<StoreInst>(I) && cast<StoreInst>(I).getAlignment()) {
1713 Out << ", align " << cast<StoreInst>(I).getAlignment();
1716 printInfoComment(I);
1721 //===----------------------------------------------------------------------===//
1722 // External Interface declarations
1723 //===----------------------------------------------------------------------===//
1725 void Module::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1726 raw_os_ostream OS(o);
1729 void Module::print(raw_ostream &OS, AssemblyAnnotationWriter *AAW) const {
1730 SlotTracker SlotTable(this);
1731 AssemblyWriter W(OS, SlotTable, this, AAW);
1735 void Type::print(std::ostream &o) const {
1736 raw_os_ostream OS(o);
1740 void Type::print(raw_ostream &o) const {
1744 o << getDescription();
1747 void Value::print(raw_ostream &OS, AssemblyAnnotationWriter *AAW) const {
1749 OS << "printing a <null> value\n";
1753 if (const Instruction *I = dyn_cast<Instruction>(this)) {
1754 const Function *F = I->getParent() ? I->getParent()->getParent() : 0;
1755 SlotTracker SlotTable(F);
1756 AssemblyWriter W(OS, SlotTable, F ? F->getParent() : 0, AAW);
1758 } else if (const BasicBlock *BB = dyn_cast<BasicBlock>(this)) {
1759 SlotTracker SlotTable(BB->getParent());
1760 AssemblyWriter W(OS, SlotTable,
1761 BB->getParent() ? BB->getParent()->getParent() : 0, AAW);
1763 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(this)) {
1764 SlotTracker SlotTable(GV->getParent());
1765 AssemblyWriter W(OS, SlotTable, GV->getParent(), 0);
1767 } else if (const Constant *C = dyn_cast<Constant>(this)) {
1768 OS << C->getType()->getDescription() << ' ';
1769 std::map<const Type *, std::string> TypeTable;
1770 WriteConstantInt(OS, C, TypeTable, 0);
1771 } else if (const Argument *A = dyn_cast<Argument>(this)) {
1772 WriteAsOperand(OS, this, true,
1773 A->getParent() ? A->getParent()->getParent() : 0);
1774 } else if (isa<InlineAsm>(this)) {
1775 WriteAsOperand(OS, this, true, 0);
1777 // FIXME: PseudoSourceValue breaks this!
1778 //assert(0 && "Unknown value to print out!");
1782 void Value::print(std::ostream &O, AssemblyAnnotationWriter *AAW) const {
1783 raw_os_ostream OS(O);
1787 // Value::dump - allow easy printing of Values from the debugger.
1788 void Value::dump() const { print(errs()); errs() << '\n'; errs().flush(); }
1790 // Type::dump - allow easy printing of Types from the debugger.
1791 void Type::dump() const { print(errs()); errs() << '\n'; errs().flush(); }
1793 // Type::dump - allow easy printing of Types from the debugger.
1794 // This one uses type names from the given context module
1795 void Type::dump(const Module *Context) const {
1796 WriteTypeSymbolic(errs(), this, Context);
1801 // Module::dump() - Allow printing of Modules from the debugger.
1802 void Module::dump() const { print(errs(), 0); errs().flush(); }