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/MDNode.h"
27 #include "llvm/Module.h"
28 #include "llvm/ValueSymbolTable.h"
29 #include "llvm/TypeSymbolTable.h"
30 #include "llvm/ADT/DenseSet.h"
31 #include "llvm/ADT/StringExtras.h"
32 #include "llvm/ADT/STLExtras.h"
33 #include "llvm/Support/CFG.h"
34 #include "llvm/Support/MathExtras.h"
35 #include "llvm/Support/raw_ostream.h"
41 // Make virtual table appear in this compilation unit.
42 AssemblyAnnotationWriter::~AssemblyAnnotationWriter() {}
44 //===----------------------------------------------------------------------===//
46 //===----------------------------------------------------------------------===//
48 static const Module *getModuleFromVal(const Value *V) {
49 if (const Argument *MA = dyn_cast<Argument>(V))
50 return MA->getParent() ? MA->getParent()->getParent() : 0;
52 if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
53 return BB->getParent() ? BB->getParent()->getParent() : 0;
55 if (const Instruction *I = dyn_cast<Instruction>(V)) {
56 const Function *M = I->getParent() ? I->getParent()->getParent() : 0;
57 return M ? M->getParent() : 0;
60 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
61 return GV->getParent();
65 // PrintEscapedString - Print each character of the specified string, escaping
66 // it if it is not printable or if it is an escape char.
67 static void PrintEscapedString(const char *Str, unsigned Length,
69 for (unsigned i = 0; i != Length; ++i) {
70 unsigned char C = Str[i];
71 if (isprint(C) && C != '\\' && C != '"')
74 Out << '\\' << hexdigit(C >> 4) << hexdigit(C & 0x0F);
78 // PrintEscapedString - Print each character of the specified string, escaping
79 // it if it is not printable or if it is an escape char.
80 static void PrintEscapedString(const std::string &Str, raw_ostream &Out) {
81 PrintEscapedString(Str.c_str(), Str.size(), Out);
91 /// PrintLLVMName - Turn the specified name into an 'LLVM name', which is either
92 /// prefixed with % (if the string only contains simple characters) or is
93 /// surrounded with ""'s (if it has special chars in it). Print it out.
94 static void PrintLLVMName(raw_ostream &OS, const char *NameStr,
95 unsigned NameLen, PrefixType Prefix) {
96 assert(NameStr && "Cannot get empty name!");
98 default: assert(0 && "Bad prefix!");
100 case GlobalPrefix: OS << '@'; break;
101 case LabelPrefix: break;
102 case LocalPrefix: OS << '%'; break;
105 // Scan the name to see if it needs quotes first.
106 bool NeedsQuotes = isdigit(NameStr[0]);
108 for (unsigned i = 0; i != NameLen; ++i) {
110 if (!isalnum(C) && C != '-' && C != '.' && C != '_') {
117 // If we didn't need any quotes, just write out the name in one blast.
119 OS.write(NameStr, NameLen);
123 // Okay, we need quotes. Output the quotes and escape any scary characters as
126 PrintEscapedString(NameStr, NameLen, OS);
130 /// PrintLLVMName - Turn the specified name into an 'LLVM name', which is either
131 /// prefixed with % (if the string only contains simple characters) or is
132 /// surrounded with ""'s (if it has special chars in it). Print it out.
133 static void PrintLLVMName(raw_ostream &OS, const Value *V) {
134 PrintLLVMName(OS, V->getNameStart(), V->getNameLen(),
135 isa<GlobalValue>(V) ? GlobalPrefix : LocalPrefix);
138 //===----------------------------------------------------------------------===//
139 // TypePrinting Class: Type printing machinery
140 //===----------------------------------------------------------------------===//
142 static DenseMap<const Type *, std::string> &getTypeNamesMap(void *M) {
143 return *static_cast<DenseMap<const Type *, std::string>*>(M);
146 void TypePrinting::clear() {
147 getTypeNamesMap(TypeNames).clear();
150 bool TypePrinting::hasTypeName(const Type *Ty) const {
151 return getTypeNamesMap(TypeNames).count(Ty);
154 void TypePrinting::addTypeName(const Type *Ty, const std::string &N) {
155 getTypeNamesMap(TypeNames).insert(std::make_pair(Ty, N));
159 TypePrinting::TypePrinting() {
160 TypeNames = new DenseMap<const Type *, std::string>();
163 TypePrinting::~TypePrinting() {
164 delete &getTypeNamesMap(TypeNames);
167 /// CalcTypeName - Write the specified type to the specified raw_ostream, making
168 /// use of type names or up references to shorten the type name where possible.
169 void TypePrinting::CalcTypeName(const Type *Ty,
170 SmallVectorImpl<const Type *> &TypeStack,
171 raw_ostream &OS, bool IgnoreTopLevelName) {
172 // Check to see if the type is named.
173 if (!IgnoreTopLevelName) {
174 DenseMap<const Type *, std::string> &TM = getTypeNamesMap(TypeNames);
175 DenseMap<const Type *, std::string>::iterator I = TM.find(Ty);
182 // Check to see if the Type is already on the stack...
183 unsigned Slot = 0, CurSize = TypeStack.size();
184 while (Slot < CurSize && TypeStack[Slot] != Ty) ++Slot; // Scan for type
186 // This is another base case for the recursion. In this case, we know
187 // that we have looped back to a type that we have previously visited.
188 // Generate the appropriate upreference to handle this.
189 if (Slot < CurSize) {
190 OS << '\\' << unsigned(CurSize-Slot); // Here's the upreference
194 TypeStack.push_back(Ty); // Recursive case: Add us to the stack..
196 switch (Ty->getTypeID()) {
197 case Type::VoidTyID: OS << "void"; break;
198 case Type::FloatTyID: OS << "float"; break;
199 case Type::DoubleTyID: OS << "double"; break;
200 case Type::X86_FP80TyID: OS << "x86_fp80"; break;
201 case Type::FP128TyID: OS << "fp128"; break;
202 case Type::PPC_FP128TyID: OS << "ppc_fp128"; break;
203 case Type::LabelTyID: OS << "label"; break;
204 case Type::MetadataTyID: OS << "metadata"; break;
205 case Type::IntegerTyID:
206 OS << 'i' << cast<IntegerType>(Ty)->getBitWidth();
209 case Type::FunctionTyID: {
210 const FunctionType *FTy = cast<FunctionType>(Ty);
211 CalcTypeName(FTy->getReturnType(), TypeStack, OS);
213 for (FunctionType::param_iterator I = FTy->param_begin(),
214 E = FTy->param_end(); I != E; ++I) {
215 if (I != FTy->param_begin())
217 CalcTypeName(*I, TypeStack, OS);
219 if (FTy->isVarArg()) {
220 if (FTy->getNumParams()) OS << ", ";
226 case Type::StructTyID: {
227 const StructType *STy = cast<StructType>(Ty);
231 for (StructType::element_iterator I = STy->element_begin(),
232 E = STy->element_end(); I != E; ++I) {
233 CalcTypeName(*I, TypeStack, OS);
234 if (next(I) != STy->element_end())
243 case Type::PointerTyID: {
244 const PointerType *PTy = cast<PointerType>(Ty);
245 CalcTypeName(PTy->getElementType(), TypeStack, OS);
246 if (unsigned AddressSpace = PTy->getAddressSpace())
247 OS << " addrspace(" << AddressSpace << ')';
251 case Type::ArrayTyID: {
252 const ArrayType *ATy = cast<ArrayType>(Ty);
253 OS << '[' << ATy->getNumElements() << " x ";
254 CalcTypeName(ATy->getElementType(), TypeStack, OS);
258 case Type::VectorTyID: {
259 const VectorType *PTy = cast<VectorType>(Ty);
260 OS << "<" << PTy->getNumElements() << " x ";
261 CalcTypeName(PTy->getElementType(), TypeStack, OS);
265 case Type::OpaqueTyID:
269 OS << "<unrecognized-type>";
273 TypeStack.pop_back(); // Remove self from stack.
276 /// printTypeInt - The internal guts of printing out a type that has a
277 /// potentially named portion.
279 void TypePrinting::print(const Type *Ty, raw_ostream &OS,
280 bool IgnoreTopLevelName) {
281 // Check to see if the type is named.
282 DenseMap<const Type*, std::string> &TM = getTypeNamesMap(TypeNames);
283 if (!IgnoreTopLevelName) {
284 DenseMap<const Type*, std::string>::iterator I = TM.find(Ty);
291 // Otherwise we have a type that has not been named but is a derived type.
292 // Carefully recurse the type hierarchy to print out any contained symbolic
294 SmallVector<const Type *, 16> TypeStack;
295 std::string TypeName;
297 raw_string_ostream TypeOS(TypeName);
298 CalcTypeName(Ty, TypeStack, TypeOS, IgnoreTopLevelName);
301 // Cache type name for later use.
302 if (!IgnoreTopLevelName)
303 TM.insert(std::make_pair(Ty, TypeOS.str()));
308 // To avoid walking constant expressions multiple times and other IR
309 // objects, we keep several helper maps.
310 DenseSet<const Value*> VisitedConstants;
311 DenseSet<const Type*> VisitedTypes;
314 std::vector<const Type*> &NumberedTypes;
316 TypeFinder(TypePrinting &tp, std::vector<const Type*> &numberedTypes)
317 : TP(tp), NumberedTypes(numberedTypes) {}
319 void Run(const Module &M) {
320 // Get types from the type symbol table. This gets opaque types referened
321 // only through derived named types.
322 const TypeSymbolTable &ST = M.getTypeSymbolTable();
323 for (TypeSymbolTable::const_iterator TI = ST.begin(), E = ST.end();
325 IncorporateType(TI->second);
327 // Get types from global variables.
328 for (Module::const_global_iterator I = M.global_begin(),
329 E = M.global_end(); I != E; ++I) {
330 IncorporateType(I->getType());
331 if (I->hasInitializer())
332 IncorporateValue(I->getInitializer());
335 // Get types from aliases.
336 for (Module::const_alias_iterator I = M.alias_begin(),
337 E = M.alias_end(); I != E; ++I) {
338 IncorporateType(I->getType());
339 IncorporateValue(I->getAliasee());
342 // Get types from functions.
343 for (Module::const_iterator FI = M.begin(), E = M.end(); FI != E; ++FI) {
344 IncorporateType(FI->getType());
346 for (Function::const_iterator BB = FI->begin(), E = FI->end();
348 for (BasicBlock::const_iterator II = BB->begin(),
349 E = BB->end(); II != E; ++II) {
350 const Instruction &I = *II;
351 // Incorporate the type of the instruction and all its operands.
352 IncorporateType(I.getType());
353 for (User::const_op_iterator OI = I.op_begin(), OE = I.op_end();
355 IncorporateValue(*OI);
361 void IncorporateType(const Type *Ty) {
362 // Check to see if we're already visited this type.
363 if (!VisitedTypes.insert(Ty).second)
366 // If this is a structure or opaque type, add a name for the type.
367 if (((isa<StructType>(Ty) && cast<StructType>(Ty)->getNumElements())
368 || isa<OpaqueType>(Ty)) && !TP.hasTypeName(Ty)) {
369 TP.addTypeName(Ty, "%"+utostr(unsigned(NumberedTypes.size())));
370 NumberedTypes.push_back(Ty);
373 // Recursively walk all contained types.
374 for (Type::subtype_iterator I = Ty->subtype_begin(),
375 E = Ty->subtype_end(); I != E; ++I)
379 /// IncorporateValue - This method is used to walk operand lists finding
380 /// types hiding in constant expressions and other operands that won't be
381 /// walked in other ways. GlobalValues, basic blocks, instructions, and
382 /// inst operands are all explicitly enumerated.
383 void IncorporateValue(const Value *V) {
384 if (V == 0 || !isa<Constant>(V) || isa<GlobalValue>(V)) return;
387 if (!VisitedConstants.insert(V).second)
391 IncorporateType(V->getType());
393 // Look in operands for types.
394 const Constant *C = cast<Constant>(V);
395 for (Constant::const_op_iterator I = C->op_begin(),
396 E = C->op_end(); I != E;++I)
397 IncorporateValue(*I);
400 } // end anonymous namespace
403 /// AddModuleTypesToPrinter - Add all of the symbolic type names for types in
404 /// the specified module to the TypePrinter and all numbered types to it and the
405 /// NumberedTypes table.
406 static void AddModuleTypesToPrinter(TypePrinting &TP,
407 std::vector<const Type*> &NumberedTypes,
411 // If the module has a symbol table, take all global types and stuff their
412 // names into the TypeNames map.
413 const TypeSymbolTable &ST = M->getTypeSymbolTable();
414 for (TypeSymbolTable::const_iterator TI = ST.begin(), E = ST.end();
416 const Type *Ty = cast<Type>(TI->second);
418 // As a heuristic, don't insert pointer to primitive types, because
419 // they are used too often to have a single useful name.
420 if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
421 const Type *PETy = PTy->getElementType();
422 if ((PETy->isPrimitiveType() || PETy->isInteger()) &&
423 !isa<OpaqueType>(PETy))
427 // Likewise don't insert primitives either.
428 if (Ty->isInteger() || Ty->isPrimitiveType())
431 // Get the name as a string and insert it into TypeNames.
433 raw_string_ostream NameOS(NameStr);
434 PrintLLVMName(NameOS, TI->first.c_str(), TI->first.length(), LocalPrefix);
435 TP.addTypeName(Ty, NameOS.str());
438 // Walk the entire module to find references to unnamed structure and opaque
439 // types. This is required for correctness by opaque types (because multiple
440 // uses of an unnamed opaque type needs to be referred to by the same ID) and
441 // it shrinks complex recursive structure types substantially in some cases.
442 TypeFinder(TP, NumberedTypes).Run(*M);
446 /// WriteTypeSymbolic - This attempts to write the specified type as a symbolic
447 /// type, iff there is an entry in the modules symbol table for the specified
448 /// type or one of it's component types.
450 void llvm::WriteTypeSymbolic(raw_ostream &OS, const Type *Ty, const Module *M) {
451 TypePrinting Printer;
452 std::vector<const Type*> NumberedTypes;
453 AddModuleTypesToPrinter(Printer, NumberedTypes, M);
454 Printer.print(Ty, OS);
457 //===----------------------------------------------------------------------===//
458 // SlotTracker Class: Enumerate slot numbers for unnamed values
459 //===----------------------------------------------------------------------===//
463 /// This class provides computation of slot numbers for LLVM Assembly writing.
467 /// ValueMap - A mapping of Values to slot numbers
468 typedef DenseMap<const Value*, unsigned> ValueMap;
471 /// TheModule - The module for which we are holding slot numbers
472 const Module* TheModule;
474 /// TheFunction - The function for which we are holding slot numbers
475 const Function* TheFunction;
476 bool FunctionProcessed;
478 /// mMap - The TypePlanes map for the module level data
482 /// fMap - The TypePlanes map for the function level data
487 /// Construct from a module
488 explicit SlotTracker(const Module *M);
489 /// Construct from a function, starting out in incorp state.
490 explicit SlotTracker(const Function *F);
492 /// Return the slot number of the specified value in it's type
493 /// plane. If something is not in the SlotTracker, return -1.
494 int getLocalSlot(const Value *V);
495 int getGlobalSlot(const GlobalValue *V);
497 /// If you'd like to deal with a function instead of just a module, use
498 /// this method to get its data into the SlotTracker.
499 void incorporateFunction(const Function *F) {
501 FunctionProcessed = false;
504 /// After calling incorporateFunction, use this method to remove the
505 /// most recently incorporated function from the SlotTracker. This
506 /// will reset the state of the machine back to just the module contents.
507 void purgeFunction();
509 // Implementation Details
511 /// This function does the actual initialization.
512 inline void initialize();
514 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
515 void CreateModuleSlot(const GlobalValue *V);
517 /// CreateFunctionSlot - Insert the specified Value* into the slot table.
518 void CreateFunctionSlot(const Value *V);
520 /// Add all of the module level global variables (and their initializers)
521 /// and function declarations, but not the contents of those functions.
522 void processModule();
524 /// Add all of the functions arguments, basic blocks, and instructions
525 void processFunction();
527 SlotTracker(const SlotTracker &); // DO NOT IMPLEMENT
528 void operator=(const SlotTracker &); // DO NOT IMPLEMENT
531 } // end anonymous namespace
534 static SlotTracker *createSlotTracker(const Value *V) {
535 if (const Argument *FA = dyn_cast<Argument>(V))
536 return new SlotTracker(FA->getParent());
538 if (const Instruction *I = dyn_cast<Instruction>(V))
539 return new SlotTracker(I->getParent()->getParent());
541 if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
542 return new SlotTracker(BB->getParent());
544 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
545 return new SlotTracker(GV->getParent());
547 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
548 return new SlotTracker(GA->getParent());
550 if (const Function *Func = dyn_cast<Function>(V))
551 return new SlotTracker(Func);
557 #define ST_DEBUG(X) cerr << X
562 // Module level constructor. Causes the contents of the Module (sans functions)
563 // to be added to the slot table.
564 SlotTracker::SlotTracker(const Module *M)
565 : TheModule(M), TheFunction(0), FunctionProcessed(false), mNext(0), fNext(0) {
568 // Function level constructor. Causes the contents of the Module and the one
569 // function provided to be added to the slot table.
570 SlotTracker::SlotTracker(const Function *F)
571 : TheModule(F ? F->getParent() : 0), TheFunction(F), FunctionProcessed(false),
575 inline void SlotTracker::initialize() {
578 TheModule = 0; ///< Prevent re-processing next time we're called.
581 if (TheFunction && !FunctionProcessed)
585 // Iterate through all the global variables, functions, and global
586 // variable initializers and create slots for them.
587 void SlotTracker::processModule() {
588 ST_DEBUG("begin processModule!\n");
590 // Add all of the unnamed global variables to the value table.
591 for (Module::const_global_iterator I = TheModule->global_begin(),
592 E = TheModule->global_end(); I != E; ++I)
596 // Add all the unnamed functions to the table.
597 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
602 ST_DEBUG("end processModule!\n");
606 // Process the arguments, basic blocks, and instructions of a function.
607 void SlotTracker::processFunction() {
608 ST_DEBUG("begin processFunction!\n");
611 // Add all the function arguments with no names.
612 for(Function::const_arg_iterator AI = TheFunction->arg_begin(),
613 AE = TheFunction->arg_end(); AI != AE; ++AI)
615 CreateFunctionSlot(AI);
617 ST_DEBUG("Inserting Instructions:\n");
619 // Add all of the basic blocks and instructions with no names.
620 for (Function::const_iterator BB = TheFunction->begin(),
621 E = TheFunction->end(); BB != E; ++BB) {
623 CreateFunctionSlot(BB);
624 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
625 if (I->getType() != Type::VoidTy && !I->hasName())
626 CreateFunctionSlot(I);
629 FunctionProcessed = true;
631 ST_DEBUG("end processFunction!\n");
634 /// Clean up after incorporating a function. This is the only way to get out of
635 /// the function incorporation state that affects get*Slot/Create*Slot. Function
636 /// incorporation state is indicated by TheFunction != 0.
637 void SlotTracker::purgeFunction() {
638 ST_DEBUG("begin purgeFunction!\n");
639 fMap.clear(); // Simply discard the function level map
641 FunctionProcessed = false;
642 ST_DEBUG("end purgeFunction!\n");
645 /// getGlobalSlot - Get the slot number of a global value.
646 int SlotTracker::getGlobalSlot(const GlobalValue *V) {
647 // Check for uninitialized state and do lazy initialization.
650 // Find the type plane in the module map
651 ValueMap::iterator MI = mMap.find(V);
652 return MI == mMap.end() ? -1 : (int)MI->second;
656 /// getLocalSlot - Get the slot number for a value that is local to a function.
657 int SlotTracker::getLocalSlot(const Value *V) {
658 assert(!isa<Constant>(V) && "Can't get a constant or global slot with this!");
660 // Check for uninitialized state and do lazy initialization.
663 ValueMap::iterator FI = fMap.find(V);
664 return FI == fMap.end() ? -1 : (int)FI->second;
668 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
669 void SlotTracker::CreateModuleSlot(const GlobalValue *V) {
670 assert(V && "Can't insert a null Value into SlotTracker!");
671 assert(V->getType() != Type::VoidTy && "Doesn't need a slot!");
672 assert(!V->hasName() && "Doesn't need a slot!");
674 unsigned DestSlot = mNext++;
677 ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" <<
679 // G = Global, F = Function, A = Alias, o = other
680 ST_DEBUG((isa<GlobalVariable>(V) ? 'G' :
681 (isa<Function>(V) ? 'F' :
682 (isa<GlobalAlias>(V) ? 'A' : 'o'))) << "]\n");
686 /// CreateSlot - Create a new slot for the specified value if it has no name.
687 void SlotTracker::CreateFunctionSlot(const Value *V) {
688 assert(V->getType() != Type::VoidTy && !V->hasName() &&
689 "Doesn't need a slot!");
691 unsigned DestSlot = fNext++;
694 // G = Global, F = Function, o = other
695 ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" <<
696 DestSlot << " [o]\n");
701 //===----------------------------------------------------------------------===//
702 // AsmWriter Implementation
703 //===----------------------------------------------------------------------===//
705 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
706 TypePrinting &TypePrinter,
707 SlotTracker *Machine);
711 static const char *getPredicateText(unsigned predicate) {
712 const char * pred = "unknown";
714 case FCmpInst::FCMP_FALSE: pred = "false"; break;
715 case FCmpInst::FCMP_OEQ: pred = "oeq"; break;
716 case FCmpInst::FCMP_OGT: pred = "ogt"; break;
717 case FCmpInst::FCMP_OGE: pred = "oge"; break;
718 case FCmpInst::FCMP_OLT: pred = "olt"; break;
719 case FCmpInst::FCMP_OLE: pred = "ole"; break;
720 case FCmpInst::FCMP_ONE: pred = "one"; break;
721 case FCmpInst::FCMP_ORD: pred = "ord"; break;
722 case FCmpInst::FCMP_UNO: pred = "uno"; break;
723 case FCmpInst::FCMP_UEQ: pred = "ueq"; break;
724 case FCmpInst::FCMP_UGT: pred = "ugt"; break;
725 case FCmpInst::FCMP_UGE: pred = "uge"; break;
726 case FCmpInst::FCMP_ULT: pred = "ult"; break;
727 case FCmpInst::FCMP_ULE: pred = "ule"; break;
728 case FCmpInst::FCMP_UNE: pred = "une"; break;
729 case FCmpInst::FCMP_TRUE: pred = "true"; break;
730 case ICmpInst::ICMP_EQ: pred = "eq"; break;
731 case ICmpInst::ICMP_NE: pred = "ne"; break;
732 case ICmpInst::ICMP_SGT: pred = "sgt"; break;
733 case ICmpInst::ICMP_SGE: pred = "sge"; break;
734 case ICmpInst::ICMP_SLT: pred = "slt"; break;
735 case ICmpInst::ICMP_SLE: pred = "sle"; break;
736 case ICmpInst::ICMP_UGT: pred = "ugt"; break;
737 case ICmpInst::ICMP_UGE: pred = "uge"; break;
738 case ICmpInst::ICMP_ULT: pred = "ult"; break;
739 case ICmpInst::ICMP_ULE: pred = "ule"; break;
744 static void WriteConstantInt(raw_ostream &Out, const Constant *CV,
745 TypePrinting &TypePrinter, SlotTracker *Machine) {
746 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
747 if (CI->getType() == Type::Int1Ty) {
748 Out << (CI->getZExtValue() ? "true" : "false");
751 Out << CI->getValue();
755 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
756 if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEdouble ||
757 &CFP->getValueAPF().getSemantics() == &APFloat::IEEEsingle) {
758 // We would like to output the FP constant value in exponential notation,
759 // but we cannot do this if doing so will lose precision. Check here to
760 // make sure that we only output it in exponential format if we can parse
761 // the value back and get the same value.
764 bool isDouble = &CFP->getValueAPF().getSemantics()==&APFloat::IEEEdouble;
765 double Val = isDouble ? CFP->getValueAPF().convertToDouble() :
766 CFP->getValueAPF().convertToFloat();
767 std::string StrVal = ftostr(CFP->getValueAPF());
769 // Check to make sure that the stringized number is not some string like
770 // "Inf" or NaN, that atof will accept, but the lexer will not. Check
771 // that the string matches the "[-+]?[0-9]" regex.
773 if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
774 ((StrVal[0] == '-' || StrVal[0] == '+') &&
775 (StrVal[1] >= '0' && StrVal[1] <= '9'))) {
776 // Reparse stringized version!
777 if (atof(StrVal.c_str()) == Val) {
782 // Otherwise we could not reparse it to exactly the same value, so we must
783 // output the string in hexadecimal format! Note that loading and storing
784 // floating point types changes the bits of NaNs on some hosts, notably
785 // x86, so we must not use these types.
786 assert(sizeof(double) == sizeof(uint64_t) &&
787 "assuming that double is 64 bits!");
789 APFloat apf = CFP->getValueAPF();
790 // Floats are represented in ASCII IR as double, convert.
792 apf.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
795 utohex_buffer(uint64_t(apf.bitcastToAPInt().getZExtValue()),
800 // Some form of long double. These appear as a magic letter identifying
801 // the type, then a fixed number of hex digits.
803 if (&CFP->getValueAPF().getSemantics() == &APFloat::x87DoubleExtended) {
805 // api needed to prevent premature destruction
806 APInt api = CFP->getValueAPF().bitcastToAPInt();
807 const uint64_t* p = api.getRawData();
808 uint64_t word = p[1];
810 int width = api.getBitWidth();
811 for (int j=0; j<width; j+=4, shiftcount-=4) {
812 unsigned int nibble = (word>>shiftcount) & 15;
814 Out << (unsigned char)(nibble + '0');
816 Out << (unsigned char)(nibble - 10 + 'A');
817 if (shiftcount == 0 && j+4 < width) {
821 shiftcount = width-j-4;
825 } else if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEquad)
827 else if (&CFP->getValueAPF().getSemantics() == &APFloat::PPCDoubleDouble)
830 assert(0 && "Unsupported floating point type");
831 // api needed to prevent premature destruction
832 APInt api = CFP->getValueAPF().bitcastToAPInt();
833 const uint64_t* p = api.getRawData();
836 int width = api.getBitWidth();
837 for (int j=0; j<width; j+=4, shiftcount-=4) {
838 unsigned int nibble = (word>>shiftcount) & 15;
840 Out << (unsigned char)(nibble + '0');
842 Out << (unsigned char)(nibble - 10 + 'A');
843 if (shiftcount == 0 && j+4 < width) {
847 shiftcount = width-j-4;
853 if (isa<ConstantAggregateZero>(CV)) {
854 Out << "zeroinitializer";
858 if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
859 // As a special case, print the array as a string if it is an array of
860 // i8 with ConstantInt values.
862 const Type *ETy = CA->getType()->getElementType();
863 if (CA->isString()) {
865 PrintEscapedString(CA->getAsString(), Out);
867 } else { // Cannot output in string format...
869 if (CA->getNumOperands()) {
870 TypePrinter.print(ETy, Out);
872 WriteAsOperandInternal(Out, CA->getOperand(0),
873 TypePrinter, Machine);
874 for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
876 TypePrinter.print(ETy, Out);
878 WriteAsOperandInternal(Out, CA->getOperand(i), TypePrinter, Machine);
886 if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
887 if (CS->getType()->isPacked())
890 unsigned N = CS->getNumOperands();
893 TypePrinter.print(CS->getOperand(0)->getType(), Out);
896 WriteAsOperandInternal(Out, CS->getOperand(0), TypePrinter, Machine);
898 for (unsigned i = 1; i < N; i++) {
900 TypePrinter.print(CS->getOperand(i)->getType(), Out);
903 WriteAsOperandInternal(Out, CS->getOperand(i), TypePrinter, Machine);
909 if (CS->getType()->isPacked())
914 if (const ConstantVector *CP = dyn_cast<ConstantVector>(CV)) {
915 const Type *ETy = CP->getType()->getElementType();
916 assert(CP->getNumOperands() > 0 &&
917 "Number of operands for a PackedConst must be > 0");
919 TypePrinter.print(ETy, Out);
921 WriteAsOperandInternal(Out, CP->getOperand(0), TypePrinter, Machine);
922 for (unsigned i = 1, e = CP->getNumOperands(); i != e; ++i) {
924 TypePrinter.print(ETy, Out);
926 WriteAsOperandInternal(Out, CP->getOperand(i), TypePrinter, Machine);
932 if (isa<ConstantPointerNull>(CV)) {
937 if (isa<UndefValue>(CV)) {
942 if (const MDString *S = dyn_cast<MDString>(CV)) {
944 PrintEscapedString(S->begin(), S->size(), Out);
949 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
950 Out << CE->getOpcodeName();
952 Out << ' ' << getPredicateText(CE->getPredicate());
955 for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) {
956 TypePrinter.print((*OI)->getType(), Out);
958 WriteAsOperandInternal(Out, *OI, TypePrinter, Machine);
959 if (OI+1 != CE->op_end())
963 if (CE->hasIndices()) {
964 const SmallVector<unsigned, 4> &Indices = CE->getIndices();
965 for (unsigned i = 0, e = Indices.size(); i != e; ++i)
966 Out << ", " << Indices[i];
971 TypePrinter.print(CE->getType(), Out);
978 Out << "<placeholder or erroneous Constant>";
982 /// WriteAsOperand - Write the name of the specified value out to the specified
983 /// ostream. This can be useful when you just want to print int %reg126, not
984 /// the whole instruction that generated it.
986 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
987 TypePrinting &TypePrinter,
988 SlotTracker *Machine) {
990 PrintLLVMName(Out, V);
994 const Constant *CV = dyn_cast<Constant>(V);
995 if (CV && !isa<GlobalValue>(CV)) {
996 WriteConstantInt(Out, CV, TypePrinter, Machine);
1000 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
1002 if (IA->hasSideEffects())
1003 Out << "sideeffect ";
1005 PrintEscapedString(IA->getAsmString(), Out);
1007 PrintEscapedString(IA->getConstraintString(), Out);
1015 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
1016 Slot = Machine->getGlobalSlot(GV);
1019 Slot = Machine->getLocalSlot(V);
1022 Machine = createSlotTracker(V);
1024 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
1025 Slot = Machine->getGlobalSlot(GV);
1028 Slot = Machine->getLocalSlot(V);
1037 Out << Prefix << Slot;
1042 /// WriteAsOperand - Write the name of the specified value out to the specified
1043 /// ostream. This can be useful when you just want to print int %reg126, not
1044 /// the whole instruction that generated it.
1046 void llvm::WriteAsOperand(std::ostream &Out, const Value *V, bool PrintType,
1047 const Module *Context) {
1048 raw_os_ostream OS(Out);
1049 WriteAsOperand(OS, V, PrintType, Context);
1052 void llvm::WriteAsOperand(raw_ostream &Out, const Value *V, bool PrintType,
1053 const Module *Context) {
1054 if (Context == 0) Context = getModuleFromVal(V);
1056 TypePrinting TypePrinter;
1057 std::vector<const Type*> NumberedTypes;
1058 AddModuleTypesToPrinter(TypePrinter, NumberedTypes, Context);
1060 TypePrinter.print(V->getType(), Out);
1064 WriteAsOperandInternal(Out, V, TypePrinter, 0);
1070 class AssemblyWriter {
1072 SlotTracker &Machine;
1073 const Module *TheModule;
1074 TypePrinting TypePrinter;
1075 AssemblyAnnotationWriter *AnnotationWriter;
1076 std::vector<const Type*> NumberedTypes;
1078 // Each MDNode is assigned unique MetadataIDNo.
1079 std::map<const MDNode *, unsigned> MDNodes;
1080 unsigned MetadataIDNo;
1082 inline AssemblyWriter(raw_ostream &o, SlotTracker &Mac, const Module *M,
1083 AssemblyAnnotationWriter *AAW)
1084 : Out(o), Machine(Mac), TheModule(M), AnnotationWriter(AAW), MetadataIDNo(0) {
1085 AddModuleTypesToPrinter(TypePrinter, NumberedTypes, M);
1088 void write(const Module *M) { printModule(M); }
1090 void write(const GlobalValue *G) {
1091 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(G))
1093 else if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(G))
1095 else if (const Function *F = dyn_cast<Function>(G))
1098 assert(0 && "Unknown global");
1101 void write(const BasicBlock *BB) { printBasicBlock(BB); }
1102 void write(const Instruction *I) { printInstruction(*I); }
1104 void writeOperand(const Value *Op, bool PrintType);
1105 void writeParamOperand(const Value *Operand, Attributes Attrs);
1107 const Module* getModule() { return TheModule; }
1110 void printModule(const Module *M);
1111 void printTypeSymbolTable(const TypeSymbolTable &ST);
1112 void printGlobal(const GlobalVariable *GV);
1113 void printMDNode(const MDNode *Node, bool StandAlone);
1114 void printAlias(const GlobalAlias *GV);
1115 void printFunction(const Function *F);
1116 void printArgument(const Argument *FA, Attributes Attrs);
1117 void printBasicBlock(const BasicBlock *BB);
1118 void printInstruction(const Instruction &I);
1120 // printInfoComment - Print a little comment after the instruction indicating
1121 // which slot it occupies.
1122 void printInfoComment(const Value &V);
1124 } // end of anonymous namespace
1127 void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType) {
1129 Out << "<null operand!>";
1132 TypePrinter.print(Operand->getType(), Out);
1135 WriteAsOperandInternal(Out, Operand, TypePrinter, &Machine);
1139 void AssemblyWriter::writeParamOperand(const Value *Operand,
1142 Out << "<null operand!>";
1145 TypePrinter.print(Operand->getType(), Out);
1146 // Print parameter attributes list
1147 if (Attrs != Attribute::None)
1148 Out << ' ' << Attribute::getAsString(Attrs);
1150 // Print the operand
1151 WriteAsOperandInternal(Out, Operand, TypePrinter, &Machine);
1155 void AssemblyWriter::printModule(const Module *M) {
1156 if (!M->getModuleIdentifier().empty() &&
1157 // Don't print the ID if it will start a new line (which would
1158 // require a comment char before it).
1159 M->getModuleIdentifier().find('\n') == std::string::npos)
1160 Out << "; ModuleID = '" << M->getModuleIdentifier() << "'\n";
1162 if (!M->getDataLayout().empty())
1163 Out << "target datalayout = \"" << M->getDataLayout() << "\"\n";
1164 if (!M->getTargetTriple().empty())
1165 Out << "target triple = \"" << M->getTargetTriple() << "\"\n";
1167 if (!M->getModuleInlineAsm().empty()) {
1168 // Split the string into lines, to make it easier to read the .ll file.
1169 std::string Asm = M->getModuleInlineAsm();
1171 size_t NewLine = Asm.find_first_of('\n', CurPos);
1172 while (NewLine != std::string::npos) {
1173 // We found a newline, print the portion of the asm string from the
1174 // last newline up to this newline.
1175 Out << "module asm \"";
1176 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.begin()+NewLine),
1180 NewLine = Asm.find_first_of('\n', CurPos);
1182 Out << "module asm \"";
1183 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.end()), Out);
1187 // Loop over the dependent libraries and emit them.
1188 Module::lib_iterator LI = M->lib_begin();
1189 Module::lib_iterator LE = M->lib_end();
1191 Out << "deplibs = [ ";
1193 Out << '"' << *LI << '"';
1201 // Loop over the symbol table, emitting all id'd types.
1202 printTypeSymbolTable(M->getTypeSymbolTable());
1204 for (Module::const_global_iterator I = M->global_begin(), E = M->global_end();
1208 // Output all aliases.
1209 if (!M->alias_empty()) Out << "\n";
1210 for (Module::const_alias_iterator I = M->alias_begin(), E = M->alias_end();
1214 // Output all of the functions.
1215 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
1219 static void PrintLinkage(GlobalValue::LinkageTypes LT, raw_ostream &Out) {
1221 case GlobalValue::PrivateLinkage: Out << "private "; break;
1222 case GlobalValue::InternalLinkage: Out << "internal "; break;
1223 case GlobalValue::AvailableExternallyLinkage:
1224 Out << "available_externally ";
1226 case GlobalValue::LinkOnceAnyLinkage: Out << "linkonce "; break;
1227 case GlobalValue::LinkOnceODRLinkage: Out << "linkonce_odr "; break;
1228 case GlobalValue::WeakAnyLinkage: Out << "weak "; break;
1229 case GlobalValue::WeakODRLinkage: Out << "weak_odr "; break;
1230 case GlobalValue::CommonLinkage: Out << "common "; break;
1231 case GlobalValue::AppendingLinkage: Out << "appending "; break;
1232 case GlobalValue::DLLImportLinkage: Out << "dllimport "; break;
1233 case GlobalValue::DLLExportLinkage: Out << "dllexport "; break;
1234 case GlobalValue::ExternalWeakLinkage: Out << "extern_weak "; break;
1235 case GlobalValue::ExternalLinkage: break;
1236 case GlobalValue::GhostLinkage:
1237 Out << "GhostLinkage not allowed in AsmWriter!\n";
1243 static void PrintVisibility(GlobalValue::VisibilityTypes Vis,
1246 default: assert(0 && "Invalid visibility style!");
1247 case GlobalValue::DefaultVisibility: break;
1248 case GlobalValue::HiddenVisibility: Out << "hidden "; break;
1249 case GlobalValue::ProtectedVisibility: Out << "protected "; break;
1253 void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
1254 if (GV->hasInitializer())
1255 // If GV is initialized using Metadata then separate out metadata
1256 // operands used by the initializer. Note, MDNodes are not cyclic.
1257 if (MDNode *N = dyn_cast<MDNode>(GV->getInitializer())) {
1258 SmallVector<const MDNode *, 4> WorkList;
1259 // Collect MDNodes used by the initializer.
1260 for (MDNode::const_elem_iterator I = N->elem_begin(), E = N->elem_end();
1262 const Value *TV = *I;
1264 if (const MDNode *NN = dyn_cast<MDNode>(TV))
1265 WorkList.push_back(NN);
1268 // Print MDNodes used by the initializer.
1269 while (!WorkList.empty()) {
1270 const MDNode *N = WorkList.back(); WorkList.pop_back();
1271 printMDNode(N, true);
1276 if (GV->hasName()) {
1277 PrintLLVMName(Out, GV);
1281 if (!GV->hasInitializer() && GV->hasExternalLinkage())
1284 PrintLinkage(GV->getLinkage(), Out);
1285 PrintVisibility(GV->getVisibility(), Out);
1287 if (GV->isThreadLocal()) Out << "thread_local ";
1288 if (unsigned AddressSpace = GV->getType()->getAddressSpace())
1289 Out << "addrspace(" << AddressSpace << ") ";
1290 Out << (GV->isConstant() ? "constant " : "global ");
1291 TypePrinter.print(GV->getType()->getElementType(), Out);
1293 if (GV->hasInitializer()) {
1295 if (MDNode *N = dyn_cast<MDNode>(GV->getInitializer()))
1296 printMDNode(N, false);
1298 writeOperand(GV->getInitializer(), false);
1301 if (GV->hasSection())
1302 Out << ", section \"" << GV->getSection() << '"';
1303 if (GV->getAlignment())
1304 Out << ", align " << GV->getAlignment();
1306 printInfoComment(*GV);
1310 void AssemblyWriter::printMDNode(const MDNode *Node,
1312 std::map<const MDNode *, unsigned>::iterator MI = MDNodes.find(Node);
1313 // If this node is already printed then just refer it using its Metadata
1315 if (MI != MDNodes.end()) {
1316 Out << "metadata !" << MI->second;
1321 // Print standalone MDNode.
1323 Out << "!" << MetadataIDNo << " = ";
1324 Out << "constant metadata ";
1327 for (MDNode::const_elem_iterator I = Node->elem_begin(), E = Node->elem_end();
1329 const Value *TV = *I;
1332 else if (const MDNode *N = dyn_cast<MDNode>(TV))
1333 printMDNode(N, StandAlone);
1337 writeOperand(*I, true);
1343 MDNodes[Node] = MetadataIDNo++;
1346 void AssemblyWriter::printAlias(const GlobalAlias *GA) {
1347 // Don't crash when dumping partially built GA
1349 Out << "<<nameless>> = ";
1351 PrintLLVMName(Out, GA);
1354 PrintVisibility(GA->getVisibility(), Out);
1358 PrintLinkage(GA->getLinkage(), Out);
1360 const Constant *Aliasee = GA->getAliasee();
1362 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Aliasee)) {
1363 TypePrinter.print(GV->getType(), Out);
1365 PrintLLVMName(Out, GV);
1366 } else if (const Function *F = dyn_cast<Function>(Aliasee)) {
1367 TypePrinter.print(F->getFunctionType(), Out);
1370 WriteAsOperandInternal(Out, F, TypePrinter, &Machine);
1371 } else if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(Aliasee)) {
1372 TypePrinter.print(GA->getType(), Out);
1374 PrintLLVMName(Out, GA);
1376 const ConstantExpr *CE = cast<ConstantExpr>(Aliasee);
1377 // The only valid GEP is an all zero GEP.
1378 assert((CE->getOpcode() == Instruction::BitCast ||
1379 CE->getOpcode() == Instruction::GetElementPtr) &&
1380 "Unsupported aliasee");
1381 writeOperand(CE, false);
1384 printInfoComment(*GA);
1388 void AssemblyWriter::printTypeSymbolTable(const TypeSymbolTable &ST) {
1389 // Emit all numbered types.
1390 for (unsigned i = 0, e = NumberedTypes.size(); i != e; ++i) {
1393 // Make sure we print out at least one level of the type structure, so
1394 // that we do not get %2 = type %2
1395 TypePrinter.printAtLeastOneLevel(NumberedTypes[i], Out);
1396 Out << "\t\t; type %" << i << '\n';
1399 // Print the named types.
1400 for (TypeSymbolTable::const_iterator TI = ST.begin(), TE = ST.end();
1403 PrintLLVMName(Out, &TI->first[0], TI->first.size(), LocalPrefix);
1406 // Make sure we print out at least one level of the type structure, so
1407 // that we do not get %FILE = type %FILE
1408 TypePrinter.printAtLeastOneLevel(TI->second, Out);
1413 /// printFunction - Print all aspects of a function.
1415 void AssemblyWriter::printFunction(const Function *F) {
1416 // Print out the return type and name.
1419 if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, Out);
1421 if (F->isDeclaration())
1426 PrintLinkage(F->getLinkage(), Out);
1427 PrintVisibility(F->getVisibility(), Out);
1429 // Print the calling convention.
1430 switch (F->getCallingConv()) {
1431 case CallingConv::C: break; // default
1432 case CallingConv::Fast: Out << "fastcc "; break;
1433 case CallingConv::Cold: Out << "coldcc "; break;
1434 case CallingConv::X86_StdCall: Out << "x86_stdcallcc "; break;
1435 case CallingConv::X86_FastCall: Out << "x86_fastcallcc "; break;
1436 case CallingConv::ARM_APCS: Out << "arm_apcscc "; break;
1437 case CallingConv::ARM_AAPCS: Out << "arm_aapcscc "; break;
1438 case CallingConv::ARM_AAPCS_VFP:Out << "arm_aapcs_vfpcc "; break;
1439 default: Out << "cc" << F->getCallingConv() << " "; break;
1442 const FunctionType *FT = F->getFunctionType();
1443 const AttrListPtr &Attrs = F->getAttributes();
1444 Attributes RetAttrs = Attrs.getRetAttributes();
1445 if (RetAttrs != Attribute::None)
1446 Out << Attribute::getAsString(Attrs.getRetAttributes()) << ' ';
1447 TypePrinter.print(F->getReturnType(), Out);
1449 WriteAsOperandInternal(Out, F, TypePrinter, &Machine);
1451 Machine.incorporateFunction(F);
1453 // Loop over the arguments, printing them...
1456 if (!F->isDeclaration()) {
1457 // If this isn't a declaration, print the argument names as well.
1458 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
1460 // Insert commas as we go... the first arg doesn't get a comma
1461 if (I != F->arg_begin()) Out << ", ";
1462 printArgument(I, Attrs.getParamAttributes(Idx));
1466 // Otherwise, print the types from the function type.
1467 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
1468 // Insert commas as we go... the first arg doesn't get a comma
1472 TypePrinter.print(FT->getParamType(i), Out);
1474 Attributes ArgAttrs = Attrs.getParamAttributes(i+1);
1475 if (ArgAttrs != Attribute::None)
1476 Out << ' ' << Attribute::getAsString(ArgAttrs);
1480 // Finish printing arguments...
1481 if (FT->isVarArg()) {
1482 if (FT->getNumParams()) Out << ", ";
1483 Out << "..."; // Output varargs portion of signature!
1486 Attributes FnAttrs = Attrs.getFnAttributes();
1487 if (FnAttrs != Attribute::None)
1488 Out << ' ' << Attribute::getAsString(Attrs.getFnAttributes());
1489 if (F->hasSection())
1490 Out << " section \"" << F->getSection() << '"';
1491 if (F->getAlignment())
1492 Out << " align " << F->getAlignment();
1494 Out << " gc \"" << F->getGC() << '"';
1495 if (F->isDeclaration()) {
1500 // Output all of its basic blocks... for the function
1501 for (Function::const_iterator I = F->begin(), E = F->end(); I != E; ++I)
1507 Machine.purgeFunction();
1510 /// printArgument - This member is called for every argument that is passed into
1511 /// the function. Simply print it out
1513 void AssemblyWriter::printArgument(const Argument *Arg,
1516 TypePrinter.print(Arg->getType(), Out);
1518 // Output parameter attributes list
1519 if (Attrs != Attribute::None)
1520 Out << ' ' << Attribute::getAsString(Attrs);
1522 // Output name, if available...
1523 if (Arg->hasName()) {
1525 PrintLLVMName(Out, Arg);
1529 /// printBasicBlock - This member is called for each basic block in a method.
1531 void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {
1532 if (BB->hasName()) { // Print out the label if it exists...
1534 PrintLLVMName(Out, BB->getNameStart(), BB->getNameLen(), LabelPrefix);
1536 } else if (!BB->use_empty()) { // Don't print block # of no uses...
1537 Out << "\n; <label>:";
1538 int Slot = Machine.getLocalSlot(BB);
1545 if (BB->getParent() == 0)
1546 Out << "\t\t; Error: Block without parent!";
1547 else if (BB != &BB->getParent()->getEntryBlock()) { // Not the entry block?
1548 // Output predecessors for the block...
1550 pred_const_iterator PI = pred_begin(BB), PE = pred_end(BB);
1553 Out << " No predecessors!";
1556 writeOperand(*PI, false);
1557 for (++PI; PI != PE; ++PI) {
1559 writeOperand(*PI, false);
1566 if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(BB, Out);
1568 // Output all of the instructions in the basic block...
1569 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
1570 printInstruction(*I);
1572 if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(BB, Out);
1576 /// printInfoComment - Print a little comment after the instruction indicating
1577 /// which slot it occupies.
1579 void AssemblyWriter::printInfoComment(const Value &V) {
1580 if (V.getType() != Type::VoidTy) {
1582 TypePrinter.print(V.getType(), Out);
1585 if (!V.hasName() && !isa<Instruction>(V)) {
1587 if (const GlobalValue *GV = dyn_cast<GlobalValue>(&V))
1588 SlotNum = Machine.getGlobalSlot(GV);
1590 SlotNum = Machine.getLocalSlot(&V);
1594 Out << ':' << SlotNum; // Print out the def slot taken.
1596 Out << " [#uses=" << V.getNumUses() << ']'; // Output # uses
1600 // This member is called for each Instruction in a function..
1601 void AssemblyWriter::printInstruction(const Instruction &I) {
1602 if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, Out);
1606 // Print out name if it exists...
1608 PrintLLVMName(Out, &I);
1610 } else if (I.getType() != Type::VoidTy) {
1611 // Print out the def slot taken.
1612 int SlotNum = Machine.getLocalSlot(&I);
1614 Out << "<badref> = ";
1616 Out << '%' << SlotNum << " = ";
1619 // If this is a volatile load or store, print out the volatile marker.
1620 if ((isa<LoadInst>(I) && cast<LoadInst>(I).isVolatile()) ||
1621 (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile())) {
1623 } else if (isa<CallInst>(I) && cast<CallInst>(I).isTailCall()) {
1624 // If this is a call, check if it's a tail call.
1628 // Print out the opcode...
1629 Out << I.getOpcodeName();
1631 // Print out the compare instruction predicates
1632 if (const CmpInst *CI = dyn_cast<CmpInst>(&I))
1633 Out << ' ' << getPredicateText(CI->getPredicate());
1635 // Print out the type of the operands...
1636 const Value *Operand = I.getNumOperands() ? I.getOperand(0) : 0;
1638 // Special case conditional branches to swizzle the condition out to the front
1639 if (isa<BranchInst>(I) && cast<BranchInst>(I).isConditional()) {
1640 BranchInst &BI(cast<BranchInst>(I));
1642 writeOperand(BI.getCondition(), true);
1644 writeOperand(BI.getSuccessor(0), true);
1646 writeOperand(BI.getSuccessor(1), true);
1648 } else if (isa<SwitchInst>(I)) {
1649 // Special case switch statement to get formatting nice and correct...
1651 writeOperand(Operand , true);
1653 writeOperand(I.getOperand(1), true);
1656 for (unsigned op = 2, Eop = I.getNumOperands(); op < Eop; op += 2) {
1658 writeOperand(I.getOperand(op ), true);
1660 writeOperand(I.getOperand(op+1), true);
1663 } else if (isa<PHINode>(I)) {
1665 TypePrinter.print(I.getType(), Out);
1668 for (unsigned op = 0, Eop = I.getNumOperands(); op < Eop; op += 2) {
1669 if (op) Out << ", ";
1671 writeOperand(I.getOperand(op ), false); Out << ", ";
1672 writeOperand(I.getOperand(op+1), false); Out << " ]";
1674 } else if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&I)) {
1676 writeOperand(I.getOperand(0), true);
1677 for (const unsigned *i = EVI->idx_begin(), *e = EVI->idx_end(); i != e; ++i)
1679 } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&I)) {
1681 writeOperand(I.getOperand(0), true); Out << ", ";
1682 writeOperand(I.getOperand(1), true);
1683 for (const unsigned *i = IVI->idx_begin(), *e = IVI->idx_end(); i != e; ++i)
1685 } else if (isa<ReturnInst>(I) && !Operand) {
1687 } else if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
1688 // Print the calling convention being used.
1689 switch (CI->getCallingConv()) {
1690 case CallingConv::C: break; // default
1691 case CallingConv::Fast: Out << " fastcc"; break;
1692 case CallingConv::Cold: Out << " coldcc"; break;
1693 case CallingConv::X86_StdCall: Out << " x86_stdcallcc"; break;
1694 case CallingConv::X86_FastCall: Out << " x86_fastcallcc"; break;
1695 case CallingConv::ARM_APCS: Out << " arm_apcscc "; break;
1696 case CallingConv::ARM_AAPCS: Out << " arm_aapcscc "; break;
1697 case CallingConv::ARM_AAPCS_VFP:Out << " arm_aapcs_vfpcc "; break;
1698 default: Out << " cc" << CI->getCallingConv(); break;
1701 const PointerType *PTy = cast<PointerType>(Operand->getType());
1702 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1703 const Type *RetTy = FTy->getReturnType();
1704 const AttrListPtr &PAL = CI->getAttributes();
1706 if (PAL.getRetAttributes() != Attribute::None)
1707 Out << ' ' << Attribute::getAsString(PAL.getRetAttributes());
1709 // If possible, print out the short form of the call instruction. We can
1710 // only do this if the first argument is a pointer to a nonvararg function,
1711 // and if the return type is not a pointer to a function.
1714 if (!FTy->isVarArg() &&
1715 (!isa<PointerType>(RetTy) ||
1716 !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
1717 TypePrinter.print(RetTy, Out);
1719 writeOperand(Operand, false);
1721 writeOperand(Operand, true);
1724 for (unsigned op = 1, Eop = I.getNumOperands(); op < Eop; ++op) {
1727 writeParamOperand(I.getOperand(op), PAL.getParamAttributes(op));
1730 if (PAL.getFnAttributes() != Attribute::None)
1731 Out << ' ' << Attribute::getAsString(PAL.getFnAttributes());
1732 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
1733 const PointerType *PTy = cast<PointerType>(Operand->getType());
1734 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1735 const Type *RetTy = FTy->getReturnType();
1736 const AttrListPtr &PAL = II->getAttributes();
1738 // Print the calling convention being used.
1739 switch (II->getCallingConv()) {
1740 case CallingConv::C: break; // default
1741 case CallingConv::Fast: Out << " fastcc"; break;
1742 case CallingConv::Cold: Out << " coldcc"; break;
1743 case CallingConv::X86_StdCall: Out << " x86_stdcallcc"; break;
1744 case CallingConv::X86_FastCall: Out << " x86_fastcallcc"; break;
1745 case CallingConv::ARM_APCS: Out << " arm_apcscc "; break;
1746 case CallingConv::ARM_AAPCS: Out << " arm_aapcscc "; break;
1747 case CallingConv::ARM_AAPCS_VFP:Out << " arm_aapcs_vfpcc "; break;
1748 default: Out << " cc" << II->getCallingConv(); break;
1751 if (PAL.getRetAttributes() != Attribute::None)
1752 Out << ' ' << Attribute::getAsString(PAL.getRetAttributes());
1754 // If possible, print out the short form of the invoke instruction. We can
1755 // only do this if the first argument is a pointer to a nonvararg function,
1756 // and if the return type is not a pointer to a function.
1759 if (!FTy->isVarArg() &&
1760 (!isa<PointerType>(RetTy) ||
1761 !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
1762 TypePrinter.print(RetTy, Out);
1764 writeOperand(Operand, false);
1766 writeOperand(Operand, true);
1769 for (unsigned op = 3, Eop = I.getNumOperands(); op < Eop; ++op) {
1772 writeParamOperand(I.getOperand(op), PAL.getParamAttributes(op-2));
1776 if (PAL.getFnAttributes() != Attribute::None)
1777 Out << ' ' << Attribute::getAsString(PAL.getFnAttributes());
1779 Out << "\n\t\t\tto ";
1780 writeOperand(II->getNormalDest(), true);
1782 writeOperand(II->getUnwindDest(), true);
1784 } else if (const AllocationInst *AI = dyn_cast<AllocationInst>(&I)) {
1786 TypePrinter.print(AI->getType()->getElementType(), Out);
1787 if (AI->isArrayAllocation()) {
1789 writeOperand(AI->getArraySize(), true);
1791 if (AI->getAlignment()) {
1792 Out << ", align " << AI->getAlignment();
1794 } else if (isa<CastInst>(I)) {
1797 writeOperand(Operand, true); // Work with broken code
1800 TypePrinter.print(I.getType(), Out);
1801 } else if (isa<VAArgInst>(I)) {
1804 writeOperand(Operand, true); // Work with broken code
1807 TypePrinter.print(I.getType(), Out);
1808 } else if (Operand) { // Print the normal way.
1810 // PrintAllTypes - Instructions who have operands of all the same type
1811 // omit the type from all but the first operand. If the instruction has
1812 // different type operands (for example br), then they are all printed.
1813 bool PrintAllTypes = false;
1814 const Type *TheType = Operand->getType();
1816 // Select, Store and ShuffleVector always print all types.
1817 if (isa<SelectInst>(I) || isa<StoreInst>(I) || isa<ShuffleVectorInst>(I)
1818 || isa<ReturnInst>(I)) {
1819 PrintAllTypes = true;
1821 for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) {
1822 Operand = I.getOperand(i);
1823 // note that Operand shouldn't be null, but the test helps make dump()
1824 // more tolerant of malformed IR
1825 if (Operand && Operand->getType() != TheType) {
1826 PrintAllTypes = true; // We have differing types! Print them all!
1832 if (!PrintAllTypes) {
1834 TypePrinter.print(TheType, Out);
1838 for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) {
1840 writeOperand(I.getOperand(i), PrintAllTypes);
1844 // Print post operand alignment for load/store
1845 if (isa<LoadInst>(I) && cast<LoadInst>(I).getAlignment()) {
1846 Out << ", align " << cast<LoadInst>(I).getAlignment();
1847 } else if (isa<StoreInst>(I) && cast<StoreInst>(I).getAlignment()) {
1848 Out << ", align " << cast<StoreInst>(I).getAlignment();
1851 printInfoComment(I);
1856 //===----------------------------------------------------------------------===//
1857 // External Interface declarations
1858 //===----------------------------------------------------------------------===//
1860 void Module::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1861 raw_os_ostream OS(o);
1864 void Module::print(raw_ostream &OS, AssemblyAnnotationWriter *AAW) const {
1865 SlotTracker SlotTable(this);
1866 AssemblyWriter W(OS, SlotTable, this, AAW);
1870 void Type::print(std::ostream &o) const {
1871 raw_os_ostream OS(o);
1875 void Type::print(raw_ostream &OS) const {
1877 OS << "<null Type>";
1880 TypePrinting().print(this, OS);
1883 void Value::print(raw_ostream &OS, AssemblyAnnotationWriter *AAW) const {
1885 OS << "printing a <null> value\n";
1889 if (const Instruction *I = dyn_cast<Instruction>(this)) {
1890 const Function *F = I->getParent() ? I->getParent()->getParent() : 0;
1891 SlotTracker SlotTable(F);
1892 AssemblyWriter W(OS, SlotTable, F ? F->getParent() : 0, AAW);
1894 } else if (const BasicBlock *BB = dyn_cast<BasicBlock>(this)) {
1895 SlotTracker SlotTable(BB->getParent());
1896 AssemblyWriter W(OS, SlotTable,
1897 BB->getParent() ? BB->getParent()->getParent() : 0, AAW);
1899 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(this)) {
1900 SlotTracker SlotTable(GV->getParent());
1901 AssemblyWriter W(OS, SlotTable, GV->getParent(), AAW);
1903 } else if (const Constant *C = dyn_cast<Constant>(this)) {
1904 TypePrinting TypePrinter;
1905 TypePrinter.print(C->getType(), OS);
1907 WriteConstantInt(OS, C, TypePrinter, 0);
1908 } else if (const Argument *A = dyn_cast<Argument>(this)) {
1909 WriteAsOperand(OS, this, true,
1910 A->getParent() ? A->getParent()->getParent() : 0);
1911 } else if (isa<InlineAsm>(this)) {
1912 WriteAsOperand(OS, this, true, 0);
1914 assert(0 && "Unknown value to print out!");
1918 void Value::print(std::ostream &O, AssemblyAnnotationWriter *AAW) const {
1919 raw_os_ostream OS(O);
1923 // Value::dump - allow easy printing of Values from the debugger.
1924 void Value::dump() const { print(errs()); errs() << '\n'; }
1926 // Type::dump - allow easy printing of Types from the debugger.
1927 // This one uses type names from the given context module
1928 void Type::dump(const Module *Context) const {
1929 WriteTypeSymbolic(errs(), this, Context);
1933 // Type::dump - allow easy printing of Types from the debugger.
1934 void Type::dump() const { dump(0); }
1936 // Module::dump() - Allow printing of Modules from the debugger.
1937 void Module::dump() const { print(errs(), 0); }