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) {
117 } else if (C != '"' && isprint(C)) {
121 OS << hexdigit((C >> 4) & 0x0F);
122 OS << hexdigit((C >> 0) & 0x0F);
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);
148 //===----------------------------------------------------------------------===//
149 // SlotTracker Class: Enumerate slot numbers for unnamed values
150 //===----------------------------------------------------------------------===//
154 /// This class provides computation of slot numbers for LLVM Assembly writing.
158 /// ValueMap - A mapping of Values to slot numbers
159 typedef DenseMap<const Value*, unsigned> ValueMap;
162 /// TheModule - The module for which we are holding slot numbers
163 const Module* TheModule;
165 /// TheFunction - The function for which we are holding slot numbers
166 const Function* TheFunction;
167 bool FunctionProcessed;
169 /// mMap - The TypePlanes map for the module level data
173 /// fMap - The TypePlanes map for the function level data
178 /// Construct from a module
179 explicit SlotTracker(const Module *M);
180 /// Construct from a function, starting out in incorp state.
181 explicit SlotTracker(const Function *F);
183 /// Return the slot number of the specified value in it's type
184 /// plane. If something is not in the SlotTracker, return -1.
185 int getLocalSlot(const Value *V);
186 int getGlobalSlot(const GlobalValue *V);
188 /// If you'd like to deal with a function instead of just a module, use
189 /// this method to get its data into the SlotTracker.
190 void incorporateFunction(const Function *F) {
192 FunctionProcessed = false;
195 /// After calling incorporateFunction, use this method to remove the
196 /// most recently incorporated function from the SlotTracker. This
197 /// will reset the state of the machine back to just the module contents.
198 void purgeFunction();
200 // Implementation Details
202 /// This function does the actual initialization.
203 inline void initialize();
205 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
206 void CreateModuleSlot(const GlobalValue *V);
208 /// CreateFunctionSlot - Insert the specified Value* into the slot table.
209 void CreateFunctionSlot(const Value *V);
211 /// Add all of the module level global variables (and their initializers)
212 /// and function declarations, but not the contents of those functions.
213 void processModule();
215 /// Add all of the functions arguments, basic blocks, and instructions
216 void processFunction();
218 SlotTracker(const SlotTracker &); // DO NOT IMPLEMENT
219 void operator=(const SlotTracker &); // DO NOT IMPLEMENT
222 } // end anonymous namespace
225 static SlotTracker *createSlotTracker(const Value *V) {
226 if (const Argument *FA = dyn_cast<Argument>(V))
227 return new SlotTracker(FA->getParent());
229 if (const Instruction *I = dyn_cast<Instruction>(V))
230 return new SlotTracker(I->getParent()->getParent());
232 if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
233 return new SlotTracker(BB->getParent());
235 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
236 return new SlotTracker(GV->getParent());
238 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
239 return new SlotTracker(GA->getParent());
241 if (const Function *Func = dyn_cast<Function>(V))
242 return new SlotTracker(Func);
248 #define ST_DEBUG(X) cerr << X
253 // Module level constructor. Causes the contents of the Module (sans functions)
254 // to be added to the slot table.
255 SlotTracker::SlotTracker(const Module *M)
256 : TheModule(M), TheFunction(0), FunctionProcessed(false), mNext(0), fNext(0) {
259 // Function level constructor. Causes the contents of the Module and the one
260 // function provided to be added to the slot table.
261 SlotTracker::SlotTracker(const Function *F)
262 : TheModule(F ? F->getParent() : 0), TheFunction(F), FunctionProcessed(false),
266 inline void SlotTracker::initialize() {
269 TheModule = 0; ///< Prevent re-processing next time we're called.
272 if (TheFunction && !FunctionProcessed)
276 // Iterate through all the global variables, functions, and global
277 // variable initializers and create slots for them.
278 void SlotTracker::processModule() {
279 ST_DEBUG("begin processModule!\n");
281 // Add all of the unnamed global variables to the value table.
282 for (Module::const_global_iterator I = TheModule->global_begin(),
283 E = TheModule->global_end(); I != E; ++I)
287 // Add all the unnamed functions to the table.
288 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
293 ST_DEBUG("end processModule!\n");
297 // Process the arguments, basic blocks, and instructions of a function.
298 void SlotTracker::processFunction() {
299 ST_DEBUG("begin processFunction!\n");
302 // Add all the function arguments with no names.
303 for(Function::const_arg_iterator AI = TheFunction->arg_begin(),
304 AE = TheFunction->arg_end(); AI != AE; ++AI)
306 CreateFunctionSlot(AI);
308 ST_DEBUG("Inserting Instructions:\n");
310 // Add all of the basic blocks and instructions with no names.
311 for (Function::const_iterator BB = TheFunction->begin(),
312 E = TheFunction->end(); BB != E; ++BB) {
314 CreateFunctionSlot(BB);
315 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
316 if (I->getType() != Type::VoidTy && !I->hasName())
317 CreateFunctionSlot(I);
320 FunctionProcessed = true;
322 ST_DEBUG("end processFunction!\n");
325 /// Clean up after incorporating a function. This is the only way to get out of
326 /// the function incorporation state that affects get*Slot/Create*Slot. Function
327 /// incorporation state is indicated by TheFunction != 0.
328 void SlotTracker::purgeFunction() {
329 ST_DEBUG("begin purgeFunction!\n");
330 fMap.clear(); // Simply discard the function level map
332 FunctionProcessed = false;
333 ST_DEBUG("end purgeFunction!\n");
336 /// getGlobalSlot - Get the slot number of a global value.
337 int SlotTracker::getGlobalSlot(const GlobalValue *V) {
338 // Check for uninitialized state and do lazy initialization.
341 // Find the type plane in the module map
342 ValueMap::iterator MI = mMap.find(V);
343 return MI == mMap.end() ? -1 : (int)MI->second;
347 /// getLocalSlot - Get the slot number for a value that is local to a function.
348 int SlotTracker::getLocalSlot(const Value *V) {
349 assert(!isa<Constant>(V) && "Can't get a constant or global slot with this!");
351 // Check for uninitialized state and do lazy initialization.
354 ValueMap::iterator FI = fMap.find(V);
355 return FI == fMap.end() ? -1 : (int)FI->second;
359 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
360 void SlotTracker::CreateModuleSlot(const GlobalValue *V) {
361 assert(V && "Can't insert a null Value into SlotTracker!");
362 assert(V->getType() != Type::VoidTy && "Doesn't need a slot!");
363 assert(!V->hasName() && "Doesn't need a slot!");
365 unsigned DestSlot = mNext++;
368 ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" <<
370 // G = Global, F = Function, A = Alias, o = other
371 ST_DEBUG((isa<GlobalVariable>(V) ? 'G' :
372 (isa<Function>(V) ? 'F' :
373 (isa<GlobalAlias>(V) ? 'A' : 'o'))) << "]\n");
377 /// CreateSlot - Create a new slot for the specified value if it has no name.
378 void SlotTracker::CreateFunctionSlot(const Value *V) {
379 assert(V->getType() != Type::VoidTy && !V->hasName() &&
380 "Doesn't need a slot!");
382 unsigned DestSlot = fNext++;
385 // G = Global, F = Function, o = other
386 ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" <<
387 DestSlot << " [o]\n");
392 //===----------------------------------------------------------------------===//
393 // AsmWriter Implementation
394 //===----------------------------------------------------------------------===//
396 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
397 std::map<const Type *, std::string> &TypeTable,
398 SlotTracker *Machine);
402 /// fillTypeNameTable - If the module has a symbol table, take all global types
403 /// and stuff their names into the TypeNames map.
405 static void fillTypeNameTable(const Module *M,
406 std::map<const Type *, std::string> &TypeNames) {
408 const TypeSymbolTable &ST = M->getTypeSymbolTable();
409 TypeSymbolTable::const_iterator TI = ST.begin();
410 for (; TI != ST.end(); ++TI) {
411 // As a heuristic, don't insert pointer to primitive types, because
412 // they are used too often to have a single useful name.
414 const Type *Ty = cast<Type>(TI->second);
415 if (!isa<PointerType>(Ty) ||
416 !cast<PointerType>(Ty)->getElementType()->isPrimitiveType() ||
417 !cast<PointerType>(Ty)->getElementType()->isInteger() ||
418 isa<OpaqueType>(cast<PointerType>(Ty)->getElementType()))
419 TypeNames.insert(std::make_pair(Ty, '%' + getLLVMName(TI->first)));
425 static void calcTypeName(const Type *Ty,
426 std::vector<const Type *> &TypeStack,
427 std::map<const Type *, std::string> &TypeNames,
428 std::string &Result) {
429 if (Ty->isInteger() || (Ty->isPrimitiveType() && !isa<OpaqueType>(Ty))) {
430 Result += Ty->getDescription(); // Base case
434 // Check to see if the type is named.
435 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
436 if (I != TypeNames.end()) {
441 if (isa<OpaqueType>(Ty)) {
446 // Check to see if the Type is already on the stack...
447 unsigned Slot = 0, CurSize = TypeStack.size();
448 while (Slot < CurSize && TypeStack[Slot] != Ty) ++Slot; // Scan for type
450 // This is another base case for the recursion. In this case, we know
451 // that we have looped back to a type that we have previously visited.
452 // Generate the appropriate upreference to handle this.
453 if (Slot < CurSize) {
454 Result += "\\" + utostr(CurSize-Slot); // Here's the upreference
458 TypeStack.push_back(Ty); // Recursive case: Add us to the stack..
460 switch (Ty->getTypeID()) {
461 case Type::IntegerTyID: {
462 unsigned BitWidth = cast<IntegerType>(Ty)->getBitWidth();
463 Result += "i" + utostr(BitWidth);
466 case Type::FunctionTyID: {
467 const FunctionType *FTy = cast<FunctionType>(Ty);
468 calcTypeName(FTy->getReturnType(), TypeStack, TypeNames, Result);
470 for (FunctionType::param_iterator I = FTy->param_begin(),
471 E = FTy->param_end(); I != E; ++I) {
472 if (I != FTy->param_begin())
474 calcTypeName(*I, TypeStack, TypeNames, Result);
476 if (FTy->isVarArg()) {
477 if (FTy->getNumParams()) Result += ", ";
483 case Type::StructTyID: {
484 const StructType *STy = cast<StructType>(Ty);
488 for (StructType::element_iterator I = STy->element_begin(),
489 E = STy->element_end(); I != E; ++I) {
490 calcTypeName(*I, TypeStack, TypeNames, Result);
491 if (next(I) != STy->element_end())
500 case Type::PointerTyID: {
501 const PointerType *PTy = cast<PointerType>(Ty);
502 calcTypeName(PTy->getElementType(), TypeStack, TypeNames, Result);
503 if (unsigned AddressSpace = PTy->getAddressSpace())
504 Result += " addrspace(" + utostr(AddressSpace) + ")";
508 case Type::ArrayTyID: {
509 const ArrayType *ATy = cast<ArrayType>(Ty);
510 Result += "[" + utostr(ATy->getNumElements()) + " x ";
511 calcTypeName(ATy->getElementType(), TypeStack, TypeNames, Result);
515 case Type::VectorTyID: {
516 const VectorType *PTy = cast<VectorType>(Ty);
517 Result += "<" + utostr(PTy->getNumElements()) + " x ";
518 calcTypeName(PTy->getElementType(), TypeStack, TypeNames, Result);
522 case Type::OpaqueTyID:
526 Result += "<unrecognized-type>";
530 TypeStack.pop_back(); // Remove self from stack...
534 /// printTypeInt - The internal guts of printing out a type that has a
535 /// potentially named portion.
537 static void printTypeInt(raw_ostream &Out, const Type *Ty,
538 std::map<const Type *, std::string> &TypeNames) {
539 // Primitive types always print out their description, regardless of whether
540 // they have been named or not.
542 if (Ty->isInteger() || (Ty->isPrimitiveType() && !isa<OpaqueType>(Ty))) {
543 Out << Ty->getDescription();
547 // Check to see if the type is named.
548 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
549 if (I != TypeNames.end()) {
554 // Otherwise we have a type that has not been named but is a derived type.
555 // Carefully recurse the type hierarchy to print out any contained symbolic
558 std::vector<const Type *> TypeStack;
559 std::string TypeName;
560 calcTypeName(Ty, TypeStack, TypeNames, TypeName);
561 TypeNames.insert(std::make_pair(Ty, TypeName));//Cache type name for later use
566 /// WriteTypeSymbolic - This attempts to write the specified type as a symbolic
567 /// type, iff there is an entry in the modules symbol table for the specified
568 /// type or one of it's component types. This is slower than a simple x << Type
570 void llvm::WriteTypeSymbolic(std::ostream &Out, const Type *Ty,
572 raw_os_ostream RO(Out);
573 WriteTypeSymbolic(RO, Ty, M);
576 void llvm::WriteTypeSymbolic(raw_ostream &Out, const Type *Ty, const Module *M){
579 // If they want us to print out a type, but there is no context, we can't
580 // print it symbolically.
582 Out << Ty->getDescription();
584 std::map<const Type *, std::string> TypeNames;
585 fillTypeNameTable(M, TypeNames);
586 printTypeInt(Out, Ty, TypeNames);
590 // PrintEscapedString - Print each character of the specified string, escaping
591 // it if it is not printable or if it is an escape char.
592 static void PrintEscapedString(const std::string &Str, raw_ostream &Out) {
593 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
594 unsigned char C = Str[i];
595 if (isprint(C) && C != '"' && C != '\\') {
599 << (char) ((C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A'))
600 << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
605 static const char *getPredicateText(unsigned predicate) {
606 const char * pred = "unknown";
608 case FCmpInst::FCMP_FALSE: pred = "false"; break;
609 case FCmpInst::FCMP_OEQ: pred = "oeq"; break;
610 case FCmpInst::FCMP_OGT: pred = "ogt"; break;
611 case FCmpInst::FCMP_OGE: pred = "oge"; break;
612 case FCmpInst::FCMP_OLT: pred = "olt"; break;
613 case FCmpInst::FCMP_OLE: pred = "ole"; break;
614 case FCmpInst::FCMP_ONE: pred = "one"; break;
615 case FCmpInst::FCMP_ORD: pred = "ord"; break;
616 case FCmpInst::FCMP_UNO: pred = "uno"; break;
617 case FCmpInst::FCMP_UEQ: pred = "ueq"; break;
618 case FCmpInst::FCMP_UGT: pred = "ugt"; break;
619 case FCmpInst::FCMP_UGE: pred = "uge"; break;
620 case FCmpInst::FCMP_ULT: pred = "ult"; break;
621 case FCmpInst::FCMP_ULE: pred = "ule"; break;
622 case FCmpInst::FCMP_UNE: pred = "une"; break;
623 case FCmpInst::FCMP_TRUE: pred = "true"; break;
624 case ICmpInst::ICMP_EQ: pred = "eq"; break;
625 case ICmpInst::ICMP_NE: pred = "ne"; break;
626 case ICmpInst::ICMP_SGT: pred = "sgt"; break;
627 case ICmpInst::ICMP_SGE: pred = "sge"; break;
628 case ICmpInst::ICMP_SLT: pred = "slt"; break;
629 case ICmpInst::ICMP_SLE: pred = "sle"; break;
630 case ICmpInst::ICMP_UGT: pred = "ugt"; break;
631 case ICmpInst::ICMP_UGE: pred = "uge"; break;
632 case ICmpInst::ICMP_ULT: pred = "ult"; break;
633 case ICmpInst::ICMP_ULE: pred = "ule"; break;
638 static void WriteConstantInt(raw_ostream &Out, const Constant *CV,
639 std::map<const Type *, std::string> &TypeTable,
640 SlotTracker *Machine) {
641 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
642 if (CI->getType() == Type::Int1Ty) {
643 Out << (CI->getZExtValue() ? "true" : "false");
646 Out << CI->getValue();
650 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
651 if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEdouble ||
652 &CFP->getValueAPF().getSemantics() == &APFloat::IEEEsingle) {
653 // We would like to output the FP constant value in exponential notation,
654 // but we cannot do this if doing so will lose precision. Check here to
655 // make sure that we only output it in exponential format if we can parse
656 // the value back and get the same value.
658 bool isDouble = &CFP->getValueAPF().getSemantics()==&APFloat::IEEEdouble;
659 double Val = isDouble ? CFP->getValueAPF().convertToDouble() :
660 CFP->getValueAPF().convertToFloat();
661 std::string StrVal = ftostr(CFP->getValueAPF());
663 // Check to make sure that the stringized number is not some string like
664 // "Inf" or NaN, that atof will accept, but the lexer will not. Check
665 // that the string matches the "[-+]?[0-9]" regex.
667 if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
668 ((StrVal[0] == '-' || StrVal[0] == '+') &&
669 (StrVal[1] >= '0' && StrVal[1] <= '9'))) {
670 // Reparse stringized version!
671 if (atof(StrVal.c_str()) == Val) {
676 // Otherwise we could not reparse it to exactly the same value, so we must
677 // output the string in hexadecimal format!
678 assert(sizeof(double) == sizeof(uint64_t) &&
679 "assuming that double is 64 bits!");
680 Out << "0x" << utohexstr(DoubleToBits(Val));
684 // Some form of long double. These appear as a magic letter identifying
685 // the type, then a fixed number of hex digits.
687 if (&CFP->getValueAPF().getSemantics() == &APFloat::x87DoubleExtended)
689 else if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEquad)
691 else if (&CFP->getValueAPF().getSemantics() == &APFloat::PPCDoubleDouble)
694 assert(0 && "Unsupported floating point type");
695 // api needed to prevent premature destruction
696 APInt api = CFP->getValueAPF().bitcastToAPInt();
697 const uint64_t* p = api.getRawData();
700 int width = api.getBitWidth();
701 for (int j=0; j<width; j+=4, shiftcount-=4) {
702 unsigned int nibble = (word>>shiftcount) & 15;
704 Out << (unsigned char)(nibble + '0');
706 Out << (unsigned char)(nibble - 10 + 'A');
707 if (shiftcount == 0 && j+4 < width) {
711 shiftcount = width-j-4;
717 if (isa<ConstantAggregateZero>(CV)) {
718 Out << "zeroinitializer";
722 if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
723 // As a special case, print the array as a string if it is an array of
724 // i8 with ConstantInt values.
726 const Type *ETy = CA->getType()->getElementType();
727 if (CA->isString()) {
729 PrintEscapedString(CA->getAsString(), Out);
731 } else { // Cannot output in string format...
733 if (CA->getNumOperands()) {
735 printTypeInt(Out, ETy, TypeTable);
737 WriteAsOperandInternal(Out, CA->getOperand(0),
739 for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
741 printTypeInt(Out, ETy, TypeTable);
743 WriteAsOperandInternal(Out, CA->getOperand(i), TypeTable, Machine);
752 if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
753 if (CS->getType()->isPacked())
756 unsigned N = CS->getNumOperands();
759 printTypeInt(Out, CS->getOperand(0)->getType(), TypeTable);
762 WriteAsOperandInternal(Out, CS->getOperand(0), TypeTable, Machine);
764 for (unsigned i = 1; i < N; i++) {
766 printTypeInt(Out, CS->getOperand(i)->getType(), TypeTable);
769 WriteAsOperandInternal(Out, CS->getOperand(i), TypeTable, Machine);
775 if (CS->getType()->isPacked())
780 if (const ConstantVector *CP = dyn_cast<ConstantVector>(CV)) {
781 const Type *ETy = CP->getType()->getElementType();
782 assert(CP->getNumOperands() > 0 &&
783 "Number of operands for a PackedConst must be > 0");
785 printTypeInt(Out, ETy, TypeTable);
787 WriteAsOperandInternal(Out, CP->getOperand(0), TypeTable, Machine);
788 for (unsigned i = 1, e = CP->getNumOperands(); i != e; ++i) {
790 printTypeInt(Out, ETy, TypeTable);
792 WriteAsOperandInternal(Out, CP->getOperand(i), TypeTable, Machine);
798 if (isa<ConstantPointerNull>(CV)) {
803 if (isa<UndefValue>(CV)) {
808 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
809 Out << CE->getOpcodeName();
811 Out << ' ' << getPredicateText(CE->getPredicate());
814 for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) {
815 printTypeInt(Out, (*OI)->getType(), TypeTable);
817 WriteAsOperandInternal(Out, *OI, TypeTable, Machine);
818 if (OI+1 != CE->op_end())
822 if (CE->hasIndices()) {
823 const SmallVector<unsigned, 4> &Indices = CE->getIndices();
824 for (unsigned i = 0, e = Indices.size(); i != e; ++i)
825 Out << ", " << Indices[i];
830 printTypeInt(Out, CE->getType(), TypeTable);
837 Out << "<placeholder or erroneous Constant>";
841 /// WriteAsOperand - Write the name of the specified value out to the specified
842 /// ostream. This can be useful when you just want to print int %reg126, not
843 /// the whole instruction that generated it.
845 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
846 std::map<const Type*, std::string> &TypeTable,
847 SlotTracker *Machine) {
849 PrintLLVMName(Out, V);
853 const Constant *CV = dyn_cast<Constant>(V);
854 if (CV && !isa<GlobalValue>(CV)) {
855 WriteConstantInt(Out, CV, TypeTable, Machine);
859 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
861 if (IA->hasSideEffects())
862 Out << "sideeffect ";
864 PrintEscapedString(IA->getAsmString(), Out);
866 PrintEscapedString(IA->getConstraintString(), Out);
874 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
875 Slot = Machine->getGlobalSlot(GV);
878 Slot = Machine->getLocalSlot(V);
881 Machine = createSlotTracker(V);
883 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
884 Slot = Machine->getGlobalSlot(GV);
887 Slot = Machine->getLocalSlot(V);
896 Out << Prefix << Slot;
901 /// WriteAsOperand - Write the name of the specified value out to the specified
902 /// ostream. This can be useful when you just want to print int %reg126, not
903 /// the whole instruction that generated it.
905 void llvm::WriteAsOperand(std::ostream &Out, const Value *V, bool PrintType,
906 const Module *Context) {
907 raw_os_ostream OS(Out);
908 WriteAsOperand(OS, V, PrintType, Context);
911 void llvm::WriteAsOperand(raw_ostream &Out, const Value *V, bool PrintType,
912 const Module *Context) {
913 std::map<const Type *, std::string> TypeNames;
914 if (Context == 0) Context = getModuleFromVal(V);
917 fillTypeNameTable(Context, TypeNames);
920 printTypeInt(Out, V->getType(), TypeNames);
924 WriteAsOperandInternal(Out, V, TypeNames, 0);
930 class AssemblyWriter {
932 SlotTracker &Machine;
933 const Module *TheModule;
934 std::map<const Type *, std::string> TypeNames;
935 AssemblyAnnotationWriter *AnnotationWriter;
937 inline AssemblyWriter(raw_ostream &o, SlotTracker &Mac, const Module *M,
938 AssemblyAnnotationWriter *AAW)
939 : Out(o), Machine(Mac), TheModule(M), AnnotationWriter(AAW) {
941 // If the module has a symbol table, take all global types and stuff their
942 // names into the TypeNames map.
944 fillTypeNameTable(M, TypeNames);
947 void write(const Module *M) { printModule(M); }
949 void write(const GlobalValue *G) {
950 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(G))
952 else if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(G))
954 else if (const Function *F = dyn_cast<Function>(G))
957 assert(0 && "Unknown global");
960 void write(const BasicBlock *BB) { printBasicBlock(BB); }
961 void write(const Instruction *I) { printInstruction(*I); }
962 void write(const Type *Ty) { printType(Ty); }
964 void writeOperand(const Value *Op, bool PrintType);
965 void writeParamOperand(const Value *Operand, Attributes Attrs);
967 const Module* getModule() { return TheModule; }
970 void printModule(const Module *M);
971 void printTypeSymbolTable(const TypeSymbolTable &ST);
972 void printGlobal(const GlobalVariable *GV);
973 void printAlias(const GlobalAlias *GV);
974 void printFunction(const Function *F);
975 void printArgument(const Argument *FA, Attributes Attrs);
976 void printBasicBlock(const BasicBlock *BB);
977 void printInstruction(const Instruction &I);
979 // printType - Go to extreme measures to attempt to print out a short,
980 // symbolic version of a type name.
982 void printType(const Type *Ty) {
983 printTypeInt(Out, Ty, TypeNames);
986 // printTypeAtLeastOneLevel - Print out one level of the possibly complex type
987 // without considering any symbolic types that we may have equal to it.
989 void printTypeAtLeastOneLevel(const Type *Ty);
991 // printInfoComment - Print a little comment after the instruction indicating
992 // which slot it occupies.
993 void printInfoComment(const Value &V);
995 } // end of llvm namespace
997 /// printTypeAtLeastOneLevel - Print out one level of the possibly complex type
998 /// without considering any symbolic types that we may have equal to it.
1000 void AssemblyWriter::printTypeAtLeastOneLevel(const Type *Ty) {
1001 if (const IntegerType *ITy = dyn_cast<IntegerType>(Ty)) {
1002 Out << "i" << utostr(ITy->getBitWidth());
1006 if (const FunctionType *FTy = dyn_cast<FunctionType>(Ty)) {
1007 printType(FTy->getReturnType());
1009 for (FunctionType::param_iterator I = FTy->param_begin(),
1010 E = FTy->param_end(); I != E; ++I) {
1011 if (I != FTy->param_begin())
1015 if (FTy->isVarArg()) {
1016 if (FTy->getNumParams()) Out << ", ";
1023 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1024 if (STy->isPacked())
1027 for (StructType::element_iterator I = STy->element_begin(),
1028 E = STy->element_end(); I != E; ++I) {
1029 if (I != STy->element_begin())
1034 if (STy->isPacked())
1039 if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
1040 printType(PTy->getElementType());
1041 if (unsigned AddressSpace = PTy->getAddressSpace())
1042 Out << " addrspace(" << AddressSpace << ")";
1047 if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1048 Out << '[' << ATy->getNumElements() << " x ";
1049 printType(ATy->getElementType());
1054 if (const VectorType *PTy = dyn_cast<VectorType>(Ty)) {
1055 Out << '<' << PTy->getNumElements() << " x ";
1056 printType(PTy->getElementType());
1061 if (isa<OpaqueType>(Ty)) {
1066 if (!Ty->isPrimitiveType())
1067 Out << "<unknown derived type>";
1072 void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType) {
1074 Out << "<null operand!>";
1077 printType(Operand->getType());
1080 WriteAsOperandInternal(Out, Operand, TypeNames, &Machine);
1084 void AssemblyWriter::writeParamOperand(const Value *Operand,
1087 Out << "<null operand!>";
1090 printType(Operand->getType());
1091 // Print parameter attributes list
1092 if (Attrs != Attribute::None)
1093 Out << ' ' << Attribute::getAsString(Attrs);
1095 // Print the operand
1096 WriteAsOperandInternal(Out, Operand, TypeNames, &Machine);
1100 void AssemblyWriter::printModule(const Module *M) {
1101 if (!M->getModuleIdentifier().empty() &&
1102 // Don't print the ID if it will start a new line (which would
1103 // require a comment char before it).
1104 M->getModuleIdentifier().find('\n') == std::string::npos)
1105 Out << "; ModuleID = '" << M->getModuleIdentifier() << "'\n";
1107 if (!M->getDataLayout().empty())
1108 Out << "target datalayout = \"" << M->getDataLayout() << "\"\n";
1109 if (!M->getTargetTriple().empty())
1110 Out << "target triple = \"" << M->getTargetTriple() << "\"\n";
1112 if (!M->getModuleInlineAsm().empty()) {
1113 // Split the string into lines, to make it easier to read the .ll file.
1114 std::string Asm = M->getModuleInlineAsm();
1116 size_t NewLine = Asm.find_first_of('\n', CurPos);
1117 while (NewLine != std::string::npos) {
1118 // We found a newline, print the portion of the asm string from the
1119 // last newline up to this newline.
1120 Out << "module asm \"";
1121 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.begin()+NewLine),
1125 NewLine = Asm.find_first_of('\n', CurPos);
1127 Out << "module asm \"";
1128 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.end()), Out);
1132 // Loop over the dependent libraries and emit them.
1133 Module::lib_iterator LI = M->lib_begin();
1134 Module::lib_iterator LE = M->lib_end();
1136 Out << "deplibs = [ ";
1138 Out << '"' << *LI << '"';
1146 // Loop over the symbol table, emitting all named constants.
1147 printTypeSymbolTable(M->getTypeSymbolTable());
1149 for (Module::const_global_iterator I = M->global_begin(), E = M->global_end();
1153 // Output all aliases.
1154 if (!M->alias_empty()) Out << "\n";
1155 for (Module::const_alias_iterator I = M->alias_begin(), E = M->alias_end();
1159 // Output all of the functions.
1160 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
1164 static void PrintLinkage(GlobalValue::LinkageTypes LT, raw_ostream &Out) {
1166 case GlobalValue::InternalLinkage: Out << "internal "; break;
1167 case GlobalValue::LinkOnceLinkage: Out << "linkonce "; break;
1168 case GlobalValue::WeakLinkage: Out << "weak "; break;
1169 case GlobalValue::CommonLinkage: Out << "common "; break;
1170 case GlobalValue::AppendingLinkage: Out << "appending "; break;
1171 case GlobalValue::DLLImportLinkage: Out << "dllimport "; break;
1172 case GlobalValue::DLLExportLinkage: Out << "dllexport "; break;
1173 case GlobalValue::ExternalWeakLinkage: Out << "extern_weak "; break;
1174 case GlobalValue::ExternalLinkage: break;
1175 case GlobalValue::GhostLinkage:
1176 Out << "GhostLinkage not allowed in AsmWriter!\n";
1182 static void PrintVisibility(GlobalValue::VisibilityTypes Vis,
1185 default: assert(0 && "Invalid visibility style!");
1186 case GlobalValue::DefaultVisibility: break;
1187 case GlobalValue::HiddenVisibility: Out << "hidden "; break;
1188 case GlobalValue::ProtectedVisibility: Out << "protected "; break;
1192 void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
1193 if (GV->hasName()) {
1194 PrintLLVMName(Out, GV);
1198 if (!GV->hasInitializer() && GV->hasExternalLinkage())
1201 PrintLinkage(GV->getLinkage(), Out);
1202 PrintVisibility(GV->getVisibility(), Out);
1204 if (GV->isThreadLocal()) Out << "thread_local ";
1205 Out << (GV->isConstant() ? "constant " : "global ");
1206 printType(GV->getType()->getElementType());
1208 if (GV->hasInitializer()) {
1210 writeOperand(GV->getInitializer(), false);
1213 if (unsigned AddressSpace = GV->getType()->getAddressSpace())
1214 Out << " addrspace(" << AddressSpace << ") ";
1216 if (GV->hasSection())
1217 Out << ", section \"" << GV->getSection() << '"';
1218 if (GV->getAlignment())
1219 Out << ", align " << GV->getAlignment();
1221 printInfoComment(*GV);
1225 void AssemblyWriter::printAlias(const GlobalAlias *GA) {
1226 // Don't crash when dumping partially built GA
1228 Out << "<<nameless>> = ";
1230 PrintLLVMName(Out, GA);
1233 PrintVisibility(GA->getVisibility(), Out);
1237 PrintLinkage(GA->getLinkage(), Out);
1239 const Constant *Aliasee = GA->getAliasee();
1241 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Aliasee)) {
1242 printType(GV->getType());
1244 PrintLLVMName(Out, GV);
1245 } else if (const Function *F = dyn_cast<Function>(Aliasee)) {
1246 printType(F->getFunctionType());
1250 PrintLLVMName(Out, F);
1253 } else if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(Aliasee)) {
1254 printType(GA->getType());
1256 PrintLLVMName(Out, GA);
1258 const ConstantExpr *CE = 0;
1259 if ((CE = dyn_cast<ConstantExpr>(Aliasee)) &&
1260 (CE->getOpcode() == Instruction::BitCast)) {
1261 writeOperand(CE, false);
1263 assert(0 && "Unsupported aliasee");
1266 printInfoComment(*GA);
1270 void AssemblyWriter::printTypeSymbolTable(const TypeSymbolTable &ST) {
1272 for (TypeSymbolTable::const_iterator TI = ST.begin(), TE = ST.end();
1275 PrintLLVMName(Out, &TI->first[0], TI->first.size(), LocalPrefix);
1278 // Make sure we print out at least one level of the type structure, so
1279 // that we do not get %FILE = type %FILE
1281 printTypeAtLeastOneLevel(TI->second);
1286 /// printFunction - Print all aspects of a function.
1288 void AssemblyWriter::printFunction(const Function *F) {
1289 // Print out the return type and name.
1292 if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, Out);
1294 if (F->isDeclaration())
1299 PrintLinkage(F->getLinkage(), Out);
1300 PrintVisibility(F->getVisibility(), Out);
1302 // Print the calling convention.
1303 switch (F->getCallingConv()) {
1304 case CallingConv::C: break; // default
1305 case CallingConv::Fast: Out << "fastcc "; break;
1306 case CallingConv::Cold: Out << "coldcc "; break;
1307 case CallingConv::X86_StdCall: Out << "x86_stdcallcc "; break;
1308 case CallingConv::X86_FastCall: Out << "x86_fastcallcc "; break;
1309 default: Out << "cc" << F->getCallingConv() << " "; break;
1312 const FunctionType *FT = F->getFunctionType();
1313 const AttrListPtr &Attrs = F->getAttributes();
1314 Attributes RetAttrs = Attrs.getRetAttributes();
1315 if (RetAttrs != Attribute::None)
1316 Out << Attribute::getAsString(Attrs.getRetAttributes()) << ' ';
1317 printType(F->getReturnType());
1320 PrintLLVMName(Out, F);
1324 Machine.incorporateFunction(F);
1326 // Loop over the arguments, printing them...
1329 if (!F->isDeclaration()) {
1330 // If this isn't a declaration, print the argument names as well.
1331 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
1333 // Insert commas as we go... the first arg doesn't get a comma
1334 if (I != F->arg_begin()) Out << ", ";
1335 printArgument(I, Attrs.getParamAttributes(Idx));
1339 // Otherwise, print the types from the function type.
1340 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
1341 // Insert commas as we go... the first arg doesn't get a comma
1345 printType(FT->getParamType(i));
1347 Attributes ArgAttrs = Attrs.getParamAttributes(i+1);
1348 if (ArgAttrs != Attribute::None)
1349 Out << ' ' << Attribute::getAsString(ArgAttrs);
1353 // Finish printing arguments...
1354 if (FT->isVarArg()) {
1355 if (FT->getNumParams()) Out << ", ";
1356 Out << "..."; // Output varargs portion of signature!
1359 Attributes FnAttrs = Attrs.getFnAttributes();
1360 if (FnAttrs != Attribute::None)
1361 Out << ' ' << Attribute::getAsString(Attrs.getFnAttributes());
1362 if (F->hasSection())
1363 Out << " section \"" << F->getSection() << '"';
1364 if (F->getAlignment())
1365 Out << " align " << F->getAlignment();
1367 Out << " gc \"" << F->getGC() << '"';
1368 if (F->isDeclaration()) {
1373 // Output all of its basic blocks... for the function
1374 for (Function::const_iterator I = F->begin(), E = F->end(); I != E; ++I)
1380 Machine.purgeFunction();
1383 /// printArgument - This member is called for every argument that is passed into
1384 /// the function. Simply print it out
1386 void AssemblyWriter::printArgument(const Argument *Arg,
1389 printType(Arg->getType());
1391 // Output parameter attributes list
1392 if (Attrs != Attribute::None)
1393 Out << ' ' << Attribute::getAsString(Attrs);
1395 // Output name, if available...
1396 if (Arg->hasName()) {
1398 PrintLLVMName(Out, Arg);
1402 /// printBasicBlock - This member is called for each basic block in a method.
1404 void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {
1405 if (BB->hasName()) { // Print out the label if it exists...
1407 PrintLLVMName(Out, BB->getNameStart(), BB->getNameLen(), LabelPrefix);
1409 } else if (!BB->use_empty()) { // Don't print block # of no uses...
1410 Out << "\n; <label>:";
1411 int Slot = Machine.getLocalSlot(BB);
1418 if (BB->getParent() == 0)
1419 Out << "\t\t; Error: Block without parent!";
1420 else if (BB != &BB->getParent()->getEntryBlock()) { // Not the entry block?
1421 // Output predecessors for the block...
1423 pred_const_iterator PI = pred_begin(BB), PE = pred_end(BB);
1426 Out << " No predecessors!";
1429 writeOperand(*PI, false);
1430 for (++PI; PI != PE; ++PI) {
1432 writeOperand(*PI, false);
1439 if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(BB, Out);
1441 // Output all of the instructions in the basic block...
1442 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
1443 printInstruction(*I);
1445 if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(BB, Out);
1449 /// printInfoComment - Print a little comment after the instruction indicating
1450 /// which slot it occupies.
1452 void AssemblyWriter::printInfoComment(const Value &V) {
1453 if (V.getType() != Type::VoidTy) {
1455 printType(V.getType());
1458 if (!V.hasName() && !isa<Instruction>(V)) {
1460 if (const GlobalValue *GV = dyn_cast<GlobalValue>(&V))
1461 SlotNum = Machine.getGlobalSlot(GV);
1463 SlotNum = Machine.getLocalSlot(&V);
1467 Out << ':' << SlotNum; // Print out the def slot taken.
1469 Out << " [#uses=" << V.getNumUses() << ']'; // Output # uses
1473 // This member is called for each Instruction in a function..
1474 void AssemblyWriter::printInstruction(const Instruction &I) {
1475 if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, Out);
1479 // Print out name if it exists...
1481 PrintLLVMName(Out, &I);
1483 } else if (I.getType() != Type::VoidTy) {
1484 // Print out the def slot taken.
1485 int SlotNum = Machine.getLocalSlot(&I);
1487 Out << "<badref> = ";
1489 Out << '%' << SlotNum << " = ";
1492 // If this is a volatile load or store, print out the volatile marker.
1493 if ((isa<LoadInst>(I) && cast<LoadInst>(I).isVolatile()) ||
1494 (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile())) {
1496 } else if (isa<CallInst>(I) && cast<CallInst>(I).isTailCall()) {
1497 // If this is a call, check if it's a tail call.
1501 // Print out the opcode...
1502 Out << I.getOpcodeName();
1504 // Print out the compare instruction predicates
1505 if (const CmpInst *CI = dyn_cast<CmpInst>(&I))
1506 Out << ' ' << getPredicateText(CI->getPredicate());
1508 // Print out the type of the operands...
1509 const Value *Operand = I.getNumOperands() ? I.getOperand(0) : 0;
1511 // Special case conditional branches to swizzle the condition out to the front
1512 if (isa<BranchInst>(I) && I.getNumOperands() > 1) {
1514 writeOperand(I.getOperand(2), true);
1516 writeOperand(Operand, true);
1518 writeOperand(I.getOperand(1), true);
1520 } else if (isa<SwitchInst>(I)) {
1521 // Special case switch statement to get formatting nice and correct...
1523 writeOperand(Operand , true);
1525 writeOperand(I.getOperand(1), true);
1528 for (unsigned op = 2, Eop = I.getNumOperands(); op < Eop; op += 2) {
1530 writeOperand(I.getOperand(op ), true);
1532 writeOperand(I.getOperand(op+1), true);
1535 } else if (isa<PHINode>(I)) {
1537 printType(I.getType());
1540 for (unsigned op = 0, Eop = I.getNumOperands(); op < Eop; op += 2) {
1541 if (op) Out << ", ";
1543 writeOperand(I.getOperand(op ), false); Out << ", ";
1544 writeOperand(I.getOperand(op+1), false); Out << " ]";
1546 } else if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&I)) {
1548 writeOperand(I.getOperand(0), true);
1549 for (const unsigned *i = EVI->idx_begin(), *e = EVI->idx_end(); i != e; ++i)
1551 } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&I)) {
1553 writeOperand(I.getOperand(0), true); Out << ", ";
1554 writeOperand(I.getOperand(1), true);
1555 for (const unsigned *i = IVI->idx_begin(), *e = IVI->idx_end(); i != e; ++i)
1557 } else if (isa<ReturnInst>(I) && !Operand) {
1559 } else if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
1560 // Print the calling convention being used.
1561 switch (CI->getCallingConv()) {
1562 case CallingConv::C: break; // default
1563 case CallingConv::Fast: Out << " fastcc"; break;
1564 case CallingConv::Cold: Out << " coldcc"; break;
1565 case CallingConv::X86_StdCall: Out << " x86_stdcallcc"; break;
1566 case CallingConv::X86_FastCall: Out << " x86_fastcallcc"; break;
1567 default: Out << " cc" << CI->getCallingConv(); break;
1570 const PointerType *PTy = cast<PointerType>(Operand->getType());
1571 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1572 const Type *RetTy = FTy->getReturnType();
1573 const AttrListPtr &PAL = CI->getAttributes();
1575 if (PAL.getRetAttributes() != Attribute::None)
1576 Out << ' ' << Attribute::getAsString(PAL.getRetAttributes());
1578 // If possible, print out the short form of the call instruction. We can
1579 // only do this if the first argument is a pointer to a nonvararg function,
1580 // and if the return type is not a pointer to a function.
1583 if (!FTy->isVarArg() &&
1584 (!isa<PointerType>(RetTy) ||
1585 !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
1588 writeOperand(Operand, false);
1590 writeOperand(Operand, true);
1593 for (unsigned op = 1, Eop = I.getNumOperands(); op < Eop; ++op) {
1596 writeParamOperand(I.getOperand(op), PAL.getParamAttributes(op));
1599 if (PAL.getFnAttributes() != Attribute::None)
1600 Out << ' ' << Attribute::getAsString(PAL.getFnAttributes());
1601 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
1602 const PointerType *PTy = cast<PointerType>(Operand->getType());
1603 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1604 const Type *RetTy = FTy->getReturnType();
1605 const AttrListPtr &PAL = II->getAttributes();
1607 // Print the calling convention being used.
1608 switch (II->getCallingConv()) {
1609 case CallingConv::C: break; // default
1610 case CallingConv::Fast: Out << " fastcc"; break;
1611 case CallingConv::Cold: Out << " coldcc"; break;
1612 case CallingConv::X86_StdCall: Out << " x86_stdcallcc"; break;
1613 case CallingConv::X86_FastCall: Out << " x86_fastcallcc"; break;
1614 default: Out << " cc" << II->getCallingConv(); break;
1617 if (PAL.getRetAttributes() != Attribute::None)
1618 Out << ' ' << Attribute::getAsString(PAL.getRetAttributes());
1620 // If possible, print out the short form of the invoke instruction. We can
1621 // only do this if the first argument is a pointer to a nonvararg function,
1622 // and if the return type is not a pointer to a function.
1624 if (!FTy->isVarArg() &&
1625 (!isa<PointerType>(RetTy) ||
1626 !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
1627 Out << ' '; printType(RetTy);
1628 writeOperand(Operand, false);
1631 writeOperand(Operand, true);
1635 for (unsigned op = 3, Eop = I.getNumOperands(); op < Eop; ++op) {
1638 writeParamOperand(I.getOperand(op), PAL.getParamAttributes(op-2));
1642 if (PAL.getFnAttributes() != Attribute::None)
1643 Out << ' ' << Attribute::getAsString(PAL.getFnAttributes());
1645 Out << "\n\t\t\tto ";
1646 writeOperand(II->getNormalDest(), true);
1648 writeOperand(II->getUnwindDest(), true);
1650 } else if (const AllocationInst *AI = dyn_cast<AllocationInst>(&I)) {
1652 printType(AI->getType()->getElementType());
1653 if (AI->isArrayAllocation()) {
1655 writeOperand(AI->getArraySize(), true);
1657 if (AI->getAlignment()) {
1658 Out << ", align " << AI->getAlignment();
1660 } else if (isa<CastInst>(I)) {
1663 writeOperand(Operand, true); // Work with broken code
1666 printType(I.getType());
1667 } else if (isa<VAArgInst>(I)) {
1670 writeOperand(Operand, true); // Work with broken code
1673 printType(I.getType());
1674 } else if (Operand) { // Print the normal way...
1676 // PrintAllTypes - Instructions who have operands of all the same type
1677 // omit the type from all but the first operand. If the instruction has
1678 // different type operands (for example br), then they are all printed.
1679 bool PrintAllTypes = false;
1680 const Type *TheType = Operand->getType();
1682 // Select, Store and ShuffleVector always print all types.
1683 if (isa<SelectInst>(I) || isa<StoreInst>(I) || isa<ShuffleVectorInst>(I)
1684 || isa<ReturnInst>(I)) {
1685 PrintAllTypes = true;
1687 for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) {
1688 Operand = I.getOperand(i);
1689 if (Operand->getType() != TheType) {
1690 PrintAllTypes = true; // We have differing types! Print them all!
1696 if (!PrintAllTypes) {
1702 for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) {
1704 writeOperand(I.getOperand(i), PrintAllTypes);
1708 // Print post operand alignment for load/store
1709 if (isa<LoadInst>(I) && cast<LoadInst>(I).getAlignment()) {
1710 Out << ", align " << cast<LoadInst>(I).getAlignment();
1711 } else if (isa<StoreInst>(I) && cast<StoreInst>(I).getAlignment()) {
1712 Out << ", align " << cast<StoreInst>(I).getAlignment();
1715 printInfoComment(I);
1720 //===----------------------------------------------------------------------===//
1721 // External Interface declarations
1722 //===----------------------------------------------------------------------===//
1724 void Module::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1725 raw_os_ostream OS(o);
1728 void Module::print(raw_ostream &OS, AssemblyAnnotationWriter *AAW) const {
1729 SlotTracker SlotTable(this);
1730 AssemblyWriter W(OS, SlotTable, this, AAW);
1734 void Type::print(std::ostream &o) const {
1735 raw_os_ostream OS(o);
1739 void Type::print(raw_ostream &o) const {
1743 o << getDescription();
1746 void Value::print(raw_ostream &OS, AssemblyAnnotationWriter *AAW) const {
1748 OS << "printing a <null> value\n";
1752 if (const Instruction *I = dyn_cast<Instruction>(this)) {
1753 const Function *F = I->getParent() ? I->getParent()->getParent() : 0;
1754 SlotTracker SlotTable(F);
1755 AssemblyWriter W(OS, SlotTable, F ? F->getParent() : 0, AAW);
1757 } else if (const BasicBlock *BB = dyn_cast<BasicBlock>(this)) {
1758 SlotTracker SlotTable(BB->getParent());
1759 AssemblyWriter W(OS, SlotTable,
1760 BB->getParent() ? BB->getParent()->getParent() : 0, AAW);
1762 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(this)) {
1763 SlotTracker SlotTable(GV->getParent());
1764 AssemblyWriter W(OS, SlotTable, GV->getParent(), 0);
1766 } else if (const Constant *C = dyn_cast<Constant>(this)) {
1767 OS << C->getType()->getDescription() << ' ';
1768 std::map<const Type *, std::string> TypeTable;
1769 WriteConstantInt(OS, C, TypeTable, 0);
1770 } else if (const Argument *A = dyn_cast<Argument>(this)) {
1771 WriteAsOperand(OS, this, true,
1772 A->getParent() ? A->getParent()->getParent() : 0);
1773 } else if (isa<InlineAsm>(this)) {
1774 WriteAsOperand(OS, this, true, 0);
1776 // FIXME: PseudoSourceValue breaks this!
1777 //assert(0 && "Unknown value to print out!");
1781 void Value::print(std::ostream &O, AssemblyAnnotationWriter *AAW) const {
1782 raw_os_ostream OS(O);
1786 // Value::dump - allow easy printing of Values from the debugger.
1787 void Value::dump() const { print(errs()); errs() << '\n'; errs().flush(); }
1789 // Type::dump - allow easy printing of Types from the debugger.
1790 void Type::dump() const { print(errs()); errs() << '\n'; errs().flush(); }
1792 // Type::dump - allow easy printing of Types from the debugger.
1793 // This one uses type names from the given context module
1794 void Type::dump(const Module *Context) const {
1795 WriteTypeSymbolic(errs(), this, Context);
1800 // Module::dump() - Allow printing of Modules from the debugger.
1801 void Module::dump() const { print(errs(), 0); errs().flush(); }