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/AssemblyAnnotationWriter.h"
20 #include "llvm/LLVMContext.h"
21 #include "llvm/CallingConv.h"
22 #include "llvm/Constants.h"
23 #include "llvm/DerivedTypes.h"
24 #include "llvm/InlineAsm.h"
25 #include "llvm/IntrinsicInst.h"
26 #include "llvm/Operator.h"
27 #include "llvm/Module.h"
28 #include "llvm/ValueSymbolTable.h"
29 #include "llvm/ADT/DenseMap.h"
30 #include "llvm/ADT/SmallString.h"
31 #include "llvm/ADT/StringExtras.h"
32 #include "llvm/ADT/STLExtras.h"
33 #include "llvm/Support/CFG.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/Dwarf.h"
36 #include "llvm/Support/ErrorHandling.h"
37 #include "llvm/Support/MathExtras.h"
38 #include "llvm/Support/FormattedStream.h"
43 // Make virtual table appear in this compilation unit.
44 AssemblyAnnotationWriter::~AssemblyAnnotationWriter() {}
46 //===----------------------------------------------------------------------===//
48 //===----------------------------------------------------------------------===//
50 static const Module *getModuleFromVal(const Value *V) {
51 if (const Argument *MA = dyn_cast<Argument>(V))
52 return MA->getParent() ? MA->getParent()->getParent() : 0;
54 if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
55 return BB->getParent() ? BB->getParent()->getParent() : 0;
57 if (const Instruction *I = dyn_cast<Instruction>(V)) {
58 const Function *M = I->getParent() ? I->getParent()->getParent() : 0;
59 return M ? M->getParent() : 0;
62 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
63 return GV->getParent();
67 // PrintEscapedString - Print each character of the specified string, escaping
68 // it if it is not printable or if it is an escape char.
69 static void PrintEscapedString(StringRef Name, raw_ostream &Out) {
70 for (unsigned i = 0, e = Name.size(); i != e; ++i) {
71 unsigned char C = Name[i];
72 if (isprint(C) && C != '\\' && C != '"')
75 Out << '\\' << hexdigit(C >> 4) << hexdigit(C & 0x0F);
86 /// PrintLLVMName - Turn the specified name into an 'LLVM name', which is either
87 /// prefixed with % (if the string only contains simple characters) or is
88 /// surrounded with ""'s (if it has special chars in it). Print it out.
89 static void PrintLLVMName(raw_ostream &OS, StringRef Name, PrefixType Prefix) {
90 assert(!Name.empty() && "Cannot get empty name!");
92 default: llvm_unreachable("Bad prefix!");
94 case GlobalPrefix: OS << '@'; break;
95 case LabelPrefix: break;
96 case LocalPrefix: OS << '%'; break;
99 // Scan the name to see if it needs quotes first.
100 bool NeedsQuotes = isdigit(Name[0]);
102 for (unsigned i = 0, e = Name.size(); i != e; ++i) {
104 if (!isalnum(C) && C != '-' && C != '.' && C != '_') {
111 // If we didn't need any quotes, just write out the name in one blast.
117 // Okay, we need quotes. Output the quotes and escape any scary characters as
120 PrintEscapedString(Name, OS);
124 /// PrintLLVMName - Turn the specified name into an 'LLVM name', which is either
125 /// prefixed with % (if the string only contains simple characters) or is
126 /// surrounded with ""'s (if it has special chars in it). Print it out.
127 static void PrintLLVMName(raw_ostream &OS, const Value *V) {
128 PrintLLVMName(OS, V->getName(),
129 isa<GlobalValue>(V) ? GlobalPrefix : LocalPrefix);
132 //===----------------------------------------------------------------------===//
133 // TypePrinting Class: Type printing machinery
134 //===----------------------------------------------------------------------===//
136 /// TypePrinting - Type printing machinery.
139 TypePrinting(const TypePrinting &); // DO NOT IMPLEMENT
140 void operator=(const TypePrinting&); // DO NOT IMPLEMENT
143 /// NamedTypes - The named types that are used by the current module.
144 std::vector<StructType*> NamedTypes;
146 /// NumberedTypes - The numbered types, along with their value.
147 DenseMap<StructType*, unsigned> NumberedTypes;
153 void incorporateTypes(const Module &M);
155 void print(Type *Ty, raw_ostream &OS);
157 void printStructBody(StructType *Ty, raw_ostream &OS);
159 } // end anonymous namespace.
162 void TypePrinting::incorporateTypes(const Module &M) {
163 M.findUsedStructTypes(NamedTypes);
165 // The list of struct types we got back includes all the struct types, split
166 // the unnamed ones out to a numbering and remove the anonymous structs.
167 unsigned NextNumber = 0;
169 std::vector<StructType*>::iterator NextToUse = NamedTypes.begin(), I, E;
170 for (I = NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I) {
171 StructType *STy = *I;
173 // Ignore anonymous types.
174 if (STy->isAnonymous())
177 if (STy->getName().empty())
178 NumberedTypes[STy] = NextNumber++;
183 NamedTypes.erase(NextToUse, NamedTypes.end());
187 /// CalcTypeName - Write the specified type to the specified raw_ostream, making
188 /// use of type names or up references to shorten the type name where possible.
189 void TypePrinting::print(Type *Ty, raw_ostream &OS) {
190 switch (Ty->getTypeID()) {
191 case Type::VoidTyID: OS << "void"; break;
192 case Type::FloatTyID: OS << "float"; break;
193 case Type::DoubleTyID: OS << "double"; break;
194 case Type::X86_FP80TyID: OS << "x86_fp80"; break;
195 case Type::FP128TyID: OS << "fp128"; break;
196 case Type::PPC_FP128TyID: OS << "ppc_fp128"; break;
197 case Type::LabelTyID: OS << "label"; break;
198 case Type::MetadataTyID: OS << "metadata"; break;
199 case Type::X86_MMXTyID: OS << "x86_mmx"; break;
200 case Type::IntegerTyID:
201 OS << 'i' << cast<IntegerType>(Ty)->getBitWidth();
204 case Type::FunctionTyID: {
205 FunctionType *FTy = cast<FunctionType>(Ty);
206 print(FTy->getReturnType(), OS);
208 for (FunctionType::param_iterator I = FTy->param_begin(),
209 E = FTy->param_end(); I != E; ++I) {
210 if (I != FTy->param_begin())
214 if (FTy->isVarArg()) {
215 if (FTy->getNumParams()) OS << ", ";
221 case Type::StructTyID: {
222 StructType *STy = cast<StructType>(Ty);
224 if (STy->isAnonymous())
225 return printStructBody(STy, OS);
227 if (!STy->getName().empty())
228 return PrintLLVMName(OS, STy->getName(), LocalPrefix);
230 DenseMap<StructType*, unsigned>::iterator I = NumberedTypes.find(STy);
231 if (I != NumberedTypes.end())
232 OS << '%' << I->second;
233 else // Not enumerated, print the hex address.
234 OS << "%\"type 0x" << STy << '\"';
237 case Type::PointerTyID: {
238 PointerType *PTy = cast<PointerType>(Ty);
239 print(PTy->getElementType(), OS);
240 if (unsigned AddressSpace = PTy->getAddressSpace())
241 OS << " addrspace(" << AddressSpace << ')';
245 case Type::ArrayTyID: {
246 ArrayType *ATy = cast<ArrayType>(Ty);
247 OS << '[' << ATy->getNumElements() << " x ";
248 print(ATy->getElementType(), OS);
252 case Type::VectorTyID: {
253 VectorType *PTy = cast<VectorType>(Ty);
254 OS << "<" << PTy->getNumElements() << " x ";
255 print(PTy->getElementType(), OS);
260 OS << "<unrecognized-type>";
265 void TypePrinting::printStructBody(StructType *STy, raw_ostream &OS) {
266 if (STy->isOpaque()) {
274 if (STy->getNumElements() == 0) {
277 StructType::element_iterator I = STy->element_begin();
280 for (StructType::element_iterator E = STy->element_end(); I != E; ++I) {
293 void llvm::WriteTypeSymbolic(raw_ostream &OS, const Type *Ty, const Module *M) {
294 // FIXME: remove this function.
298 //===----------------------------------------------------------------------===//
299 // SlotTracker Class: Enumerate slot numbers for unnamed values
300 //===----------------------------------------------------------------------===//
304 /// This class provides computation of slot numbers for LLVM Assembly writing.
308 /// ValueMap - A mapping of Values to slot numbers.
309 typedef DenseMap<const Value*, unsigned> ValueMap;
312 /// TheModule - The module for which we are holding slot numbers.
313 const Module* TheModule;
315 /// TheFunction - The function for which we are holding slot numbers.
316 const Function* TheFunction;
317 bool FunctionProcessed;
319 /// mMap - The TypePlanes map for the module level data.
323 /// fMap - The TypePlanes map for the function level data.
327 /// mdnMap - Map for MDNodes.
328 DenseMap<const MDNode*, unsigned> mdnMap;
331 /// Construct from a module
332 explicit SlotTracker(const Module *M);
333 /// Construct from a function, starting out in incorp state.
334 explicit SlotTracker(const Function *F);
336 /// Return the slot number of the specified value in it's type
337 /// plane. If something is not in the SlotTracker, return -1.
338 int getLocalSlot(const Value *V);
339 int getGlobalSlot(const GlobalValue *V);
340 int getMetadataSlot(const MDNode *N);
342 /// If you'd like to deal with a function instead of just a module, use
343 /// this method to get its data into the SlotTracker.
344 void incorporateFunction(const Function *F) {
346 FunctionProcessed = false;
349 /// After calling incorporateFunction, use this method to remove the
350 /// most recently incorporated function from the SlotTracker. This
351 /// will reset the state of the machine back to just the module contents.
352 void purgeFunction();
354 /// MDNode map iterators.
355 typedef DenseMap<const MDNode*, unsigned>::iterator mdn_iterator;
356 mdn_iterator mdn_begin() { return mdnMap.begin(); }
357 mdn_iterator mdn_end() { return mdnMap.end(); }
358 unsigned mdn_size() const { return mdnMap.size(); }
359 bool mdn_empty() const { return mdnMap.empty(); }
361 /// This function does the actual initialization.
362 inline void initialize();
364 // Implementation Details
366 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
367 void CreateModuleSlot(const GlobalValue *V);
369 /// CreateMetadataSlot - Insert the specified MDNode* into the slot table.
370 void CreateMetadataSlot(const MDNode *N);
372 /// CreateFunctionSlot - Insert the specified Value* into the slot table.
373 void CreateFunctionSlot(const Value *V);
375 /// Add all of the module level global variables (and their initializers)
376 /// and function declarations, but not the contents of those functions.
377 void processModule();
379 /// Add all of the functions arguments, basic blocks, and instructions.
380 void processFunction();
382 SlotTracker(const SlotTracker &); // DO NOT IMPLEMENT
383 void operator=(const SlotTracker &); // DO NOT IMPLEMENT
386 } // end anonymous namespace
389 static SlotTracker *createSlotTracker(const Value *V) {
390 if (const Argument *FA = dyn_cast<Argument>(V))
391 return new SlotTracker(FA->getParent());
393 if (const Instruction *I = dyn_cast<Instruction>(V))
394 return new SlotTracker(I->getParent()->getParent());
396 if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
397 return new SlotTracker(BB->getParent());
399 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
400 return new SlotTracker(GV->getParent());
402 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
403 return new SlotTracker(GA->getParent());
405 if (const Function *Func = dyn_cast<Function>(V))
406 return new SlotTracker(Func);
408 if (const MDNode *MD = dyn_cast<MDNode>(V)) {
409 if (!MD->isFunctionLocal())
410 return new SlotTracker(MD->getFunction());
412 return new SlotTracker((Function *)0);
419 #define ST_DEBUG(X) dbgs() << X
424 // Module level constructor. Causes the contents of the Module (sans functions)
425 // to be added to the slot table.
426 SlotTracker::SlotTracker(const Module *M)
427 : TheModule(M), TheFunction(0), FunctionProcessed(false),
428 mNext(0), fNext(0), mdnNext(0) {
431 // Function level constructor. Causes the contents of the Module and the one
432 // function provided to be added to the slot table.
433 SlotTracker::SlotTracker(const Function *F)
434 : TheModule(F ? F->getParent() : 0), TheFunction(F), FunctionProcessed(false),
435 mNext(0), fNext(0), mdnNext(0) {
438 inline void SlotTracker::initialize() {
441 TheModule = 0; ///< Prevent re-processing next time we're called.
444 if (TheFunction && !FunctionProcessed)
448 // Iterate through all the global variables, functions, and global
449 // variable initializers and create slots for them.
450 void SlotTracker::processModule() {
451 ST_DEBUG("begin processModule!\n");
453 // Add all of the unnamed global variables to the value table.
454 for (Module::const_global_iterator I = TheModule->global_begin(),
455 E = TheModule->global_end(); I != E; ++I) {
460 // Add metadata used by named metadata.
461 for (Module::const_named_metadata_iterator
462 I = TheModule->named_metadata_begin(),
463 E = TheModule->named_metadata_end(); I != E; ++I) {
464 const NamedMDNode *NMD = I;
465 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i)
466 CreateMetadataSlot(NMD->getOperand(i));
469 // Add all the unnamed functions to the table.
470 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
475 ST_DEBUG("end processModule!\n");
478 // Process the arguments, basic blocks, and instructions of a function.
479 void SlotTracker::processFunction() {
480 ST_DEBUG("begin processFunction!\n");
483 // Add all the function arguments with no names.
484 for(Function::const_arg_iterator AI = TheFunction->arg_begin(),
485 AE = TheFunction->arg_end(); AI != AE; ++AI)
487 CreateFunctionSlot(AI);
489 ST_DEBUG("Inserting Instructions:\n");
491 SmallVector<std::pair<unsigned, MDNode*>, 4> MDForInst;
493 // Add all of the basic blocks and instructions with no names.
494 for (Function::const_iterator BB = TheFunction->begin(),
495 E = TheFunction->end(); BB != E; ++BB) {
497 CreateFunctionSlot(BB);
499 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E;
501 if (!I->getType()->isVoidTy() && !I->hasName())
502 CreateFunctionSlot(I);
504 // Intrinsics can directly use metadata. We allow direct calls to any
505 // llvm.foo function here, because the target may not be linked into the
507 if (const CallInst *CI = dyn_cast<CallInst>(I)) {
508 if (Function *F = CI->getCalledFunction())
509 if (F->getName().startswith("llvm."))
510 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
511 if (MDNode *N = dyn_cast_or_null<MDNode>(I->getOperand(i)))
512 CreateMetadataSlot(N);
515 // Process metadata attached with this instruction.
516 I->getAllMetadata(MDForInst);
517 for (unsigned i = 0, e = MDForInst.size(); i != e; ++i)
518 CreateMetadataSlot(MDForInst[i].second);
523 FunctionProcessed = true;
525 ST_DEBUG("end processFunction!\n");
528 /// Clean up after incorporating a function. This is the only way to get out of
529 /// the function incorporation state that affects get*Slot/Create*Slot. Function
530 /// incorporation state is indicated by TheFunction != 0.
531 void SlotTracker::purgeFunction() {
532 ST_DEBUG("begin purgeFunction!\n");
533 fMap.clear(); // Simply discard the function level map
535 FunctionProcessed = false;
536 ST_DEBUG("end purgeFunction!\n");
539 /// getGlobalSlot - Get the slot number of a global value.
540 int SlotTracker::getGlobalSlot(const GlobalValue *V) {
541 // Check for uninitialized state and do lazy initialization.
544 // Find the type plane in the module map
545 ValueMap::iterator MI = mMap.find(V);
546 return MI == mMap.end() ? -1 : (int)MI->second;
549 /// getMetadataSlot - Get the slot number of a MDNode.
550 int SlotTracker::getMetadataSlot(const MDNode *N) {
551 // Check for uninitialized state and do lazy initialization.
554 // Find the type plane in the module map
555 mdn_iterator MI = mdnMap.find(N);
556 return MI == mdnMap.end() ? -1 : (int)MI->second;
560 /// getLocalSlot - Get the slot number for a value that is local to a function.
561 int SlotTracker::getLocalSlot(const Value *V) {
562 assert(!isa<Constant>(V) && "Can't get a constant or global slot with this!");
564 // Check for uninitialized state and do lazy initialization.
567 ValueMap::iterator FI = fMap.find(V);
568 return FI == fMap.end() ? -1 : (int)FI->second;
572 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
573 void SlotTracker::CreateModuleSlot(const GlobalValue *V) {
574 assert(V && "Can't insert a null Value into SlotTracker!");
575 assert(!V->getType()->isVoidTy() && "Doesn't need a slot!");
576 assert(!V->hasName() && "Doesn't need a slot!");
578 unsigned DestSlot = mNext++;
581 ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" <<
583 // G = Global, F = Function, A = Alias, o = other
584 ST_DEBUG((isa<GlobalVariable>(V) ? 'G' :
585 (isa<Function>(V) ? 'F' :
586 (isa<GlobalAlias>(V) ? 'A' : 'o'))) << "]\n");
589 /// CreateSlot - Create a new slot for the specified value if it has no name.
590 void SlotTracker::CreateFunctionSlot(const Value *V) {
591 assert(!V->getType()->isVoidTy() && !V->hasName() && "Doesn't need a slot!");
593 unsigned DestSlot = fNext++;
596 // G = Global, F = Function, o = other
597 ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" <<
598 DestSlot << " [o]\n");
601 /// CreateModuleSlot - Insert the specified MDNode* into the slot table.
602 void SlotTracker::CreateMetadataSlot(const MDNode *N) {
603 assert(N && "Can't insert a null Value into SlotTracker!");
605 // Don't insert if N is a function-local metadata, these are always printed
607 if (!N->isFunctionLocal()) {
608 mdn_iterator I = mdnMap.find(N);
609 if (I != mdnMap.end())
612 unsigned DestSlot = mdnNext++;
613 mdnMap[N] = DestSlot;
616 // Recursively add any MDNodes referenced by operands.
617 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
618 if (const MDNode *Op = dyn_cast_or_null<MDNode>(N->getOperand(i)))
619 CreateMetadataSlot(Op);
622 //===----------------------------------------------------------------------===//
623 // AsmWriter Implementation
624 //===----------------------------------------------------------------------===//
626 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
627 TypePrinting *TypePrinter,
628 SlotTracker *Machine,
629 const Module *Context);
633 static const char *getPredicateText(unsigned predicate) {
634 const char * pred = "unknown";
636 case FCmpInst::FCMP_FALSE: pred = "false"; break;
637 case FCmpInst::FCMP_OEQ: pred = "oeq"; break;
638 case FCmpInst::FCMP_OGT: pred = "ogt"; break;
639 case FCmpInst::FCMP_OGE: pred = "oge"; break;
640 case FCmpInst::FCMP_OLT: pred = "olt"; break;
641 case FCmpInst::FCMP_OLE: pred = "ole"; break;
642 case FCmpInst::FCMP_ONE: pred = "one"; break;
643 case FCmpInst::FCMP_ORD: pred = "ord"; break;
644 case FCmpInst::FCMP_UNO: pred = "uno"; break;
645 case FCmpInst::FCMP_UEQ: pred = "ueq"; break;
646 case FCmpInst::FCMP_UGT: pred = "ugt"; break;
647 case FCmpInst::FCMP_UGE: pred = "uge"; break;
648 case FCmpInst::FCMP_ULT: pred = "ult"; break;
649 case FCmpInst::FCMP_ULE: pred = "ule"; break;
650 case FCmpInst::FCMP_UNE: pred = "une"; break;
651 case FCmpInst::FCMP_TRUE: pred = "true"; break;
652 case ICmpInst::ICMP_EQ: pred = "eq"; break;
653 case ICmpInst::ICMP_NE: pred = "ne"; break;
654 case ICmpInst::ICMP_SGT: pred = "sgt"; break;
655 case ICmpInst::ICMP_SGE: pred = "sge"; break;
656 case ICmpInst::ICMP_SLT: pred = "slt"; break;
657 case ICmpInst::ICMP_SLE: pred = "sle"; break;
658 case ICmpInst::ICMP_UGT: pred = "ugt"; break;
659 case ICmpInst::ICMP_UGE: pred = "uge"; break;
660 case ICmpInst::ICMP_ULT: pred = "ult"; break;
661 case ICmpInst::ICMP_ULE: pred = "ule"; break;
667 static void WriteOptimizationInfo(raw_ostream &Out, const User *U) {
668 if (const OverflowingBinaryOperator *OBO =
669 dyn_cast<OverflowingBinaryOperator>(U)) {
670 if (OBO->hasNoUnsignedWrap())
672 if (OBO->hasNoSignedWrap())
674 } else if (const PossiblyExactOperator *Div =
675 dyn_cast<PossiblyExactOperator>(U)) {
678 } else if (const GEPOperator *GEP = dyn_cast<GEPOperator>(U)) {
679 if (GEP->isInBounds())
684 static void WriteConstantInternal(raw_ostream &Out, const Constant *CV,
685 TypePrinting &TypePrinter,
686 SlotTracker *Machine,
687 const Module *Context) {
688 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
689 if (CI->getType()->isIntegerTy(1)) {
690 Out << (CI->getZExtValue() ? "true" : "false");
693 Out << CI->getValue();
697 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
698 if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEdouble ||
699 &CFP->getValueAPF().getSemantics() == &APFloat::IEEEsingle) {
700 // We would like to output the FP constant value in exponential notation,
701 // but we cannot do this if doing so will lose precision. Check here to
702 // make sure that we only output it in exponential format if we can parse
703 // the value back and get the same value.
706 bool isDouble = &CFP->getValueAPF().getSemantics()==&APFloat::IEEEdouble;
707 double Val = isDouble ? CFP->getValueAPF().convertToDouble() :
708 CFP->getValueAPF().convertToFloat();
709 SmallString<128> StrVal;
710 raw_svector_ostream(StrVal) << Val;
712 // Check to make sure that the stringized number is not some string like
713 // "Inf" or NaN, that atof will accept, but the lexer will not. Check
714 // that the string matches the "[-+]?[0-9]" regex.
716 if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
717 ((StrVal[0] == '-' || StrVal[0] == '+') &&
718 (StrVal[1] >= '0' && StrVal[1] <= '9'))) {
719 // Reparse stringized version!
720 if (atof(StrVal.c_str()) == Val) {
725 // Otherwise we could not reparse it to exactly the same value, so we must
726 // output the string in hexadecimal format! Note that loading and storing
727 // floating point types changes the bits of NaNs on some hosts, notably
728 // x86, so we must not use these types.
729 assert(sizeof(double) == sizeof(uint64_t) &&
730 "assuming that double is 64 bits!");
732 APFloat apf = CFP->getValueAPF();
733 // Floats are represented in ASCII IR as double, convert.
735 apf.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
738 utohex_buffer(uint64_t(apf.bitcastToAPInt().getZExtValue()),
743 // Some form of long double. These appear as a magic letter identifying
744 // the type, then a fixed number of hex digits.
746 if (&CFP->getValueAPF().getSemantics() == &APFloat::x87DoubleExtended) {
748 // api needed to prevent premature destruction
749 APInt api = CFP->getValueAPF().bitcastToAPInt();
750 const uint64_t* p = api.getRawData();
751 uint64_t word = p[1];
753 int width = api.getBitWidth();
754 for (int j=0; j<width; j+=4, shiftcount-=4) {
755 unsigned int nibble = (word>>shiftcount) & 15;
757 Out << (unsigned char)(nibble + '0');
759 Out << (unsigned char)(nibble - 10 + 'A');
760 if (shiftcount == 0 && j+4 < width) {
764 shiftcount = width-j-4;
768 } else if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEquad)
770 else if (&CFP->getValueAPF().getSemantics() == &APFloat::PPCDoubleDouble)
773 llvm_unreachable("Unsupported floating point type");
774 // api needed to prevent premature destruction
775 APInt api = CFP->getValueAPF().bitcastToAPInt();
776 const uint64_t* p = api.getRawData();
779 int width = api.getBitWidth();
780 for (int j=0; j<width; j+=4, shiftcount-=4) {
781 unsigned int nibble = (word>>shiftcount) & 15;
783 Out << (unsigned char)(nibble + '0');
785 Out << (unsigned char)(nibble - 10 + 'A');
786 if (shiftcount == 0 && j+4 < width) {
790 shiftcount = width-j-4;
796 if (isa<ConstantAggregateZero>(CV)) {
797 Out << "zeroinitializer";
801 if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV)) {
802 Out << "blockaddress(";
803 WriteAsOperandInternal(Out, BA->getFunction(), &TypePrinter, Machine,
806 WriteAsOperandInternal(Out, BA->getBasicBlock(), &TypePrinter, Machine,
812 if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
813 // As a special case, print the array as a string if it is an array of
814 // i8 with ConstantInt values.
816 Type *ETy = CA->getType()->getElementType();
817 if (CA->isString()) {
819 PrintEscapedString(CA->getAsString(), Out);
821 } else { // Cannot output in string format...
823 if (CA->getNumOperands()) {
824 TypePrinter.print(ETy, Out);
826 WriteAsOperandInternal(Out, CA->getOperand(0),
827 &TypePrinter, Machine,
829 for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
831 TypePrinter.print(ETy, Out);
833 WriteAsOperandInternal(Out, CA->getOperand(i), &TypePrinter, Machine,
842 if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
843 if (CS->getType()->isPacked())
846 unsigned N = CS->getNumOperands();
849 TypePrinter.print(CS->getOperand(0)->getType(), Out);
852 WriteAsOperandInternal(Out, CS->getOperand(0), &TypePrinter, Machine,
855 for (unsigned i = 1; i < N; i++) {
857 TypePrinter.print(CS->getOperand(i)->getType(), Out);
860 WriteAsOperandInternal(Out, CS->getOperand(i), &TypePrinter, Machine,
867 if (CS->getType()->isPacked())
872 if (const ConstantVector *CP = dyn_cast<ConstantVector>(CV)) {
873 Type *ETy = CP->getType()->getElementType();
874 assert(CP->getNumOperands() > 0 &&
875 "Number of operands for a PackedConst must be > 0");
877 TypePrinter.print(ETy, Out);
879 WriteAsOperandInternal(Out, CP->getOperand(0), &TypePrinter, Machine,
881 for (unsigned i = 1, e = CP->getNumOperands(); i != e; ++i) {
883 TypePrinter.print(ETy, Out);
885 WriteAsOperandInternal(Out, CP->getOperand(i), &TypePrinter, Machine,
892 if (isa<ConstantPointerNull>(CV)) {
897 if (isa<UndefValue>(CV)) {
902 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
903 Out << CE->getOpcodeName();
904 WriteOptimizationInfo(Out, CE);
906 Out << ' ' << getPredicateText(CE->getPredicate());
909 for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) {
910 TypePrinter.print((*OI)->getType(), Out);
912 WriteAsOperandInternal(Out, *OI, &TypePrinter, Machine, Context);
913 if (OI+1 != CE->op_end())
917 if (CE->hasIndices()) {
918 ArrayRef<unsigned> Indices = CE->getIndices();
919 for (unsigned i = 0, e = Indices.size(); i != e; ++i)
920 Out << ", " << Indices[i];
925 TypePrinter.print(CE->getType(), Out);
932 Out << "<placeholder or erroneous Constant>";
935 static void WriteMDNodeBodyInternal(raw_ostream &Out, const MDNode *Node,
936 TypePrinting *TypePrinter,
937 SlotTracker *Machine,
938 const Module *Context) {
940 for (unsigned mi = 0, me = Node->getNumOperands(); mi != me; ++mi) {
941 const Value *V = Node->getOperand(mi);
945 TypePrinter->print(V->getType(), Out);
947 WriteAsOperandInternal(Out, Node->getOperand(mi),
948 TypePrinter, Machine, Context);
958 /// WriteAsOperand - Write the name of the specified value out to the specified
959 /// ostream. This can be useful when you just want to print int %reg126, not
960 /// the whole instruction that generated it.
962 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
963 TypePrinting *TypePrinter,
964 SlotTracker *Machine,
965 const Module *Context) {
967 PrintLLVMName(Out, V);
971 const Constant *CV = dyn_cast<Constant>(V);
972 if (CV && !isa<GlobalValue>(CV)) {
973 assert(TypePrinter && "Constants require TypePrinting!");
974 WriteConstantInternal(Out, CV, *TypePrinter, Machine, Context);
978 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
980 if (IA->hasSideEffects())
981 Out << "sideeffect ";
982 if (IA->isAlignStack())
983 Out << "alignstack ";
985 PrintEscapedString(IA->getAsmString(), Out);
987 PrintEscapedString(IA->getConstraintString(), Out);
992 if (const MDNode *N = dyn_cast<MDNode>(V)) {
993 if (N->isFunctionLocal()) {
994 // Print metadata inline, not via slot reference number.
995 WriteMDNodeBodyInternal(Out, N, TypePrinter, Machine, Context);
1000 if (N->isFunctionLocal())
1001 Machine = new SlotTracker(N->getFunction());
1003 Machine = new SlotTracker(Context);
1005 int Slot = Machine->getMetadataSlot(N);
1013 if (const MDString *MDS = dyn_cast<MDString>(V)) {
1015 PrintEscapedString(MDS->getString(), Out);
1020 if (V->getValueID() == Value::PseudoSourceValueVal ||
1021 V->getValueID() == Value::FixedStackPseudoSourceValueVal) {
1029 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
1030 Slot = Machine->getGlobalSlot(GV);
1033 Slot = Machine->getLocalSlot(V);
1036 Machine = createSlotTracker(V);
1038 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
1039 Slot = Machine->getGlobalSlot(GV);
1042 Slot = Machine->getLocalSlot(V);
1051 Out << Prefix << Slot;
1056 void llvm::WriteAsOperand(raw_ostream &Out, const Value *V,
1057 bool PrintType, const Module *Context) {
1059 // Fast path: Don't construct and populate a TypePrinting object if we
1060 // won't be needing any types printed.
1062 ((!isa<Constant>(V) && !isa<MDNode>(V)) ||
1063 V->hasName() || isa<GlobalValue>(V))) {
1064 WriteAsOperandInternal(Out, V, 0, 0, Context);
1068 if (Context == 0) Context = getModuleFromVal(V);
1070 TypePrinting TypePrinter;
1072 TypePrinter.incorporateTypes(*Context);
1074 TypePrinter.print(V->getType(), Out);
1078 WriteAsOperandInternal(Out, V, &TypePrinter, 0, Context);
1083 class AssemblyWriter {
1084 formatted_raw_ostream &Out;
1085 SlotTracker &Machine;
1086 const Module *TheModule;
1087 TypePrinting TypePrinter;
1088 AssemblyAnnotationWriter *AnnotationWriter;
1091 inline AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac,
1093 AssemblyAnnotationWriter *AAW)
1094 : Out(o), Machine(Mac), TheModule(M), AnnotationWriter(AAW) {
1096 TypePrinter.incorporateTypes(*M);
1099 void printMDNodeBody(const MDNode *MD);
1100 void printNamedMDNode(const NamedMDNode *NMD);
1102 void printModule(const Module *M);
1104 void writeOperand(const Value *Op, bool PrintType);
1105 void writeParamOperand(const Value *Operand, Attributes Attrs);
1107 void writeAllMDNodes();
1109 void printTypeIdentities();
1110 void printGlobal(const GlobalVariable *GV);
1111 void printAlias(const GlobalAlias *GV);
1112 void printFunction(const Function *F);
1113 void printArgument(const Argument *FA, Attributes Attrs);
1114 void printBasicBlock(const BasicBlock *BB);
1115 void printInstruction(const Instruction &I);
1118 // printInfoComment - Print a little comment after the instruction indicating
1119 // which slot it occupies.
1120 void printInfoComment(const Value &V);
1122 } // end of anonymous namespace
1124 void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType) {
1126 Out << "<null operand!>";
1130 TypePrinter.print(Operand->getType(), Out);
1133 WriteAsOperandInternal(Out, Operand, &TypePrinter, &Machine, TheModule);
1136 void AssemblyWriter::writeParamOperand(const Value *Operand,
1139 Out << "<null operand!>";
1144 TypePrinter.print(Operand->getType(), Out);
1145 // Print parameter attributes list
1146 if (Attrs != Attribute::None)
1147 Out << ' ' << Attribute::getAsString(Attrs);
1149 // Print the operand
1150 WriteAsOperandInternal(Out, Operand, &TypePrinter, &Machine, TheModule);
1153 void AssemblyWriter::printModule(const Module *M) {
1154 if (!M->getModuleIdentifier().empty() &&
1155 // Don't print the ID if it will start a new line (which would
1156 // require a comment char before it).
1157 M->getModuleIdentifier().find('\n') == std::string::npos)
1158 Out << "; ModuleID = '" << M->getModuleIdentifier() << "'\n";
1160 if (!M->getDataLayout().empty())
1161 Out << "target datalayout = \"" << M->getDataLayout() << "\"\n";
1162 if (!M->getTargetTriple().empty())
1163 Out << "target triple = \"" << M->getTargetTriple() << "\"\n";
1165 if (!M->getModuleInlineAsm().empty()) {
1166 // Split the string into lines, to make it easier to read the .ll file.
1167 std::string Asm = M->getModuleInlineAsm();
1169 size_t NewLine = Asm.find_first_of('\n', CurPos);
1171 while (NewLine != std::string::npos) {
1172 // We found a newline, print the portion of the asm string from the
1173 // last newline up to this newline.
1174 Out << "module asm \"";
1175 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.begin()+NewLine),
1179 NewLine = Asm.find_first_of('\n', CurPos);
1181 std::string rest(Asm.begin()+CurPos, Asm.end());
1182 if (!rest.empty()) {
1183 Out << "module asm \"";
1184 PrintEscapedString(rest, Out);
1189 // Loop over the dependent libraries and emit them.
1190 Module::lib_iterator LI = M->lib_begin();
1191 Module::lib_iterator LE = M->lib_end();
1194 Out << "deplibs = [ ";
1196 Out << '"' << *LI << '"';
1204 printTypeIdentities();
1206 // Output all globals.
1207 if (!M->global_empty()) Out << '\n';
1208 for (Module::const_global_iterator I = M->global_begin(), E = M->global_end();
1212 // Output all aliases.
1213 if (!M->alias_empty()) Out << "\n";
1214 for (Module::const_alias_iterator I = M->alias_begin(), E = M->alias_end();
1218 // Output all of the functions.
1219 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
1222 // Output named metadata.
1223 if (!M->named_metadata_empty()) Out << '\n';
1225 for (Module::const_named_metadata_iterator I = M->named_metadata_begin(),
1226 E = M->named_metadata_end(); I != E; ++I)
1227 printNamedMDNode(I);
1230 if (!Machine.mdn_empty()) {
1236 void AssemblyWriter::printNamedMDNode(const NamedMDNode *NMD) {
1238 StringRef Name = NMD->getName();
1240 Out << "<empty name> ";
1242 if (isalpha(Name[0]) || Name[0] == '-' || Name[0] == '$' ||
1243 Name[0] == '.' || Name[0] == '_')
1246 Out << '\\' << hexdigit(Name[0] >> 4) << hexdigit(Name[0] & 0x0F);
1247 for (unsigned i = 1, e = Name.size(); i != e; ++i) {
1248 unsigned char C = Name[i];
1249 if (isalnum(C) || C == '-' || C == '$' || C == '.' || C == '_')
1252 Out << '\\' << hexdigit(C >> 4) << hexdigit(C & 0x0F);
1256 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
1258 int Slot = Machine.getMetadataSlot(NMD->getOperand(i));
1268 static void PrintLinkage(GlobalValue::LinkageTypes LT,
1269 formatted_raw_ostream &Out) {
1271 case GlobalValue::ExternalLinkage: break;
1272 case GlobalValue::PrivateLinkage: Out << "private "; break;
1273 case GlobalValue::LinkerPrivateLinkage: Out << "linker_private "; break;
1274 case GlobalValue::LinkerPrivateWeakLinkage:
1275 Out << "linker_private_weak ";
1277 case GlobalValue::LinkerPrivateWeakDefAutoLinkage:
1278 Out << "linker_private_weak_def_auto ";
1280 case GlobalValue::InternalLinkage: Out << "internal "; break;
1281 case GlobalValue::LinkOnceAnyLinkage: Out << "linkonce "; break;
1282 case GlobalValue::LinkOnceODRLinkage: Out << "linkonce_odr "; break;
1283 case GlobalValue::WeakAnyLinkage: Out << "weak "; break;
1284 case GlobalValue::WeakODRLinkage: Out << "weak_odr "; break;
1285 case GlobalValue::CommonLinkage: Out << "common "; break;
1286 case GlobalValue::AppendingLinkage: Out << "appending "; break;
1287 case GlobalValue::DLLImportLinkage: Out << "dllimport "; break;
1288 case GlobalValue::DLLExportLinkage: Out << "dllexport "; break;
1289 case GlobalValue::ExternalWeakLinkage: Out << "extern_weak "; break;
1290 case GlobalValue::AvailableExternallyLinkage:
1291 Out << "available_externally ";
1297 static void PrintVisibility(GlobalValue::VisibilityTypes Vis,
1298 formatted_raw_ostream &Out) {
1300 case GlobalValue::DefaultVisibility: break;
1301 case GlobalValue::HiddenVisibility: Out << "hidden "; break;
1302 case GlobalValue::ProtectedVisibility: Out << "protected "; break;
1306 void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
1307 if (GV->isMaterializable())
1308 Out << "; Materializable\n";
1310 WriteAsOperandInternal(Out, GV, &TypePrinter, &Machine, GV->getParent());
1313 if (!GV->hasInitializer() && GV->hasExternalLinkage())
1316 PrintLinkage(GV->getLinkage(), Out);
1317 PrintVisibility(GV->getVisibility(), Out);
1319 if (GV->isThreadLocal()) Out << "thread_local ";
1320 if (unsigned AddressSpace = GV->getType()->getAddressSpace())
1321 Out << "addrspace(" << AddressSpace << ") ";
1322 if (GV->hasUnnamedAddr()) Out << "unnamed_addr ";
1323 Out << (GV->isConstant() ? "constant " : "global ");
1324 TypePrinter.print(GV->getType()->getElementType(), Out);
1326 if (GV->hasInitializer()) {
1328 writeOperand(GV->getInitializer(), false);
1331 if (GV->hasSection()) {
1332 Out << ", section \"";
1333 PrintEscapedString(GV->getSection(), Out);
1336 if (GV->getAlignment())
1337 Out << ", align " << GV->getAlignment();
1339 printInfoComment(*GV);
1343 void AssemblyWriter::printAlias(const GlobalAlias *GA) {
1344 if (GA->isMaterializable())
1345 Out << "; Materializable\n";
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();
1363 TypePrinter.print(GA->getType(), Out);
1364 Out << " <<NULL ALIASEE>>";
1365 } else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Aliasee)) {
1366 TypePrinter.print(GV->getType(), Out);
1368 PrintLLVMName(Out, GV);
1369 } else if (const Function *F = dyn_cast<Function>(Aliasee)) {
1370 TypePrinter.print(F->getFunctionType(), Out);
1373 WriteAsOperandInternal(Out, F, &TypePrinter, &Machine, F->getParent());
1374 } else if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(Aliasee)) {
1375 TypePrinter.print(GA->getType(), Out);
1377 PrintLLVMName(Out, GA);
1379 const ConstantExpr *CE = cast<ConstantExpr>(Aliasee);
1380 // The only valid GEP is an all zero GEP.
1381 assert((CE->getOpcode() == Instruction::BitCast ||
1382 CE->getOpcode() == Instruction::GetElementPtr) &&
1383 "Unsupported aliasee");
1384 writeOperand(CE, false);
1387 printInfoComment(*GA);
1391 void AssemblyWriter::printTypeIdentities() {
1392 if (TypePrinter.NumberedTypes.empty() &&
1393 TypePrinter.NamedTypes.empty())
1398 // We know all the numbers that each type is used and we know that it is a
1399 // dense assignment. Convert the map to an index table.
1400 std::vector<StructType*> NumberedTypes(TypePrinter.NumberedTypes.size());
1401 for (DenseMap<StructType*, unsigned>::iterator I =
1402 TypePrinter.NumberedTypes.begin(), E = TypePrinter.NumberedTypes.end();
1404 assert(I->second < NumberedTypes.size() && "Didn't get a dense numbering?");
1405 NumberedTypes[I->second] = I->first;
1408 // Emit all numbered types.
1409 for (unsigned i = 0, e = NumberedTypes.size(); i != e; ++i) {
1410 Out << '%' << i << " = type ";
1412 // Make sure we print out at least one level of the type structure, so
1413 // that we do not get %2 = type %2
1414 TypePrinter.printStructBody(NumberedTypes[i], Out);
1418 for (unsigned i = 0, e = TypePrinter.NamedTypes.size(); i != e; ++i) {
1419 PrintLLVMName(Out, TypePrinter.NamedTypes[i]->getName(), LocalPrefix);
1422 // Make sure we print out at least one level of the type structure, so
1423 // that we do not get %FILE = type %FILE
1424 TypePrinter.printStructBody(TypePrinter.NamedTypes[i], Out);
1429 /// printFunction - Print all aspects of a function.
1431 void AssemblyWriter::printFunction(const Function *F) {
1432 // Print out the return type and name.
1435 if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, Out);
1437 if (F->isMaterializable())
1438 Out << "; Materializable\n";
1440 if (F->isDeclaration())
1445 PrintLinkage(F->getLinkage(), Out);
1446 PrintVisibility(F->getVisibility(), Out);
1448 // Print the calling convention.
1449 switch (F->getCallingConv()) {
1450 case CallingConv::C: break; // default
1451 case CallingConv::Fast: Out << "fastcc "; break;
1452 case CallingConv::Cold: Out << "coldcc "; break;
1453 case CallingConv::X86_StdCall: Out << "x86_stdcallcc "; break;
1454 case CallingConv::X86_FastCall: Out << "x86_fastcallcc "; break;
1455 case CallingConv::X86_ThisCall: Out << "x86_thiscallcc "; break;
1456 case CallingConv::ARM_APCS: Out << "arm_apcscc "; break;
1457 case CallingConv::ARM_AAPCS: Out << "arm_aapcscc "; break;
1458 case CallingConv::ARM_AAPCS_VFP:Out << "arm_aapcs_vfpcc "; break;
1459 case CallingConv::MSP430_INTR: Out << "msp430_intrcc "; break;
1460 case CallingConv::PTX_Kernel: Out << "ptx_kernel "; break;
1461 case CallingConv::PTX_Device: Out << "ptx_device "; break;
1462 default: Out << "cc" << F->getCallingConv() << " "; break;
1465 const FunctionType *FT = F->getFunctionType();
1466 const AttrListPtr &Attrs = F->getAttributes();
1467 Attributes RetAttrs = Attrs.getRetAttributes();
1468 if (RetAttrs != Attribute::None)
1469 Out << Attribute::getAsString(Attrs.getRetAttributes()) << ' ';
1470 TypePrinter.print(F->getReturnType(), Out);
1472 WriteAsOperandInternal(Out, F, &TypePrinter, &Machine, F->getParent());
1474 Machine.incorporateFunction(F);
1476 // Loop over the arguments, printing them...
1479 if (!F->isDeclaration()) {
1480 // If this isn't a declaration, print the argument names as well.
1481 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
1483 // Insert commas as we go... the first arg doesn't get a comma
1484 if (I != F->arg_begin()) Out << ", ";
1485 printArgument(I, Attrs.getParamAttributes(Idx));
1489 // Otherwise, print the types from the function type.
1490 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
1491 // Insert commas as we go... the first arg doesn't get a comma
1495 TypePrinter.print(FT->getParamType(i), Out);
1497 Attributes ArgAttrs = Attrs.getParamAttributes(i+1);
1498 if (ArgAttrs != Attribute::None)
1499 Out << ' ' << Attribute::getAsString(ArgAttrs);
1503 // Finish printing arguments...
1504 if (FT->isVarArg()) {
1505 if (FT->getNumParams()) Out << ", ";
1506 Out << "..."; // Output varargs portion of signature!
1509 if (F->hasUnnamedAddr())
1510 Out << " unnamed_addr";
1511 Attributes FnAttrs = Attrs.getFnAttributes();
1512 if (FnAttrs != Attribute::None)
1513 Out << ' ' << Attribute::getAsString(Attrs.getFnAttributes());
1514 if (F->hasSection()) {
1515 Out << " section \"";
1516 PrintEscapedString(F->getSection(), Out);
1519 if (F->getAlignment())
1520 Out << " align " << F->getAlignment();
1522 Out << " gc \"" << F->getGC() << '"';
1523 if (F->isDeclaration()) {
1527 // Output all of the function's basic blocks.
1528 for (Function::const_iterator I = F->begin(), E = F->end(); I != E; ++I)
1534 Machine.purgeFunction();
1537 /// printArgument - This member is called for every argument that is passed into
1538 /// the function. Simply print it out
1540 void AssemblyWriter::printArgument(const Argument *Arg,
1543 TypePrinter.print(Arg->getType(), Out);
1545 // Output parameter attributes list
1546 if (Attrs != Attribute::None)
1547 Out << ' ' << Attribute::getAsString(Attrs);
1549 // Output name, if available...
1550 if (Arg->hasName()) {
1552 PrintLLVMName(Out, Arg);
1556 /// printBasicBlock - This member is called for each basic block in a method.
1558 void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {
1559 if (BB->hasName()) { // Print out the label if it exists...
1561 PrintLLVMName(Out, BB->getName(), LabelPrefix);
1563 } else if (!BB->use_empty()) { // Don't print block # of no uses...
1564 Out << "\n; <label>:";
1565 int Slot = Machine.getLocalSlot(BB);
1572 if (BB->getParent() == 0) {
1573 Out.PadToColumn(50);
1574 Out << "; Error: Block without parent!";
1575 } else if (BB != &BB->getParent()->getEntryBlock()) { // Not the entry block?
1576 // Output predecessors for the block.
1577 Out.PadToColumn(50);
1579 const_pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
1582 Out << " No predecessors!";
1585 writeOperand(*PI, false);
1586 for (++PI; PI != PE; ++PI) {
1588 writeOperand(*PI, false);
1595 if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(BB, Out);
1597 // Output all of the instructions in the basic block...
1598 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
1599 printInstruction(*I);
1603 if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(BB, Out);
1606 /// printInfoComment - Print a little comment after the instruction indicating
1607 /// which slot it occupies.
1609 void AssemblyWriter::printInfoComment(const Value &V) {
1610 if (AnnotationWriter) {
1611 AnnotationWriter->printInfoComment(V, Out);
1616 // This member is called for each Instruction in a function..
1617 void AssemblyWriter::printInstruction(const Instruction &I) {
1618 if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, Out);
1620 // Print out indentation for an instruction.
1623 // Print out name if it exists...
1625 PrintLLVMName(Out, &I);
1627 } else if (!I.getType()->isVoidTy()) {
1628 // Print out the def slot taken.
1629 int SlotNum = Machine.getLocalSlot(&I);
1631 Out << "<badref> = ";
1633 Out << '%' << SlotNum << " = ";
1636 // If this is a volatile load or store, print out the volatile marker.
1637 if ((isa<LoadInst>(I) && cast<LoadInst>(I).isVolatile()) ||
1638 (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile())) {
1640 } else if (isa<CallInst>(I) && cast<CallInst>(I).isTailCall()) {
1641 // If this is a call, check if it's a tail call.
1645 // Print out the opcode...
1646 Out << I.getOpcodeName();
1648 // Print out optimization information.
1649 WriteOptimizationInfo(Out, &I);
1651 // Print out the compare instruction predicates
1652 if (const CmpInst *CI = dyn_cast<CmpInst>(&I))
1653 Out << ' ' << getPredicateText(CI->getPredicate());
1655 // Print out the type of the operands...
1656 const Value *Operand = I.getNumOperands() ? I.getOperand(0) : 0;
1658 // Special case conditional branches to swizzle the condition out to the front
1659 if (isa<BranchInst>(I) && cast<BranchInst>(I).isConditional()) {
1660 BranchInst &BI(cast<BranchInst>(I));
1662 writeOperand(BI.getCondition(), true);
1664 writeOperand(BI.getSuccessor(0), true);
1666 writeOperand(BI.getSuccessor(1), true);
1668 } else if (isa<SwitchInst>(I)) {
1669 // Special case switch instruction to get formatting nice and correct.
1671 writeOperand(Operand , true);
1673 writeOperand(I.getOperand(1), true);
1676 for (unsigned op = 2, Eop = I.getNumOperands(); op < Eop; op += 2) {
1678 writeOperand(I.getOperand(op ), true);
1680 writeOperand(I.getOperand(op+1), true);
1683 } else if (isa<IndirectBrInst>(I)) {
1684 // Special case indirectbr instruction to get formatting nice and correct.
1686 writeOperand(Operand, true);
1689 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
1692 writeOperand(I.getOperand(i), true);
1695 } else if (const PHINode *PN = dyn_cast<PHINode>(&I)) {
1697 TypePrinter.print(I.getType(), Out);
1700 for (unsigned op = 0, Eop = PN->getNumIncomingValues(); op < Eop; ++op) {
1701 if (op) Out << ", ";
1703 writeOperand(PN->getIncomingValue(op), false); Out << ", ";
1704 writeOperand(PN->getIncomingBlock(op), false); Out << " ]";
1706 } else if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&I)) {
1708 writeOperand(I.getOperand(0), true);
1709 for (const unsigned *i = EVI->idx_begin(), *e = EVI->idx_end(); i != e; ++i)
1711 } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&I)) {
1713 writeOperand(I.getOperand(0), true); Out << ", ";
1714 writeOperand(I.getOperand(1), true);
1715 for (const unsigned *i = IVI->idx_begin(), *e = IVI->idx_end(); i != e; ++i)
1717 } else if (isa<ReturnInst>(I) && !Operand) {
1719 } else if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
1720 // Print the calling convention being used.
1721 switch (CI->getCallingConv()) {
1722 case CallingConv::C: break; // default
1723 case CallingConv::Fast: Out << " fastcc"; break;
1724 case CallingConv::Cold: Out << " coldcc"; break;
1725 case CallingConv::X86_StdCall: Out << " x86_stdcallcc"; break;
1726 case CallingConv::X86_FastCall: Out << " x86_fastcallcc"; break;
1727 case CallingConv::X86_ThisCall: Out << " x86_thiscallcc"; break;
1728 case CallingConv::ARM_APCS: Out << " arm_apcscc "; break;
1729 case CallingConv::ARM_AAPCS: Out << " arm_aapcscc "; break;
1730 case CallingConv::ARM_AAPCS_VFP:Out << " arm_aapcs_vfpcc "; break;
1731 case CallingConv::MSP430_INTR: Out << " msp430_intrcc "; break;
1732 case CallingConv::PTX_Kernel: Out << " ptx_kernel"; break;
1733 case CallingConv::PTX_Device: Out << " ptx_device"; break;
1734 default: Out << " cc" << CI->getCallingConv(); break;
1737 Operand = CI->getCalledValue();
1738 PointerType *PTy = cast<PointerType>(Operand->getType());
1739 FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1740 Type *RetTy = FTy->getReturnType();
1741 const AttrListPtr &PAL = CI->getAttributes();
1743 if (PAL.getRetAttributes() != Attribute::None)
1744 Out << ' ' << Attribute::getAsString(PAL.getRetAttributes());
1746 // If possible, print out the short form of the call instruction. We can
1747 // only do this if the first argument is a pointer to a nonvararg function,
1748 // and if the return type is not a pointer to a function.
1751 if (!FTy->isVarArg() &&
1752 (!RetTy->isPointerTy() ||
1753 !cast<PointerType>(RetTy)->getElementType()->isFunctionTy())) {
1754 TypePrinter.print(RetTy, Out);
1756 writeOperand(Operand, false);
1758 writeOperand(Operand, true);
1761 for (unsigned op = 0, Eop = CI->getNumArgOperands(); op < Eop; ++op) {
1764 writeParamOperand(CI->getArgOperand(op), PAL.getParamAttributes(op + 1));
1767 if (PAL.getFnAttributes() != Attribute::None)
1768 Out << ' ' << Attribute::getAsString(PAL.getFnAttributes());
1769 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
1770 Operand = II->getCalledValue();
1771 PointerType *PTy = cast<PointerType>(Operand->getType());
1772 FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1773 Type *RetTy = FTy->getReturnType();
1774 const AttrListPtr &PAL = II->getAttributes();
1776 // Print the calling convention being used.
1777 switch (II->getCallingConv()) {
1778 case CallingConv::C: break; // default
1779 case CallingConv::Fast: Out << " fastcc"; break;
1780 case CallingConv::Cold: Out << " coldcc"; break;
1781 case CallingConv::X86_StdCall: Out << " x86_stdcallcc"; break;
1782 case CallingConv::X86_FastCall: Out << " x86_fastcallcc"; break;
1783 case CallingConv::X86_ThisCall: Out << " x86_thiscallcc"; break;
1784 case CallingConv::ARM_APCS: Out << " arm_apcscc "; break;
1785 case CallingConv::ARM_AAPCS: Out << " arm_aapcscc "; break;
1786 case CallingConv::ARM_AAPCS_VFP:Out << " arm_aapcs_vfpcc "; break;
1787 case CallingConv::MSP430_INTR: Out << " msp430_intrcc "; break;
1788 case CallingConv::PTX_Kernel: Out << " ptx_kernel"; break;
1789 case CallingConv::PTX_Device: Out << " ptx_device"; break;
1790 default: Out << " cc" << II->getCallingConv(); break;
1793 if (PAL.getRetAttributes() != Attribute::None)
1794 Out << ' ' << Attribute::getAsString(PAL.getRetAttributes());
1796 // If possible, print out the short form of the invoke instruction. We can
1797 // only do this if the first argument is a pointer to a nonvararg function,
1798 // and if the return type is not a pointer to a function.
1801 if (!FTy->isVarArg() &&
1802 (!RetTy->isPointerTy() ||
1803 !cast<PointerType>(RetTy)->getElementType()->isFunctionTy())) {
1804 TypePrinter.print(RetTy, Out);
1806 writeOperand(Operand, false);
1808 writeOperand(Operand, true);
1811 for (unsigned op = 0, Eop = II->getNumArgOperands(); op < Eop; ++op) {
1814 writeParamOperand(II->getArgOperand(op), PAL.getParamAttributes(op + 1));
1818 if (PAL.getFnAttributes() != Attribute::None)
1819 Out << ' ' << Attribute::getAsString(PAL.getFnAttributes());
1822 writeOperand(II->getNormalDest(), true);
1824 writeOperand(II->getUnwindDest(), true);
1826 } else if (const AllocaInst *AI = dyn_cast<AllocaInst>(&I)) {
1828 TypePrinter.print(AI->getType()->getElementType(), Out);
1829 if (!AI->getArraySize() || AI->isArrayAllocation()) {
1831 writeOperand(AI->getArraySize(), true);
1833 if (AI->getAlignment()) {
1834 Out << ", align " << AI->getAlignment();
1836 } else if (isa<CastInst>(I)) {
1839 writeOperand(Operand, true); // Work with broken code
1842 TypePrinter.print(I.getType(), Out);
1843 } else if (isa<VAArgInst>(I)) {
1846 writeOperand(Operand, true); // Work with broken code
1849 TypePrinter.print(I.getType(), Out);
1850 } else if (Operand) { // Print the normal way.
1852 // PrintAllTypes - Instructions who have operands of all the same type
1853 // omit the type from all but the first operand. If the instruction has
1854 // different type operands (for example br), then they are all printed.
1855 bool PrintAllTypes = false;
1856 Type *TheType = Operand->getType();
1858 // Select, Store and ShuffleVector always print all types.
1859 if (isa<SelectInst>(I) || isa<StoreInst>(I) || isa<ShuffleVectorInst>(I)
1860 || isa<ReturnInst>(I)) {
1861 PrintAllTypes = true;
1863 for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) {
1864 Operand = I.getOperand(i);
1865 // note that Operand shouldn't be null, but the test helps make dump()
1866 // more tolerant of malformed IR
1867 if (Operand && Operand->getType() != TheType) {
1868 PrintAllTypes = true; // We have differing types! Print them all!
1874 if (!PrintAllTypes) {
1876 TypePrinter.print(TheType, Out);
1880 for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) {
1882 writeOperand(I.getOperand(i), PrintAllTypes);
1886 // Print post operand alignment for load/store.
1887 if (isa<LoadInst>(I) && cast<LoadInst>(I).getAlignment()) {
1888 Out << ", align " << cast<LoadInst>(I).getAlignment();
1889 } else if (isa<StoreInst>(I) && cast<StoreInst>(I).getAlignment()) {
1890 Out << ", align " << cast<StoreInst>(I).getAlignment();
1893 // Print Metadata info.
1894 SmallVector<std::pair<unsigned, MDNode*>, 4> InstMD;
1895 I.getAllMetadata(InstMD);
1896 if (!InstMD.empty()) {
1897 SmallVector<StringRef, 8> MDNames;
1898 I.getType()->getContext().getMDKindNames(MDNames);
1899 for (unsigned i = 0, e = InstMD.size(); i != e; ++i) {
1900 unsigned Kind = InstMD[i].first;
1901 if (Kind < MDNames.size()) {
1902 Out << ", !" << MDNames[Kind];
1904 Out << ", !<unknown kind #" << Kind << ">";
1907 WriteAsOperandInternal(Out, InstMD[i].second, &TypePrinter, &Machine,
1911 printInfoComment(I);
1914 static void WriteMDNodeComment(const MDNode *Node,
1915 formatted_raw_ostream &Out) {
1916 if (Node->getNumOperands() < 1)
1918 ConstantInt *CI = dyn_cast_or_null<ConstantInt>(Node->getOperand(0));
1920 APInt Val = CI->getValue();
1921 APInt Tag = Val & ~APInt(Val.getBitWidth(), LLVMDebugVersionMask);
1922 if (Val.ult(LLVMDebugVersion))
1925 Out.PadToColumn(50);
1926 if (Tag == dwarf::DW_TAG_user_base)
1927 Out << "; [ DW_TAG_user_base ]";
1928 else if (Tag.isIntN(32)) {
1929 if (const char *TagName = dwarf::TagString(Tag.getZExtValue()))
1930 Out << "; [ " << TagName << " ]";
1934 void AssemblyWriter::writeAllMDNodes() {
1935 SmallVector<const MDNode *, 16> Nodes;
1936 Nodes.resize(Machine.mdn_size());
1937 for (SlotTracker::mdn_iterator I = Machine.mdn_begin(), E = Machine.mdn_end();
1939 Nodes[I->second] = cast<MDNode>(I->first);
1941 for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
1942 Out << '!' << i << " = metadata ";
1943 printMDNodeBody(Nodes[i]);
1947 void AssemblyWriter::printMDNodeBody(const MDNode *Node) {
1948 WriteMDNodeBodyInternal(Out, Node, &TypePrinter, &Machine, TheModule);
1949 WriteMDNodeComment(Node, Out);
1953 //===----------------------------------------------------------------------===//
1954 // External Interface declarations
1955 //===----------------------------------------------------------------------===//
1957 void Module::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW) const {
1958 SlotTracker SlotTable(this);
1959 formatted_raw_ostream OS(ROS);
1960 AssemblyWriter W(OS, SlotTable, this, AAW);
1961 W.printModule(this);
1964 void NamedMDNode::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW) const {
1965 SlotTracker SlotTable(getParent());
1966 formatted_raw_ostream OS(ROS);
1967 AssemblyWriter W(OS, SlotTable, getParent(), AAW);
1968 W.printNamedMDNode(this);
1971 void Type::print(raw_ostream &OS) const {
1973 OS << "<null Type>";
1977 TP.print(const_cast<Type*>(this), OS);
1979 // If the type is a named struct type, print the body as well.
1980 if (StructType *STy = dyn_cast<StructType>(const_cast<Type*>(this)))
1981 if (!STy->isAnonymous()) {
1983 TP.printStructBody(STy, OS);
1987 void Value::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW) const {
1989 ROS << "printing a <null> value\n";
1992 formatted_raw_ostream OS(ROS);
1993 if (const Instruction *I = dyn_cast<Instruction>(this)) {
1994 const Function *F = I->getParent() ? I->getParent()->getParent() : 0;
1995 SlotTracker SlotTable(F);
1996 AssemblyWriter W(OS, SlotTable, getModuleFromVal(I), AAW);
1997 W.printInstruction(*I);
1998 } else if (const BasicBlock *BB = dyn_cast<BasicBlock>(this)) {
1999 SlotTracker SlotTable(BB->getParent());
2000 AssemblyWriter W(OS, SlotTable, getModuleFromVal(BB), AAW);
2001 W.printBasicBlock(BB);
2002 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(this)) {
2003 SlotTracker SlotTable(GV->getParent());
2004 AssemblyWriter W(OS, SlotTable, GV->getParent(), AAW);
2005 if (const GlobalVariable *V = dyn_cast<GlobalVariable>(GV))
2007 else if (const Function *F = dyn_cast<Function>(GV))
2010 W.printAlias(cast<GlobalAlias>(GV));
2011 } else if (const MDNode *N = dyn_cast<MDNode>(this)) {
2012 const Function *F = N->getFunction();
2013 SlotTracker SlotTable(F);
2014 AssemblyWriter W(OS, SlotTable, F ? F->getParent() : 0, AAW);
2015 W.printMDNodeBody(N);
2016 } else if (const Constant *C = dyn_cast<Constant>(this)) {
2017 TypePrinting TypePrinter;
2018 TypePrinter.print(C->getType(), OS);
2020 WriteConstantInternal(OS, C, TypePrinter, 0, 0);
2021 } else if (isa<InlineAsm>(this) || isa<MDString>(this) ||
2022 isa<Argument>(this)) {
2023 WriteAsOperand(OS, this, true, 0);
2025 // Otherwise we don't know what it is. Call the virtual function to
2026 // allow a subclass to print itself.
2031 // Value::printCustom - subclasses should override this to implement printing.
2032 void Value::printCustom(raw_ostream &OS) const {
2033 llvm_unreachable("Unknown value to print out!");
2036 // Value::dump - allow easy printing of Values from the debugger.
2037 void Value::dump() const { print(dbgs()); dbgs() << '\n'; }
2039 // Type::dump - allow easy printing of Types from the debugger.
2040 void Type::dump() const { print(dbgs()); }
2042 // Module::dump() - Allow printing of Modules from the debugger.
2043 void Module::dump() const { print(dbgs(), 0); }